Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
28 views53 pages

MVC 01

The document provides a comprehensive overview of the Model-View-Controller (MVC) design pattern as implemented in ASP.NET, detailing its components including Models, Controllers, and Views. It covers essential topics such as action results, routing, data transfer methods (ViewData, ViewBag, TempData), and the use of View Models for passing multiple models to views. Additionally, it discusses the Entity Framework, Web API, authentication methods, exception handling, logging, and deployment strategies.

Uploaded by

vikaslaps
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)
28 views53 pages

MVC 01

The document provides a comprehensive overview of the Model-View-Controller (MVC) design pattern as implemented in ASP.NET, detailing its components including Models, Controllers, and Views. It covers essential topics such as action results, routing, data transfer methods (ViewData, ViewBag, TempData), and the use of View Models for passing multiple models to views. Additionally, it discusses the Entity Framework, Web API, authentication methods, exception handling, logging, and deployment strategies.

Uploaded by

vikaslaps
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
You are on page 1/ 53

Part - I

Contents
What is MVC ........................................................................................................................................... 3
Models & Data .................................................................................................................................... 3
Controllers........................................................................................................................................... 3
Views with Razor ................................................................................................................................. 3
ASP.NET MVC Basics ............................................................................................................................... 4
Action Results.................................................................................................................................. 4
Action Parameters .......................................................................................................................... 5
Routing ................................................................................................................................................ 6
Custom Routing............................................................................................................................... 6
Attribute Routing ............................................................................................................................ 7
ViewData ............................................................................................................................................. 8
ViewBag .............................................................................................................................................. 8
TempData............................................................................................................................................ 9
View Models ..................................................................................................................................... 10
Partial Views...................................................................................................................................... 11
Entity Framework.................................................................................................................................. 12
DbContext ......................................................................................................................................... 13
Code First .......................................................................................................................................... 14
Data Annotations .......................................................................................................................... 16
Model Validation........................................................................................................................... 20
Db First .............................................................................................................................................. 21
Model First ........................................................................................................................................ 22
Web API................................................................................................................................................. 26
Authentication ...................................................................................................................................... 33
No Authentication ......................................................................................................................... 33
Individual User Accounts .............................................................................................................. 34
Work and School Accounts ........................................................................................................... 37

Ravi 8310068586 1
Windows Authentication .............................................................................................................. 37
Exception Handling ............................................................................................................................... 38
Using try catch .................................................................................................................................. 39
Custom Errors ................................................................................................................................... 39
Action result (method) level ......................................................................................................... 39
With logging .................................................................................................................................. 40
Class level ...................................................................................................................................... 40
Error.cshtml .................................................................................................................................. 41
App level ....................................................................................................................................... 41
Error Controller ............................................................................................................................. 42
Exception Logging ......................................................................................................................... 43
Logging .................................................................................................................................................. 43
Log4Net ............................................................................................................................................. 43
Send Email............................................................................................................................................. 45
Life Cycle ............................................................................................................................................... 47
Forms .................................................................................................................................................... 48
Form: Weakly Typed ..................................................................................................................... 51
Deployment .......................................................................................................................................... 52

Ravi 8310068586 2
What is MVC
Model View Controller (MVC)
MVC is a design pattern used to decouple user-interface (view), data (model), and application logic
(controller). This pattern helps to achieve separation of concerns.
Using the MVC pattern for websites, requests are routed to a Controller that is responsible for
working with the Model to perform actions and/or retrieve data. The Controller chooses the View
to display, and provides it with the Model. The View renders the final page, based on the data in the
Model.
ASP.NET gives you a powerful, patterns-based way to build dynamic websites using the MVC pattern
that enables a clean separation of concerns.

Models & Data


The Model in an MVC application represents the state of the application and any business logic or
operations that should be performed by it. Business logic should be encapsulated in the model,
along with any implementation logic for persisting the state of the application.
Create clean model classes and easily bind them to your database. Declaratively define validation
rules, using C# attributes, which are applied on the client and server.
ASP.NET supports many database engines including SQLite, SQL Server, Oracle, MySQL, PostgreSQL,
DB2 and more, as well as non-relational stores such as MongoDB, Redis, and Azure Cosmos DB.

Controllers
Simply route requests to controller actions, implemented as normal C# methods. Data from the
request path, query string, and request body are automatically bound to method parameters.
Controllers are the components that handle user interaction, work with the model, and ultimately
select a view to render. In an MVC application, the view only displays information; the controller
handles and responds to user input and interaction. In the MVC pattern, the controller is the initial
entry point, and is responsible for selecting which model types to work with and which view to
render (hence its name - it controls how the app responds to a given request).

Views with Razor


Views are responsible for presenting content through the user interface. They use the Razor view
engine to embed .NET code in HTML mark-up. There should be minimal logic within views, and any
logic in them should relate to presenting content. If you find the need to perform a great deal of
logic in view files in order to display data from a complex model, consider using a View Component,
ViewModel, or view template to simplify the view.
The Razor syntax provides a simple, clean and lightweight way to render HTML content based on
your view. Razor lets you render a page using C#, producing fully HTML5 compliant web pages.

Ravi 8310068586 3
ASP.NET MVC Basics
Action Results

public ActionResult Random()


{
var customer = new Customer() { FirstName = "Raj", LastName = "Kumar", Phone =
"9876543210" };
return View(customer);
//return Content("Welcome to ASP.Net MVC !");
//return HttpNotFound();
//return new EmptyResult();
//return RedirectToAction("Index", "Home");
//return RedirectToAction("Index", "Home", new { page = 1, sortBy = "name" });
}

localhost:44379/?page=1&sortBy=name

Type Helper Method


ViewResult View()
PartialViewResult PartialView()
ContentResult Content()
RedirectResult Redirect()
RedirectToRouteresult RedirectToAction()
JsonResult Json()
FileResult File()
HttpNotFound HttpNotFound()
EmptyResult

Ravi 8310068586 4
Action Parameters
Parameter Sources
URL Query String Form Data
/Customer/Edit/1 /Customer/Edit/?id=1 Id=1

CustomerController.cs

public ActionResult Edit(int id)


{
return Content("id " + id);
}

https://localhost:44379/Customer/Edit/1 URL
https://localhost:44379/Customer/Edit/?id=1 query string

https://localhost:44379/Customer/Edit will throw Server Error

public ActionResult Edit(int CustId)


{
return Content("id " + CustId);
}
https://localhost:44379/Customer/Edit/?id=1 will throw Server Error
https://localhost:44379/Customer/Edit/1 will throw Server Error

https://localhost:44379/Customer/Edit/?CustId=1

Optional Parameter:
public ActionResult Display(int? pageIndex, string sortBy)
{
if (!pageIndex.HasValue)
{
pageIndex = 1;
}
if (string.IsNullOrWhiteSpace(sortBy))
{
sortBy = "Name";
}
return Content(string.Format("pageIndex={0} SortBy={1}", pageIndex, sortBy));
}

https://localhost:44379/Customer/Display
pageIndex=1 SortBy=Name

https://localhost:44379/Customer/Display/?pageIndex=5

