MVC 01
MVC 01
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.
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).
Ravi 8310068586 3
ASP.NET MVC Basics
Action Results
localhost:44379/?page=1&sortBy=name
Ravi 8310068586 4
Action Parameters
Parameter Sources
URL Query String Form Data
/Customer/Edit/1 /Customer/Edit/?id=1 Id=1
CustomerController.cs
https://localhost:44379/Customer/Edit/1 URL
https://localhost:44379/Customer/Edit/?id=1 query string
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:
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" } ) ;
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
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
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.
Ravi 8310068586 9
View Models
View Models are used to pass two different models to the view from the controller.
Ravi 8310068586 10
Razor Views Syntax
@model CodeFirst.ViewModels.CustMoviesViewModel
@{
ViewBag.Title = "GetCustomerMovies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@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>
}
@{
var className = Model.Movies.Count > 5 ? "highlight" : "regular";
}
Commenting
@*
This is comment
On multiple lines
*@
Partial Views
Need to create a partial view for the navigation bar in the _Layout.cshtml
Ravi 8310068586 11
@Html.Partial("_NavBar")
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.
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
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
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Department
{
// Primary Key
public int Id { get; set; }
//public int DepartmentId { 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; }
[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; }
[Display(Name = "Department")]
[ForeignKey("DepartmentId")]
public Department Department { get; set; }
}
5. Rebuild Project
In case of errors related to Entity Framework, uninstall and install entity framework again.
PM> install-package EntityFramework
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
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
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; }
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; }
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; }
}
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
RegularExpression Specifies that the field value must match with specified Regular Expression
Remote Validates input on the client by calling an action method on the server.
Url Validates that the property has a URL format.
[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; }
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
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’
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
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.
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)
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
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.
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.
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();
}
namespace YottaBot.WebAPI.Controllers
{
Ravi 8310068586 28
{
// 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;
}
}
}
Ravi 8310068586 29
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.
Formatters.XmlFormatter);
Areas folder
Need to read from database and hence install Entity Framework for this project.
Right click on project and click on Manage NuGet Packages
Ravi 8310068586 30
Search for Entity Framework and install the below:
<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
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();
}
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 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>
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;
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;
};
//Res.Headers.
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.
Registered Accounts
When creating the project, you can choose the authentication type
Once open the application in the browser, you could see options for register and login.
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)
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"
});
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_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
})
});
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>
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();
}
Ravi 8310068586 38
Server Error in '/' Application.
Attempted to divide by zero.
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();
}
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);
}
}
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
{
Ravi 8310068586 41
}
Please note that all the controller classes should be inherited from BaseController class.
Error Controller
Scenario-8 Handling 404 errors
https://localhost:44380/abc
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)
Log4Net
Step-1: Install Package
Ravi 8310068586 43
</appender>
</log4net>
</configuration>
Ravi 8310068586 44
}
rollingStyle options:
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()
{
// 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"));
Ravi 8310068586 46
Life Cycle
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);
}
@{
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>
}))
{
<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")
}
In Views/Home Employee.cshtml
<h3><b>Forms: Weakly Typed</b></h3>
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.
Ravi 8310068586 52
Right click on the ‘TestApp’ in IIS manager and Manage Application and then Browse
Ravi 8310068586 53