0% found this document useful (0 votes)
10 views56 pages

Summery - Ofbackend (AutoRecovered) (AutoRecovered)

Uploaded by

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

Summery - Ofbackend (AutoRecovered) (AutoRecovered)

Uploaded by

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

Class 9:

Databases: A database is a structured collection of data that can be easily accessed, managed, and
updated.

Relational Database: A relational database stores data points that are related to each other. It organizes
data into tables (also called relations), which consist of rows and columns.

Key Concepts of Relational Databases

1. Tables: A table is a collection of related data entries and it consists of rows and columns.
o Rows: Also known as records or tuples, each row in a table represents a single data item.
o Columns: Also known as attributes or fields, columns represent the properties or
characteristics of the data.
2. Primary Key (PK): A unique identifier for each record in a table. It ensures that each record can
be uniquely identified by a specific column or a combination of columns.
3. Foreign Key (FK): A field in one table that uniquely identifies a row of another table creates a
link between the two tables, enforcing referential integrity within the database.

Types of Relationships

1. One-to-One: Each row in Table A is linked to exactly one row in Table B, and vice versa. This
type of relationship is less common and is used when you need to split data into two tables but
still maintain a direct link between them.
2. One-to-Many: Each row in Table A can be linked to multiple rows in Table B, but each row in
Table B is linked to only one row in Table A. This is the most common type of relationship.
3. Many-to-Many: Multiple rows in Table A can be linked to multiple rows in Table B. This
requires a third table, known as a junction table, to manage the relationships.

Entity-Relationship Diagram (ERD): An ERD is a visual representation of the data and its
relationships in a system. It helps in designing and understanding the database structure.

Key Concepts of an ERD

1. Entities: Objects or concepts that represent real-world things within the system. Each entity
becomes a table in the database.
2. Attributes: Details or properties of an entity. Attributes describe the characteristics of an entity
and become columns in the table.
3. Relationships: Describes how entities are related to each other. Relationships can be one-to-one,
one-to-many, or many-to-many.

Uses of an ERD

 Database Design: Visualize entities and their relationships to design a database schema.
 Documentation: Provides a clear schema and relationship documentation for future reference.
 Communication: Facilitates communication between stakeholders, developers, and database
administrators by providing a clear and understandable representation of the database structure.

Example ERD Components


1. Entity: Customer
o Attributes: CustomerID (PK), FirstName, LastName, Email
2. Entity: Order
o Attributes: OrderID (PK), OrderDate, CustomerID (FK)
3. Relationship: Customer to Order (One-to-Many)
o Each customer can have multiple orders, but each order is linked to only one customer.
Class 10:

: ‫يعني بدل ما استخدم الداتا بيس دغري التعامل مع الداتا بقدر استخدم اشي بدالو الي هو‬
‫احنا نزلنا الباكج تاعتها‬

Entity Framework is an Object-Relational Mapper (ORM) for .NET.

 It enables developers to work with a database using .NET objects, acting as a bridge between the
application and the database.
 Essentially, it translates the code into database operations, allowing for seamless interaction
between the two.

ORM (Object-Relational Mapper) is a programming technique used to convert data between


incompatible systems using Object-Oriented Programming (OOP) principles.

Key Concepts of Migration:

 Database schema: the structure of the database: tables, columns, relationships, etc.).
 Migration: It's a tool for managing and applying changes to your database schema without
manually writing SQL.
 Evolving Schema: You can continuously change and improve the structure of your database
(add/modify tables and columns).
 Generated as Code: Every change is automatically turned into code, ensuring that changes are
consistent and can be tracked through version control like Git.
1. Open VS code
2. Asp.net core empty
3. http instead of https
4. program.cs

namespace WebApplication1  Program is the main class of your program.