Ravi 8310068586 5
pageIndex=5 SortBy=Name

https://localhost:44379/Customer/Display/?pageIndex=5&sortBy=Age
pageIndex=5 SortBy=Age

https://localhost:44379/Customer/Display/2/Age
HTTP Error 404.0 - Not Found

Model binding goes through the following steps after the routing system selects the action method:

Finds the first parameter of Display, an integer named pageIndex.


Looks through the available sources in the HTTP request and finds pageIndex = "2" in route data.
Converts the string "2" into integer 2.
Finds the next parameter of Display, a string named sortBy.
Looks through the sources and finds "Age". Name matching is not case-sensitive.

Routing
Routing is the process of directing an HTTP request to a controller and the functionality of this
processing is implemented in System.Web.Routing.
The MVC framework leverages routing to direct a request to a controller. The Global.asax file is that
part of your application, where you will define the route for your application.

Custom Routing
Now the requirement is to pass multiple parameters like /Customer/ByDOJ/2015/04
Convention Based Routes
RouteConfig.cs in App_Start folder
routes.MapRoute(
"CustomerByDOJ",
"Customer/ByDOJ/{year}/{month}",
new { controller = "Customer", action = "ByDOJ" } ) ;

public ActionResult ByDOJ(short year, byte month)


{
return Content(year + " / " + month);
}

https://localhost:44379/Customer/ByDOJ/2015/12

https://localhost:44379/Customer/ByDOJ/?year=2015&month=12
https://localhost:44379/Customer/ByDOJ/?year=18&month=5

to accept year only in 4 digit and month only in 2 digit:

Ravi 8310068586 6
new { controller = "Customer", action = "ByDOJ" },
new { year = @"\d{4}", month = @"\d{2}" } );

https://localhost:44379/Customer/ByDOJ/19/12
HTTP Error 404.0 - Not Found
To allow only 2017 or 2018 for year:
new { controller = "Customer", action = "ByDOJ" } ,
new { year = @"2017|2018" } );

https://localhost:44379/Customer/ByDOJ/2000/12
HTTP Error 404.0 - Not Found

Attribute Routing
routes.MapMvcAttributeRoutes();

[Route("Customer/ByDOJ/{year}/{month}")]
public ActionResult ByDOJ(short year, byte month)
{
return Content(year + " / " + month);
}

[Route("Customer/ByDOJ/{year}/{month:regex(\\d{2}):range(1,12)}")]

https://localhost:44379/Customer/ByDOJ/2000/13
HTTP Error 404.0 - Not Found

Constraint Description Example


Matches uppercase or lowercase Latin alphabet characters
alpha {x:alpha}
(a-z, A-Z)
bool Matches a Boolean value. {x:bool}
datetime Matches a DateTime value. {x:datetime}
decimal Matches a decimal value. {x:decimal}
double Matches a 64-bit floating-point value. {x:double}
float Matches a 32-bit floating-point value. {x:float}
guid Matches a GUID value. {x:guid}
int Matches a 32-bit integer value. {x:int}
Matches a string with the specified length or within a {x:length(6)}
length
specified range of lengths. {x:length(1,20)}
long Matches a 64-bit integer value. {x:long}
max Matches an integer with a maximum value. {x:max(10)}
maxlength Matches a string with a maximum length. {x:maxlength(10)}

Ravi 8310068586 7
Constraint Description Example
min Matches an integer with a minimum value. {x:min(10)}
minlength Matches a string with a minimum length. {x:minlength(10)}
range Matches an integer within a range of values. {x:range(10,50)}
{x:regex(^\d{3}-\d{3}-
regex Matches a regular expression.
\d{4}$)}

ViewData
ViewData – Dictionary object
It is a dictionary which can contain key-value pairs where each key must be string. We can use it in
transferring data from Controller to View. We can only transfer data from Controller to view but if
we wish to pass data back again to controller then it is not possible. So it is valid only for the
current request.
public ActionResult Index()
{
ViewData["Student"] = "Raj kumar";
return View();
}
Write the following Razor code in it in the index view.
<div>
<h2>UsingViewData</h2> @ViewData["Student"]
</div>
Using @ViewData["Students"] will not be checked during compile-time. And it happens only at
runtime.

ViewBag
ViewBag – Dynamic object
ViewBag is also similar to ViewData. It is used to transfer data from Controller to View. It is a type of
Dynamic object, that means use of the variable and references to its members bypass compile-time
type checking. Instead, these operations are resolved at run time.
public ActionResult Index()
{
ViewBag.MyName = "Raj kumar";
return View();
}

<div>
<h2>Using ViewBag</h2> @ViewBag.MyName
</div>

Ravi 8310068586 8
Using @ViewBag.YourName will not be checked during compile-time. And it happens only at
runtime.

Try to avoid using viewData and ViewBag since type checking is not available during compile time.

TempData
TempData – Dictionary object
TempData is a dictionary object derived from TempDataDictionary. It is for subsequent HTTP
requests; unlike ViewBag and ViewData, those stay only for current request. It can be used to
maintain data between controller actions as well as redirects.

public ActionResult Index()


{
TempData["Name"] = "Raj Kumar";
return RedirectToAction("Index1");
}

public ActionResult Index1()


{
ViewBag.data = TempData["Name"].ToString();
return View();
}

Add a new View(Index1.cshtml) and write the following code in it.


<div>
<h2>Using TempData</h2>
@ViewBag.data
</div>

ViewData ViewBag TempData


to pass data from controller to to pass data from controller to to pass data from the current
view view request to the next request
Available for the current Also available for the current It keeps the information for the
request only. If redirection request only. If redirection time of an HTTP Request. This
occurs, then its value becomes occurs, then its value becomes means only from one page to
null null another. It helps to maintain
the data when we move from
one controller to another
controller or from one action to
another action
Requires typecasting for Doesn’t require typecasting for It requires typecasting for
complex data type and checks complex data type complex data type and checks
for null values to avoid error for null values to avoid error.
Generally, it is used to store
only one time messages like the
error messages and validation
messages

Ravi 8310068586 9
View Models
View Models are used to pass two different models to the view from the controller.

Have two models:

public class Customer


{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
}

public class Movie


{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
}

Add a folder called ‘ViewModels’ in your project


Create a view model class CustMoviesViewModel.cs inside the folder ‘ViewModels’
public class CustMoviesViewModel
{
public Customer Customer { get; set; }
public List<Movie> Movies { get; set; }
}

Create a new ActionResult in Customer controller


