Summery - Ofbackend (AutoRecovered) (AutoRecovered)
Summery - Ofbackend (AutoRecovered) (AutoRecovered)
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.
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.
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.
: يعني بدل ما استخدم الداتا بيس دغري التعامل مع الداتا بقدر استخدم اشي بدالو الي هو
احنا نزلنا الباكج تاعتها
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.
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
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
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));
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
بمودل مش معرف انو تيبل:
-2
13. RUN SQL SERVER ???
15. Add-migration
16. update-database
=====
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
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:
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.
}
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 });
_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();
// 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:
3. The Service uses an Interface to ensure it follows a specific structure while handling the logic.
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;
}
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;
// 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
builder.Services.AddDbContext<EmployeeDbContext>(optionsX =>
optionsX.UseSqlServer(ConnectionStringVar));
builder.Services.AddScoped<IEmployee, EmployeeService>();
app.Run();
}
}
}
We don’t use repository pattern here:( in our example):
Simplified Example
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.
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: ??
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?}");
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": "*"
===========================================================
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
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
localhoste/7000/Api/emloyees/7/allProjects
localhoste/7000/Api/emloyees/6/allProjects
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:
// 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:
EXCUTE:
tunifyplatformserver
TunifyAdmin
Were$0787898717
TunifyPlatform
Class 15: Authentication then authorization
Authentication : who are you
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
}
Then alt + entre === choose using : Microsoft.AspNetCore.Identity.EntityFrameworkCore
// when we use identity we use string as pk instead of integer
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 register
public Task<UserDto> Register(RegisterdUserDto registerdUserDto, ModelStateDictionary modelState); }
9- Create inside model folder another folder named: DTO --- file : RegisterdUserDto.cs
};
if (result.Succeeded)
{
return new UserDto()
{
Id = user.Id,
Username = user.UserName
};
}
modelState.AddModelError(errorCode, error.Description);
}
return null;
}
12- Usercontroller:
namespace ErdAndEF.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
[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>();
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);
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
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.
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
"JWT": {
"SecretKey": "jbkbabaioeflanything12oknebsneha102nfsa32"
},
5- In program.cs : add
builder.Services.AddScoped<JwtTokenService>();
7- Program.cs:
});
++
app.UseAuthorization();
8- At UserDto.cs add:
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);
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);
}
//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>()
}
});
});
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"); }
modelBuilder.Entity<IdentityRole>().HasData(role);
18- Add-migration seedRole -- update-database
It will not access because user is NOT authorized and for admin too !!!!!!!!!!!!!
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)
};
}
Delete:
{
"userName": "NoorAlbonne",
"email": "[email protected]",
"password": "Were$0787898717",
"roles": [
"Admin"
TunifyAdmin
Were$0787898717
TunifyPlatform