0% found this document useful (0 votes)
1 views98 pages

Net Core MVC

.Net Core is an open-source, cross-platform development platform by Microsoft designed for building high-performance applications. It offers advantages over the traditional .Net framework, such as modularity, improved performance, and long-term support, making it suitable for various application types including web, mobile, and cloud applications. The document also outlines the steps for creating an ASP.NET Core MVC project, including setting up models, controllers, and using Entity Framework for database interactions.

Uploaded by

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

Net Core MVC

.Net Core is an open-source, cross-platform development platform by Microsoft designed for building high-performance applications. It offers advantages over the traditional .Net framework, such as modularity, improved performance, and long-term support, making it suitable for various application types including web, mobile, and cloud applications. The document also outlines the steps for creating an ASP.NET Core MVC project, including setting up models, controllers, and using Entity Framework for database interactions.

Uploaded by

Bob Marley
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

.

Net Core MVC


22/08/2024
What is .Net Core?
 .Net core is a new session of the .net framework or free, open-
source, general-purpose, development platform maintained by
Microsoft. It was designed to build modern high performance and
scalable applications that could run on windows, macOS and Linux.
 .Net core aimed to prove a unified platform for developing various
application including web application desktop applications,
microservices and more.
 .Net core is written from scratch to e a modular, lightweight, fast and
cross-platform. It includes the core features required to run a basic
.net core application other features are provided as NuGet packages
which you can add to your application as needed.
 In this way, the .Net core application speeds up performance reduce
the memory foot print and becomes easy to maintain.
Why .Net core over .Net framework?
 There are some limitations to the .Net framework. For example, it
only runs on the windows platform also, you need to use different
.Net APIs for different windows devices such as windows desktop,
windows store, windows phone and web applications.
 The following are some of the reasons why you might choose .net
core over the .net framework for application development.
 Open source.
 Performance and moderization
 Long term support
 Cross platform compatibility
What type of application can you develop with [Link] core?
 Web: [Link] core mvc, web API, razor pages and microservices.
 Mobile
 Console
 Desktop
 IOT
 ML
 Gaming Applications
 Cloud Applications
23/08/2024
 Create a project of [Link] core [mvc], project name as HRMProject.
 Folder structure of a project
 Connected service – azure , sql server connections will show here.
 Dependencies
 Analyzers – analyzing the code, we have default packages here
 Frameworks – we have 2 packages
 Packages – we need to install 4 packages for MVC, they are.
 [Link]
 [Link]
 [Link]
 [Link] – view support
 Install above NuGet packages from tools option.
Properties folder
 Launchsettings – by default it will be development.
 [Link] folder – it has some static files.
 Controllers
 Models
 Views – we will refer the controller name
 Shared folder – [Link] is a main page
 [Link] - configure a connection string.
 [Link] file -

 What is controller?

A controller is a special class in the [Link] core application with .cs


extension. The controller class must be inherited from the controller
base class. In [Link] core mvc the controller base class provides many
properties, methods and features that handles HTTP Request and
produces response in our application. It provides action result methods
model state management, validations, tempdata, view bag, viewdata
etc.
Controller Characteristics / Features :

 Inherited from controller base class.


 Contains action methods that response for Http Request.
 Interact with models to retrieve or update the data and deletion
also.
 Selects view to render html or return data directly.

Controller Concepts :
 MVC Controller – Empty – it cretas an empty controller.
 MVC Controller with read/write – this template will create the
controller with 5 action methods to create, to read, to update, to
delete and list entities.
 MVC Controller with views using entity framework – this template will
create and mvc controller with actions and razor views to create, to
read, to update, to delete and list entities using entity framework core.

Models in [Link] core mvc: Model is a class with .cs extension


that defines the properties and behavior of the data entities in your
application. Those are simple classes that represents the objects in
your application.

Use cases of Models:

 Data representation – model represents the data in memory used by


your application. They typically map to database tables or external
data sources.
 Business logic: Models may contain business rules and validation
logic ensuring data integrity and consistency.
 Communication: Models facilitate communication between different
parts of the application such as controller views and data access
layer.
What is View?
 In mvc, design pattern the view is a component that contains logic to
represent the data as a user interface with which the end user can
interact that means the view is used to render the UI. The extension
for view is. cshtml
Types of view:
 Razor views
 Partial views
 View component
 Layout views

Razor Views: These are most common views in mvc razor views using a
razor syntax means combination of html and c#.

Partial Views: Those are reusable views components that can be


embedded with other views. They are used for rendering common
elements like header, footer and navigation bars.
View component: Those are similar to partial views but more powerful.
They can encapsule the view and the logic.
Layout View: Those provides a consistent look and feel across multiple
views in your application. They define a common template for your pages
including header, footer and navigation bars.

Task:
 Take array of number from 1-20 then print, write a print method and
call in main method, then apply the following methods.
Prime number();
Even number();
Odd number();
Reverse number();
====================================================
24/08/2024
 Create a new project of [Link] core[mvc] and name it as
“HRMProject”.
 Right click on model’s folder and add class and name it has
“Products.”, define properties

[Key]
public Guid ProductId {get; set;}
public string ProductName {get; set;} = [Link];
public decimal Price {get; set;}
Short cut for creating property is PROP

 Right click on controller and create controller and select template as


MVC controller read/write actions name it as Products.
 Create a new folder for DbContext name as HRMDbContext, right
click on HRMDbContext add class with HRMDatabse.
 In HRMDatabase create constructor using shortcur is crot.
 public HRMDatabase()
 Extend the class with DbContext.
public class HRMDatabase : DbContext
 Pass the params in the constructor like public
HRMDatabase(DbContextOptions<HRMDatabase>options):base(opti
ons)
{

}
 Create a Dbset .
public DbSet<Product> Products { get; set; }
in this, off brackets(<>) we are giving model name.
 Right click on controller and create controller and select template as
MVC controller read/write actions name as ProductsController, while
adding its showing error.
o To solve the above error we need to check the migration.
o Open tools, manage nuget, package manager console.
o Type add-migration productmigration
 Unable to create a 'DbContext' of type ''. The exception 'Unable to