public ActionResult GetCustomerMovies()
{
var customer = new Customer() { FirstName = "Raj", LastName = "Kumar", Phone =
"9876543210" };
var movies = new List<Movie>
{
new Movie { Title = "Movie 11", ReleaseDate = DateTime.Now.AddYears(-10) } ,
new Movie { Title = "Movie 22", ReleaseDate = DateTime.Now.AddYears(-15) }
};

var custMovies = new CustMoviesViewModel {


Customer = customer,
Movies = movies
};
return View(custMovies);

Create a View GetCustomerMovies.cshtml

Ravi 8310068586 10
Razor Views Syntax

@model CodeFirst.ViewModels.CustMoviesViewModel
@{
ViewBag.Title = "GetCustomerMovies";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@Model.Customer.FirstName @Model.Customer.LastName @Model.Customer.Phone</h2>

@if (@Model.Movies.Count>0)
{
<ul>
@foreach (var movie in Model.Movies)
{
<li> <b>@movie.Title</b> </li>
}
</ul>
}
else
{
<text> No movies rented</text>
}

Rendering classes dynamically

@{
var className = Model.Movies.Count > 5 ? "highlight" : "regular";
}

<p class="@className">@Model.Customer.FirstName @Model.Customer.LastName


@Model.Customer.Phone</p>

Remember the css class is to be defined in Site.css in the Content folder

Commenting
@*
This is comment
On multiple lines
*@

Partial Views
Need to create a partial view for the navigation bar in the _Layout.cshtml

Create a new view in your shared view folder _NavBar


Enable the checkbox Create as partial view
This view will not have any layout since it is a partial view.
Move (cut and paste) the below navbar div from _Layout.cshtml to the partial view _NavBar

<div class="navbar navbar-inverse navbar-fixed-top">

In _Layout.cshtml, render the navbar as follows:

Ravi 8310068586 11
@Html.Partial("_NavBar")

Passing model to the partial view

This will be useful in scenarios like you need to display category list in the navigation menu.

@model CodeFirst.ViewModels.CustMoviesViewModel

When you add the above model directive to your _Layout.cshtml the view model
CustMoviesViewModel is automatically passed to the _NavBar partial view.

If you want to pass only one model then you can explicitly pass as shown below:

@Html.Partial("_NavBar", Model.Movies)

Entity Framework
Entity Framework 6 (EF6) is a tried and tested object-relational mapper (O/RM) for .NET with many
years of feature development and stabilization.
As an O/RM, EF6 reduces the impedance mismatch between the relational and object-oriented
worlds, enabling developers to write applications that interact with data stored in relational
databases using strongly-typed .NET objects that represent the application's domain, and eliminating
the need for a large portion of the data access "plumbing" code that they usually need to write.

Database First Code First Model First

We design the tables in the We create our domain classes. We create a UML diagram.
database system.
EF generates database tables. EF generates domain classes
EF generates domain classes. and database.

Visual Studio 2019 provides the following options to work with EF;
 EF Designer From Database Dataase first
 Empty EF Designer model Model First
 Empty Code First model Code First
 Code First from database Code First

Code First or Database First?


Both enable end to end operations on your requirements.

Ravi 8310068586 12
Code first ensures full versioning of your database. Also improves productivity.

Model First
We use a visual designer in visual studio to model our classes and associations with a kind of UML
diagram. The visual designer for model and classes is poor.

DbContext
In order to use Entity Framework to query, insert, update, and delete data using .NET objects, you
first need to create a Model which maps the entities and relationships that are defined in your
model to tables in a database.
Once you have a model, the primary class your application interacts with is
System.Data.Entity.DbContext (often referred to as the context class). You can use a DbContext
associated to a model to:
 Write and execute queries
 Materialize query results as entity objects
 Track changes that are made to those objects
 Persist object changes back on the database
 Bind objects in memory to UI controls
The recommended way to work with context is to define a class that derives from DbContext and
exposes DbSet properties that represent collections of the specified entities in the context. If you are
working with the EF Designer, the context will be generated for you. If you are working with Code
First, you will typically write the context yourself.
public class AccentureContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}

Lifetime
The lifetime of the context begins when the instance is created and ends when the instance is either
disposed or garbage-collected. Use using if you want all the resources that the context controls to be
disposed at the end of the block. When you use using, the compiler automatically creates a
try/finally block and calls dispose in the finally block.
public void UseProducts()
{
using (var context = new ProductContext())
{
// Perform data access using the context
}
}

Connections
By default, the context manages connections to the database. The context opens and closes
connections as needed. For example, the context opens a connection to execute a query, and then
closes the connection when all the result sets have been processed.

Ravi 8310068586 13
Code First

1. Install Entity Framework 6


Tools – Nuget Package Manager - Package Manager Console
PM> install-package EntityFramework
To install a particular version
PM> Install-Package EntityFramework -Version 6.4.0

2. Create the model class in Models folder Employee.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Department
{
// Primary Key
public int Id { get; set; }
//public int DepartmentId { get; set; }

[Required (ErrorMessage = "Department Name is required !")]


[StringLength(64, ErrorMessage = "Maximum of 64 Characters only !")]
[MinLength(2, ErrorMessage = "Minimum of 2 Characters required !")]
[Index(IsUnique = true)]
[Display(Name = " Department")]
public string Name { get; set; }
}

public class Employee


{
// Primary Key
public int Id { get; set; }

[StringLength(6)]
[MinLength(6, ErrorMessage = "Employee Code should be 6 Characters. Ex:
M10054")]
public string Code { get; set; }

[Required]
[Index(IsUnique = true)]
[StringLength(32)]
[MinLength(3, ErrorMessage = "First Name should be 3 to 32 Characters")]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[StringLength(32)]
[MinLength(3, ErrorMessage = "Last Name should be 3 to 32 Characters")]
[Display(Name = "Last Name")]
public string LastName { get; set; }

[Display(Name = "Date of Joining")]


[DataType(DataType.Date),
DisplayFormat(DataFormatString = "{0:dd/MM/yy}",
ApplyFormatInEditMode = true)]
public DateTime? DOJ { get; set; }

[Required]
[Phone]

Ravi 8310068586 14
[RegularExpression(@"\d{10}", ErrorMessage = "10 digits numbers only -
Example: 9512341234")]
[StringLength(10)]
//[MinLength(10, ErrorMessage = "Mobile Phone should be in 10 digits
1234567890 format")]
public string Mobile { get; set; }

[Required]
[EmailAddress]
[StringLength(128)]
//[MinLength(128, ErrorMessage = "Email Phone should be in [email protected]
format")]
public string Email { get; set; }

[DisplayFormat(NullDisplayText = "No Department")]


[Display(Name = "Department")]
public int? DepartmentId { get; set; }

[Display(Name = "Department")]
[ForeignKey("DepartmentId")]
public Department Department { get; set; }
}

3. Create DbContext in Models folder and Specify entity sets


The main class that coordinates Entity Framework functionality for a given data model is the
database context class. You create this class by deriving from the System.Data.Entity.DbContext
class.
In Entity Framework terminology, an entity set typically corresponds to a database table, and an
entity corresponds to a row in the table.
Add reference to using System.Data.Entity;
using System.Data.Entity;
public class NewDbContext: DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}

4. Add connection string to web.config


<connectionStrings>
<add name="NewDbContext"
connectionString="data source=localhost; initial catalog=NewDb; integrated security=SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>

5. Rebuild Project

6. Enable Migrations (Need to do only once for the project)


PM> enable-migrations
PM> enable-migrations -force

In case of errors related to Entity Framework, uninstall and install entity framework again.
PM> install-package EntityFramework

7. Create migration version


PM> add-migration CreateEmployee

Ravi 8310068586 15
Could see a new folder ‘Migrations’ created and a new class file added having necessary
create table, key and index and also for dropping them. 202108230537003_CreateEmployee.cs

To run the push the changes to the database,


PM> update-database

Database ‘NewDb’ has been created. And the following tables are created and available in NewDb:
I. Departments
II. Employees

8. Add a new controller for Departments MVC 5 Controller with views, using Entity Framework

9. Add a new controller for Employees MVC 5 Controller with views, using Entity Framework

10. Use https://localhost:44361/Customers to manage customers and

11. use https://localhost:44361/Movies to manage movies

Data Annotations
1. Key
Code First will look for a property named “Id”, or a combination of class name and “Id”, such as
“BlogId”. This property will map to a primary key column in the database.
If code first does not find a property that matches this convention it will throw an exception because
of Entity Framework’s requirement that you must have a key property. You can use the key
annotation to specify which property is to be used as the Entity Key.
// Primary key
public int id { get; set; }

// Primary key
public int DepartmentId { get; set; }

public class Blog


{
// Primary key
[Key]
public int PrimaryTrackingKey { get; set; }
}

Composite keys
public class Passport
{
[Key]
[Column(Order=1)]
public int PassportNumber { get; set; }
[Key]
[Column(Order = 2)]

Ravi 8310068586 16
public string IssuingCountry { get; set; }
}

Only the relative ordering within the foreign key properties needs to be the same, the exact values
assigned to Order do not need to match. For example, in the following class, 3 and 4 could be used in
place of 1 and 2.
public class PassportStamp
{
[Key]
public int StampId { get; set; }

[ForeignKey("Passport")]
[Column(Order = 1)]
public int PassportNumber { get; set; }

[ForeignKey("Passport")]
[Column(Order = 2)]
public string IssuingCountry { get; set; }
}

2. Required
[Required]
public string Title { get; set; }

The title field is required.

3. MaxLength and MinLength


[MaxLength(12),MinLength(5)]
public string UserName { get; set; }
with error message:
[MaxLength(10, ErrorMessage="UserrName must be 12 characters or less"),MinLength(5)]

4. NotMapped
You can mark any properties that do not map to the database with the NotMapped annotation such
as this FullName property.
[NotMapped]
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}

5. Index

Ravi 8310068586 17
The Index attribute was introduced in Entity Framework 6.1. If you are using an earlier version the
information in this section does not apply.
For example, the following code will result in an index being created on the Rating column of the
Posts table in the database.
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[Index]
public int Rating { get; set; }
public int BlogId { get; set; }
}
Specify name for the index:
[Index("PostRatingIndex")]
public int Rating { get; set; }

[Index(IsUnique = true)]
[StringLength(20)]
public string Username { get; set; }

Multiple-Column Indexes:
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[Index("IX_BlogIdAndRating", 2)]
public int Rating { get; set; }
[Index("IX_BlogIdAndRating", 1)]
public int BlogId { get; set; }
}

6. ForeignKey
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime DateCreated { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
[ForeignKey("BlogId")]
public Blog Blog { get; set; }
public ICollection<Comment> Comments { get; set; }
}

7. Table and Column

Ravi 8310068586 18
If you are letting Code First create the database, you may want to change the name of the tables and
columns it is creating. You can also use Code First with an existing database. But it's not always the
case that the names of the classes and properties in your domain match the names of the tables and
columns in your database.
[Table("InternalBlogs")]
public class Blog

[Column("BlogDescription", TypeName="ntext")]
public String Description {get;set;}
Here is the table after it’s been regenerated.

8. ComplexType

[ComplexType]
public class BlogDetails
{
public DateTime? DateCreated { get; set; }

[MaxLength(250)]
public string Description { get; set; }
}

Notice that BlogDetails does not have any type of key property.

Now you can add a property in the Blog class to represent the BlogDetails for that blog.
public BlogDetails BlogDetail { get; set; }

In the database, the Blog table will contain all of the properties of the blog including the properties
contained in its BlogDetail property. By default, each one is preceded with the name of the complex
type, BlogDetail.

9. DataType
10. Range

Ravi 8310068586 19
11. StringLength
12. DisplayName
13. DisplayFormat
14. Timestamp
15. Bind
16. ConcurrencyCheck
17. ScaffoldColumn
[ScaffoldColumn(false)]

Model Validation
Validation attributes let you specify validation rules for model properties.
Built-in attributes
Attribute Description
Required Indicates that the property is a required field

StringLength Defines a maximum length for string field

Range Defines a maximum and minimum value for a numeric field

RegularExpression Specifies that the field value must match with specified Regular Expression

CreditCard Specifies that the specified field is a credit card number


CustomValidation Specified custom validation method to validate the field
EmailAddress Validates with email address format

FileExtension Validates with file extension

MaxLength Specifies maximum length for a string field

MinLength Specifies minimum length for a string field


Phone Specifies that the field is a phone number using regular expression for phone
numbers
Compare Validates that two properties in a model match

Remote Validates input on the client by calling an action method on the server.
Url Validates that the property has a URL format.

[Required(ErrorMessage = "Please enter a valid phone number")]


[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }

[Required(ErrorMessage = "Please enter a valid email address")]


[EmailAddress]
public string Email { get; set; }

[Required]
*Display(Name = “Please enter a valid User Name”)+
[StringLength(12, ErrorMessage = "UserName length can't be more than 12.")]

Ravi 8310068586 20
[RegularExpression (@"(\S\D)+", ErrorMessage =" Space and numbers not allowed")]
public string UserName { get; set; }

[Required]
[DataType (DataType.Password)]
[Display (Name = "Enter Password")]
public string CurrentPassword { get; set; }

[Range(18,55)]
public int Age { get; set; }

[Required (ErrorMessage="Company Email address Required")]


[DataType(DataType.EmailAddress)]
public string CompanyEmailAddress { get; set; }

[Required (ErrorMessage="Company Phone number is Required")]


[DataType(DataType.PhoneNumber)]
public int CompanyPhoneNumber { get; set; }

There are many data types the user can select to validate the input. Using this, you can validate for
the exact data type as in the following:
 Credit Card number
 Currency
 Custom
 Date
 DateTime
 Duration
 Email Address
 HTML
 Image URL
 Multiline text
 Password
 Phone number
 Postal Code
 Text
 Tine
 Upload

Db First
Create new Asp.Net MVC project.

Right click on Models folder Ado.net entity data model – EF designer from database
Add new connection string
Save connection settings in Web.config as InfosysEntities
Next – select EF version 6.0
Next – select db objects to be included (tables, views etc.)
Ex: Dept, Employee

Rebuild project

Ravi 8310068586 21
Create Dept Controller
Right click on Controllers folder – Add – New Scaffolded item - MVC 5 Controller with views, using
Entity Framework – select Dept model

Create Employee Controller


Right click on Controllers folder – Add – New Scaffolded item - MVC 5 Controller with views, using
Entity Framework – select Employee model

Use https://localhost:44360/Depts to manage Depts and

use https://localhost:44360/Employees to manage Employees

Model First
Create new Asp.Net MVC project.

Right click on Models folder Ado.net entity data model – Empty EF Designer model

Right click on the design surface and Add New Entity and provide entity name as ‘Employee’
Also provide set name, key property and key property type.

Right click on Department entity and click on Add New – Scalar Property – and enter ‘Name’

Right click on Name property and view Properties pane.

Ravi 8310068586 22
Create Employee entity
Add FirstName, LastName, DOJ properties

Next step is to create Navigational properties for each entity department and employee.
Right click on the design surface and add new Association

Ravi 8310068586 23
Ravi 8310068586 24
Compile your project

Right click on the design surface and select Generate Database from Model

Provide the connection string

Once done, you could see a new file EmployeeModel.edmx.sql created with all necessary sql
statements.

Open the sql file, right click on the surface and select Execute option.

Provide connection details and click on Connect

Rebuild the project

Create two different controllers for Department and Employee

Ravi 8310068586 25
Web API
Application programming interface (API) is a set of subroutine definitions, protocols, and tools for
building software and applications. API is some kind of interface which has a set of functions that
allow programmers to access specific features or data of an application, operating system or other
services.
Web API, is an API over the web which can be accessed using HTTP protocol. We can build Web API
using different technologies such as Java, .NET, PHP etc.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range
of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building
RESTful applications on the .NET Framework.
The ASP.NET Web API is an extensible framework for building HTTP based services that can be
accessed in different applications on different platforms such as web, windows, mobile etc. It works
more or less the same way as ASP.NET MVC web application except that it sends data as a response
instead of html view. It is like a webservice or WCF service but the exception is that it only supports
HTTP protocol.
ASP.NET Web API Characteristics
1. ASP.NET Web API is an ideal platform for building RESTful services.
2. ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request/response
pipeline
3. ASP.NET Web API maps HTTP verbs to method names.
4. ASP.NET Web API supports different formats of response data. Built-in support for JSON,
XML, BSON format. (Binary JSON)
5. ASP.NET Web API can be hosted in IIS, Self-hosted or other web server that supports .NET
4.0+.
6. ASP.NET Web API framework includes new HttpClient to communicate with Web API server.
HttpClient can be used in ASP.MVC server side, Windows Form application, Console
application or other apps. (Browsers, Mobile Apps, Desktop Apps, IOTs)

When to choose WCF?


 Choose WCF if your service needs to support multiple protocols such as HTTP, TCP, Named
pipe. Single service with multiple end points (one end point with TCP to be consumed by a
.Net client application and another end point with HTTP for a Java client.
 Choose WCF if you want to build service with WS-* standards like Reliable Messaging,
Transactions, Message Security.
 Choose WCF if you want to use Request-Reply, One Way, and Duplex message exchange
patterns.
 Choose WCF if you use .NET Framework 3.5. Web API does not support .NET 3.5 or below.

When to choose ASP.NET Web API?


 Choose Web API if you want to build a service that supports only HTTP protocol.

Ravi 8310068586 26
 Choose Web API to build RESTful HTTP based services.
 Choose Web API if you are familiar with ASP.NET MVC.
 Choose Web API if you are using .NET framework 4.0 or above.
WCF service also supports RESTful services but there are lot many configuration changes to be done
on WCF.

http://digitech.com/api/employees

http protocol
digitech.com domain name
api optional
employees Endpoint

Resource Verb Action

/Employees GET Get list of employees

/Employees/1 GET Get employee with id = 1

/Employees POST Create a new employee

/Employees/1 PUT / PATCH Update employee with id = 1

/Employees/1 DELETE Delete employee with id = 1

Put updates the entire object – First name, last name … (all the properties of the object are updated)
Patch – Partial update (subset of the properties) – only First name and Gender properties.

Step by step – Creating Web API for employee data


Create a Blank Solution in Visual Studio ‘YottaBotAPI’
Add a new Web API project named ‘YottaBotAPI.WebAPI’
Add a new ASP.NET empty web application named ‘YottaBotAPI.Service’
Add a new ASP.NET empty web application named ‘YottaBotAPI.Data’
Rebuild solution and add reference of Service and Data to WebAPI project
Add reference of Data to Service project
Install Entity Framework in Data project
Select Data project as default project in package manager console
PM> install-package EntityFramework
And ensure EntityFramework reference has been added to Data project
Right click on Data project and add new ADO.Net Entity Data Model named ‘NewDbModel’

Ravi 8310068586 27
EF Designer from Database - Provide connection string to NewDb database - select Departments and
Employees table
NewDbModel.edmx is created with the 2 entities.

Install Entity Framework in Servce project


PM> install-package EntityFramework

Create a folder ‘Services’ in Service project


Also add an interface ‘IEmployeeService.cs’ in Services folder.
Declare the interface as public
using YottaBotAPI.Data;
public interface IEmployeeService
{
List<Employee> GetEmployees();

Employee GetEmployee(int id);


}

Add a class ‘EmployeeService.cs’ in Services folder.

using YottaBotAPI.Data;
using System.Data;
public class EmployeeService : IEmployeeService
{
private NewDbEntities db = new NewDbEntities();
public List<Employee> GetEmployees()
{
// Get only active employees
var employees = db.Employees.ToList().Where(e => e. == true);
return employees.ToList();
}

public Employee GetEmployee(int id)


{
throw new NotImplementedException();
}
}

Update Connection string in web.config of WebAPI project

Add API EmployeeControler in WebAPI project


using YottaBot.Service.Services;
using YottaBot.Data;
using System.Data.Entity;

namespace YottaBot.WebAPI.Controllers
{

public class EmployeeController : ApiController

Ravi 8310068586 28
{

private IEmployeeService empService = new EmployeeService();


private InfosysEntities db = new InfosysEntities();

// GET api/Employee
// list of employees
public IEnumerable<Employee> Get()
{
//return db.Employees.ToList();
return empService.GetEmployees();
}

// GET api/Employee/5
// View details of a particular employee by id
public Employee Get(int id)
{
var employee = db.Employees.Find(id);
return employee;
}

// POST api/Employee/Create
// Create New Employee
public Employee Post([FromBody] Employee employee)
{
db.Employees.Add(employee);
db.SaveChanges();
return employee;
}

// PUT api/Employee/5
// Update employee by id
public Employee Put([FromBody] Employee employee)
{
db.Entry(employee).State = EntityState.Modified;
db.SaveChanges();
return employee;
}

// DELETE api/Employee/5
// delete employee by id
public Employee Delete(int id)
{
var employee = db.Employees.Find(id);
db.Employees.Remove(employee);
db.SaveChanges();
return employee;
}
}
}

// add the below code if you use json serialization


GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Referenc
eLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Ravi 8310068586 29
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.
Formatters.XmlFormatter);

Create a WebAPI for credit card validation

File – New – Project –

Template - C#, Windows, Web

Asp.Net Web Application – press Next

In the next screen select Web API template

Inside the project App_Start folder


WebApiConfig.cs

Areas folder

No Defalut views in views folder


No shared folder in views folder

Need to read from database and hence install Entity Framework for this project.
Right click on project and click on Manage NuGet Packages

Click on Browse tab,

Ravi 8310068586 30
Search for Entity Framework and install the below:

Add connection string in Web.config

<connectionStrings>
<add name="PaypalDbContext " connectionString="data source=.\SQLEXPRESS; initial
catalog=Paypal; integrated security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Create a model CashfreeDb using entity model - code first from database

Add a controller MVC 5 controller with read /write actions – CashfreeController.cs

Update the below code to insert three credit card information in the credit card table of Cashfree
database.

// GET: Cashfree/Create
public ActionResult Create()
{
using (var cashfreeDb = new CashfreeDb())
{
cashfreeDb.CreditCards.Add(new CreditCard { CardNumber = "1234",
CardHolderName = "Raj", CardPin = "123" });
cashfreeDb.CreditCards.Add(new CreditCard { CardNumber = "5678",
CardHolderName = "Kumar", CardPin = "567" });
cashfreeDb.CreditCards.Add(new CreditCard { CardNumber = "9876",
CardHolderName = "King", CardPin = "987" });

cashfreeDb.SaveChanges();
}

return Content("Cards Added to the database");


}

Right click on the Controller folder and create a new controller of type Web API 2 Controller - Empty

CashfreeAPIController.cs

// Cashfree/ValidateCard/1234/Raj/123
[Route("Cashfree/ValidateCard/{CardNum}/{CardHolderName}/{CardPin}")]
public IHttpActionResult Get([FromUri]string CardNum, [FromUri]string
CardHolderName, [FromUri]string CardPin)
{
bool isValidCard = false;
using (var CashfreeDb = new CashfreeDb())
{
// match in database table 'CreditCard' with Card Number, Hoder Name
and Card Pin
// using SingleOrDefault

Ravi 8310068586 31
var creditCard = CashfreeDb.CreditCards.Where(cc => cc.CardNumber.Equals(CardNum) &&
cc.CardHolderName == CardHolderName && cc.CardPin ==
CardPin).SingleOrDefault();

if (creditCard != null)
{
isValidCard = true;
}

//// match in database table 'CreditCard' with Card Number, Hoder Name
and Card Pin
//// use this when you need to return more than one row
//var creditCard = from cc in CashfreeDb.CreditCards
// where cc.CardNumber == CardNum && cc.CardHolderName
== CardHolderName && cc.CardPin == CardPin
// select cc;
//if (creditCard.Count() == 1)
//{
// isValidCard = true;
//}

return Ok(creditCard);

//return Ok(isValidCard);

}
}

Return type here is Generics

return Ok(creditCard);

<CreditCard xmlns:i="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://schemas.datacontract.org/2004/07/Gateway.Models">
<CardHolderName>Raj</CardHolderName>
<CardNumber>1234 </CardNumber>
<CardPin>123</CardPin>
</CreditCard>

Calling Web API from client machine:

using System.Threading.Tasks;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

// https://localhost:44381/MakePayment
[Route("MakePayment/")]
public async Task<ActionResult> MakePayment()
{
bool isValidCard = false;

//Hosted Web API REST Service base url


https://localhost:44381/Paypal/ValidateCard/1234/Raj/123
string Baseurl = "https://localhost:44381/";

Ravi 8310068586 32
using (var client = new System.Net.Http.HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);

//client.DefaultRequestHeaders.Clear();

client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));

