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

Chapter 7 Linq and Framwork

The document outlines the required products and topics for a .NET development course, including Visual Studio 2022 and SQL Server versions. It covers essential concepts such as Entity Framework, LINQ, and MVC architecture, along with practical exercises for implementing these technologies. Additionally, it provides guidance on setting up a development environment and using Entity Framework for database interactions.

Uploaded by

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

Chapter 7 Linq and Framwork

The document outlines the required products and topics for a .NET development course, including Visual Studio 2022 and SQL Server versions. It covers essential concepts such as Entity Framework, LINQ, and MVC architecture, along with practical exercises for implementing these technologies. Additionally, it provides guidance on setting up a development environment and using Entity Framework for database interactions.

Uploaded by

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

Required Products

Visual studio 2022 community edition


https://www.c-sharpcorner.com/article/getting-started-with-visual-studi
o-2022-community-edition/

SQL Server 2014 or more 180 days


https://www.dataneb.com/post/sql-server-2014-standard-download

SQL Server 2017 or more 180 days Enterprise or standard edition


https://www.tektutorialshub.com/sql-server/how-to-download-and-inst
all-sql-server-2017/
https://www.microsoft.com/en-us/evalcenter/evaluate-sql-server-2017-
rtm
.NET OutLines
1. XML Serialization/Deserialization
2. JSON Serialization/Deserialization
3. .NET Framework versions
4. Entity Framework Design
1. EF Basics
2. EF Core
5. More on LINQ query
6. Dependency Injection
7. Delegates
8. Asynchronous Programming
9. MVC
10. Program.cs
11. MVC/WEB API .net 6
12. Microsoft Identity
13. Security
14. Deploying MVC and WEBAPI to MS Web server (IIS): if time permits
15. Roles and Claims: If Time Permits
3-.NET Framework versions
. Introduction to .NET Framework
• .NET (pronounced dot net) is a framework that provides a programming
guidelines that can be used to develop a wide range of applications–––from
web to mobile to Windows-based applications.

• The .NET framework can work with several programming languages such as C#,
VB.NET, C++ and F#. At Grand Circus, we use C#.

• Visual Studio is a very powerful Integrated Development Environment (IDE)


where you actually write your C# or .NET programs.
• It’s popular because it supports code editing, interface design, server
management, debugging, and performance analysis.
• You can download Visual Studio (Community Edition 2019/2022) for free
3-.NET Framework versions
.NET for future versions

2022
4- EF Design: EFBasics
(
https://www.entityframeworktutorial.net/what-is-entityfra
mework.aspx
)

1. What is Entity Framework?

2. What is an Entity in Entity Framework?

3. What is an Entity in Entity Framework Core ?

4. Development Approaches with Entity Framework


4- EF Design: EFBasics
1. What is Entity Framework?

• Official Definition: “Entity Framework is an object-relational mapper (O/RM)


that enables .NET developers to work with a database using .NET objects. It
eliminates the need for most of the data-access code that developers usually
need to write.”

• You compose queries using UML model (Domain classes, Entity Data Model-EDM)
• You add instances to object collection
• You delete from object collection
• You modify properties of an object
• And then you write back these changes to databases

• Slide 40 illustrates where the Entity Framework fits into your application.
4- EF Design: EFBasics
1. What is Entity Framework?
• Prior to .NET 3.5, developers often used to write ADO.NET code or Enterprise Data Access Block to save or retrieve
application data from the underlying database
• They used to open a connection to the database, create basic.net query objects to fetch data, create DataSets to
store fetched data, modify and validate data with datasets, submit data to the databases.
• What are business rules:
• Are annotation rules applied on DTO object properties, or for advanced rules, are applied via partial class (service class)
• Example of business rules
• Employee age must be greater or equal to 18
• Employees must have learners license for at least three months which should not be expired (means should not be older than 12
months)
• Employee Address attribute must not be empty
• Employees Matched regex phone number: "425-555-BOGUS"
• With EF, business rules are applied on DTOs
• Where they must be configured and why
• Validation and business rules are preferred to be implemented at the DTO model instead of JavaScript at the Front End
• The rules related to a DTO are auto generated with HTML redirected to front-end as AJAX and JavaScripts
• This View POSTS to a controller action methods having the DTO model as input parameter
• Partial classes can be added to DTO for advanced Business Rule that are validated at the controller level
• Why they must be defined at the DTO model?
• Having the flexibility to change business rules in one place, without having these changes ripple throughout the application, is a sign
of a well-written application
• Security: The complex rules are defined at Back end not Front End
• Note Annex1 for more information about implementing Business Rules with partial classes
Entity Framework
4- EF Design: EFBasics : MVC: Architecture API
Layers: presentation layer, Application layer: DTO (model Layer)+ BL services layer + EDM Entities are used by the repositories code
Repositories, EF Entities layer, database layer
Entity Data Layer
Application
Business Layer
logic
Service Layer+Repositories
Presentation layer
1-[Service Layer
(BusinessLogic)]
2-Repositories+Interfaces The
Database
+Service Layer can be :
MSSQL,
DTOs are decorated by ORACLE,
Annnotation.Val(BL) and by MySql,
Partial classes: BL Service layer Repositories use PostgreSQL,
Used to Validate DTO into:
1-Controllers context class to MonGOdb,
2-Browsers by using JS Scripts manipulate the EDM …
defined into Views

Angular, React js,…


1- DTOs +DataAnnotation(rule1)
2-Partial Classes or Service layer
orBusines logic for DTOs(rule2)