resolve service for type
'[Link]`1[HRMProject.H
[Link]]' while attempting to activate
'[Link]'.' was thrown while
attempting to create an instance. For the different patterns supported
at design time, see [Link]

 Create a connection string in [Link]


 "connectionStrings": {
 "con": "Data source=DESKTOP-78H5NU7; Database=HRM;
TrustServerCertificate=True; Integrated Security=True;"
 },
Here, con is a user defined.
Datasource means we should give the sql servername.
 After executing above code also its giving same error
Unable to create a 'DbContext' of type ''. The exception 'Unable to
resolve service for type
'[Link]`1[HRMProject.
[Link]]' while attempting to activate
'[Link]'.' was thrown while
attempting to create an instance. For the different patterns
supported at design time, see
[Link]
 In [Link] file, write below code.
// Add services to the container.
[Link]<HRMDatabase>(op =>
[Link]([Link]("con")));

 Again do migration.
 Update-database, it will update the schemas to the database.
 Right Create on a controller folder and add controller with entity .
 In program,cs change the controller name
pattern: "{controller=Products}/{action=Index}/{id?}");
25/08/2024

Entity Framework Code First Approach:


 In code first approach, is one of the three approaches to interact with
the database we need to use the code first approach when we don’t
have a existing database for our application. In this approach we start
developing our domain entities and context class first rather than
designing the database first, and then based on domain classes and
context classes the entity framework will create the database.
 This approach is best suited for applications that are highly domain
centric and we have domain model classes create first the developers
who will follow domain driven design (ddd principles) prefer to coding
with the domain classes first and then generate the database.
Steps for code first approach process:
[Link] a new project with [Link] Web App(Model-View-Controller) and
give project name.
[Link] 4 packages,
[Link]
[Link]
[Link]
[Link]
[Link] Models, right click on models folder and add class. In that class
add properties. PROP is the shortcut for the property.
Define Primary Key for required fields like [Key].
If we don’t want any primary key for object, we need to give the
[Keyless], it will not assign any key to the object.
[Link] the connection string in [Link] file.
[Link] DbContext Class, right click on project name and create one
folder, right click on created folder and add class.
[Link] constructor, ctor is the shortcut for constructor, implement the
DbContext to the class.
[Link] a table.
[Link] service using AddDbContext in the [Link] file.
[Link] Migration, select the tools, then NuGet Package Manager,
Package Manager console. Then console will open in the VS. write a
command for migration add-migration migrationname.
[Link] migration class will develop automatically.
[Link] need to update the database write a command in the console
update-database.
[Link] got to database and check the created database, in that check the
related table with columns and primary key.
[Link] Controller, Right click on controller folder and add controller with
MVC Controller with views, entityframework template. Then select Model
class and DbContext then click on add.
[Link] the controller name in [Link] file.
[Link], run the application, In that we can perform operations like create,
edit, delete, details and can check the inserted data in database also.
Note:
 In model if we add validations, it is server-side validations.
 In views if we add validations, it is client-side validations.
 Server-side validations play major role because it uses
authentication.
Task:
Do code first approach using relations with person and candidate tables,
take properties for person table as personid(primarykey), person name,
lastname, gender, age.
Take properties for candidate table as candidate id, address, education,
personid(Foreignkey).
26/08/2024

DbFirstApproach:
 Create a new project with [Link] Web App(Model-View-Controller)
and give project name as “DbFirstApproach”.
 Install 4 packages,
[Link]
[Link]
[Link]
[Link]
 Open package manager console, write a command like
PM> Scaffold-DbContext "Data Source = DESKTOP-78H5NU7;
Database = HRM; TrustServerCertificate = True; Integrated
Security = True" [Link] -
OutputDir Models
 It generates a [Link] page.
 Right click on controller folder and add controller with MVC Controller
with views, entityframework template. Then select Model class and
DbContext then click on add.
 In [Link] file, write the below code,
[Link]< HrmContext>();
//<HrmContext> is a generated Model file, give the classname.
And change the controller’s name.
 Run the application.
Note : when we give the GUID as a datatype, for adding next record we
need to select the new Id in SQL server. select NEWID()
Task:
[Link] is DBFirst Approach in EntityFramework core?
[Link] is CodeFirstApproach in EntityFramework Core?
[Link] between DBFirstApproach and CodeFirstApproach?
1. This approach is useful when working with existing databases or
complex database structures. It can also be suitable for large applications
that rely heavily on data. The database first approach can offer rapid
development and integration with minimal code writing. It can also make it
easier to map and create keys and relationships, since developers don't
need to write them in code. However, it might result in less control over the
generated code and could potentially lead to a less domain-driven
approach to application design.

2. The code first approach is a strategy in Entity Framework that allows


developers to create, maintain, and move databases and tables entirely
using code, The code first approach is useful when developers don't have a
database and want to start working on a new project. It also allows
developers to focus on the application's domain model and express
complex relationships using code. This approach is often preferred when
the database schema is unavailable. It's also suitable when developers
require flexibility to modify data models and is ideal for agile development.

27/08/2024
GitHub Process: push to origin branch(vs)
 Search Git in google.
 Select downloads of windows 64-bit.
 Installed and click next.
 Search download GitHub Desktop.
 Click on download for windows (64bit).
 After downloading, click on create free account?
 Enter your email, password, username.
 To fetch the updates from the main branch,
o First select current branch.
o Then choose branch to merge, select main branch.
o Click on “Create a merge commit”.
PostMan:
 APIs will be tested here when we use web API.
28/08/2024
LINQ: Linq means language integrated query. It is a powerful set of
technologies based on the integration of query capabilities directly into the
C# language. Linq queries are the first-class language constructrd in c# just
like classes, methods and events. Ling provides a consistent query
experience to query objects, relational database and XML files. Linq is a
uniform query syntax in c# to retrieve data from difference source and
formats. Linq query return results an object. It enables you to use object-
oriented approach on the result set.
It’s a case sensitive, same as c# language.
Program: example for LinqQuery syntax

Output:
Ball
James
Mohan

LINQ API in .Net:


 Namespace for Linq is [Link].
 We can write linq queries for the classes that mplemented