// certificate
System.Net.ServicePointManager.ServerCertificateValidationCallback =
delegate (
object s,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
) {
return true;
};

// Sending request to find web api REST service resource


GetAllEmployees using HttpClient
System.Net.Http.HttpResponseMessage Res = await
client.GetAsync("Paypal/ValidateCard/5678/Kumar/567");

//Res.Headers.

// Checking the response is successful or not which is sent using


HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
string CardResponse = Res.Content.ReadAsStringAsync().Result;

//Deserializing the response recieved from web api and storing


into the Employee list
isValidCard = JsonConvert.DeserializeObject<bool>(CardResponse);

return Content(isValidCard.ToString());
}

Authentication
There are new identity components that are a part of ASP.NET MVC and see how to customize
membership for our users and roles.

No Authentication
The first option is No Authentication and this option is used when you want to build a website that
doesn't care who the visitors are.

Ravi 8310068586 33
It is open to anyone and every person connects as every single page. You can always change that
later, but the No Authentication option means there will not be any features to identify users
coming to the website.

Individual User Accounts


The second option is Individual User Accounts and this is the traditional forms-based authentication
where users can visit a website. They can register, create a login, and by default their username is
stored in a SQL Server database using some new ASP.NET identity features, which we'll look at.
The password is also stored in the database, but it is hashed first. Since the password is hashed, you
don't have to worry about plain-text passwords sitting in a database.
This option is typically used for internet sites where you want to establish the identity of a user. In
addition to letting a user create a local login with a password for your site, you can also enable logins
from third parties like Microsoft, Google, Facebook, and Twitter.
This allows a user to log into your site using their Live account or their Twitter account and they can
select a local username, but you don't need to store any passwords.
This is the option that we'll spend some time with in this module; the individual user accounts
option.