Service layer: it operates on DTO to enforce Data Transfer Object (DTO) or ViewModel + [Service layer(Business Logic)]
business rule, calculation, transformation, etc. Library to be used at any layer
4- EF Design: EFBasics
1. What is Entity Framework?
• Entity Data Model

Standard
4- EF Design: EFBasics
1. What is Entity Framework?
• Entity Data Model object collection
• In repositories, instance of context class is created and used
Inheritance
4- EF Design: EFBasics
1. What is Entity Framework?

• As per the MVC architecture figure, Entity Framework API fits between the
EDM (domain classes) and the database.

• It inserts/deletes data, added/removed to/from collections, into the database

• Updates the databases with the object’s modified properties

• Executes the queries built on top of collections/EDM entities to retrieves data


from the database and converts it to DTO business entities objects automatically.
4- EF Design: EFBasics
1. What is Entity Framework?
• Executes the queries built on top of EDM to retrieves data from the database
and converts it to DTO business entities objects automatically.

In repositories

EDM Linq query example 1


to get _ctx: instance
list of students of context class

IList<StudentDTO> students = new List<StudentDTO>();


students = await _ctx.Students.Select(s =>
new StudentDTO
{
StudentId = s.StudentId, EDM Collection
StudentName = s.StudentName,
standard = new StandardDTO
{ Navigation
StandardName = s.Standard.StandardName
}
}
).ToListAsync<StudentDTO>();
4- EF Design: EFBasics
1. What is Entity Framework? Context Class
• Starting from an existing database
• EF API Creates the context class and the EDM from the existing DB (Databse first) which
contains the entity classes + all their association/Navigation (1—1, 1--*, *--*)
• EF API Generates the DB from the model if the DB is not yet created (Model first)
• A context class that inherits from DbContext
• Contains all the entity classes collections
• public virtual DbSet<Course> Courses { get; set; }
• Contains the mapping between the entities and database tables into the
OnModelingCreating() method (DBFirst)
• Holds the references/tracks all the entity objects as soon as retrieved from the database
and having changes in their properties, inserted/deleted into/from EDM collection
objects
• Has methods that allow
• To formulate LINQ CRUD queries against the EFModel and return one or more entity object(s)
• The EF API will transform all the LINQ to SQL statements to be executed by the
underlying database
• To Save changes to the underlying database via EF API, which reads tracking status set by the
context class via EF-API on entities(Insert, update, delete), transform them to SQL and apply
the changes to the Database
4- EF Design: EFBasics
1. What is Entity Framework? This code is useful with Code
• Context class that inherits from DbContext first to override default and annotation configurati
ons of the model class and to change the default m
• SchoolContext ctx; ctx.SaveChanges() apping to the database

EDM classes: collection of entities


2.
4- EF Design:
What is an Entity in Entity Framework?:
EFBasics
An Entity can include two types of properties: Scalar Properties and Navigation Properties.
Standard 0..1 <--------- * Student Context class:
public class Student
{
//scalar properties
public int StudentId { get; set; } public class Standard
public string StudentName { get; set; } {
public DateTime? DateOfBirth { get; set; } public int StandardId { get; set; }
public byte[] Photo { get; set; } public string StandardName { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; } //Collection Navigation Property
//Reference Navigation Property public virtual ICollection<Student> Students { get; set; }
public virtual Standard Standard { get; set; } }
//Foreign key Property: default convention
Standard 0..1 * Student

//public int StandardId { get; set; } //StandardStandardId


public int? StandardId { get; set; } //StandardStandardId
}
This code is useful with Code