IQuerable<T> or INumerable<T> interfaces. The [Link]
namespace includes those intrfaces for linq queries. Linq
queries uses extension methods for classes that implemented I
Enumerable or IQuerable interfaces.
 Enumerable and Querable are 2 static classes that contains
extension methods to write Linq queries.
[Link] Class: The enumerable class includes extension methods
for the classes that implement IEnumerable<T> interface.
 IEnumerbale interface we can write linq queries to retrieve data from
the built-in collections.
[Link]: the queryable class includes extension methods for classes
that implement iqueryable<T> interface. The iqueyrable<T> interface is
used to provide querying capabilities against a specific data source where
the datatype of data is known.
Key Points:
 Use system. LINQ namespace, we can use linq.
 LINQ API includes 2 main statics classes Enumerable and
Queryable.
 The static Enumerable class includes extension methods for classes
that implements the IEnumerable<T> interface.
 IEnumerable<T> type of collections or in-memory collections like list,
dictionary, sorted list, queue, hash, hash set, linked list.
 The static queryable class includes extension methods for classes
that implemented the IQueryable<T> interface.
 There are 2 basic ways to write linq queries using IEumerable
collections or IQuerable data source.
[Link] syntax or query expression syntax
[Link] syntax or method extension syntax or fluent.
LINQ Query Syntax:
 Query syntax is similar to sql for the databases.
 It is defined within the C# code.

Syntax:

from <range variable> in <IEnumerable> or IQuery<T> Collection>


<Standard Query Operators> <Lambda expressions>
<select or groupBy operator> <result formation>

 The LINQ query syntax starts with from keyword and ends with
select keyword.

29/08/2024
Difference between IQueryable and IEnumerable:
[Link]<T>: It works with in-memory collection.
Example: Arrays
 It executes queries in-memory after all data is loaded.
 It is potentially less efficient with large data sets since it pulls all data
into memory before applying the query.
 The queries are applied to data already in-memory
IQueryable:
 It works with data sources that support querying such as databases.
 It constructs and executes query at data source and the query is
translated and optimized before execution.
 It is more efficient with large data sets and remote data sources as
queries are executed at the server or database level.
 It builds and expression tree that is translated into a query suitable for
the data source.
 Fetching the data is called querying, larger data is display here.
 When we have list, that time will use IEnumerable.
 While fetching data we can use IEnumerable when it has smaller data
and it filters the data also.
Example for IEnumerable:
List<Customer> customers = new List<Customer>
{
New customer {Id=1, Name=”Alice”, Age=30}
New customer{Id=2, Name=”Bob”,Age=25}
New customer{Id=3, Nmae=”Charlie”, Age=35}
};
//IEnumerable query: applies the filter in memory
IEnumerable<Customer> filteredCustomers =
[Link](c=>[Link]>=30); //Query is executed in-memory
Foreach(var customer in filteredCustomers)
{
[Link]($”{[Link]},{[Link]},{[Link]}”);
}

Class Customer
{
Public int Id {get; set;}
Public string Name {get; set;}
Public int Age {get; set;}
}

Task:
[Link] is difference between IEnumerable and IQueryable?
[Link] is IQueryable?
[Link] is IEnumerable?
[Link] is the impact of IQueryable on performance compare to
IEnumerable?
[Link] u explain when to use IQueryable and IEnumerable?

30/08/2024
Structure of LINQ Query Syntax:
Var result = from s in strList
where [Link](“tutorials”)
Select s;
result = Result variable
s = range variable
strList = sequence(IEnumerable or IQueryable)
from, select = standard query operators
Contains = conditional expression

Example:
Output: Java

LINQ Method Syntax:


 Method syntax is also known as fluent syntax and also known as
method expression.
 Method syntax uses extension methods includes in the enumerable
and query able static classes.
 The compiler converts query syntax into method syntax at compile
time.
Syntax:
Var result = [Link](s => [Link](“Tutorial));

Example:
Lambda Expression:
 The Lambda expression is a shorter way of representing anonymous
method using a special syntax.
 It is defined by =>
 Lambda expressions with multiple parameters.
 Lambda expressions with specified parameters type.
 Lambda expressions with specified multiple parameters.
 Lambda expressions without parameters.
 Lambda expressions with multiple statements in lambda expression
body.
 Declare local variable in lambda expression body.
 Assign lambda expression to delegate.
 Assign delegate with lambda expression assign to action delegate.
 Lambda expression in linq query.
Lambda Expression Syntax:
S => [Link] > 12 && [Link] < 20;
Here, s = parameter
=> - Lambda operator
[Link] > 12 && [Link] > 20 - body expression
[Link] Expression with multiple parameters

[Link] with specified parameter:


(Student s, int youngAge) => [Link] >= youngAge;

[Link] expression without parameter:


() => [Link]("Parameter less lambda expression")

[Link] statements in lambda expression body:


(s, youngAge) =>
{
[Link]("Lambda expression with multiple statements in the
body");
return [Link] >= youngAge;
}

[Link] Local variable in lambda expression body:


s =>
{
[Link] = 18;
[Link]("Lambda expression with multiple statements in the
body");
return [Link] >= youngAge;
}

[Link] Lambda Expression to delegate:


Func<Student, bool> isStudentTeenAger => [Link] > 12 && [Link] < 20;
Student std = new Student() { Age = 21 };
bool isTeam = isStudentTeenAger(std);

[Link] delegate with lambda expression:


Action<Student> PrintStudentDetail = s => [Link]("Name:
{0}, Age:{1}", [Link], [Link]);
Student std = new Student() { Name:"Bill", Age = 21};
printStudentDetail(std);

Task:
[Link] is query syntax?
[Link] is method syntax?
[Link] between query syntax and method syntax?
[Link] is lambda expression, how will you define?
[Link] many ways we are defining lambda expression can you define?

31/08/2024
Standard Query Operators:
 Standard query operators in LINQ are actually extension methods for
the I Enumerable<T> and IQueryable<T> types.
 They are defied in the [Link] and
[Link] classes.
 They are over 50 standard query operators available in Linq.
 That provide different functionality like sorting, filtering,
concatenation, grouping, aggregation etc.
[Link]:
standard operator
 Where
 Of type
[Link]:
Standard operators of Sorting
 OrderBy
 OrderByDescending
 ThenBy
 ThenByDescending
 Reverse
[Link]
Standard operators of Grouping
 GroupBy
 ToLookUp
[Link]
Standard operators of Join
 GroupJoin
 Join
[Link]
Standard operators of projection
 Select
 SelectMany
[Link]
Standard operators of aggregation
 Aggregate
 Average
 Count
 LongCount
 Max
 Min
 Sum
[Link]
Standard operators of Qualifiers
 All
 Any
 Contains
[Link]
Standard operators of Elements
 ElementAt
 ElementAtDefault
 First
 First or Default
 Last
 Last or Default
 Single
 Single or default
[Link]
Standard operators of Set
 Distinct
 Except
 Intersect
 Union
[Link]
Standard operators of Partition
 Skip
 Skip while
 Take
 Take while
[Link]
Standard operators of Concatenation
 Concat
[Link]
Standard operators of Equality
 SequenceEqual
[Link]
Standard operators of Generation
 DefaultEmpty
 Empty
 Range
 Repeat
[Link]
Standard operators of Conversion
 AsEnumerable
 AsQueryable
 Cast
 ToArray
 ToDictionary
 ToList

Filtering Operators:
 Filtering operators in linq filter the sequence based on given criteria.
 We have 2 types of filtering operators.
o Where
o OfType
[Link]:
 The Where operator filters the collection based on a given criteria
expression and return new collection.
 The criteria can be specified as a lambda expression or funk delegate
type.
Example:
[Link]:
 The OfType operator filters the collection based on the ability to cast
an element in a collection to a specific type.
 Use of OfType operator to filter the collection based on each element
type.
Example:
In [Link] file,
KeyPoints:
 The where operator filters the collection based on a predicted
function.
 The OfType operator filters the collection based on a given type.
 Where and OfType extension methods can be called multiple times in
a single linq query.
Sorting Operator:
A Sorting operator arranges the elements of the collection in ascending or
descending order.
[Link]:
 It sort the values of a collection in ascending or descending order.
 It sorts the collection in ascending order by default, why because
ascending keyword is optional here.
[Link]:
 It sorts the collection in descending order
 OrderByDescending is valid only with a method syntax.
 It is not valid in query syntax because the query syntax uses
descending attributes.
KeyPoints:
Linq query syntax supports multiple sorting fields separated by comma (,)
where ever you have to use “OrderBy” and “OrderByDescending” method.

[Link] and ThenByDescendig:


 ThenBy and ThenByDescending extension methods are used to
sorting on a multiple fields.
 The OrderBy method sorts the collection in ascending order based on
specific field use ThenBy method after OrderBy to sort the collection
on other fields in ascending order.
 Linq will sort first the collection based on primary field which is
specified by OrderBy method the sort the result collection in
ascending order again based on secondary field specified by ThenBy
method.
 The same way use ThenByDescending method to apply secondary
descending order.
 Method syntax is only possible to the ThenBy and TheByDescending
methods.
 No difference in ThenBy and ThenByDescending.
KeyPoints:
 OrderBy and ThenBy sorts collections in ascending order by default.
 ThenB or ThenByDescending is used for second level sorting in
method syntax.
 ThenByDescending method sorts the collection in descending order
on another field.
 ThenBy or ThenByDescending is not applicable in query syntax.
 Apply secondary sorting in query syntax by separarting fields using
comma.
[Link]:
The Reverse, reverses the order of the elements but does not alter the
original list ordering unless followed by toList or another method force that
enumeration.

Example for sorting operators:


04/09/2024
 It returns a new collection that contains elements form both
collections which satisfies the specified expression.
 It is the same as a inner join of sql.

05/09/2024
[Link]:
 The group join operator perform the same task as join operator
except that group join returns a result in group based on specified
group key.
 The group join operator joins two sequences based on key and
groups.
 The result by matching key and then return the collection of group
results and key.
 Group join requires same parameters as joins.
 It works as a left join.
Example:
Key differences in result:
Join(inner join) : only customers with matching orders are included.
GroupJoin(Left join): all customers are included for those without orders,
the orders group is empty.

Explanation:
Join: Filters customers who have orders. It’s a one to one or many to one
match between the two collecions.
GroupJoin: Groups the orders under each customer, providing a more
hierarchical structure where even customers without orders are includes.

Projection Operators: There are 2 projection operators available in linq.


[Link]
[Link]

[Link]:
 Select operator always returns an IEnumerable collection which
contains elements based on a transformation function.
 Its similar to select clause in sql.
 It produce a flat result set.
 The linq query syntax must end with a select or GroupBy clause.

06/09/2024
[Link]:
 In linq, selected many operator is used to project each element of a
collection into an IEnumberable<t> and flatten the result collections
into a single collection.
 It can be combining the results of multiple sequence into one single
sequence.
Example:
Grouping Operators:
 This operator do the same thing as the “GroupBy” clause of sql query.
 The grouping operators create a group of elements based on the
given key.
 There is a 2 types of grouping operators.
[Link]
[Link]

[Link]
 The GroupBy operator returns a group of elements from the given
collection based on some given key value.
 Each group is represented by IGrouping<key>,<value> object.
 GroupBy method as 8 overload methods.
[Link]: ToLookUp is the same as GroupBy, the only difference is
GroupBy execution is deferred, whereas ToLookUp execution is immediate.
Also, ToLookUp is only applicable I method syntax. ToLookUp is not
supported in the query syntax

Example for grouping operator:


Qualifiers Operators:
 It evaluates elements of the sequence on some condition and return
a Boolean value to indicate that some or all elements satisfy the
condition.
[Link]
[Link]
[Link]
[Link]: The All operator evaluates each element in the given collection and a
specified condition and returns true if all the elements satisfy condition.
Example:
Bool isAllStudentTeenAger = [Link](s => [Link] && [Link] < 20);
[Link]: Any checks whether the any element satisfy given condition or not.
Example:
bool isAnyStudentTenager = [Link](s => [Link] && [Link] < 20);
 With Any methos we have 2 scenarios
 Without condition
 With condition
Without Condition: in without condition the any method checks if a
sequence contains at least one element with condition.
With Condition: In this any method if any element in the sequence
satisfies the provided condition.
Key Points:
 If sequence is empty, any method returns false.
 If no element matches the condition any method also returns false.
[Link]:
 The contains operator checks whether a specified element exists in the
collection or not and returns a Boolean,
 The contains extension method has following 2 overloads.
 The first overload method requires a value to check in the collection.
Example
Aggregation Operator:
 The aggregation operator performs mathematical operations like count,
sum, avg on the numeric properties of the elements in the collection.
[Link]: It performs a custom aggregation operation on the values in
collection.
[Link]:
 An Avg extension method calculates the average of numeric items in the
collection.
 Avg method returns nullable or non-nullable decimals or float values.
[Link]: The Count operator returns the number of elements in the
collection or number of elements that have satisfied the given condition.
[Link]: The Max method returns the largest numeric element from a
collection.
[Link]: The sum method calculates the numeric items sum in the
condition.

Example for aggregation operators:


Element Operators: Element operators return a particular element from a
sequence.
Types of element operators:
[Link]
[Link] or Default
[Link]
4First or Default
[Link]
[Link] or Default
[Link]
[Link] or Default

[Link]: The ElementAt method return an element from the specific


index from a given collection.
 If the specified index is out of range of the collection then it will
through an “IndexOutOfRangeException”.
[Link] or Default: This method also return an element from the
specified index from a collection and the specified index is out of range of
the collection, then it will return default value of the datatype instead of
throwing an error.
[Link] and First or Default: The First and First or Default method returns
an element from the 0th index in the collection.
 The first method returns the first element of a collection or the first
element that satisfies a condition.
 First or Default returns the element of a collection or the first element
that satisfies a condition and returns a default value if index is out of
range.
 Throws an Exception “NoElementFound”.
[Link] and Last or Default: The Last or Default extension method return
the last element from the collection.
 Last returns last element from a collection or the last element that
satisfies a condition throws exception if “Noelementfound”.
 Last or Default returns last element from a collection or the last
element that satisfies a condition, it returns default value if no
element found.
[Link] and Single or Default:
 Single return the only element from a collection or the only element
that satisfies a condition. If single method found no elements or more
than one element in the condition throws “InvalidOperationException”.
 Single or Default it also same as a single except that it returns a
default value of a specified generic type instead of throwing an
exception if no element found for the specified condition however, it
will throw “InvalidOperationException” if it found more than one
element from the specified condition.

[Link] Operator: The Concat() method appends two sequences


of the same type and returns a new sequence.

Example:
[Link] Operator: The distinct extension method returns a new
collection of unique elements from the given collection.
Example:
One-to-one Relation:
 Create a project as “OneToOneRelation”.
 Install 4 packages.
 In [Link] file, give the connection to the server.
o "ConnectionStrings": {
o "con": "Data Source = DESKTOP-78H5NU7; Database =
OneToOne ; TrustServerCertificate = True; Integrated Security
= True;"
o },
 Right click on models folder and create a class and name it as
“[Link]”
o
 Right click on models folder and add class name as
“[Link]”
o

 Now, we need to create a DbContext class, now right click on model


folder and add class name as “[Link]”.
o

 Add services in [Link] file


 [Link]<OneToOneDatabase>(op =>
[Link]([Link]("con")));

 Add migration in “Package Manager Console”, type command as

o Add-migration onetoone
Update the migration
o Update-database
 Check in sql server, whether the data is updated or not.

One-To-One Relation:
 One-to-one relationship in mvc involves defining and managing the
connection between two models such that each instance of one
model relates to exactly one instance of another.
 The mvc pattern ensure that the data and its relationships are
managed by model that presented by view and manipulated by
controller.
 The concepts of helping in structing and managing data of objects
with in application in mvc.
[Link] Management: This refers to the life cycle and visibility of data or
objects.
 It determines how long data can share across different
components or request in an application.
[Link] Management: This concept describes objects or data that
exits only temporarily often for the duration of a single request or session.
 This is also known as request scope or session scope.
[Link] Management: A design pattern that ensures a class has only
one instance an provide global point of access to that one instance.

Summary:
[Link] management: It manages the visibility life style of objects.
[Link]: It refers temporary objects that are only for short period.
[Link]: A design pattern ensures a single instance of a class and a
global access point.
Those concepts help in structing and managing data and object with in
application.

14/09/2024

Return Types:
[Link]: The most versatile return type. It represents a result of an
action method and allows for only different kinds of responses.
[Link]<T>: A generic version of action result that allows returning
a specific type “T”, along side the action result. Useful for API’s and actions
that return both models and different result types.
[Link]<T>: Used for returning collect of items in API controller.
[Link] core automation serializes this to Json.
4.T(Model): When returning a single object model especially in Web API
controller, the model is automatically serialized to Json.
[Link]:
 Async: Marks a method as asynchronous. It returns task<t> or
void.
 Await: Pauses the execution of the async method until the
awaited task completes allowing other operations to continue.
 Task<IActionResult>: Uses for asynchronous operations allows
the action method to perform asynchronous work and return
Iaction result.
 TaskActionResult<T>: Asyncronous version of actionresult<t>.
Useful for when per a asynchronous operations that return a
specific type.
 ContentResult: Return plain text content. Useful for when you
want to return simple string or html.
 FileResult: Returns a file to the client its commonly ued for file
downloads.
 RedirectToActionResult: It redirect to another action method. It
can be used to navigate to different actions with in the same
controller or different controller.

Common Return Types:


[Link]: It returns the view.
[Link]: Returns json data.
[Link]: It redirects to another URL.
Validation Attributes:
[Link]: Ensure a property is not null or empty.
[Link]: sets the maximum and minimum length for the string
property.
[Link]: Specified a valid range of numeric property.
[Link] Expression: Validate the property against a regular expression
pattern.
[Link]: Validate the property contains a valid email address.
[Link]: Compares the value of one property with another property. It
most commonly used for confirming password fields.
[Link]: Validates that the property contains a valid phone number.
[Link]: Validates the property contains a valid url.
[Link]: Specifies type of data for a property which can affected how it
is displayed and validate. It is used for “hints”.
[Link]: Validates that the file has one of the allowed file
extensions.
[Link] Validation: Allows specifying a custom validation method.

Http Verbs: Http herbs are fundamentals to restful APIs and web
applications.
 Each verb serves a different purpose when interacting with resources
on a server.
List of Http verbs:
HttpGet, HttpPost, HttpPost, HttpPatch, HttpDelete, HttpHead, HttpOptions,
HttpTrans, HttpConnect.

16/09/2024
Data Passing Techniques:
[Link]: It is a dictionary object in [Link] core mvc that allows us to
pass data from a controller action method to view.
 It provides a flexible way to pass data allowing us to use key, value
pairs.
 viewdata is useful when we need to pass dynamic data or data that
doesn’t fit well into a strongly type model.
Example:
In [Link] file,

In [Link] file,
In [Link] file.
Advantages of ViewData:
 viewdata does not provide type safety; it stores data as an object
only.
 We need to cast the data to the appropriate type when retrieving it.
 Viewdata returns null, if a key does not exist so need to check for null
or use the “?” to avoid exceptions.
 Viewdata is best to small amount of data.
 Viewdata is a dynamic object, so we can pass any datatype.

ViewBag:
 View bag is a dynamic object that provides a way to pass data from
the controller action method to view.
 It allows us to create properties dynamically and add properties to the
viewbag object in the controller actions which are accessible in views.

TempData: Tempdata in [Link] core mvc is one of the mechanism for


passing a small amount of temporary data from controller method to view
and another action method within the same controller or different controller.
17/09/2024

Methods in TempData: Those methods are primary used by [Link] core


framework to handle life cycle of tempdata.

[Link](): The load method, loads the tempdata values from the current
http context.
 The framework typically invoke this method internally and it is not
commonly used directly in application core.
[Link](): The save method is used to save the current state of tempdata
into the HttpContext.
 Its typically called automatically by the [Link] core framework at the
end of request ensuring that any changes made to tempdata during
the request or persistent/hold/save for the next request.
[Link](): The keep method marks all items in tempdata to be retain for the
next request.
 This method is useful to ensure that tempdata is not cleared after
reading.
[Link](): This method reads an item from tempdata without removing it.
This is useful when you need to access the same tempdata items across
multiple request or in multiple places with in the same request.
 The peek allows the data to be read and still remain in tempdata for
further request.
Example:
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,

18/09/2024
Strongly Typed View In [Link] Core MVC:
 A strongly typed view in [Link] core mvc is also associated with
specific class known as view model.
 This class defines the data and behavior, the view needs to display or
interact with.
 It is a view that except a specific data model to pass and inform to
controller action method.

Why strongly typed view is needed?


[Link] Safety
[Link] support.
[Link] Support.

Routing:
What is routing in [Link] core mvc?
Routing in [Link] core mvc is a mechanism that inspects the incoming
“HttpRequest” and then maps that request to the appropriate controller
actions.

Incoming Http Request


|
|
|
Url Parsing
|
|
|
|
Find matching Route
|
|
|
No | Yes
|---------------Route Found------------|
| |
| |
| |
Http 404 error Process the request

There are 4 types of routing supported by [Link] core mvc.


[Link] routing
[Link] routing

[Link] Routing: It defines url patterns and map them to


controller action based on conventional rather than explicitly, specifying
route on each action or controller.
 The conventional routing follows a set of conventions to map
incoming requests to specific controller actions.
 It is configured globally in [Link] class using the middleware
map controller route.
 That middleware allows centralize the routing configuration.
Example:
In [Link] file,
[Link](
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
[Link] Routing: It allows developers to define routing directly on
controller actions, or at the controller level using attributes.
 This approach provides more control and flexibility over. How URLs
are mapped to controller actions compare to conventional routing.
 This approach is useful for APIs.
[Link] Routing: custom routing in [Link] core mvc allows us to define
our own routing patterns for our web application.
 It gives more flexibility and control over the URLs, how the URLs are
mapped to controller actions.
 The custom route is configure in [Link] class using
mapcontrollerroute middleware.
Example:
[Link](
name: "CustomRoute",
pattern: "{controller=Home}/{action=Index}/{id?}");

19/09/2024
[Link](): It reads the value without marking it for deletion in the
current request, but if you access it using tempdata <key> afterward it will
be removed unless you call keep method explicitly.

Use case: When you want to read the value without consuming it
immediately, but you don’t want to persist or maintain the value for future
request.

Html Helpers in MVC:


 Html helpers in [Link] core mvc simplify the process of creating html
elements on web page and binding data to them.
 Using the html helpers reduces the inter using typos or errors while
manually writing html code.
 Html helpers facilitate model binding, validation, integration with
[Link] core mv features such as tag helpers, form validations and
data annotations.
 They also promoted code reusability and maintainability so making
views clear and easier to maintain.
 All html helpers are methods.
Types of Html helpers in [Link] core mvc: The html helpers are 3
types.
[Link] html helpers.
[Link] typed html helpers.
[Link] html helpers.
Strongly Typed Html Helpers: These helpers are associated with a
specific data model and allow for complete-time checking of model
properties. They use lambda expression to refer to model properties
directly. Example includes,
[Link](model=>[Link])
[Link](model=>[Link])
[Link](model=>[Link])

Custom Html Helpers: you can create custom html helpers by defining
reusable methods to generate specific html markup. These helpers are
typically used when you need custom functionality that the built-in helpers
do not provide.

Input controller Helpers: Generate html input elements such as text


boxes, check boxes, radio buttons etc, example includes,
[Link]()
[Link]()
[Link]()

Display Control Helpers: Render read-only representations of model


properties. Example includes.
[Link]()
[Link]()
[Link]()

Form Helpers: Help generate form elements and manage the form
submissions. Example includes,
[Link]()
[Link]()

Validation Helpers: Display validation message related to model


validation. Example includes,
[Link]()
[Link]()

20/09/2024
Example for Html helpers:
In [Link] file,

In [Link] file,
In [Link] file,
23/09/2024
Tag Helpers in MVC:
 Tag helpers in mvc allows server-side code to participate in creating
and rendering html elements in razor views.
 They provide a way to add server-side functionality to html elements
in a more readable way than traditional html helpers.
 Tag helpers enhance html elements with attributes that generates
dynamic html and allows developers to create more maintainable
templates.

Key Characteristics:
 Tag helpers use html like syntax which allows to create, to edit and
razor view easily.
 Tag helpers support model-binding.
 Tag helpers support encapsulate the rendering logic and can be
reused across different views and reducing code duplication.
 We can create custom tag helpers also.

Types of Tag Helpers:


[Link]-in tag helpers
[Link] tag helpers

Tag Helpers Attributes:


[Link]-action: It specifies the action method for the form or hyperlink.
[Link]-Controller: It specifies the controller to use with Asp-action.
[Link]-Area: It specifies the arear to use for routing when multiple areas
are defined in the application.
[Link]-For: It binds as an input, select label, element to a model property.
[Link]-Items: It provides a collection of items for selected elements.
[Link]-Route: It specifies a route name for the link.
[Link]-Page: It specifies a razor page instead of an mvc action.
[Link]-Validation-For: It displays a validation message for a specific model
property.
[Link]-Hide-For: It specifies which element should be hidden.

24/09/2024
Dependency Injection: It is a design pattern it is used to implement
inversion of control. It allowing a program to follow the dependency
inversion principle.
 It enables to create a dependent objects outside of the class and
provide those objects to a class in various ways.

Key Points:
 DI promotes loosely coupling between classes and making them
easier to manage and test.
 Instead of a class creating its own dependencies and it receives them
from an external source.
Types of Dependency Injection:
[Link] injection
[Link] injection
[Link] injection

[Link] Injection: The dependencies are provided through a class


constructor.
[Link] Injection: Dependencies are provided through public
properties of a class.
[Link] Injection: Dependencies are provided through method
properties.

Limitations:
 It introduces additional complexity in configuration and understanding
for new developers.
 Runtime resolutions of dependencies can slightly impact perform.
 Debugging is difficulty.
 Improper handling of service lifetimes can lead to memory leakage or
unwanted behavior.
Example:
Create service file, In [Link] file,

In [Link] file,
In [Link] file,

In [Link] file,
On Product folder create model, and names it as [Link]. In
[Link] file,
In home controller folder, in [Link] file,

In [Link] file,

25/09/2024
Data Binding Attributes:
[Link]: The data bind from the body of the HttpRequest.
 This is commonly used for Json payloads in post request.
 The model binder reads the body and deserialize into the specific
model type.
Example:
Public class MyModel
{
Public string Name{get;set;}
Public int Age{get;set;}
}
[HttpPost]
Public IActionResult Create([FromBody] MyModel model)
{
If([Link])
{
//process the model
return ok();
}
return Badrequest(Modelstate);
}
[Link]: Binds data from form fields in a post request.
 This is useful for traditional webforms where data sent as key value
pairs.
Example:
Public class MyFormModel
{
Public string FirstName{get;set;}
Public string LastName{get;set;}
}
[HttpPost]
Public IActionResult SubmitForm([FromForm] MyFormModel formModel)
{
if([Link])
{
//process the form data
return RedirectToAction(“success”);
}
return view(fromModel);
}
[Link]: Binds data from the query string of the url.
 This is commonly used for get request such as filtering.
Example:
[HttpGet]
Public IActionResult Search([FromQuery] string query, [FromQuery] int
page=1)
{
//use the query and page parameter to perform a search
return view();
}
[Link]: binds data from route parameters specified in the url.
 This is useful for APIs where identifiers are part of the url.
Example:
[HttpGet(“Products/{id}”)]
Public IActionResult GetProduct([FromRoute] int id)
{
//retrieve the product by id
return view();
}
[Link]: binds data from the HTTP Request headers.
 This can be used to read custom headers or standard errors.
Example:
[HttpGet]
Public IActionResult GetData([FromHeader] string authorization)
{
//use the authorization header for passing
return ok();
}
[Link]: Binds parameters from the dependency injection
container.
 This allows you to direct inject service into your action method.
Example:
Public class ProductController : Controller
{
Public ProductController()
{
}
Public IActionResult Index([FromServices] IProductService
productService)
{
Var product = [Link]();
Return view(product);
}
}
Attributes:
1.[InsertAuthorize]: The purpose of authorize attribute to restrict access to
users.
2.[AllowAnonymous]: The purpose is to allow access to anonymous
users.
3.[HttpGet], [HttpPost], [HttpPut], [HttpDelete], [HttpHeader],
[HttpOptions]: It specifies the Http methods.
4.[Route]: It specifies custom routing.
5.[Produces]: It specifies response type.

Filters:
[Link] filter: checks if a user is authorized.
[Link] Filter: Executes code before and after an action method.
[Link] Filter: Executes code before and after the result is generated.
[Link] Filter: Handles exceptions that occur during action execution.
[Link] Filter: Executes code before and after resource execution.

28/09/2024
Example on Authorization Filter:
 Right click on project name and add class and name it as
[Link], in that file write below code.
In [Link] file,
Create views for the Authorized, RoleBased, Unauthorized
methods.
In [Link] file,

In [Link] file,

In [Link] file,
In [Link] file,

In [Link] file,
30/09/2024
Example for CustomResult filter:
Create a controller, In [Link] file,

In [Link] file,
In [Link] file,

In [Link] file
01/10/2024
Middleware: In [Link] core mvc, middleware is a software that sit
between the incoming Http request and the application logic processing the
request before they reach the mvc pipeline or response before they sent
back to the client.
 Middleware is typically used for task like authentication, logging and
exception handling etc.
Built-in Middleware’s:
[Link] Middleware: It handles authentication and authorization.
[Link] Middleware: It catches exceptions and handles
error pagers or logger.
[Link] Middleware: Routes requested to specific end points.
[Link] Middleware: It serves static files like images, json files and
css files.
[Link] Middleware: It handles cross origin resource sharing.

05/10/2024
Views in MVC: views are components in the mvc architecture that are
responsible for rendering the user interface they take data from model and
present in a format i.e, suitable for interaction.
[Link] Folder
 Controller View
[Link] Folder
 _layout.cshtml
 _viewimports.cshtml
 _viewstart.cshtml

 A view folder contains sub folders for each controller.


 The shared folder contains views and layout files that are shared
across multiple views.
1._layout.cshtml: The file serves as a template for your view it is usually
contains the common html structure that you want to apply multiple pages.
2._viewimports.html: The file allows you to include namespace, tag
helpers and other directives that you want to available in all views within
the folder or its sub folder.
 This file is especially used for reducing the repeated code in each
view.
3._viewstart.cshtml: This file sets the default layout for views.
 It is executed before each view is rendered, allowing you to specify
which layout use for the view in that folder.
@RenderBody(): It is used to define a place holder where the content of a
child view will be inserted in layout views.
For getting data of multiple objects:
@model IEnumerable<[Link]>
<div>
@foreach(var data in Model)
{
@if(data != null)
{
<table>
<tr>
<th>ProductId</th>
<th>ProductName</th>
<th>ProductDescription</th>
<th>ProductPrice</th>
</tr>
<tr>
<td>
@[Link]
</td>
</tr>
<tr>
@[Link]
</tr>
</table>
}
else
{
<label>Orders are found...</label>
}
}
</div>
For filtering data, the data and rendering in view.
@Model IQueryable<[Link]>

For fetching the single data in view


@Model [Link]
@if(model != null)
{
}

Example for listing of objects:


In [Link] file,

In [Link] file,
In [Link] file,
WEB API
07/10/2024

Introduction:
 A web Api(Application Program Interface) in the context of [Link] is
a core that allows you to build Http services. Those services can be
consumed by wide range of clients such as browsers, mobile devices
and desktop.
 Web Api are mainly used to develop restful services which expose
data via standard http methods like Get, Post, Put, Patch, Delete etc.

Key Points of Web Api:


 In web Api each request is independent and carries enough
information for the server to understand it.
 Web Apis is stateless.
 Its typically communicate over http or https making it suitable for
mobile and web applications and Ios applications.
 Web Apis is light weight.
 Web Apis are using http as the communication protocol with any
client like web app, mobile app or desktop app that can send http
request and can consume Apis data.
Difference between MVC and web Api:
MVC Web API
Used for building web application Used to build restful services.
with views.
It typically returns views. It typically returns data like Json,
xml format.
In MVC, designed UI pages for In web Api, design for creating
rendering. services to explore data to client.
In MVC, follows a convention- In Web Api, uses attribute-based
based routing system. routing.
In MVC, returns views or Json for In Web Api, it returns Json, xml or
ajax request. other structured data formats.
How Web API Works?
 The client makes an Http request to the web Api.
 The request is routed to the appropriate controller action in the web
Api based on the Http method and URL patterns.
 The controller processprocesses the request often by interacting with
the database or perform some business logic.
 The controller action returns a response (typically json or xml) to the
client.
 This response contains the requested data or a status message like
success or error message.
Steps for creating Web Api:
 Create new project then select the project name as “[Link] core
Web API” then click on next give the project name as “WebApiCrud”.
 Install 3 packages
o [Link]
o [Link]
o [Link]
 In packages folder, check whether swagger is present or not. If not,
install the swagger.
 Right click on project and add new folder name it as Models.
 Create another folder and name it as “RepoDbContext”.
 Right click on models add class name it as “[Link]”.
 In [Link] file,
o
 Right click on controller folder add controller select “API” and add API
Controller-Empty name is as “[Link]”.
 Right click on project and add one new folder and name it as
“ServiceLayer”.
 Add another folder and name it as “RepoLayer”.
 Right click on RepoLayer folder and add calss name is as
“[Link]”.
 Right click on RepLayer and add interface and name it as
“[Link]”.
 Same in serviceLayer add class name as “[Link]” and
one interface name it as “[Link]”.
 Right click on RepoDbContext and add one class name it as
“[Link]”.
 In [Link] file, give connection string.
o

 In [Link] file,
o

 In [Link] file,

o
 In Package Manager console, do migration.
o Add-migration studentmigartion
o Update-database
 Then we need to check in sql server, data is created or not.
16/10/2024
 In DB First Approach, if we add the columns to the existing table, to
implement it into the code we have a below code,
o While scaffolding at last we need to write as -OutputDir Models
-force.
One-to-Many Relation:
 In relational database, a one-to-many relationships means that one
record in a table is related to many records in another table.
 This is a fundamental concept in database design where the foreign
key in child table references the primary key of parent table to
establish the relationship.
18/10/2024
Many-to-Many Relation:
 In many-to-many relationship in each record from one table can
related to many records in another table and vise-versa.
 It is commonly used in databases to model scenarios where entities
from two different tables are linked with multiple connections between
them.
 In many-to-many actually internally works one-to-one relation.
22/10/2024
How To Create a Project in GitHub:
 Open Visual Studio.
 Create Project for example, Web Api.
 In bottom of Vs Code, Click on “Add to Source Control” select Git.
 Give Repository name and click on “Create and Push”.

 Next, Click on Sync(Pull then Push).


 In GitHub, click on Add, select Clone Repository, then click on
Refresh button it will show recently created Repository name, select
and click on clone Repository.
 In VS, in a project right click on project name and add one folder and
create a class in it.
How to create a branch for PR_Request:
 In Git, select branch from the menu bar, select branch name and give
a name to it and click on create branch.
 After that, select 2nd option then click on switch branch (if u have
done any changes in the existing branch) or select 1st option for new
branch creation.
 Select publish branch.
 Give a description and click on “Commit to Branch”.
 Click “push to origin”.
 Then click on “create Pull Request”.
 Add Reviewer.
 Assign yourself.
 Add project name.
 Click on “pull request”.
Note: We need to fetch the origin everyday morning.
How to get recent changes:
 Click on current branch.
 Click on “Merge to”.
 Select branch and click on “create a merge commit”.
23/10/2024
Project Deploying into Azure:
 Right click on project.
 Select publish option.
 Click on new profile.
 Select the target server and click on next then select the app
services.
 Click on next and select the project.
 Click on next and click on create new for setting the URL suffix.
 Click on create, after that select the project and click on finish.
 Then we can get the site URL.

You might also like