Registered Accounts
When creating the project, you can choose the authentication type

Click on Change and choose Individual User Accounts

Once open the application in the browser, you could see options for register and login.

Click on Register and provide details and click on Register button

Ravi 8310068586 34
A new SQL Server database file created with a name similar to this aspnet-Individualacc-
20210831094319.mdf in the folder App_Data

Open the mdf file in Sql Server Management Studio (run as Administrator)

SELECT * FROM [dbo].[AspNetUsers]

You will find a row with the registered user information.

Using Google account


Creating Client Id and client secret in google app:
https://console.developers.google.com/
Left side men click on Credentials
+ Create Credentials
OAuth Client Id
Web Application
Name: mvc login

https://www.youtube.com/watch?v=WsRyvWvo4EI

in MVC application
App_Start folder - Startup.Auth.cs

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{

Ravi 8310068586 35
ClientId = "xxx-.apps..com",
ClientSecret = "xxx"
});

Using Twitter account


Create Consumer Key and consumer secret in apps.twitter.com
https://developer.twitter.com/en/portal/projects-and-apps

Apps.twitter.com
Sign in with your twitter account
Click on Create an app
Apply for developer twitter account
Primary reason – Student
What would you like us to call you? AspNetAccount

App name : TwitterMvcDemo


Application description:
Website URL: https://127.0.0.1:44379/
Enable Sign in with Twitter – Enable the checkbox
Callback URLs: : https://127.0.0.1:44379/
Tell us how this app will be used:
Permissions: Choose the only option Read-only
Website and Callback URL: http://127.0.0.1