4- EF Design: EFBasics
first to override default and annotation configurations
of the model class and to change the default mapping t
o the database
Default conventions:
2. What is an Entity in Entity Framework?: TableName= EntityName,
• Context Class: Mapping between entities and database table Attributes=Entity Property,
ForeignKey=NavPropertyName+Id,
Protected override void OnModelingCreating (ModelBuilder modelBuilder){ Ondelete is cascade by default,

VS 2019 Syntax

Child Entity

Parent Entity
EDM

Child-Parent
This code is useful with Code

4- EF Design: EFBasics
first to override default and annotation configurations
of the model class and to change the default mapping t
o the database

2. What is an Entity in Entity Framework?:


• Context Class: Mapping between entities and database table
The HasColumnName attribute is applied to a
VS 2019 Syntax property to specify the database column that the
property should map to when the entity's property
name and the database column name differ.

Syntax2

Child-Parent
.ToTable, .Property, .HasOne,… are Fluent APIs
4- EF Design: EFBasics
2. What is an Entity in Entity Framework?:
LINQ query example 1 recall
Category 1 …. * Student
Context class:

Get the list of students with the standardName

Navigation from Student to Standard using the Standard reference navigation property
4- EF Design: EFBasics
2. What is an Entity in Entity Framework?:
LINQ query example 2
Category 1 …. * Student
Context class:

Get all the available Standards to be displayed with a given student

public IList<StandardDTO> standards { get; set; }:added as a property to the StudentDTO


4- EF Design: EF Core
3. What is Entity Framework Core?

• Runs on Windows/Linux machines

• Runs on mobile device:


• Create a MobileApp (Xamarin.Forms, or net multi platform app UI - .net
MAUI-), add an EF core for Sqlite DB+Model+ContextClass+CRUD Views and
run it, android device (Linux OS) or IOS
4- EF Design: EF Core
4. Development Approaches with Entity Framework
• DB First

• Code First
4- EF Design: EF Core
4. Development Approaches with Entity Framework: DB First

• The DbContext class and all the mappings are created first by the EF API
• The DbContext class has a method called OnModelCreating that takes an instance of
ModelBuilder class as a parameter.
• This method contains a code describing the mapping between the EDM and the database, and, with
DBFirst, is useful only as documentation
• Each time the database is modified, the context collections, the EDM, and the mapping into
OnModelCreating method of the context class have to be regenerated by rerunning the scaffold
 Scaffold-DbContext
"Server=YourServerName;Database=SchoolDB;Trusted_Connection=True;MultipleActiveResultSets=t
rue; trustServerCertificate=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models –
Force

• Remark:
• With code first, the code in OnModelCreating is optional and is used by EF API, to override default and
annotation configurations of the model class, thus changing the default mapping to the database, add
unique Foreign constraint, custom query logic, such as advanced filtering, sorting, or joining operation

• If you want to manage database schema changes based on code into OnModelCreating, you should
consider using the Code-First approach
4- EF Design: EF Core
4. Development Approaches with Entity Framework: DB First
PRACTICE3 : DB First
a. Startup SQLServer 2014 and attach the schooldb database
b. Startup your vs2022 and create an MVC .net Core Web App
c. Go to Tools -> NuGet Package Manager -> Package Manager Console and:
1. Open the properties of the project and Adjust/check the .net core framework to version 6
2. Install-Package Microsoft.EntityFrameworkCore.SqlServer -version 7.0.2
3. install-package Microsoft.EntityframeworkCore.Tools -version 7.0.2
4. install-package Microsoft.EntityframeworkCore -version 7.0.2
5. install-package Microsoft.VisualStudio.Web.CodeGeneration.Design -version 6.0.12
6. install-package Newtonsoft.Json -version 13.0.2
7. Create your conceptual model:
 Scaffold-DbContext
"Server=YourServerName;Database=SchoolDB;Trusted_Connection=True;MultipleActiveResultSets=true;
trustServerCertificate=true" tMicrosoft.EntityFrameworkCore.SqlServer -OutputDir DBEFModels –Force
 Check the context class and the OnModelCreating method into the context class
 Note that, in DBFirst, in general the purpose of this method is to list the mapping between the
entities and the MSSQL tables
4- EF Design: EF Core
4. Development Approaches with Entity Framework: DB First
PRACTICE3 : DB First
After scaffolding you should obtain the following

In the application add the following folders that contain the StudentDTO and the StandardDTO Described in the next slides
APL
4- EF Design: EF Core
Practice3 Continued

Try the queries in slide 50 and 51.


Write in your controller action methods similar to:

Public async Task<TypeToBeReturned> ActionMethodName {


await …..
}
Examples:
Public async Task<StudenDTO> ActionMethodName {
await …..
}

Public async Task<IList<StudenDTO>> GetStudents {


await …..
}
Practice3 Continued
4- EF Design: EF Core
For example slide 50:
Write in your controller an action method similar to:
public class StandardDTO
{
[Key]
public int StandardId { get; set; }
public string? StandardName { get; set; }
}
public class StudentDTO
{
[Key]
public int StudentId { get; set; }
public string? StudentName { get; set; }
public StandardDTO? standard { get; set; }
public int StandardId { get; set; }
}
Try the same slide 51
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
Code First
4.
4- EF Design: EF Core
Development Approaches with Entity Framework: Code First
1. Once the context class and the entities are ready, we have to apply a migration and an update
add-migration MyFirstMigration -Context MyDataBaseContext
Update-Database -Context MyDataBaseContext
2. A ContextModelSnapshot is created first, after the first migration, to map domain classes to
database tables by using the BuildModel() method and the Modelbuider class, and this model is used
to create the database after the command Update-Database
3. EF Core API will create the primary key column for the property named Id or <Entity Class Name>Id (case
insensitive)
For example, EF Core API will create a column as PrimaryKey in the Students table if the Student
class includes a property named id, ID, iD, Id, studentid, StudentId,STUDENTID, or sTUdentID
4. As per the foreign key convention, EF Core API will create a foreign key column for
each reference navigation property, in a child entity association with one of the following naming
patterns.
• <Reference Navigation Property Name>Id
• <Reference Navigation Property Name><Principal Primary Key Property Name>
5. After that, every change in domain classes requires a migration to update the database
add-migration MyMigration -Context MyDataBaseContext
Update-Database -Context MyDataBaseContext

6. When again migrating Domain classes to database, EF Core API will adjust the tables with the modifications
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
• Code First Approach: Category 1 …. * Student Category  Student

public class Student (Parent  Child)


StudentId is primary key in Student
{
public int StudentId//Id//ID { get; set; } Stdid Catid
public string StudentName { get; set; } 10 1 public class Category
10 2 {
public DateTime? DateOfBirth { get; set; }
public byte[] Photo { get; set; } public int CagteoryId//Id//ID { get; set; }
public decimal Height { get; set; } public string CategoryName { get; set; }
public float Weight { get; set; } //Collection Navigation Property
public virtual ICollection<Student> Students { get; set; }
//Reference Navigation Property }
public virtual Category Category { get; set; }
//used as a Foreign key: must follow the convention
public int CategoryId { get; set; } //CategoryCategoryId
}

add-migration MyFirstMigration -Context MyDataBaseContext


Update-Database -Context MyDataBaseContext
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
• Code First Approach: Category 0..1 …. * Student

public class Student


{
public int StudentId { get; set; }
public string StudentName { get; set; } public class Category
public DateTime? DateOfBirth { get; set; } {
public byte[] Photo { get; set; } public int CagteoryId { get; set; }
public decimal Height { get; set; } public string CategoryName { get; set; }
public float Weight { get; set; } //Collection Navigation Property
public virtual ICollection<Student> Students { get; set; }
//Reference Navigation Property }
public virtual Category Category { get; set; }
public int? CategoryId { get; set; } //CategoryCategoryId
}

add-migration MyFirstMigration -Context MyDataBaseContext


Update-Database -Context MyDataBaseContext
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
Remark: Student 1 …. 0..1 StudentAddress: Make Unique Key NB: Constraints are defined into the child tables
PK

4-10 is not
5 null Allowed.
Std 10 has
Now 2 adr 1 and 4
3-40 is not
Allowed.(PK)
1 0..1 10 ad1
10 ad2
In Two: Not allowed
Address unique key:10 ad1,20 ad1 is not allowed

StudentID as primary key in both tables Student and StudentAddress

Into StdAdr Or adopt Three


4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
Remark: Student 1 …. 0..1 StudentAddress (Parent ---- Child)
StudentAddressId as PK, StudentId Not null
Std Unique
Both are set in
Into OnModelCreating() of the contextClass StudentAddress
StudentAddressId StudentId
1
=>PK
10
4- EF Design: EF Core Both are set in
StudentAddress
1 20
Part A- : Student 1 <----- 0..1 StudentAddress : Note slide 64, second case

StudentAddressId StudentId
1 10
1 =>unique
2 10

2
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
Remark: Student 1 …. 0..1 StudentAddress (Parent ---- Child) : Use the convention of one Key

Unique Key
Not null

Address Unique Key


4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
Remark: Student 1 …. 0..1 StudentAddress (Parent ---- Child) : Use the convention of one Key

Address

Navigations refer to the parent

1- Note the navigations


2- Note that the foreign key is primary key in StudentAddress
4- EF Design: EF Core
4. Development Approaches with Entity Framework: Code First
Student 1 …. 0..1 StudentAddress (Parent ---- Child) : The DBContext class

public class Practice4MethodFirstSchoolDBContext: DbContext


{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentAddress> StudentAddresss { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{ optionsBuilder.UseSqlServer(@"Server=Home;Database=Practice4MethodFirstSchoolDB;Trusted_Conne
ction=True; trustServerCertificate=true");
}
}
4- EF Design: EF Core
https://www.entityframeworktutorial.net/efcore/entity-framework-core.aspx
4. Development Approaches with Entity Framework: Code First
 Practice4: Code First. Use the same project created in practice3
• Given the classes:
• Student2(int StudentId, string Name) 0..1 ----- * Course2(int CourseId, string CourseName)
• Create within your application the folder named CodeFirstModel as depicted:
• Create the classes Student2 and Course2, their
navigations (Ref S62-63) and the context class
School2Context
• Add a migration for your Model
• Update your Database
• Open and Check the class created under the migration
folder:
• What is the purpose of this class ?
• Confirm that the database school2 is created in MSSQL
and verify the relationships by rightCliking Course2,
Design, rightckick anywhere into your empty screen,
Click Relationships, check the PK, FK and allow null
For StudentId
4- EF Design: EF Core

For security, Configure this in Program.cs and appsettings.json


CourseEntity

4- EF Design: EF Core CourseId StudentId

Student 0..1 <----- * Course


1 10 1 10
1 20 2 10
1 30 3 10

Course: StudentId foreign Key


4- EF Design: EF Core
Student 0..1 <----- * Course CourseEntity
CourseId StudentId
1 10 1 10
1 20 2 10
1 30 3 10

The foreign key is indexed for performance optimization


4- EF Design: EF Core
4. First Application (Continued)
Practice4 Continued: (do not forget to add add-migration and then update-database)
A-
Adjust practice 3, add StudentAdress class:
Student2 1 <------ 0..1 StudentAddress2(int StudentAddressId , Address, City)
Verify: StudentId is a unique index into the child table
Remark: Note slide 72
Add migration2 and note the content of the migration class

B-
Student2 0..1 <------ 0..1 StudentAddress2(int StudentAddressId , Address, City)
Consider StudentAddress is the child

C-
Addition practice: adjust the code for practice 3 for:
Student2(int StudentId, string Name) * ----- * Course2(int CourseId, string CourseName)

https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-cor
e.aspx
4- EF Design: EF Core
Student2(int StudentId, string Name) * ----- * Course2(int CourseId, string CourseName) Continued : Database

Propose a method for A Student may not have a Course,


Part D- : Student 0.. * ---- 0..* Course A Course may not have a Student
4- EF Design: EF Core
Return to https://www.entityframeworktutorial.net/entityframework6/introduction.aspx
1. Saving Data + Apply to your DBSchool model (Demo)
2. Querying in Entity Framework Context class:
• LINQ-to-Entities queries operate on the entity set (DbSet type properties) to access the data from the
underlying database.
• The DbSet class is derived from IQuerayable. So, we can use LINQ for querying against DbSet (S78, 81, 82)
• EF API executes this SQL query to the underlying database
3. Linq-to-Entities Query: DONE in Demo
4. Eager/lazy Loading in Entity Framework
5. Practice5: All student_Course_Teacher, StandardTeachers in Demo, 1...* standardTeachets into
DTO objects
6. Transaction in Entity Framework(DbContext.Database.BeginTransaction())
• using (IDbContextTransaction transaction = ctx0.Database.BeginTransaction())
7. Handling Concurency Conflict (Not required: read only)
• Optimistic concurrency : If you don't enable the detection of such conflicts, whoever updates the database last
overwrites the other user's changes.
1. https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/concurrency?view=aspnetcore-7.0
2. https://learn.microsoft.com/en-us/ef/core/saving/concurrency?tabs=data-annotations
3. https://learn.microsoft.com/en-us/ef/core/saving/concurrency?tabs=data-annotations#resolving-concurrenc
4- EF Design: EF Core
4. Development Approaches with Entity Framework: DB First

In the application add the following folders that contain the StudentDTO and the StandardDTO Described in the next slides
APL
4- EF Design: EF Core - More on Transaction
• By default, if the database provider supports transactions, all
changes in a single call to SaveChanges are applied in a transaction.

• If any of the changes fail, then the transaction is rolled back and
none of the changes are applied to the database.

• This means that SaveChanges is guaranteed to either


completely succeed, or leave the database unmodified if an error
occurs.

• For most applications, this default behavior is sufficient. You should


only manually control transactions if your application requirements
deem it necessary as shown previously
5- More on LINQ query
• https://www.tutorialsteacher.com/linq/linq-tutorials

• Extension Methods:
• https://www.geeksforgeeks.org/extension-method-in-c-sharp/
• Any data structure that implements IQueryable or IEnumerable,
can benefit from the static extension class methods defined into
the LINQ API (S81, 82)

• Show how DbSet implements IQueryable

• Query Syntax starts with from clause and must end with
Select or GroupBy clause.
5- More on LINQ query
• https://www.tutorialsteacher.com/linq/linq-tutorials

• Besides the advantages listed in the section “Why LINQ”:


https://www.tutorialsteacher.com/linq/why-linq , it
provides safety against injection attack
• https://portswigger.net/web-security/sql-injection#subverting
-application-logic

TextBox: Bill’ --
5- More on LINQ query
• This case could not occur with LINQ:
EF6DBFIRST
EF6DBFIRST
6- IOC & Dependency Injection

1. Coupling Classes

2. Inversion Of Control

3. Dependency Injection
6- IOC & Dependency Injection
1- Coupling Classes
• By applying the Dependency Inversion Principles (DIP) you will end by loosely coupled class
• Highly coupled classes
• When one class, c1 (dependent), depends on another, c2 (dependency) that means c1 uses an instance of
c2 and that c1 could not be used unless c2’s design is completed.
• There exists more then one class like c1 that depends on c2
• Changes in c2 name will lead to errors when using dependent classes

• The dependency class could be made loosely coupled

• Loosely coupled means changes in the loosely coupled class should not force other classes to change, so
the dependent classes can become maintainable, extendable and testable

• Maintainable: you can change the name of the loosely coupled (dependency) class implementing different
method coding without worrying about other classes depending on it

• Testable : classes depending on loosely coupled classes can be tested as a unit because a mock class
with name1 can be used instead of a concrete one with name2 without any modification in the dependent
class

• Extendable : if your class is loosely coupled, then any other class that extends it can be easily loosely
6- IOC & Dependency Injection
1-Coupling Classes/Inversion Of Control (IOC)

• Target: it is used to invert different kinds of controls in object-oriented


design to achieve loose coupling between classes

• To explain this:
• Suppose you drive a car to your work place. This means you control the car. The IoC
principle suggests to invert the control, meaning that instead of driving the car yourself,
you hire a person that will drive the car.
6- IOC & Dependency Injection
1-Coupling Classes/DI principle
• The DI Principle definition (DIP)

1. Dependency classes (Classes that other classes depend on) should


implement abstraction interfaces

2. Apply Dependency Injection (DI)

• DI is a design pattern used to automate and implement Inversion of Control (IoC)


• Uses an IoC container to register the dependency classes to be injected
6- IOC & Dependency Injection
3- Dependency Injection/IoC
• Dependency Injection (DI) is a design pattern used to Define and implement IoC (2 nd DIP)
• We are going to implement Dependency Injection to move the dependency object creation completely
out of the BusinessLogic class.
• Direct consequence: change the name of the dependency class (service) without any change in the dependent class
(client)

Client class: Controller or API


Service: Repository
-----------------------
Client class: Repository
Service: dbContextClass

• The injector class creates an instance of the service class, and injects that object into a client class so
the class does not need to instantiate the service class
• => The injector perform the job of instantiation instead of the Client class, thus the Injector implements the IoC
• The injection of the service class into the client class can be via the client Constructor or via a client
Property injection
6- IOC & Dependency Injection
3- Dependency Injection

• Dependency Injection (DI) is a design pattern used to implement IoC

Service1
Service2
=> Service3

IService
=> (First DIP)

• In this case an instance of the CustDataAccess class needs to be injected into the
CustomerBusinessLogic class by using an IoC injector class as prescribed before.
• For different implementation, we need to change the service name three times and use three injectors
each one is for each class
• If the Services have the same signature (methods and params) => IService
6- IOC & Dependency Injection
3- Dependency Injection
• Dependency Injection (DI) is a design pattern used to implement IoC
• Conclusion

• Designing an injector class is someway cumbersome because we have to create multiple


injectors for multiple dependency classes

• One way to auto inject different versions of a dependency service class is by using the
IoC Container framework

• Here the IoC Container helps us


• An interface with its required class is registered with the IoC container (IService Sv1 or Sv2 or
Sv3)
• Every time this interface is encountered in the constructor of other classes, the DI injects
automatically an instance of the dependency class registered with the IoC container
• For different implementation we only need to change the service name into the IoC container
6- IOC & Dependency Injection
3- Dependency Injection
Classic code without Dependency Injection
// Not following the Dependency Inversion Principle

public class SalaryCalculator //Dependency class


{
public float CalculateSalary(int hoursWorked, float hourlyRate) => hoursWorked * hourlyRate;
}

public class EmployeeDetails These classes do not follow the “ IoC and the
{ Dependency Inversion Principle” as the higher-
public int HoursWorked { get; set; } level class EmployeeDetails is directly depending
public int HourlyRate { get; set; } upon the lower level SalaryCalculator class
public float GetSalary()
{
var salaryCalculator = new SalaryCalculator();
return salaryCalculator.CalculateSalary(HoursWorked, HourlyRate);
}
}
6- IOC & Dependency Injection
3- Dependency Injection
Same code with Dependency Injection

Apply DIP: Abstraction, DI IoC:

public interface ISalaryCalculator


{
float CalculateSalary(int hoursWorked, float hourlyRate);
}

public class SalaryCalculatorModified : ISalaryCalculator


{
public float CalculateSalary(int hoursWorked, float hourlyRate)=> hoursWorked * hourlyRate;
}
6- IOC & Dependency Injection
3- Dependency Injection
Same code with Dependency Injection
public class EmployeeDetailsModified //Hosting Class
{
private readonly ISalaryCalculator _salaryCalculator;
public int HoursWorked { get; set; }
public int HourlyRate { get; set; }
//Apply DI/IoC
public EmployeeDetailsModified(ISalaryCalculator salaryCalculator)
{
_salaryCalculator = salaryCalculator;
}
public float GetSalary()
{
return _salaryCalculator.CalculateSalary(HoursWorked, HourlyRate);
}
}
6- IOC & Dependency Injection
3- Dependency Injection
public class Client //Hosting Class
Another Example {
private Service _service;
public class Service
{ public Client()
public void Serve() {
{ this._service = new Service();
Console.WriteLine("Service Called"); }

//To Do: Some Stuff public void Start()


} {
} Console.WriteLine("Service Started");
this._service.Serve();
Client class has a dependency on the Service class
//To Do: Some Stuff
}
}
6- IOC & Dependency Injection
3- Dependency Injection
public class Client //Hosting Class
Apply DIP: Abstraction, DI IoC: {
public interface IService private IService _service;
{
void Serve(); //Apply DI IoC
} public Client(IService service)
{
public class Service : IService this._service = service;
{ }
public void Serve()
{ public void Start()
Console.WriteLine("Service Called"); {
Console.WriteLine("Service Started");
//To Do: Some Stuff this._service.Serve();
}
} //To Do: Some Stuff
}
}
6- IOC & Dependency Injection
3- Dependency Injection
Service classes: public interface IMailService
{
public interface IMobileServive void Execute();
{ }
void Execute();
} public class EmailService : IMailService
public class SMSService : IMobileServive {
{ public void Execute()
public void Execute() {
{ Console.WriteLine("Email service Executing.");
Console.WriteLine("SMS service executing."); }
} }
}
6- IOC & Dependency Injection
3- Dependency Injection
Client Class: Apply DIP: Abstraction, DI IoC:
public void SendNotification()
---------------- {
public class NotificationSender //Hosting Class ObjMobileSerivce.Execute();
{ ObjMailService.Execute();
private IMobileServive ObjMobileSerivce = null; }
private IMailService ObjMailService = null; }

//injection through constructor


public NotificationSender(IMobileServive tmpService,
IMailService tmpMailService)
{
ObjMobileSerivce = tmpService;
ObjMailService=tmpMailService;
}
6- IOC & Dependency Injection
3- Dependency Injection
IOC containers (A.K.A DI containers)
• Is a framework for implementing automatic dependency injection

• All the DI IoC containers must provide easy support for the following DI lifecycle:

• Register: The container must know which dependency to instantiate when it encounters a
particular type or Interface.

• Resolve:
• The di Resolver will automatically creates instances of the injected service classes when needed by the
hosting classes and inject them into the hosting class constructor

• Dispose: The container must manage the lifetime of the dependency objects.
6- IOC & Dependency Injection
3- IoC container (A.K.A DI containers)
• Application
• Register: Services required to startup the application are registered into the
IoC DI container that makes configured services available throughout an app.
• In MVC CORE, a service class can be DBContext class, customer service class like,
Repository class, MailService, etc, or .net framework classes (RazorPages,
ControllerWithView,..)

• Resolve: The DI/IoC container automatically creates an instances of the


registered classes when needed by the hosting class
• The Hosting class can be any class where the dependency class is injected e.g:
• The controller/WEB API (where we can inject the Repository) or the Repository (where we can
inject the context)

• Manages/Dispose object life-time (Later in upcoming slides)


6- IOC & Dependency Injection
3- Dependency Injection
Built in dependency injection with .net6-7 Core VS 2022
• WebApplicationBuilder Class
• A builder for web applications and services.
• ASP.NET Core includes dependency injection (DI) that makes configured services
available throughout an app. Services are added to the DI container with
WebApplicationBuilder: builder.Services.Add(…)
Register:
builder.services.AddSingleton<IUserService,
UserService>();

----- Injection into an MVC controller or into a web api


controller ---------
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
----- call a method -------------
_userService.SendMail(Data)
6- IOC & Dependency Injection
3- Dependency Injection
Service lifetime

• Singleton, services.AddSingleton<Interface, class>(), created once for the lifetime of


the application
• One and only one instance of class is created at the startup of the controller
• That single instance is used by all http requests throughout the controller’s application
• Scoped, services.AddScoped<Interface, class>(), created once per request
• We get the same instance within the same scope of a given http request (e.g.:Contoller
action+rendered view ARE within the same http scope), but different instance across different
http post request throughout the controller’s application
• Transient, services.AddTransient<Interface, class>(), the service is created each time
it is requested
• A new instance is provided every time an instance is requested whether it is in the scope of
the same http request or across different request of action methods across the same
controller’s application
6- IOC & Dependency Injection
3- Dependency Injection
EF core DbContext with dependency injection
Into Program.cs:
---------------
builder.Services.AddDbContext<SchoolDbContext>(options =>

options.UseSqlServer( builder.Configuration.GetConnectionString(
"SchoolDBConnectionString")));
Into the ShoolDBController::

public class SchoolDbController : DbContext


{
private SchoolDBContext _ctx;
public SchoolDbController(SchoolDBContext ctx)
{
_ctx=ctx;
}
}
7- Delegates

Delegates in C#
7- Delegates
• C# delegates are similar to pointers to functions and presents
references to methods with a particular parameter list and return
type

• A function can have one or more parameters of different data types

• Delegates can be passed as parameters


7- Delegates
Instantiating delegates
public static int AddNum(int p) {
// delegate declaration
num += p;
public delegate int NumberChanger(int n);
return num;
}
static int num = 10;
public static int MultNum(int q) {
//Registering methods with the delegate num *= q;
NumberChanger nc1 = new NumberChanger(AddNum); return num;
NumberChanger nc2 = new NumberChanger(MultNum); }

int a=nc1(25); //35


Console.WriteLine("Value of Num: {0}", a);
int b=nc2(5); //50
Console.WriteLine("Value of Num: {0}", b);
7- Delegates
Multicasting of a Delegate
static int num = 10;
public delegate int NumberChanger(int n);
NumberChanger nc; public static int AddNum(int p) {
num += p;
//Registering methods with the delegate return num;
NumberChanger nc1 = new NumberChanger(AddNum); }
NumberChanger nc2 = new NumberChanger(MultNum);

nc = nc1;
nc += nc2;

//calling multicast
public static int MultNum(int q) {
int r=nc(5); 15, 15*5
num *= q;
Console.WriteLine("Value of Num: {0}", r);
return num;
Console.ReadKey();
}

Value of Num: 75
7- Delegates
Passing delegates as params
// this method takes the delegate as parameter and uses it to
// call the methods as required
static FileStream fs; public static void sendString(printString ps) {
static StreamWriter sw; ps("Hello World");
}
// delegate declaration
public delegate void printString(string s);

public static void WriteToScreen(string str) {


Console.WriteLine("The String is: {0}", str);
}
static void Main(string[] args) {
//this method prints to a file //Registering methods with the delegate
public static void WriteToFile(string s) { printString ps1 = new printString(WriteToScreen);
fs = new FileStream("c:\\message.txt", printString ps2 = new printString(WriteToFile);
FileMode.Append, FileAccess.Write); sendString(ps1);
sw = new StreamWriter(fs); sendString(ps2);
sw.WriteLine(s); Console.ReadKey();
sw.Flush(); }
sw.Close();
fs.Close();
7- Delegates
Passing Delegates between classes
Library
public delegate double calculate(double p1, double p2);
class Class1 Your program Code
{
//You must specify the Public access modifier [class Class2]
//note the delegate used as a parameter and used inside {
//Class1.f1 to call Class2.f1 and Class3.f1 //must have the same signature as the delegate
public static double f1(double a, double b)
public double f1(double a, int b, calculate dl) {
{ return a * b;
double d = dl(a, b); }
return a + b + d; a+b+a*b or a+b+a/b }
} [class Class3]
} {
public static double f1(double a, double b)
Your program Code: Import the library
{
calculate dl1=new calculate(Class2.f1);
return a / b;
calculate dl2=new calculate(Class3.f1);
}
Class1 cl1=new Class1();
}
double r1=cl1.f1(5.5,6,dl1); double r2=cl1.f1(15.5,9,dl2)
7- Delegates
Passing Delegates between classes
Library
public delegate void calculate();
class Reactor Your program Code
{
Calculate Cl; class ReactorListener
int Temp=0; {
public void SetDelegate(calculate dl) {Cl=dl} //must have the same signature as the delegate
public void ChekTemperature() public static void TemperatureHandler ()
{ {
while (Temp <=800) { Temp=GetTempFromSensor() }; // turn on heater or turn off reactor or
Cl(); flood the reactor with more water
} }
public int GetTempFromSensor() { …………….. Return temp}; }
}
Your program Code: Import the library
calculate dl1=new calculate(ReactorListener.TemperatureHandler);
Reactor R=new Reactor();
R.SetDelagate(dl1); R.ChekTemperature()
8- Asynchronous Programming
• Asynchronous Webservice.
• Up until now, we have called methods synchronously

• That means unless the web method is not finished, our form /View/Calling method processing is
blocked

• At times you may need to call web methods in asynchronous fashion

• For example for a book title you call many Web API methods that return the cost of the title by
individual suppliers

• If you call the web methods in synchronous fashion, the total time taken will be the summation of the
processing time taken by the individual web methods

• On the other hand, if you call the web methods in asynchronous fashion, the time taken will be reduced
to the processing time taken by the lengthiest web method
8- Asynchronous Programming
• Asynchronous Call.
8- Asynchronous Programming
• Asynchronous programming is a means of parallel programming in which a unit of
work runs separately from the main application thread and notifies the calling thread of
its completion, failure or progress

• The main benefits of asynchronous programming using async / await include the
following: Increase the performance (Thread pool) and responsiveness (Parallel
execution) of your application, particularly when you have long-running operations
that do not require to block the execution
8- Asynchronous Programming
• 3 patterns for asynchronous programming

• Asynchronous Programming Model (APM)

• Event-based Asynchronous Pattern (EAP)

• Task-based Asynchronous Pattern (TAP).


8- Asynchronous Programming
• Synchronous Programming

string url = "http://www.elnashra.com";


WebClient client = new WebClient();
string content = client.DownloadString(url);
Console.WriteLine(content.Substring(0, 9000));
for (int i = 0; i <= 100; i++)
Console.WriteLine("HiHi " + i.ToString().Trim());
8- Asynchronous Programming
• Asynchronous Programming Model (APM)
String url = "http://www.elnashra.com";
WebRequest request = WebRequest.Create(url);
IAsyncResult result = request.BeginGetResponse(ReadResponse, null);
for (int i=0; i <= 100;i++)
Console.WriteLine("HiHi " + i.ToString().Trim());

void ReadResponse(IAsyncResult ar)


{
WebResponse response = request.EndGetResponse(ar);
Stream stream = response.GetResponseStream();
var reader = new StreamReader(stream);
string content = reader.ReadToEnd();
Console.WriteLine(content.Substring(0, 9000));
Console.WriteLine()
}
8- Asynchronous Programming
• Event-based Asynchronous Pattern (EAP)

String url = "http://www.elnashra.com";


WebClient client = new WebClient();
client.DownloadStringCompleted += //Register the Event in
WebClient Client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(url)); // Method in WebClient
for (int i=0; i <= 100;i++) //that will raise the event
Console.WriteLine("Hi " + i.ToString().Trim());}

private void Client_DownloadStringCompleted(object sender,


DownloadStringCompletedEventArgs e)
{
Console.WriteLine(e.Result.Substring(0, 9000))
}
8- Asynchronous Programming
• Task-based Asynchronous Pattern (TAP)
private void Form1_Load(object sender, EventArgs e)
{
Task<int> d= TaskBasedAsyncPatternAsync();
for (int i = 0; i <= 1000; i++)
Console.WriteLine("Hi " + i.ToString().Trim());
}
private static async Task<int> TaskBasedAsyncPatternAsync()
{
//await Task.Delay(10000);
Console.WriteLine("InTask"); //Will be displayed first, then the 1000 hi then the web result
String url = "http://www.elnashra.com";
WebClient client = new WebClient();
string content = await client.DownloadStringTaskAsync(url); //hold the exec
till completed
Console.WriteLine(content.Substring(0, 900));
//Console.WriteLine();
return 1;
}
8- Asynchronous Programming
• Example 2:

Console.WriteLine("hi before");
Task<int> d = Hi_async(); //Note the return type of an async method
for (int i = 0; i <= 1000; i++)
label1.Text = "Hi " + i.ToString().Trim();

private static async Task<int> Hi_async()


{
Console.WriteLine("hi from inside before");
//Method supended to 10 seconds. control returned to program )(For loop)
await Task.Delay(10000);
Console.WriteLine("hi from inside after ");
return 1;
}
8- Asynchronous Programming
1. You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous
programming

2. A request starts in the same way by fetching a thread from the thread pool.

3. But now we have marked our method query as async.

4. It instructs the .NET runtime that we expect the method call to take a while to complete.

5. When await, the calling program blocks, the calling thread will be freed ASAP, returned to the calling program to continue
the work if exists, then put back in the thread pool.

6. Another thread from the pool continue the await execution to the END. Selecting thread from the pool is very fast because
it is in a waiting state not blocked one, thus does not involve a context switching creation

7. Now we only have threads allocated that have work to do.

8. After await done, we are not guaranteed to get the same thread back: When the asynchronous operation is completed, a
callback is scheduled to execute the code that follows the await keyword (the continuation). This callback may run on a
thread from a thread pool, not necessarily the original calling thread used in step 6
Use delegate for interThread
Communication
• private delegate void delegateName (Type data);
public static async Task SendPdfWithMails ()
{
• Code: delegateName dl = new delegateName(mailStatus);
int count = 0;
public static async void callMethod() { await Task.Run(() =>
{
Task<int> d = SendPdfWithMails(); for (int i = 0; i < 100; i++)
………… {
//Proccess to send mail, print pdf,…
} count += 1;
// delegate to add to a collection the status of each sent
//mail
private static void mailSatus(Type data) { dl(DATA);
//Task.Delay(200).Wait();
if (data !=null) {… }; }
});
} }
Remark:
it is a good practice to always write Async Simulate Async sending mails
method, so we can profit when needed from
the Async advantages
8- Asynchronous Programming
Remark: sometimes we need to block an Asyn call:
public static async void callMethod() {
int count =await SendPdfWithMails(); //Option 1 the method is blocked here, continue same TH
//or // until a running code in encountered with await
//Task<int> task=SendPdfWithMails(); //Option 2
//int count = await task; //the method is blocked here, continue same TH
Console.WriteLine("count=" + count); // until a running code in encountered with await
=====================
public static async Task<int> SendPdfWithMails ()
{
int count = 0;
await Task.Run(() => // Pick up other thread than the calling method
{
for (int i = 0; i < 100; i++)
{
//Proccess to send mail
count += 1;
Task.Delay(200).Wait(); //simulate a long work to make sure that we can suspend this code
}
});
return count;
}

You might also like