{  Main is the starting point of the
public class Program application, just like the first page of a
{ book.
public static void Main(string[] args)  args holds any extra information when the
{ app starts (we won’t use it for now).
var builder = WebApplication.CreateBuilder(args); This line creates a builder, which is a tool that
var app = builder.Build(); prepares the application (your web app) to start.
It’s like setting up all the tools before starting a
app.MapGet("/", () => "Hello World!"); job.
app.Run(); }}} This line "builds" the web application. It’s like
taking the tools you've prepared and putting them
together to make your web app ready to run.
If someone visits the home page (for example,
http://localhost:5000/), the page will show the text
"Hello World!".
5. add – new folder – Data
6. add inside Data - EmployeeDbContext.cs (( ‫بدنا نحول الرسمة الفريمورك ل حقيقة عال فيجول‬
‫بيسك‬
namespace WebApplication1.Data - A database context (like EmployeeDbContext) acts as a bridge
{ between your application and the database.
public class EmployeeDbContext : DbContext - Instead of writing complex code to get or save employee data,
// ‫!! بس هاي ما رح تشتغل اال بس انزل بكجز‬ you use this tool to do it more easily.
DbContext:
{  This is a class provided by Entity Framework Core.
}  It contains a lot of built-in functionality that makes it easier
} to work with databases.
Benefits of Inheriting from DbContext:
easily connect to your database without writing complex
connection code, CRUD Operations, You can write queries using
LINQ (a powerful query language in C#) to fetch data from the
database, Tracking Change, Transactions ensure that a series
of database operations are treated as a single unit of work.

7. install

7.0.20

using Microsoft.EntityFrameworkCore; //add this to the ‫ بس بدنا اعدادات‬DbContext ‫هسا اوك احنا ورثنا من ال‬
top of code ‫معينة جواها نتحكم فيهازي نوع الداتا بيس زاسمها‬
constructor ‫والباسوررد وهاد بتم باستدام ال‬
namespace WebApplication1.Data
{ This declares the constructor for the EmployeeDbContext class.
public class EmployeeDbContext : DbContext ==DbContextOptions is a special type provided by Entity
{ Framework includes:
// constructor make environment to connection to the  Database Provider: SQL Server
database provider  Connection String: The information needed to connect
public EmployeeDbContext(DbContextOptions options) : to the specific database (like the database name, server,
base(options) username, and password).
{ : base(options):
 This part means you are calling the
}
} constructor of the parent class, which is
DbContext.
 base(options): This passes the options
parameter to the DbContext constructor.
 Why is this important? Because DbContext
needs this information to establish a
connection to the database when it’s used.
8. install : its translation to translate and handle and create shortcut for us for
command lines and communicate with database

7.0.20

9. create entity that we want to translate – make folder model – employee


‫ ف في طريقتين اتحكم فيها لتصير هيك شو همه؟‬,‫ بس الباقي ال‬Required ‫ بكون‬ID ‫ هسا الـ‬++
DataAnnotations vs FluentApi (is better to write clean code)

namespace WebApplication1.Models Defining this class allows you


{ to use Entity Framework to
public class Employee interact with the employee
{ data in a structured way.
// They prefer to name it id (not emloyeeID) TO BE distinguishable in database
public int Id { get; set; } // PK (primary key) is unique
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string PostalCode { get; set; }
10. add this to appsetting.json: connection to your SQL Server database
{ Trusted_Connection=True: Use
"ConnectionStrings": { Windows Authentication (your
"DefaultConnection": "Server=(localdb)\\ Windows account) to connect.
MSSQLLocalDB;Database=EmployeesDB;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"
},
"Logging": { MultipleActiveResultSets=true:
"LogLevel": { Allow multiple queries to run at the
"Default": "Information", same time.
"Microsoft.AspNetCore": "Warning"
} Logging: The Logging section
}, helps you track what your
"AllowedHosts": "*" application is doing. It’s useful for
} debugging and monitoring.

Security: The AllowedHosts


section helps control access to
your application.

11. access JSON file?


using Microsoft.EntityFrameworkCore;
using WebApplication1.Data;

namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
string ConnectionServciesVar = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<EmployeeDbContext>(optionX => optionX.UseSqlServer(ConnectionServciesVar));

var app = builder.Build();

app.MapGet("/", () => "Hello World!");


app.MapGet("/newpage", () => "Hello World!, from Noor Yasser!");

app.Run();

 What it does: You get a key (the connection string) that tells your application how to find the database.
 builder.Configuration: Think of this as a way to access your app’s settings.
 .GetConnectionString("DefaultConnection"): This is looking for a connection string called "DefaultConnection". It’s
like asking, “Where’s the key to my database?”

====================================================================
 What it does: You set up your application to use that key when it needs to connect to the database.
 builder.Services.AddDbContext<EmployeeDbContext>: This tells the app, “Whenever I need to work with the
Employee database, use this EmployeeDbContext.”
 (optionX => optionX.UseSqlServer(ConnectionServciesVar)):This part says, “When I connect to the database,
use SQL Server and the key I just saved (ConnectionServciesVar).”

12. //we need to tell the DB context that we have new table or entity waiting for it
models ‫ الي عندي انو في‬DBcontext ‫ طرق لحتى اخبر الـ‬3 ‫هسا في عندي‬
!!‫ يعني بتعرف عليهم كمودل مش كالس‬tables ‫(بدي تحولهم لـ‬domin modaels )
1- Using Dbset (As u use usually and in this lecture).
‫‪2-‬‬

‫انك تربط مودل معرف عندك اصال انو تيبل هون بمثالنا ‪blogs‬‬ ‫‪-3‬‬
‫بمودل مش معرف انو تيبل‪:‬‬

‫;‪using Microsoft.EntityFrameworkCore‬‬ ‫هو بخلي البرنامج عندي يعترف‬


‫بانو المودل عبارة عن تيبل‬
‫‪namespace WebApplication1.Data‬‬ ‫بالداتا بيس‬
‫{‬ ‫‪Purpose of DbSet: It acts like a‬‬
public class EmployeeDbContext : DbContext table in your database. You can
{ think of it as a way to manage a
public EmployeeDbContext(DbContextOptions options) : base(options) group of entities (records) in that
{ table. For example, you can add
new employees, retrieve
} existing ones, update them, or
// to communicate with specific table in DB delete them. Employee? TABLE
public DbSet<Employee> employees { get; set; } NAME
} employees: This is the name of the
} property. You can use this name to
access the DbSet<Employee> from
{ get; set; }: other parts of your code.
 This syntax defines a property with both a getter and a setter.
 get: Allows you to read the value of the employees property. This is how you can ‫ازا ما عملت هي الخطوة وعملت‬
access the collection of Employee entities. ‫ادد مايقريشن المايقريشن رح‬
 set: Allows you to assign a new value to the employees property. In practice, ‫ النو مش مربوطين هيك‬,‫تطلع فاضية‬
this is typically handled by Entity Framework, so you don't usually set this ‫لسا‬
property directly.
You can use this property to
perform various data operations like
querying, adding, updating, or
deleting employee records.

‫ ازا بدي ياه ما يعتبرها ك تيبل؟‬, ‫طب العكس‬


1- annotation

-2
13. RUN SQL SERVER ???

Sqllocaldb start MSSQLLocalDB

14. OPEN SQL SERVER MANAGEMENT STUDIO

15. Add-migration
16. update-database

==============================Now its added table to


DB==========================

NOW I CAN SEE ENTITES


‫‪17.It will undo current migration‬‬

‫‪undo all migration‬‬

‫=====‬

‫‪18. remove-migration‬‬

‫بحذف اخر وحدة‬

‫‪+++++++‬‬

‫هسا ازا عندي اكتر من ‪ migration‬مثال ‪ 10‬وبدي احذف الـ ‪ migration‬رقم ‪ 6‬شو بعمل؟‬

‫‪Update-database -migration:6‬‬

‫وبعدها بعمل‬
‫‪remove-migration‬‬

‫هاد معناه انو جوا المايقريشن محطوط انو رح ينعمل دروب ل تيبل مثال‬
Class 11:

What is an API?

An Application Programming Interface (API) is a set of rules and protocols that allow different
software applications to communicate with each other. APIs define the methods and data formats that
applications use to request and exchange information.

‫معناه بشكل عملي؟‬

‫ على نفس الجهاز تبعي بصير اسم‬project2 ‫ بدك توصللها من‬project1 ‫ بـ‬sum ‫ اسمها‬function ‫مثال عندك‬
‫ ازا حدا من امريكا وانا باالردن بدو ينادي ال‬--- API !!! )‫الفنكشن (طبعا منضيف شوية بهارات اضافات‬
WEB API (WEB SERVICE) ‫ هاد بصير اسمو‬API

Why Use an API?

 Sharing Data: APIs let different systems share information easily.


 Simplicity: They make complex systems easier to use by hiding the details.
 Speed: Instead of building everything from scratch, developers can use APIs to add features
quickly.
 Reuse: APIs allow developers to use existing services instead of creating new ones.

CRUD Operations

1. Create (POST): Adds new data to a database. For example, creating a new user account.
2. Read (GET): Retrieves data from a database. For instance, fetching the details of an existing
user.
3. Update (PUT/PATCH): Modifies existing data in a database. For example, updating a user’s
information.
4. Delete (DELETE): Removes data from a database. For instance, deleting a user account.

Controllers

Controllers are classes or components in a web application that handle incoming HTTP requests and
return responses. They are responsible for:

 Receive Requests: They listen for incoming requests (like when you click a button).
 Process Requests: They carry out the necessary actions, like fetching data from a database.
 Send Responses: They return data back to the user, often in a format like JSON

.Endpoints or routes are specific paths defined in an API that map to controller actions. They determine
how different parts of the application respond to various HTTP requests.

Endpoints: These are specific URLs that correspond to actions in your application. For example, an
endpoint might be /api/users to manage user data.

========================
controller and the API are not the same, but they are related.

 Controller: It's a class in your application that handles incoming HTTP requests and sends back
responses. It contains the logic for what happens when someone calls an API.
 API: It's the overall interface that allows different systems (like frontend and backend) to
communicate. The API defines the endpoints, like /api/employees, and the controller handles
what each endpoint does (like fetching data, adding data, etc.).

So, The controller is part of the API, responsible for executing code when an API call is made.

Example?

When you make a request like `GET /api/employees`, the **controller** processes it, fetches employee data from the database,
and sends it back to you. The API is how you access this functionality, while the controller is the part that runs the code to do the
work. Example in a simplified form:

 API route: /api/employees


 Controller: Gets employee data and sends it to you when you call the API.

Navigation properties in Entity Framework are used to manage relationships between


entities in the database. They represent foreign key relationships and enable easy
navigation from one related entity to another (e.g., an Employee entity can have a
navigation property for the Department entity it belongs to).

‫شو يعني ومتى منستخدمها؟‬


‫ ؟؟ فبستخدمها‬post‫ عن طريق ال‬blog ‫ ) للــ‬navigate(‫بدي انتقل‬

Benefits of Navigation Properties

1. Automatic Relationship Management: Navigation properties automatically


handle complex relationships, such as foreign keys, behind the scenes.

2. Simplified Data Access: They allow easy access to related data without needing to
write complex joins or queries.

3. Efficient Data Retrieval: When used with features like lazy loading or eager
loading, navigation properties improve efficiency by retrieving only the necessary
related data.

One To One Relationship

One To Many Relationship


‫‪Many To Many Relationship:‬‬
‫هو لحالو بالمايقريشن بعمل تيبل ثالث‬

‫او انا بعمل التيبل ال‪3‬‬


using ErdAndEF.Models; OnModelCreating Method: This method is used to configure how your
using Microsoft.EntityFrameworkCore; (tables) behave in the database.

namespace ErdAndEF.Data Calling the Base Method:


{ base.OnModelCreating(modelBuilder);
public class EmployeeDbContext : DbContext  This line calls the base class's OnModelCreating method to
{ ensure any default configurations are applied.
public EmployeeDbContext(DbContextOptions options) : base(options)
{

}
public DbSet<Employee> employees { get; set; } modelBuilder.Entity<EmployeeProjects>().HasKey(pk => new
public DbSet<Project> Projects { get; set; } { pk.ProjectID, pk.EmployeeID });
protected override void OnModelCreating(ModelBuilder modelBuilder)
 This line sets a composite key for the EmployeeProjects
{ table. It means that each record in this table will be uniquely
base.OnModelCreating(modelBuilder); identified by combining ProjectID and EmployeeID. This is
useful for managing relationships where multiple employees
modelBuilder.Entity<EmployeeProjects>().HasKey(pk => new { pk.ProjectID, can be linked to multiple projects.
pk.EmployeeID });

// seed employees data ( just to test )


modelBuilder.Entity<Employee>().HasData(
new Employee { Id = 6, FirstName = "Ahmad",LastName = "Mohsen", Email =
"[email protected]",Phone = "022555554"},
new Employee { Id = 7, FirstName = "Essa", LastName = "Mohsen", Email =
"[email protected]", Phone = "022555554" }
);}}}
namespace ErdAndEF.Models When to Use ICollection<T>:
{  One-to-Many Relationships:
public class Employee  If one entity can have multiple related entities. For example,
{ if you have a Department class and each department can
public int Id { get; set; } // PK have multiple Employee instances, the Department class
public string FirstName { get; set; } would have an ICollection<Employee> property.
public string LastName { get; set; } public class Department
public string Email { get; set; } {
public string Phone { get; set; } public int Id { get; set; }
public string Name { get; set; }
public ICollection<EmployeeProjects> employeeProjects { get; set; } public ICollection<Employee> Employees { get; set; } // One
department has many employees
================================== }
namespace ErdAndEF.Models  Many-to-Many Relationships:
{
public class Project
 If entities can be associated with multiple instances of each
{ other. For example, in the case of Employee and Project,
public int Id { get; set; } where each employee can work on multiple projects, and
public string ProjectName { get; set; } each project can have multiple employees, you would use
public string Budget { get; set; } an ICollection<EmployeeProjects> in both Employee and
public double Hours { get; set; } Project.
public class Employee
{
public ICollection<EmployeeProjects> employeeProjects { get; set;} public int Id { get; set; }
public ICollection<EmployeeProjects> EmployeeProjects { get;
================================== set; } // Employee can be in many projects
namespace ErdAndEF.Models }
{
public class EmployeeProjects public class Project
{ // ‫الي انضافو جديد‬ {
public int Id { get; set; }
public int EmployeeID { get; set; }
public ICollection<EmployeeProjects> EmployeeProjects { get;
public Employee Employee { get; set; }
set; } // Project can have many employees
public int ProjectID { get; set; }
}
public Project Project { get; set; } }
namespace ErdAndEF.Controllers  [Route("api/[controller]")]:
{  This sets up the URL path for the controller.
[Route("api/[controller]")]
[ApiController]  If your controller is called EmployeesController, the URL to
// Inherits from ControllerBase, which provides common functionality for API access it will be api/employees.
controllers.  The [controller] part automatically uses the name of the
public class EmployeesController : ControllerBase controller without the "Controller" suffix.
{  [ApiController]:
//Dependency Injection  This tells the framework that this controller is meant for
private readonly EmployeeDbContext _context; handling API requests.
public EmployeesController(EmployeeDbContext context)
{  It enables helpful features, like automatic validation of data
_context = context; sent in requests, making it easier to work with APIs.
}
Dependency Injection = Getting what you need from the
outside, instead of creating it yourself.
// GET: api/Employees
[HttpGet] Imagine this:
public async Task<ActionResult<IEnumerable<Employee>>> Getemployees() You have a robot that makes sandwiches. The robot needs
{ ingredients (bread, cheese, etc.) to make the sandwich.
if (_context.employees == null) Now, there are two ways to get the ingredients:
{ 1. The robot goes out and buys the ingredients every time
return NotFound(); it needs them.
} 2. You give the robot the ingredients whenever it needs to
return await _context.employees.ToListAsync(); make a sandwich.
} How does this relate to Dependency Injection?
 The robot is your class (like EmployeesController).
// GET: api/Employees/5  The ingredients are the things your class needs to work
[HttpGet("{id}")] (like EmployeeDbContext—the database connection).
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
 You giving the robot the ingredients is like
Dependency Injection—you give your class the tools it
if (_context.employees == null)
needs from outside, so it doesn’t have to create them itself.
{
--  EmployeeDbContext context is like the ingredients the class
return NotFound();
needs.
}
--  Instead of the controller going and creating its own connection to
var employee = await _context.employees.FindAsync(id);
the database, it gets that connection from somewhere else.
if (employee == null)
So??????????????/
{
return NotFound(); The controller takes an instance of EmployeeDbContext in its
} constructor. This allows the controller to access the
return employee; database context to perform operations on the
} employees table.
Updates an existing employee’s data.
// PUT: api/Employees/5 Task: represents an asynchronous operation that may not
[HttpPut("{id}")] have completed yet.
public async Task<IActionResult> PutEmployee(int id, Employee employee)
{
ActionResult :return different types of HTTP responses (like
if (id != employee.Id) 200 OK, 404 Not Found, etc.) depending on the situation.?
{ if its 200? will return IEnumerable<Employee>? list of
return BadRequest(); Employee objects
}

_context.Entry(employee).State = EntityState.Modified;

try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(id))
{
return NotFound();
}
else
{
throw;
}
}

return NoContent();
}

// POST: api/Employees
[HttpPost]
public async Task<ActionResult<Employee>> PostEmployee(Employee employee)
{
if (_context.employees == null)
{
return Problem("Entity set 'EmployeeDbContext.employees' is null.");
}
_context.employees.Add(employee);
await _context.SaveChangesAsync();

return CreatedAtAction("GetEmployee", new { id = employee.Id }, employee);


}

// DELETE: api/Employees/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteEmployee(int id)
{
if (_context.employees == null)
{
return NotFound();
}
var employee = await _context.employees.FindAsync(id);
if (employee == null)
{
return NotFound();
}

_context.employees.Remove(employee);
await _context.SaveChangesAsync();

return NoContent();
}

// A helper method that checks if an employee with the given ID exists in the
database.
private bool EmployeeExists(int id)
{
return (_context.employees?.Any(e => e.Id == id)).GetValueOrDefault();
}
}
}
Example Flow:

1. A request comes to the Controller.

2. The Controller calls a method in the Service.

3. The Service uses an Interface to ensure it follows a specific structure while handling the logic.

+++ Interface to It specifies what methods should be implemented without


providing the implementation details.+ Interacts With: Repository/Service

Lecture 12: Repo Design Patterns Services and Data Injection


1- Make folder (Repositories) inside it two folders (Interfaces) + (Services)
2- Make interface.cs named as (IEmployee.cs)

using ErdAndEF.Models; It serves as a contract that any implementation


(like EmployeeService) must follow.
namespace ErdAndEF.Repositories.Interfaces
{ ‫هو متل عقد الزم تتبعو الـ سيرفسز‬
public interface IEmployee
{
Task<Employee> CreateEmployee(Employee employee);
Task<List<Employee>> GetAllEmployees();
Task<Employee> GetEmployeeById(int employeeId);
Task<Employee> UpdateEmployee(int id,Employee employee);
Task DeleteEmployee(int id);
}
}
3- Inside Services we create class named EmployeeService.cs

public class EmployeeService : IEmployee


{
IEmployee will be incorrect so? Result? Will implement all interfaces

Hover it and enter + alt implement interface

4- Copy this from controller file:


5. And paste it in but change EmployeesController to EmployeeService:

public class EmployeeService : IEmployee  This class implements the IEmployee interface and
{ contains the actual business logic to interact with the
private readonly EmployeeDbContext _context; database.( ensuring that EmployeeService follows a
// constructor consistent structure.)
public EmployeeService(EmployeeDbContext context)
{  This is the constructor for the EmployeeService class. It
_context = context; receives an EmployeeDbContext object (context) and
} assigns it to _context.
-This allows the service class to interact with the database
// employees from dbset through _context.
public async Task<Employee> CreateEmployee(Employee employee)
{
_context.employees.Add(employee);
await _context.SaveChangesAsync();

return employee;
}

public async Task DeleteEmployee(int id)


{
var getEmployee = await GetEmployeeById(id); EntityState.Deleted marks the retrieved employee entity
_context.Entry(getEmployee).State = EntityState.Deleted; as deleted.
await _context.SaveChangesAsync();

public async Task<List<Employee>> GetAllEmployees()


{
var allEmployees = await _context.employees.ToListAsync();
return allEmployees;
}

public async Task<Employee> GetEmployeeById(int employeeId)


{

var employee = await _context.employees.FindAsync(employeeId);


return employee;
}

public async Task<Employee> UpdateEmployee(int id, Employee


employee)
{
var exsitingEmployee = await _context.employees.FindAsync(id);
exsitingEmployee = employee;
await _context.SaveChangesAsync();

return employee;
}
}
}
6. Now, we want to use repositories to deal with databases (not immediately
as previously)? So? Update controller
namespace ErdAndEF.Controllers Modify Controller to Use Service
{  The EmployeesController now uses the IEmployee
[Route("api/[controller]")] service to handle requests.
[ApiController]  Role: It acts as a bridge between the client (API
public class EmployeesController : ControllerBase requests) and the business logic (service). It retrieves
{ data from the service and returns it to the client.
private readonly IEmployee _employee;

public EmployeesController(IEmployee context)


{
_employee = context;
}

// GET: api/Employees
[Route("/employees/GetAllEmployees")]
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>>
Getemployees()
{
return await _employee.GetAllEmployees();
}

// GET: api/Employees/5
[HttpGet("{id}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
return await _employee.GetEmployeeById(id);
}

// PUT: api/Employees/5
[HttpPut("{id}")]
public async Task<IActionResult> PutEmployee(int id, Employee
employee)
{
var updateEmployee = await _employee.UpdateEmployee(id, employee);
return Ok(updateEmployee);
}

// POST: api/Employees
[HttpPost]
public async Task<ActionResult<Employee>>
PostEmployee(Employee employee)
{
var newEmployee = await _employee.CreateEmployee(employee);
return Ok(newEmployee);
}

// DELETE: api/Employees/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteEmployee(int id)
{
var deletedEmployee = _employee.DeleteEmployee(id);
return Ok(deletedEmployee);
}
}
7. Edit program.cs

namespace ErdAndEF Update Program.cs for Dependency Injection


{  The Program.cs file is where you set up
public class Program dependency injection, telling the application
{ how to resolve interfaces to their
public static void Main(string[] args) implementations.
{
var builder = WebApplication.CreateBuilder(args);
 Role: This is where you configure the services
builder.Services.AddControllers(); so that when an IEmployee is requested, an
EmployeeService instance will be provided.
// Get the connection string settings
string ConnectionStringVar =
builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<EmployeeDbContext>(optionsX =>
optionsX.UseSqlServer(ConnectionStringVar));

builder.Services.AddScoped<IEmployee, EmployeeService>();

var app = builder.Build();


app.MapControllers();

app.MapGet("/", () => "Hello World!");


app.MapGet("/newpage", () => "Hello World! from the new page");

app.Run();
}
}
}
We don’t use repository pattern here:( in our example):

Simplified Example

 User sends a request to get all employees.


 Controller receives this request and asks the Service for the list of employees.
 Service interacts with the Database to fetch the data.
 Service returns the data back to the Controller.
 Controller sends the response back to the user.

comparing :

 repository Pattern: Ideal for larger, more complex applications where clear separation of concerns,
scalability, and testability are priorities.
 Direct Service Approach: Suitable for smaller applications or prototypes where simplicity and quick
development are key.

Steps if I want to use it:

1. A user sends a request to get all employees.

2. The Controller receives this request and calls the Service.

3. The Service calls the Repository to fetch the employee data from the database.

4. The Repository queries the database and returns the list of employees to the Service.

5. The Service returns the list to the Controller, which then sends it back to the user.

Class 12: ??

Class 13: Routing:

Routing in a web application is the process of mapping URLs (Uniform Resource


Locators) to specific code that handles requests. It matches incoming HTTP requests
to the appropriate controller actions based on predefined rules or patterns. This
process is crucial in web development frameworks like ASP.NET Core for managing
how a user interacts with the application through HTTP methods such as GET, POST,
PUT, and DELETE.
‫!!!!!!!!!!!ترتيبهم‬

Models-> Services -> interface -> controller

1- Its called (conventional routing): We will not use it now/ we will use it in MVC lec//NOT
NOW

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

2- Seed project data:

modelBuilder.Entity<EmployeeProjects>().HasData(
new EmployeeProjects { EmployeeID = 6 , ProjectID = 1},
new EmployeeProjects { EmployeeID = 6, ProjectID = 2 },
new EmployeeProjects { EmployeeID = 7, ProjectID = 1 }
);
3- Add-migration seedingProjectData
4- Update-database

:: ‫ ف شو عمل راح غير االسم‬postalcode ‫\\هسا عمر لقى انو هو حاذف سطر من الكود الي فيه ال‬
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\
MSSQLLocalDB;Database=EmployeesDBTest;Trusted_Connection=True;TrustServerCertificate=True;M
ultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"

‫وعمل ادد مايقريشن وابديت داتا ومشي الحال‬

===========================================================

5- Now we need to make a relation between employee data + project data


 Add controller for projects – and we have already made for employee

Compost key: (combine btw 2 pk keys)

modelBuilder.Entity<EmployeeProjects>().HasKey(pk => new { pk.ProjectID, pk.EmployeeID });


In the DbContext class, define the composite key for the join table between employees and projects.
6- /// Define relationships

modelBuilder.Entity<EmployeeProjects>() Now, define the relationships between Employee, Project, and


.HasOne(ep => ep.Employee) EmployeeProjects. Each EmployeeProject entity has one
.WithMany(e => e.employeeProjects) Employee and one Project.
.HasForeignKey(e => e.EmployeeID);

modelBuilder.Entity<EmployeeProjects>()
.HasOne(ep => ep.Project)
.WithMany(e => e.employeeProjects)
.HasForeignKey(e => e.ProjectID);
Add-migration makeEmployeeProjectRelation +++++++ Update-database

7- Seed employee data ++ we want to relate one employee with one project

modelBuilder.Entity<EmployeeProjects>().HasData(
new EmployeeProjects { EmployeeID = 6 , ProjectID = 1},
new EmployeeProjects { EmployeeID = 6, ProjectID = 2 },
new EmployeeProjects { EmployeeID = 7, ProjectID = 1 }
);
Add-migration addSeedDataForEmployee +++++++++++++++ Update-database

8- In (EmployeeService// get all projects for a given employee by id

public async Task<List<Project>> GetProjectsForEmployee(int employeeId)


{
var projectsForEmployee = await _context.EmployeeProjects
.Where(ep => ep.EmployeeID == employeeId)
.Select(ep => ep.Project) // Select the Project related to the Employee
.ToListAsync(); // Convert the result to a List

return projectsForEmployee;
}
The controller here is responsible for managing the request-response cycle but doesn’t contain business logic or data
access code.
9- Implement interface

Task<List<Project>> GetProjectsForEmployee( int employeeId);

10- (employeeController) file :

[HttpGet("{id}/allProjects")] The controller here is


public async Task<ActionResult<List<Project>>> GetProjectsForEmployee(int id) responsible for managing the
{ request-response cycle
// Call the service to get projects
var projects = await _employee.GetProjectsForEmployee(id); but doesn’t contain business
logic or data access code.
// Return HTTP response with the projects
return Ok(projects);
}
11- test it?

localhoste/7000/Api/emloyees/7/allProjects

localhoste/7000/Api/emloyees/6/allProjects

7 ‫ وبروجكت واحد ل‬6 ‫ بروجكتس ل‬2 ‫رح يطلعلي‬

12- we will create a method that will add an employee to a project ( we want to create it
without using seed data) in ProjectsController.cs

[HttpPost]
[Route("{projectId}/{emplyeeId}")]
public async Task<IActionResult> AddEmployeeToAProject(int projectId, int emplyeeId)
{
EmployeeProjects emplyeeProjectsVar = new EmployeeProjects()
{
ProjectID = projectId,
EmployeeID = emplyeeId
};
_context.Entry(emplyeeProjectsVar).State = EntityState.Added;
await _context.SaveChangesAsync();
return Ok();
13- d
Class 14:

1- Install Swashbuckle.AspNetCore package


2- Add this to program.cs
builder.Services.AddSwaggerGen adds Swagger generation services to your application. allowing
( you to create and serve API documentation. AddSwaggerGen is
option => responsible for setting up metadata (the description and
{ structure) of your API.
option.SwaggerDoc("employeesApi", new
Microsoft.OpenApi.Models.OpenApiInfo() ++option here allows you to configure how the Swagger
{ documentation behaves.
Title = "Employees Api Doc", //title of the API
documentation This creates a Swagger documentation for an API. The first
Version = "v1",//The version of the API ("v1"). argument, "employeesApi", is the name of this API
Description = "Api for managing all emolyees"});}); documentation.
The OpenApiInfo object that contains metadata : Title,
var app = builder.Build(); Version, Description.

// call swagger service It makes Swagger available for serving the API documentation.
app.UseSwagger  The Swagger service is configured to generate JSON
( documentation for the API at a specific route.
options => RouteTemplate: This defines the route at which the Swagger
{ JSON will be accessible.
options.RouteTemplate =
"api/{documentName}/swagger.json"; //route
}  app.UseSwaggerUI: This line enables the Swagger UI in your
); app, which is a nice interactive web interface to view and interact
with your API.
// call swagger UI options.SwaggerEndpoint("/api/employeesApi/
app.UseSwaggerUI swagger.json", "Emp Api"): This configures Swagger UI to load
( the API documentation from the Swagger JSON file generated
options => earlier (at /api/employeesApi/swagger.json).
{  "Emp Api" is the name displayed in the Swagger UI
options.SwaggerEndpoint("/api/employeesApi/swagger.json", interface for the API.
"Emp Api");  options.RoutePrefix = "EmpSwagger": This defines the URL
options.RoutePrefix = " EmpSwagger"; path where Swagger UI will be available. In this case, it's at
} /EmpSwagger, so if you navigate to
); http://localhost:5000/EmpSwagger, you'll see the interactive
Swagger UI.
3- Run program: localhost/7000/
4- TRY IT OUT --- EXCUTE IT
5- Creat azur account : Home - Microsoft Azure
6- 6
In 3 pic below (don’t do anyrhing - skip)
‫بعدها اضغط على اسمها‬
DON’T FORGET TO CHANGE PASSWORD
‫ازا طلع معي ايرور بكون بسبب ال منطقة الحل؟‬
IF WE TRY GET:

WE WILL RESEVE 500 ERROE

EXCUTE:

tunifyplatformserver

TunifyAdmin

Were$0787898717

TunifyPlatform
Class 15: Authentication then authorization
Authentication : who are you

Authorization : what u allowed to do

1- Install: Microsoft.AspNetCore.Identity.EntityFrameworkCore
2- Move to DBContext File:

To make identity take care of our app ? it should inherit from IdentityDbContext instead of
DBContext

(we can put in < IdentityUser> If I don’t want to add any new prop but here I want to
add)so I will put ApplicationUser

public class EmployeeDbContext : IdentityDbContext<ApplicationUser>


{
public EmployeeDbContext(DbContextOptions options) : base(options)
{

}
Then alt + entre === choose using : Microsoft.AspNetCore.Identity.EntityFrameworkCore
// when we use identity we use string as pk instead of integer

3- In Model Folder add : ApplicationUser.cs

namespace ErdAndEF.Models
{
public class ApplicationUser : IdentityUser
{
}
}
4- Make sure that u are connect to db
5- Add migration IdentityImplement + update database

6- Add services : that is responsible for activating the identity in our app
(program.cs)

// Add Identity Service


builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<EmployeeDbContext>();
app.UseAuthentication();

7- Add controller: UsersController.cs


8- Create interface named : IUser.cs

public interface IUser


{

// Add register
public Task<UserDto> Register(RegisterdUserDto registerdUserDto, ModelStateDictionary modelState); }

9- Create inside model folder another folder named: DTO --- file : RegisterdUserDto.cs

public class RegisterdUserDto


{
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
10- Make anorther file inside DTO : UserDto.cs

public class UserDto


{
public string Id { get; set; }
public string Username { get; set; }
}
11- Add inside service folder: IdentitiUserService.cs

public class IdentitiUserService : IUser


{
Alt + enter == impleament interface

public class IdentitiUserService : IUser


{
private UserManager<ApplicationUser> _userManager;

public IdentitiUserService(UserManager<ApplicationUser> Manager)


{
_userManager = Manager;

public async Task<UserDto> Register(RegisterdUserDto registerdUserDto, ModelStateDictionary modelState)


{
var user = new ApplicationUser()
{
UserName = registerdUserDto.UserName,
Email = registerdUserDto.Email,

};

var result = await _userManager.CreateAsync(user, registerdUserDto.Password);

if (result.Succeeded)
{
return new UserDto()
{
Id = user.Id,
Username = user.UserName
};
}

foreach (var error in result.Errors)


{
var errorCode = error.Code.Contains("Password") ? nameof(registerdUserDto) :
error.Code.Contains("Email") ? nameof(registerdUserDto) :
error.Code.Contains("Username") ? nameof(registerdUserDto) : "";

modelState.AddModelError(errorCode, error.Description);
}

return null;
}

12- Usercontroller:

namespace ErdAndEF.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{

private readonly IUser userService;

public UsersController(IUser context)


{
userService = context;
}

[HttpPost("Register")]
public async Task<ActionResult<UserDto>> Register(RegisterdUserDto registerdUserDto)
{
var user = await userService.Register(registerdUserDto, this.ModelState);
if (ModelState.IsValid)
{
return user;
}
if (user == null)
{
return Unauthorized();
}
return BadRequest();
}
13- Add to program.cs:

builder.Services.AddScoped<IUser, IdentitiUserService>();

14- Run + try to post

If we try to post password 1234 it will show mistake to us”

Implement login?
15- Iuser.cs

// Add login
public Task<UserDto> UserAuthentication(string username, string password);
16- IdentitiUserService.cs : alt + enter --- implement

// login
public async Task<UserDto> UserAuthentication(string username, string password)
{
var user = await _userManager.FindByNameAsync(username);

bool passValidation = await _userManager.CheckPasswordAsync(user, password);

if (passValidation)
{
return new UserDto()
{
Id = user.Id,
Username = user.UserName
};
}

return null;
}
17- UsersController.cs:

// login
[HttpPost("Login")]
public async Task<ActionResult<UserDto>> Login(LoginDto loginDto)
{
var user = await userService.UserAuthentication(loginDto.Username, loginDto.Password);

if (user == null)
{
return Unauthorized();
}

return user;
}
18- Make file LoginDto

public class LoginDto


{
public string Username { get; set; }
public string Password { get; set; }
}
19- Run ++ post + try login in right + wrong pass

Class 16:
JWT Token

A JWT (JSON Web Token) is a method for securely transmitting information between parties as a JSON
object. It is widely used in scenarios involving authentication and authorization.

JWT Use Cases:

1. Authentication:
o JWTs are used to verify the identity of a user. When a user logs in, the server generates a
JWT and sends it to the client. The client then includes this token in subsequent requests
to prove its identity.
2. Authorization:
o JWTs help grant or deny access to resources based on user permissions or roles. The
server checks the token to see if the user is authorized to access a particular resource or
perform a specific action.
3. Secure Information Transmission:
o JWTs provide a secure way to transmit information between systems. Since the token is
signed, it ensures the integrity of the data, making it difficult for unauthorized parties to
tamper with the content.
4. Access to Protected APIs:
o JWTs are often used to provide access to protected APIs. The client includes the JWT in
the request header, and the API server validates the token before allowing access to its
endpoints.
5. Single Sign-On (SSO):
o JWTs enable Single Sign-On (SSO) by allowing users to log in to multiple applications
using a single set of credentials. The token is shared across different services, enabling a
seamless user experience.

Summary:

JWTs are essential in modern web applications, particularly for securely handling user authentication and
authorization, ensuring secure communication, and enabling efficient access control across multiple
systems.

Steps:
1- Install : Microsoft.AspNetCore.Authentication.JwtBearer

2- Make inside services folder : JwtTokenService.cs

private readonly IConfiguration _configuration;


private readonly SignInManager<ApplicationUser> _signInManager;

public JwtTokenService(IConfiguration configuration , SignInManager<ApplicationUser> signInManager)


{
_configuration = configuration;
_signInManager = signInManager;}

3- In IdentitiUserService.cs inject Jwt:

// inject jwt service

private JwtTokenService jwtTokenService;

public IdentitiUserService(UserManager<ApplicationUser> Manager, JwtTokenService jwtTokenService)


{
_userManager = Manager;
this.jwtTokenService = jwtTokenService; }

4- In appsettings.json: add at first

"JWT": {
"SecretKey": "jbkbabaioeflanything12oknebsneha102nfsa32"

},

5- In program.cs : add

builder.Services.AddScoped<JwtTokenService>();

6- JwtTokenService.cs COMPLETE INSIDE IT:

public static TokenValidationParameters ValidateToken(IConfiguration configuration)


{
return new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = GetSecurityKey(configuration),
ValidateIssuer = false,
ValidateAudience = false
};}
private static SecurityKey GetSecurityKey(IConfiguration configuration)
{
var secretKey = configuration["JWT:SecretKey"];
if (secretKey == null)
{
throw new InvalidOperationException("Jwt Secret key is not exsist");}

var secretBytes = Encoding.UTF8.GetBytes(secretKey);


return new SymmetricSecurityKey(secretBytes);
}
public async Task<string> GenerateToken(ApplicationUser user, TimeSpan expiryDate)
{
var userPrincliple = await _signInManager.CreateUserPrincipalAsync(user);
if (userPrincliple == null)
{
return null;
}

var signInKey = GetSecurityKey(_configuration);

var token = new JwtSecurityToken


(
expires: DateTime.UtcNow + expiryDate,
signingCredentials: new SigningCredentials(signInKey, SecurityAlgorithms.HmacSha256),
claims: userPrincliple.Claims
);

return new JwtSecurityTokenHandler().WriteToken(token);}}}

7- Program.cs:

// add auth service to the app using jwt


builder.Services.AddAuthentication(
options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}
).AddJwtBearer(
options =>
{
options.TokenValidationParameters = JwtTokenService.ValidateToken(builder.Configuration);

});

++

app.UseAuthorization();

8- At UserDto.cs add:

public string Token { get; set; }

9- IdentitiUserService.cs :

// login
public async Task<UserDto> UserAuthentication(string username, string password)
{
var user = await _userManager.FindByNameAsync(username);
bool passValidation = await _userManager.CheckPasswordAsync(user, password);

if (passValidation)
{
return new UserDto()
{
Id = user.Id,
Username = user.UserName,
Token = await jwtTokenService.GenerateToken(user, System.TimeSpan.FromMinutes(7))
};}
return null;
10- Run program + try to post we will get token (copy it)
11- Go to JWT.io:

12- In IUser.cs:
// add user profile
public Task<UserDto> userProfile(ClaimsPrincipal claimsPrincipal);

13- In IdentitiUserService.cs : implement public class


IdentitiUserService : IUser (alt + enter)

Add this lines:

public async Task<UserDto> userProfile(ClaimsPrincipal claimsPrincipal)


{
var user = await _userManager.GetUserAsync(claimsPrincipal);

return new UserDto()


{
Id = user.Id,
Username = user.UserName,
Token = await jwtTokenService.GenerateToken(user, System.TimeSpan.FromMinutes(7)) // just for development
purposes
};
}}

14 – add to UsersController.cs:

[Authorize(Roles = "Admin")] // only logged in users can have access to the profile
[HttpGet("Profile")]
public async Task<ActionResult<UserDto>> Profile()
{
return await userService.userProfile(User);
}

14- Try it in post man:

15- In program.cs : add

//swagger configuration
builder.Services.AddSwaggerGen
(

option =>
{
option.SwaggerDoc("employeesApi", new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Employees Api Doc",
Version = "v1",
Description = "Api for managing all emolyees"
});
//add these lines
option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Please enter user token below."
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});

16- Run program – you will see the authorization button :


Paste it here:

Close :
17- EmployeeDbContext.cs in?

// step 2
// seed Projects data
modelBuilder.Entity<Project>().HasData(
new Project { Id = 1 , ProjectName = "Project A" , Budget = "8000 JD" , Hours = 120},
new Project { Id = 2, ProjectName = "Project B", Budget = "12000 JD", Hours = 180 },
new Project { Id = 3, ProjectName = "Project C", Budget = "15000 JD", Hours = 160 }
);
seedRoles(modelBuilder, "Admin" , "create", "update", "delete");
seedRoles(modelBuilder, "User", "update"); }

private void seedRoles(ModelBuilder modelBuilder, string roleName, params string[] permission )


{
var role = new IdentityRole
{
Id = roleName.ToLower(),
Name = roleName,
NormalizedName = roleName.ToUpper(),
ConcurrencyStamp = Guid.Empty.ToString()
};

// add claims for the users


// complete

modelBuilder.Entity<IdentityRole>().HasData(role);
18- Add-migration seedRole -- update-database
It will not access because user is NOT authorized and for admin too !!!!!!!!!!!!!

So ????????????????????????????????? we missed add Role

19- RegisterdUserDto.cs + UserDto.cs

public IList<string> Roles { get; set; }


20- IdentitiUserService.cs

if (result.Succeeded)
{
// add roles to the new rigstred user
await _userManager.AddToRolesAsync(user, registerdUserDto.Roles);
return new UserDto()
{
Id = user.Id,
Username = user.UserName,
Roles = await _userManager.GetRolesAsync(user)

};
}

Because we implement admin before we should go to!

Delete:
{

"userName": "NoorAlbonne",

"email": "[email protected]",

"password": "Were$0787898717",

"roles": [

"Admin"

I can access user profrile from here and from postman


tunifyplatformserver

TunifyAdmin

Were$0787898717

TunifyPlatform

You might also like