App_Start - Startup.Auth.cs

app.UseTwitterAuthentication(new TwitterAuthenticationOptions
{

Ravi 8310068586 36
ConsumerKey = "XXXX",
ConsumerSecret = "XXXX",
BackchannelCertificateValidator = new
CertificateSubjectKeyIdentifierValidator(new[]
{
"A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3
Secure Server CA - G2
"0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3
Secure Server CA - G3
"7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3
Public Primary Certification Authority - G5
"39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3
Secure Server CA - G4
"5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High
A A
"B13EC36903F8BF4701D498261A0802EF63642BC3" //DigiCert High
Assurance EV Root CA
})
});

Work and School Accounts


The third option is to use organizational accounts and this is typically used for business applications
where you will be using active directory federation services.
You will either set up Office 365 or use Azure Active Directory Services, and you have a single sign-on
for internal apps and Cloud apps.
You will also need to provide an app ID so your app will need to be registered with the Windows
Azure management portal if this is Azure based, and the app ID will uniquely identify this application
amongst all the applications that might be registered.

Windows Authentication
The fourth option is Windows authentication, which works well for intranet applications.
A user logs into Windows desktop and can launch a browser to the application that sits inside the
same firewall. ASP.NET can automatically pick up the user's identity, the one that was established by
active directory. This option does not allow any anonymous access to the site, but again that is a
configuration setting that can be changed.

When creating the project, you can choose the authentication type

Ravi 8310068586 37
<system.web>
<compilation debug="true" targetFramework="4.8"/>
<httpRuntime targetFramework="4.8"/>
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

The ? wildcard represents unauthenticated users


* represents all users
<allow users="dan,matthew" />
<deny users="*" />

Once you open your application in the browser, could see it has used your windows
domain\username for authentication and the logged in user will be displayed at top right of the
page.

Exception Handling
public ActionResult Index()
{
int a = 1;
int b = 0;
int c;
c = a / b; //it would cause exception. DivisionByZeroException
return View();
}

Scenario-1 No exception handling


Running as it is:

Ravi 8310068586 38
Server Error in '/' Application.
Attempted to divide by zero.

Using try catch


Scenario-2 Exception handling using try catch
Implementing try catch and automatically redirect to the view Error.cshtml
public ActionResult Index()
{
int a = 1;
int b = 0;
int c;
try
{
c = a / b; //it would cause exception.
}
catch (Exception ex)
{
// log error to file/data base/windows event log
// Send email to all stack-holders (technical team, business team)
return View("Error");
}
finally
{
}
return View();
}

Error.
An error occurred while processing your request.

Custom Errors
Scenario-3
Configuring custom errors in web.config and automatically redirect to the view Error.cshtml in the
shared folder
<system.web>
<customErrors mode="On"></customErrors>
<compilation debug="true" targetFramework="4.8"/>
<httpRuntime targetFramework="4.8"/>
</system.web>

Error.
An error occurred while processing your request.
Action result (method) level
Scenario-4 Action result (method) level

Ravi 8310068586 39
Configuring custom errors in web.config and capture a particular type of exception and redirect to
the view DivError.cshtml in the shared folder. This is on Action result (method) level.
[HandleError (ExceptionType=typeof(DivideByZeroException), View ="DivError")]
public ActionResult Index()
{
int a = 1;
int b = 0;
int c;
c = a / b; //it would cause exception.
return View();
}

With logging
Scenario-5 With logging
Configuring custom errors in web.config and capture a particular type of exception and redirect to
the view DivError.cshtml in the shared folder, Also log the error message
[MyHandleError (ExceptionType=typeof(DivideByZeroException), View ="DivError")]
public ActionResult Index()
{
int a = 1;
int b = 0;
int c;
c = a / b; //it would cause exception.
return View();
}

public class MyHandleError : HandleErrorAttribute


{
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);

// log error to log file


// send email to stack-holders
}
}

Class level
Scenario-6 Configuring custom errors in web.config and capture generic exception at class level
[MyHandleError(ExceptionType = typeof(Exception), View = "Error")]
public class HomeController : Controller
{
...
}
public class MyHandleError : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{

Ravi 8310068586 40
base.OnException(filterContext);

// log error to log file


// send email to stack-holders

}
}

Error.cshtml
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
<div style="background-color: #A52A2A; color: White; height: 10px;">
</div>
<div style="background-color: #F5F5DC; color: White; height: 170px;">
<div style=" padding:20px;">
<h3>
Application Error:</h3>
<h4>
Sorry, an error occurred while processing your request.
</h4>
<h6>@Html.ActionLink("Go Back To Home Page", "Index", "Home")</h6>
<br />
<br />
</div>
</div>
<div style="background-color: #A52A2A; color: White; height: 20px;">
</div>

App level
Scenario-7 Configuring custom errors in web.config and capture generic exception at app level
[MyHandleError(ExceptionType = typeof(Exception), View = "Error")]
public class BaseController : Controller
{

public class HomeController : BaseController


{

Ravi 8310068586 41
}
Please note that all the controller classes should be inherited from BaseController class.

App Level and Method level

Error Controller
Scenario-8 Handling 404 errors
https://localhost:44380/abc

Server Error in '/' Application.


The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have
been removed, had its name changed, or is temporarily unavailable. Please review the following
URL and make sure that it is spelled correctly.
Requested URL: /abc
Step-1 Add 404 error in web.config
<customErrors mode="On">
<error statusCode="404" redirect="Error/PageNotFound"/>
</customErrors>

Step-2 Create a new ErrorController class


public class ErrorController : Controller
{
// GET: Error
public ActionResult PageNotFound()
{
return View();
}
}

Step-3 Create view PageNotFound.cshtml


@{
ViewBag.Title = "PageNotFound";
}

<h2>The Page you have requested is Not Found !</h2>

The Page you have requested is Not Found !

Ravi 8310068586 42
Exception Logging

Logging
We have different logging libraries which can be implemented with ASP.NET MVC application.
1. Log4net (Logging in text file + logging in SQL database)
2. Nlog (Logging in text file + logging in SQL database)
3. Serilog (Logging in text file + logging in SQL database)
4. Elmah (logging in SQL database)

Create new library project named ‘Logger’

Log4Net
Step-1: Install Package

PM> Install-Package log4net


PM> Install-Package log4net -Version 1.2.10
Step-2: Add log4net.config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<appender name="console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger -
%message%newline" />
</layout>
</appender>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file value="demo.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="12" />
<maximumFileSize value="2MB"/>
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger -
%message%newline" />
</layout>

Ravi 8310068586 43
</appender>
</log4net>
</configuration>

Step-3: Set Copy to Output Directory to Copy Always

Step-4: Tell log4net to Load Your Config

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

Step-5: Log Errors, Info etc., from your code


class Program
{
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
;
static void Main(string[] args)
{
log.Info("Hello logging world!");
Console.WriteLine("Hit enter");
Console.ReadLine();
}

Ravi 8310068586 44
}

log4net Log levels:


All (log everything)
Debug
Info
Warn
Error
Fatal
Off (don’t log anything)

rollingStyle options:

Once Roll files once per program execution

Size Roll files based only on the size of the file

Date Roll files based only on the date

Composite Roll files based on both the size and date of the file

Log4View
Log file is a text file and can be viewed using any text editor.
To have a better view, log file can be viewed using Log4View application. (Can download free
version from https://www.log4view.com/download-en)

Send Email
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com" port="587"
userName="[email protected]"
password="password"
enableSsl="true" />
</smtp>
</mailSettings>
</system.net>

using System.Net.Mail

Ravi 8310068586 45
public ActionResult SendEmail()
{

MailMessage message = new MailMessage();

// to email id
message.To.Add(new MailAddress("[email protected]", "Raj"));
//message.To.Add(new MailAddress("[email protected]", "Robot1"));

// subject
message.Subject = "Asp.net mvc test";

// body
string body = "<p>This is asp.net mvc test message</p>";
message.Body = body;
message.IsBodyHtml = true;

message.Attachments.Add(new
Attachment(@"D:\Ravi\.Net\ASP.Net\Project\Training\Asp.Net\Demo\favicon.ico"));
//message.Attachments.Add(new
Attachment(@"D:\Ravi\.Net\ASP.Net\Project\Training\Asp.Net\Demo\logfile.log.1"));

// using (SmtpClient MailClient = new SmtpClient("smtp.gmail.com", 587))


using (var smtp = new SmtpClient())
{
smtp.Send(message);
}
return Content("Email Sent Successfully");
}

Ravi 8310068586 46
Life Cycle

Home Page About Page


Global.asax.cs HomeController.cs
FilterConfig.cs _ViewStart.cshtml
RouteConfig.cs About.cshtml
BundleConfig.cs _Layout.cshtml
HomeController.cs
_ViewStart.cshtml
Index.cshtml
_Layout.cshtml

Ravi 8310068586 47
Forms
// Customer Model
public class Customer
{
public int CustID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}

// in the HomeController
// Get
public ActionResult RegisterCustomer()
{
return View();
}

[HttpPost]
public ActionResult RegisterCustomer(Models.Customer cust)
{
if (ModelState.IsValid)
{
Models.AccentureEntities db = new AccentureEntities();
db.Customers.Add(cust);
db.SaveChanges();
}
return View(cust);
}

// the view RegisterCustomer.cshtml


@model RegForm.Models.Customer

@{
ViewBag.Title = "RegisterCustomer";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Customer Registration</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Customer</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes =
new { @class = "form-control" } })

Ravi 8310068586 48
@Html.ValidationMessageFor(model => model.FirstName, "", new {
@class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new {
@class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Phone, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Phone, "", new { @class
= "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class
= "text-danger" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

@if (IsPost)
{
<div>
<h4 id="onSuccess_Message" style="color:green">Success</h4>
<h4 id="onFailure_Message" style="color:red">Failed</h4>
</div>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

Ravi 8310068586 49
// the view RegisterCustomer.cshtml using Ajax

@model RegForm.Models.Customer

@{
ViewBag.Title = "RegisterCustomer";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Customer Registration</h2>

<script src="@Url.Content("~/Scripts/jquery-3.4.1.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
type="text/javascript"></script>

@*<h4 id="id1" style="color:purple"></h4>


<hr />*@

<h3><b>Forms - Strongly Typed AJAX (Asynchronous)</b></h3>


@using (Ajax.BeginForm("RegisterCustomer", "Home", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "id1",
LoadingElementId = "LoadingImage",
OnSuccess = "onSuccess_Message",
OnFailure = "onFailure_Message"

}))
{
<table>
<tr>
<td>Enter F Name: </td>
<td>@Html.TextBoxFor(model => model.FirstName)</td>
</tr>
<tr>
<td>Enter L Name: </td>
<td>@Html.TextBoxFor(model => model.LastName)</td>
</tr>
<tr>
<td>Enter Phone: </td>
<td>@Html.TextBoxFor(model => model.Phone)</td>
</tr>
<tr>
<td>Enter Email: </td>
<td>@Html.TextBoxFor(model => model.Email)</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Create" /></td>
</tr>
</table>
<div id="LoadingImage" style="display:none">Saving ...</div>
<div id="onSuccess_Message" style="color:blue"></div>
<div id="onFailure_Message" style="color:red"></div>
}

@section Scripts {

Ravi 8310068586 50
@Scripts.Render("~/bundles/jqueryval")
}

Form: Weakly Typed

In Models folder Employee.cs


public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}

In Views/Home Employee.cshtml
<h3><b>Forms: Weakly Typed</b></h3>

<form action="/Home/Employee" method="post">


<table>
<tr>
<td>Enter ID: </td>
<td><input type="text" name="txtId" /></td>
</tr>
<tr>
<td>Enter Name: </td>
<td><input type="text" name="txtName" /></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="txtPhone" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
</table>
</form>

In HomeController.cs
public ActionResult Employee()
{
return View();
}

[HttpPost]
public void Employee(int txtId, string txtName, string txtPhone)
{
Employee emp = new Employee();
emp.Id = txtId;
emp.Name = txtName;
emp.Phone = txtPhone;
}

Ravi 8310068586 51
Deployment
What Is a Web Deployment Package?
When you build and deploy a web application project, either by using Visual Studio or by using
MSBuild directly, the end result is typically a web deployment package. The web deployment
package is a .zip file. It contains everything that IIS and Web Deploy need in order to recreate your
web application, including:
 The compiled output of your web application, including content, resource files, configuration
files, JavaScript and cascading style sheets (CSS) resources, and so on.
 Assemblies for your web application project and for any referenced projects within your
solution.
 SQL scripts to generate any databases that you're deploying with your web application.
Once the web deployment package has been generated, you can publish it to an IIS web server in
various ways. For example, you can deploy it remotely by targeting the Web Deploy Remote Agent
service or the Web Deploy Handler on the destination web server, or you can use IIS Manager to
manually import the package on the destination web server. For more information on these
approaches to deployment, see choosing the Right Approach to Web Deployment.

Right click on the project and Publish


Select the local folder to publish
Once published you could see all necessary files for your web application is available in the published
folder. Notice no source code files (.cs) are included. Source files are compiled to dlls and they are
available in the bin folder of the published folder.
Go to IIS
Right click on Default Web Site and click Add Application
Give alias name example ‘TestApp’ and physical path of the published folder
Go to Control Panel\All Control Panel Items\Programs and Features
Turn Windows features on/off
Expand Internet Information Services
World Wide Web Service
Application Development Features
Ensure your current ASP.NET version is enabled.

Ravi 8310068586 52
Right click on the ‘TestApp’ in IIS manager and Manage Application and then Browse

Deploy to Test by using the command line


msbuild D:\temp\Demo.sln /p:DeployOnBuild=true /p:PublishProfile=Test

msbuild D:\temp\Demo.sln /p:DeployOnBuild=true /p:PublishProfile=Staging


/p:Password=hdNSWsbuqno7J5uqnwKafwlfNPt1DSco7J5uqnwKafwlfNPt1DSpKHuYgCco7J5
/p:AllowUntrustedCertificate=true

msbuild D:\temp\Demo.sln /p:DeployOnBuild=true /p:PublishProfile=Production


/p:Password=hdNSWsbuqnwKafwlo7J5uqnwKafwlfNPt1DSqnwKafwlfNPt1DSpKHuYgCco7J5
/p:AllowUntrustedCertificate=true

Ravi 8310068586 53

You might also like