MCSD Web Applications ASP Net Courseware
MCSD Web Applications ASP Net Courseware
www.firebrandtraining.com
0. 1
Module 0
Introduction
Developing ASP.NET MVC 4
Web Applications
0. 2
Exam
Design the
application
architecture
(15-20%)
Design the
user
experience
(20-25%)
Troubleshoot
and debug web
applications
(20-25%)
Develop the
user interface
(15-20%)
June 2013
31 in main section
22 in main section
33 in main section
0. 3
Exam
Qs
10: Using JavaScript and jQuery for Responsive MVC 4 Web Apps
13: Using Windows Azure Web Services in ASP.NET MVC 4 Web Apps
2
55
Exam
0. 4
0. 5
0. 6
Exam Topic: none
1. 1
Module 1
Exploring ASP.NET MVC 4
Developing ASP.NET MVC 4
Web Applications
1. 2
1. 3
1. 4
1. 5
MVC Architecture
Route(s)
Controller(s)
Model(s)
View(s)
Application_Start event
NuGet packages
In ASP.NET ~ (tilde)
indicates the root of
the web application
Configuration
1. 6
MVC
http://www.contoso.com/blog/edit/16
1
9
RouteTable
2
Controller
GetBlog(int)
Action1
Action
Result
Model
View
Domain Model
GetBlogs()
3
5
ViewBag
ViewData
TempData2
UpdateBlog
(Blog)
partial
classes and
metadata
CSDL
+ .cs
Entity
Data Model
MSL
SSDL
7
Partial View
1
2
MVC Architecture
1. 7
Model Terminology
Domain Model
Represents all the data required for an
application and often created using an
ORM such as EF
Model(s)
Represent entities from the domain model
View Model(s)
Represent the data required for a particular View, which could
be sets or parts of entity models and other data too
So a model in MVC is more accurately called a view model
MVC Architecture
1. 8
http://www.contoso.com/shipper/gamma/
1. 9
Further Study
ASP.NET MVC
Official Site for ASP.NET MVC
Tutorials, videos, samples, forum, books, open source
ASP.NET MVC
http://asp.net/mvc
Blogs
Phil Haack
http://haacked.com/
Scott Hanselman
http://www.hanselman.com/
Alternatives to MVC
1. 10
Exam Topic: none
2. 1
Module 2
Designing ASP.NET MVC 4
Web Applications
Developing ASP.NET MVC 4
Web Applications
2. 2
Configuration
Visual Studio
Or Web Site
IIS
\Windows\Microsoft.NET\
Framework64\v4.0.30319\Config
2. 3
Configuration
Pages.config
<pages enableSessionState="false">
<namespaces>
Intrinsic Objects
2. 4
HttpContext Class
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx
Intrinsic Objects
2. 5
Request
HTTP request as sent from the client (request headers, cookies,
client certificate, form and query string parameters, and so on)
Response
HTTP response sent from the server to the client (response
headers, cookies, and so on)
Intrinsic Objects
2. 6
HttpContext.Application
Store shared state at application level
HttpContext.ApplicationInstance
Defines the methods, properties, and events that are common
to all application objects in an ASP.NET application
HttpApplication is the base class for applications that are
defined by the user in the Global.asax file
2. 7
Intrinsic Objects
Server Object
Member
Description
MachineName
GetLastError()
ClearError()
Execute(path)
Executes the handler for the specified virtual path in the context of the
current request
HtmlDecode(string)
HtmlEncode(string)
MapPath(path)
Returns the physical file path that corresponds to the specified virtual path
Transfer(path)
For the current request, terminates execution of the current page and
starts execution of a new page by using the specified URL path of the page
HttpServerUtility Class
https://msdn.microsoft.com/en-us/library/system.web.httpserverutility(v=vs.110).aspx
.axd Files
2. 8
Trace.axd: view the trace log for the last n requests; most
useful for Web Forms pages because they show ViewState and
page events
3. 1
Module 3
Developing ASP.NET MVC 4
Models
Developing ASP.NET MVC 4
Web Applications
3. 2
Contents
Exam Topic: Design and implement MVC controllers and actions
Implement model binding
3. 3
MOC Demos
Demo 1: Position 5-3175 and Demo 2: Position 5-6134
Visual Studio 2013: Choose the ASP.NET Web Application and
then the MVC template, NOT Empty template and use the newer
item templates e.g. MVC 5 Controller with views using EF
Visual Studio 2012: Use the Package Manager Console to install
the NuGet package for Entity Framework 5 because the latest
version is incompatible with Visual Studio 2012!
3. 4
MOC Errata
Page 03-8 (position 5, 2677)
The MOC says
[AttributeUsage(AttributeTargets.Field)]
Entity Framework
3. 5
Old Approaches
Visual Studio 2008 and .NET 3.5 SP1
Database-First with .edmx and Code Generation
Strategy=Default creates .cs files with ObjectContext and
EntityObject-derived classes
Entity Framework
3. 6
New Approaches
Visual Studio 2012 and .NET 4.5
Database-First or Model-First with .edmx and Code Generation
Strategy=None and .tt files that generate .cs files with
DbContext and POCO classes that works like Code-First
You can delete the .tt files and switch back to old style of
Code Generation Strategy=Default to support features like
Dynamic Data
Or hand-craft your own Code-First POCO and DbContext classes
with or without database initializers
You do not need an .edmx because the model will be created
at runtime
You can use attributes on POCO classes or the fluent API to
customize the runtime model
Code Generation Strategy: Legacy ObjectContext or T4
3. 7
MVC Models
Metadata Annotations
[Display(Name = "FirstName",
ResourceType = typeof(Shared)]
System.ComponentModel
[ReadOnly(true)]: read-only
System.Web.Mvc
System.ComponentModel.DataAnnotations
[DisplayFormat(HtmlEncode = false, NullDisplayText = "Unpaid",
DataFormatString = "{0:c}", ConvertEmptyStringToNull = true,
ApplyFormatInEditMode = false)]
public decimal Salary { get; set; }
// will not be included at all
[ScaffoldColumn(false)]
public decimal Salary { get; set; }
*DisplayAttribute.ResourceType Property
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.resourcetype(v=vs.110).aspx
3. 8
MVC Models
Derived classes
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
[Range(18, 65)]
[RegularExpression(@"\d+")]
[CreditCard]
New in 4.5
[Required(AllowEmptyStrings = false)]
DataType enumeration
CreditCard
Text
DateTime
Html
Date
MultilineText
Time
EmailAddress
Duration
Password
PhoneNumber
Url
Currency
ImageUrl
3. 9
MVC Models
Custom Validation
Two techniques for custom validation
CustomValidationAttribute
Inherit from ValidationAttribute (see next slide)
3. 10
MVC Models
Custom Validation
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = false)]
public class ValidatePasswordLengthAttribute : ValidationAttribute
{
private int MinimumCharacters { get; set; }
public int MaximumCharacters { get; set; }
public ValidatePasswordLengthAttribute(int minChars = 6) : base()
{ // minChars is optional because it has a default value
MinimumCharacters = minChars;
MaximumCharacters = int.MaxValue; // default can be overridden
}
public override bool IsValid(object value)
{ // IsValid throws exception if not overridden
var s = (value as string);
return ((s != null) && (s.Length >= MinimumCharacters)
&& (s.Length <= MaximumCharacters));
}
}
Constructor parameters can be set unnamed if in order
Public properties can be set in attributes
or out of order if named with param: value (not shown)
MVC Models
3. 11
Exam Topic: none
The CLI spec doesnt mention it and if you use IL directly you
can create a generic attribute
The part of the C# 3 spec that bans it - section 10.1.4 Class
base specification doesnt give any justification
Eric Lippert, Microsoft: no particular reason, except to avoid
complexity in both the language and compiler for a use case
which doesnt add much value
Why does C# forbid generic attribute types?
http://stackoverflow.com/questions/294216/why-does-c-sharp-forbid-generic-attribute-types
MVC Models
3. 12
MVC Models
3. 13
Model Binders
There are five model binders built-in to ASP.NET MVC
DefaultModelBinder (most commonly used)
HttpPostedFileBaseModelBinder
ByteArrayModelBinder
LinqBinaryModelBinder
CancellationTokenModelBinder
MVC Models
3. 14
DefaultModelBinder
Maps a browser request to a data object
Provides a concrete implementation of a model binder
3. 15
MVC Models
3. 16
MVC Models
3. 17
MVC Models
Entity Framework
3. 18
Database Initializers
System.Data.Entity has several initializers
CreateDatabaseIfNotExists<TContext>: will recreate and
optionally re-seed the database only if the database doesnt
exist
DropCreateDatabaseAlways<TContext>: will always recreate
and optionally re-seed the database the first time that a
context is used in the app domain
DropCreateDatabaseIfModelChanges<TContext>: will delete,
recreate, and optionally re-seed the database only if the model
has changed since the database was created
MigrateDatabaseToLatestVersion<TContext,
TMigrationsConfiguration>: will use Code First Migrations to
update the database to the latest version
For all, create a derived class and override the Seed method
Database.SetInitializer<TContext> Method
http://msdn.microsoft.com/en-us/library/gg679461(v=vs.113).aspx
3. 19
3. 20
10
3. 21
3. 22
11
3. 23
12
4. 1
Module 4
Developing ASP.NET MVC 4
Controllers
Developing ASP.NET MVC 4
Web Applications
4. 2
Contents
Exam Topic: Design and implement MVC controllers and actions
Implement action behaviors
Implement action results
New in MVC 5: Apply authentication filters
New in MVC 5: Specify an override filter
Exam Topic: Control application behavior by using MVC extensibility points
Implement MVC filters and controller factories
Page 04-4
The MOC says which will return all photos and then take first
Photo firstPhoto = context.Photos.ToList()[0];
4. 3
Filters
Types of Filter
Filters are custom attributes that provide a declarative
means to add pre-action and post-action behavior to
controller action methods
There are built-in filters like [Authorize], [AllowAnonymous],
[HandleError], and you can create custom ones
Filters
4. 4
Pre-Defined Filters
Some common filters
Base classes to inherit from for custom filters: ActionFilter,
Filter (and implement IActionFilter or IResultFilter)
Exception handling: HandleError
HTTP verbs: AcceptVerbs, HttpDelete, HttpGet, HttpHead,
HttpOptions, HttpPatch, HttpPost, HttpPut
4. 5
Filters
Result filter
OnResultExecuting:
cannot change
response but can
cancel response
[MyCustomActionFilter]
[MyCustomResultFilter]
public ActionResult Index()
{
// fetch model
return View(model);
}
// response is returned
OnResultExecuted
Filters
4. 6
Controller.OnException Method
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception(v=vs.118).aspx
4. 7
Filters
Warning!
[MyCustomActionAndResultFilter]
public ActionResult Index()
Filters
4. 8
Global Filters
Global filters are useful to apply a filter to all
controllers and their actions
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute()); // in template already
filters.Add(new AuthorizeAttribute());
// disallow anonymous users
filters.Add(new MyCustomActionAndResultFilterAttribute());
}
4. 9
ViewBag
ViewData is a dictionary of objects that is derived from
ViewDataDictionary and accessible using strings as keys
ViewData["Message"] = "Hello world!";
4. 10
ActionResult
Description
ContentResult
EmptyResult
FileResult
JavaScriptResult
Returns JavaScript
JsonResult
PartialViewResult
RedirectResult,
RedirectToRouteResult
ViewResult
return PartialView();
return Redirect("products/detail/5");
return View();
Design
4. 11
Design
4. 12
4. 13
New in MVC 5
Authentication Filters
using System.Web.Mvc;
using System.Web.Mvc.Filters;
New in MVC 5
4. 14
Overriding Filters
We can exclude a specific action method or controller
from the global filter or controller level filter
OverrideAuthenticationAttribute,
OverrideAuthorizationAttribute, OverrideActionFiltersAttribute,
OverrideResultAttribute, OverrideExceptionAttribute
[Authorize(Users = "Admin")]
public class HomeController : Controller
{
public ActionResult Index() {
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
[OverrideAuthorization]
public ActionResult About() {
return View();
}
5. 1
Module 5
Developing ASP.NET MVC 4
Views
Developing ASP.NET MVC 4
Web Applications
5. 2
Contents
Exam Topic: Compose the UI layout of an application
Implement partials for reuse in different areas of the application
Design and implement pages by using Razor templates (Razor view engine)
Exam Topic: Plan for search engine optimization and accessibility
Use analytical tools to parse HTML
View and evaluate conceptual structure by using plugs-in for browsers
Write semantic markup (HTML5 and ARIA) for accessibility, for example, screen readers
5. 3
MOC Errata
Page 05-32
Task 3: Complete the photo gallery partial view.
6. After the if statement, add a P element, and call the
@Html.DisplayFor helper to render the words Created By:
followed by the value of the item.UserName property.
7. After the UserName display controls, add a P element, and call
the @Html.DisplayFor helper to render the words Created On:
followed by the value of the item.CreatedDate property.
It should say DisplayNameFor
MVC Views
5. 4
MVC Views
5. 5
MVC Views
5. 6
5. 7
MVC Views
@Model.Title
MVC Views
5. 8
5. 9
MVC Views
5. 10
MVC Views
@model NorthwindMvcDemo.Models.Shipper
@Html.DisplayNameFor(model => model.ShipperID) @* => Shipper ID *@
@Html.DisplayFor(model => model.ShipperID) @* 00001 *@
@Html.DisplayNameFor(model => model.CompanyName) @* => Name of Company *@
Html Method
Description
DisplayFor
DisplayNameFor
5. 11
MVC Views
<div>ProductID</div>
<div>@Model.ProductID</div>
Strings to display
Labels, text boxes, and validation to create or update
@Html.LabelFor(m => m.ProductID)
@Html.TextBoxFor(m => m.ProductID)
@Html.ValidationMessageFor(m => m.ProductID)
5. 12
MVC Views
[UIHint("_EmailLink")]
public string Email { get; set; }
ASP.NET MVC Templates - http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1introduction.html/
5. 13
MVC Views
Text to show
HTML
attributes
(or null)
5. 14
MVC Views
@model Customer
<!-- details of a customer -->
<h2>Orders</h2>
@{ Html.RenderPartial("_ListOrders"); }
@Html.Partial("_ListOrders")
_ListOrders.cshtml
When a partial view is created it gets its own copy of the ViewBag
so if it changes the ViewBag then the parents copy is not affected
But changes to the Model are affected!
5. 15
MVC Views
@{ Html.RenderAction
("ListOrders", Model); }
1
public class CustomerController : Controller
{
[ChildActionOnly]
2 public PartialViewResult ListOrders(Customer c)
{
List<Order> orders = GetOrders(c.CustomerID);
return PartialView("_ListOrders", orders);
MVC Views
5. 16
ChildActionOnly Attribute
Designed for Html.Action and Html.RenderAction
@Html.Action("GetMoreModelData")
MVC Views
5. 17
MVC Views
5. 18
5. 19
MVC Views
Build Views
By default Visual Studio doesnt build your views so if
there is a compile error you wont know until you run
the application
This is because it is very slow!
Turn on Compile-time View Checking for ASP.NET MVC Projects in TFS Build 2010
http://blogs.msdn.com/b/jimlamb/archive/2010/04/20/turn-on-compile-time-view-checking-for-asp-net-mvc-projects-in-tfs-build-2010.aspx
5. 20
Multimedia
Video Sources
You can specify a list of alternative sources for
browsers that do not understand some video formats
Can also embed Flash or Silverlight using the object tag
Can also embed text or hyperlink to download a video
<video controls="controls" autoplay="autoplay">
<source src="small.mp4" type="video/mp4" />
<source src="small.ogv" type="video/ogg" />
<!-- embed Flash via the object tag and set parameters -->
<object type="application/x-shockwave-flash"
Mozilla and Opera
width="0" height="0" data="small.swf">
<param name="movie" value="small.swf" />
Internet Explorer
<param name="quality" value="high" />
</object>
<!-- if browser doesnt support Flash either -->
<a href="small.mp4">Download</a> the video as MP4.
</video>
HTML5 Video
http://www.w3schools.com/html/html5_video.asp
https://yoast.com/articles/valid-flash-embedding/
10
6. 1
Module 6
Testing and Debugging ASP.NET
MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
6. 2
Contents
Topic
Error Handling
Slide
3
Debugging
Health Monitoring
13
Testing
17
Code Contracts
27
Comparison of Technologies
30
34
Glimpse
38
6. 3
Error Handling
Default Behaviour
By default, MVC will show detailed unhandled
exceptions including lines of code and the stack trace
which is useful during development but NOT in
production
public ActionResult ThrowError()
{
throw new ArgumentException(
"You asked me to throw an error!");
}
Error Handling
6. 4
6. 5
Error Handling
6. 6
Error Handling
// GET: /Home/Error404
public ActionResult Error404()
{
return View();
}
<customErrors mode="On">
<error statusCode="404" redirect="Home/Error404"/>
To a static page
<customErrors mode="On">
<error statusCode="404" redirect="Error404.html"/>
@Request.QueryString["aspxerrorpath"]
Error Handling
6. 7
Global Filters
Global filters are useful to set up global error handlers
because global filters apply to all controllers and
actions
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// must go before the non-specific HandleError global filter
filters.Add(new HandleErrorAttribute
{
ExceptionType = typeof(DivideByZeroException),
View = "CustomException"
});
filters.Add(new HandleErrorAttribute()); // in template already
}
Error Handling
6. 8
Application Errors
You can log unhandled errors using the Applications
Error event in Global.asax
void Application_Error(object sender, EventArgs e)
{
HttpException ex = Server.GetLastError() as HttpException;
if (ex != null)
{
int httpStatusCode = ex.GetHttpCode(); // e.g. 500
int hresultCode = ex.ErrorCode;
int eventCode = ex.WebEventCode;
}
}
HttpException Class
https://msdn.microsoft.com/en-us/library/system.web.httpexception(v=vs.110).aspx
6. 9
Debugging
Configuring
Debugging for a web site is
controlled via two settings
Debugging
6. 10
Debugging
6. 11
Remote Sites
Visual Studio and IIS on different machines
\Program Files\Microsoft Visual Studio 10.0\Common7\IDE
\Remote Debugger\x86\msvsmon.exe
Run on the remote server prior to debugging (no need to install)
Msvsmon started a new server named user@machine
Administrative rights allow debugging under a different identity
Release Deployment
6. 12
6. 13
Health Monitoring
What Is It?
Events can be intercepted and recorded throughout the
lifetime of an application
Starting or ending a Web application
Successful and unsuccessful authentication attempts
ASP.NET errors
Custom application events
6. 14
Health Monitoring
Event Providers
All inherit from abstract WebEventProvider class
Override ProcessEvent method to implement your own
EventLogWebEventProvider
SqlWebEventProvider
WmiWebEventProvider
Writes to WMI
SimpleMailWebEventProvider
TemplatedMailWebEventProvider
TraceWebEventProvider
6. 15
Health Monitoring
Configuring
Configured in the <healthMonitoring> section
<healthMonitoring heartBeatInterval="5" enabled="true">
<providers>
<bufferModes>
<eventMappings>
<rules>
<profiles>
minInterval
Before another event is logged (non-critical use higher values)
6. 16
Health Monitoring
Custom Extensions
Create custom extensions with IWebEventCustomEvaluator
Allows enabling or disabling the firing of a specific event
Especially useful when you implement your own custom event and
want to control the rate at which it is sent to the related provider
for processing
using System.Web.Management;
IWebEventCustomEvaluator Interface
http://msdn.microsoft.com/en-us/library/system.web.management.iwebeventcustomevaluator.aspx
6. 17
Testing
Types of Tests
Test Level
Description
Unit
Integration
System
Acceptance
Regression
Performance
Load
Stress
Testing
6. 18
6. 19
Testing
[TestMethod]
public void AddNumbersTest()
{
var target = new CalculatorEngine(); // ARRANGE
int a = 2;
int b = 2;
int expected = 4;
int actual;
actual = target.AddNumbers(a, b); // ACT
Assert.AreEqual(expected, actual); // ASSERT
}
Testing
6. 20
10
6. 21
Testing
Assert Class
Fail, Inconclusive, IsTrue, IsFalse, IsNull, IsNotNull,
IsInstanceOfType, IsNotInstanceOfType
The Assert class throws an AssertFailedException to signal a
failure which should not be captured because it is handled by
the unit test engine to indicate an assert failure
AreEqual / AreNotEqual
The two parameters have equivalence (internally uses Equals)
Assert.AreEqual(expected, actual);
AreSame / AreNotSame
6. 22
Testing
NUnit TestCase
TestCaseAttribute
Serves the dual purpose of marking a method with parameters
as a test method and providing inline data to be used when
invoking that method
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void DivideTest(int n, int d, int q)
{
Assert.AreEqual( q, n / d );
[TestCase(12, 3, Result=4)]
}
[TestCase(12, 2, Result=6)]
[TestCase(12, 4, Result=3)]
public int DivideTest(int n, int d)
{
return ( n / d );
}
Examples from NUnit documentation
TestCaseAttribute (NUnit 2.5)
http://www.nunit.org/index.php?p=testCase&r=2.6.3
11
6. 23
Testing
6. 24
Testing
12
Testing
6. 25
Testing
6. 26
Using shims to isolate your application from other assemblies for unit testing
http://msdn.microsoft.com/en-us/library/hh549176.aspx
13
6. 27
Code Contracts
Code Contracts
6. 28
Contract Class
Assume(bool, string) method
Instructs code analysis tools to assume that a condition is true,
even if it cannot be statically proven to always be true, and
displays a message if the assumption fails
Ensures(bool) method
Specifies a postcondition contract for the enclosing method or
property
14
6. 29
Code Contracts
http://www.infoq.com/articles/code-contracts-csharp
https://www.develop.com/csharpcodecontracts
Comparison of Technologies
6. 30
Description
ASP.NET Trace
(Trace.axd)
System.
Diagnostics.
Trace
Provides a set of methods and properties that help you trace the execution
of your code in any .NET application; instrument release builds; helps you
isolate problems and fix them without disturbing a running system
IntelliTrace
Health
Montoring
Performance
Analysis
Visual Studio Profiling Tools let developers measure, evaluate, and target
performance-related issues in their code
Code Analysis
15
Comparison of Technologies
6. 31
<system.web>
<trace enabled="true"
View messages with Trace.axd or send
writeToDiagnosticsTrace="true"/>
a copy to System.Diagostics.Trace
Comparison of Technologies
6. 32
16
6. 33
Comparison of Technologies
6. 34
Browser Link (1 of 2)
Clicking Refresh Linked Browsers refreshes both
17
6. 35
Browser Link (2 of 2)
A communication channel between the development
environment and one or more web browsers
Refresh your web application in several browsers at once, which
is useful for cross-browser testing
Use Ctrl to select multiple browsers for testing
6. 36
Peek Definition
Peek Definition offers a fully functional editor, so you
can change your class (or member) definition according
to your needs without leaving the active window
18
6. 37
Glimpse
What Is It?
6. 38
Exam Topic: none
19
6. 39
Other Tools
Glimpse Installation
To enable Glimpse
Click the Turn Glimpse On button
glimpse.axd
20
7. 1
Module 7
Structuring ASP.NET MVC 4
Web Applications
Developing ASP.NET MVC 4
Web Applications
7. 2
Contents
Exam Topic: Design and implement routes
Define a route to handle a URL pattern
Apply route constraints
Ignore URL patterns
Add custom route parameters
Define areas
SEO
7. 3
Robot Exclusion
Manage all robots.txt files from within IIS Manager
Modify robots.txt files from a GUI interface
SEO
7. 4
Canonical URLs
Canonicalization is the process of picking the best URL
when there are several choices
For example, in ASP.NET MVC all these represent the
home page of your web application
http://www.fb.com/
http://www.fb.com/home
http://www.fb.com/home/index
http://www.fb.com/home/index/
To get best SEO you need only one canonical URL for
your home page and all the others should redirect to it
using a 301 Moved Permanently status code
Remove Trailing Slash From the URLs of Your ASP.NET Web Site With IIS 7 URL Rewrite Module
http://www.tugberkugurlu.com/archive/remove-trailing-slash-from-the-urls-of-your-asp-net-web-sitewith-iis-7-url-rewrite-module
SEO
7. 5
Navigation
To build a usable navigation system, a website designer
has to answer four questions, in this particular order
How do I best structure the content?
How do I best explain the navigational choices?
Which type of navigation menu is best suited to accommodate
the choices?
How do I best design the navigation menu?
SEO
7. 6
Mobile-Friendly Sites
Since 21st April 2015 Google announced that the they
will boost the rankings of mobile-friendly pages
Conversely, pages designed for only large screens may see a
significant decrease in rankings in mobile search results
It has no effect on searches from tablets or desktops only
searches from mobile devices across all languages and locations
7. 7
Routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
Routing
7. 8
7. 9
Routing
Or like this
public ActionResult Index()
7. 10
Routing
URL Patterns
Route definition
{controller}/{action}/{id}
/Products/show/beverages
{resource}.axd/{*pathInfo}
/WebResource.axd?d=123456...
{table}/Details.aspx
/Products/Details.aspx
blog/{action}/{entry}
/blog/show/123
{reporttype}/{year}/{month}/{day}
/sales/2008/1/5
{locale}/{action}
/US/show
{language}-{country}/{action}
/en-US/show
{controller}.mvc/{action}/{id}
/Products.mvc/show/beverages
ASP.NET Routing
http://msdn.microsoft.com/en-us/library/cc668201.aspx
7. 11
Routing
URL
Parameters
/query/select/bikes?color=red
queryname is "select"
queryvalues is "bikes"
Request.QueryString["color"] is "red"
/query/select/bikes/onsale
queryname is "select"
queryvalues is "bikes/onsale"
/query/select/bikes
queryname is "select"
queryvalues is "bikes"
/query/select
queryname is "select"
queryvalues is null
You can only have one segment marked with * and it must be
the last segment and it is automatically optional
Routing
7. 12
Constraints
Routes can use constraints to differentiate
Without the constraint the first route would match both samples
routes.MapRoute(name: "ProductByIntegerRoute",
url: "product/{id}", // product/23
defaults: new { controller = "Product", action = "Details" },
constraints: new { id = "^\d{1,}$" }
);
routes.MapRoute(name: "ProductByStringRoute",
url: "product/{name}", // product/apple
defaults: new { controller = "Product", action = "DetailsByName" }
);
Routing
7. 13
Routing
7. 14
7. 15
Routing
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
Routing
7. 16
7. 17
Routing
routes.MapRoute(
name: "PlaceRoute",
url: "{country}/{city}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { country = new CountryRouteConstraint() }
);
IRouteConstraint Interface
http://msdn.microsoft.com/en-us/library/system.web.routing.irouteconstraint.aspx
Routing
7. 18
Route Debugger
Route Debugger is a little
utility Phil Haack wrote to
help debug issues with route
configurations
install-package routedebugger
Routing
7. 19
URL rewriting typically does not have an API for creating URLs
that are based on your patterns so if you change a pattern, you
must manually update all hyperlinks that contain the original
With ASP.NET routing, the URL is not changed, because routing
can extract values from the URL
When you have to create a URL, you pass parameter values into
a method that generates the URL for you
Using the URL Rewrite Module
http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/
MVC Areas
7. 20
10
MVC Areas
7. 21
Area Registration
When you add an area to a project, a route for the
area is defined in an AreaRegistration file
The route sends requests to the area based on the
request URL
To register routes for areas, you add code to the
Global.asax file that can automatically find the area
routes in the AreaRegistration file
AreaRegistration.RegisterAllAreas();
MVC Areas
7. 22
11
MVC Areas
7. 23
MVC Areas
7. 24
12
8. 1
Module 8
Applying Styles to ASP.NET
MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
8. 2
Contents
Topic
Slide
CSS
MVC Layouts
11
Browsers
14
Mobile Browsers
17
Exam Topic: Enhance application behavior and style based on browser detection
Detect browser features and capabilities
Create a web application that runs across multiple browsers and mobile devices
Vendor-specific CSS extensions
Exam Topic: Plan an adaptive UI layout
Plan for running applications in browsers on multiple devices (screen resolution, CSS, HTML)
Plan for mobile web applications
8. 3
CSS
<div class="removeMe">Hello</div>
<div class="hideMe">Hello</div>
CSS
/* to remove from layout */
.removeMe {
display: none;
}
/* to hide */
.hideMe {
visibility: hidden;
}
JavaScript
// to disable a
elem.disabled =
// to enable an
elem.disabled =
control
true;
control
false;
8. 4
CSS
nth-child selector
nth-child can accept numbers, special keywords such as
odd and even, and even formulae (n starts at 0)
ul li:nth-child(2) {
color: red;
}
ul li:nth-child(odd) {
color: red;
}
ul li:nth-child(3n + 2) {
color: red;
}
<ul>
<li>Aaa</li>
<li>Bbb</li>
<li>Ccc</li>
<li>Ddd</li>
<li>Eee</li>
<li>Fff</li>
<li>Ggg</li>
<li>Hhh</li>
</ul>
8. 5
CSS
nth-child vs nth-of-type
nth-child is commonly used although nth-of-type is
usually better
<div>
<p>Apples</p>
<p>Bananas</p>
</div>
<div>
<h1>Heading</h1>
<p>Apples</p>
<p>Bananas</p>
</div>
<div>
<h1>Heading</h1>
<h2>Sub</h2>
<p>Apples</p>
<p>Bananas</p>
</div>
p:nth-child(2) {
color: red;
}
p:nth-of-type(2) {
background-color: yellow;
}
8. 6
CSS
Printing
style and link elements support the MEDIA attribute,
which defines the output device for the style sheet
Values for MEDIA are screen (default), print and all
The print value specifies that the style sheet is used when the
page is printed; this value does not affect how the document
will be displayed onscreen
<style type="text/css" media="print">
div.page {
page-break-before: always;
}
</style>
8. 7
CSS
Media Queries
Different style sheets for different scenarios
<link rel='stylesheet' media='only screen and (max-width: 700px)'
href='css/narrow.css' />
CSS Specification: The keyword only can also be used to hide style
sheets from older user agents. User agents must process media
queries starting with only as if the only keyword was not present.
<link rel='stylesheet'
media='only screen and (min-width: 701px) and (max-width: 900px)'
href='css/medium.css' />
8. 8
CSS
8. 9
MVC Layouts
http://www.contoso.com/home/index/
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
@{
2a
if (User.IsInRole("Admin"))
Layout = "~/Views/Shared/_AdminLayout.cshtml";
ViewBag.Title = "Welcome to the Home Page";
}
<h2>Welcome to the Home Page</h2> 3b
@section scripts {
<script>
4b
alert('hello');
</script>
/Home/Index.cshtml
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
2b <title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody() 3a
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false) 4a
</body>
/Views/Shared/_Layout.cshtml
</html>
MVC Layouts
8. 10
_ViewStart
When using Visual Studio project templates they create
a Shared/_Layout.cshtml and a _ViewStart.cshtml
_ViewStart.cshtml is executed before every View is displayed to
set initial properties for the View such as Layout
Each View sub-folder can have its own _ViewStart.cshtml
Note
If you use PartialView() in your controllers instead of View()
then _ViewStart.cshtml will not be executed
8. 11
DisplayModeProvider.Instance.Modes.Insert(0,
new DefaultDisplayMode("iPhone") { ContextCondition =
(ctx => ctx.Request.UserAgent.IndexOf("iPhone",
StringComparison.OrdinalIgnoreCase) >= 0) });
You can then create specific views for this type of device by
giving them names such as xyz.iphone.cshtml
8. 12
8. 13
Mobile-Aware OutputCache
Override in Global.asax
public override string GetVaryByCustomString(
HttpContext context, string custom)
{
if ((context.Request.Browser.IsMobileDevice) &&
(custom == "IsMobile")) return "mobile";
base.GetVaryByCustomString(context, string);
ASP.Net MVC4 Mobile-Aware OutputCache
http://stackoverflow.com/questions/9605085/asp-net-mvc4-mobile-aware-outputcache
Browsers
8. 14
Browsers
8. 15
Browsers
8. 16
GetOverriddenBrowser()
Returns the browser capabilities object for the overridden
browser capabilities or for the actual browser if no override has
been specified
8. 17
Mobile Browsers
View Port
Mobile browsers render pages in a virtual window
(the viewport), usually wider than the screen
Users can pan and zoom to see different areas of the page
8. 18
Mobile Browsers
<meta name="viewport"
content="width=device-width">
<meta name="viewport"
content="width=device-width, initial-scale=0.5, user-scalable=no">
Using the viewport meta tag to control layout on mobile browsers
https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag?redirectlocale=en-US&redirectslug=Mobile%2FViewport_meta_tag
9. 1
Module 9
Building Responsive Pages in
ASP.NET MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
9. 2
Contents
Topic
Slide
Caching Overview
System.Web.Caching
System.Runtime.Caching
10
OutputCache
13
Caching Configuration
15
Downstream Caching
16
19
HTML5 Prefetch
21
Performance
22
9. 3
Ajax.ActionLink
MOC page 09-4: unnecessary to add [HttpGet]
MOC code on page 09-5
@Ajax.ActionLink("Refresh", "HelloWorld", new AjaxOptions {
HttpMethod = "POST", UpdateTargetId = "divMessage",
InsertionMode = InsertionMode.Replace })
InsertionMode
Replace, ReplaceWith, InsertBefore, InsertAfter
AjaxOptions Class
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions(v=vs.108).aspx
9. 4
9. 5
Caching Overview
Types of Caching
Caching stores frequently accessed data in memory
where it can be retrieved faster than it could be from a
file or database
ASP.NET MVC has two types of caching
9. 6
System.Web.Caching
using System.Web.Caching;
9. 7
System.Web.Caching
value
dependencies
absoluteExpiration
slidingExpiration
priority
onRemoveCallback
* NotRemovable means that Microsoft's algorithm will not remove such an item when
you get low on memory, but that it can expire or be removed by a dependency
9. 8
System.Web.Caching
using System.Web.Caching;
9. 9
System.Web.Caching
SqlCacheDependency
Modify the web.config
<caching>
<sqlCacheDependency enabled="true" pollTime="30000">
<databases>
<add name="Northwind" connectionStringName="NorthwindConnection"/>
using System.Web.Caching;
9. 10
System.Runtime.Caching
9. 11
System.Runtime.Caching
Get("foo")
Get("foo")
Set("foo", "something")
Thread 2
Thread 1
System.Runtime.Caching
9. 12
CacheItemPolicy
Represents a set of eviction and expiration details for a
specific cache entry
AbsoluteExpiration: DateTime
SlidingExpiration: TimeSpan
Priority: Default, NotRemovable
ChangeMonitors: CacheEntryChangeMonitor,
HostFileChangeMonitor, SqlChangeMonitor
UpdateCallback: before object is removed
RemovedCallback: after object is removed
CacheEntryUpdateArguments Class
http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheentryupdatearguments(v=vs.110).aspx
ChangeMonitor Class
http://msdn.microsoft.com/en-us/library/system.runtime.caching.changemonitor(v=vs.110).aspx
CacheItemPolicy Class
http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy(v=vs.110).aspx
9. 13
OutputCache
OutputCache Attribute
Cache the view of an action method for 15 seconds
Each route gets its own copy of the cached view
/Product/Detail/1
/Product/Detail/2
9. 14
OutputCache
Configuring Caching
Duration
VaryByParam
Location
CacheProfile
NoStore
SqlDependency
VaryByCustom
VaryByHeader
VaryByContentEncoding
Caching Configuration
9. 15
Downstream Caching
9. 16
Response.Cache Location
Use SetCacheability(HttpCacheability) to control
caching in intermediaries and browsers
Response.Cache.SetCacheability(HttpCacheability.Public);
NoCache, Server,
ServerAndNoCache
Private
Public
ServerAndPrivate
HttpCacheability Enumeration
http://msdn.microsoft.com/en-us/library/system.web.httpcacheability(v=vs.110).aspx
Downstream Caching
9. 17
HttpCachePolicy.SetAllowResponseInBrowserHistory Method
http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setallowresponseinbrowserhistory(v=vs.110).aspx
Downstream Caching
9. 18
Response.Cache Expiry
You can control how long responses get cached
Sets the Expires HTTP header to an absolute date and time
Response.Cache.SetExpires(DateTime.Parse("6:00:00PM"));
// expire in one minute
Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0));
HttpCachePolicy.SetExpires Method
http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setexpires(v=vs.110).aspx
9. 19
AppFabric Caching
Build highly responsive applications using a distributed
cache that scales independently from your application
DataCache cache = new DataCache("default");
// Add the string "value" to the cache, keyed by "item"
cache.Add("item", "value", TimeSpan.FromMinutes(30));
DataCacheItem item = cache.GetCacheItem("item");
TimeSpan timeRemaining = item.Timeout;
using Microsoft.ApplicationServer.Caching;
Note: there are better options, for example, Redis cache (see
next slide)
Microsoft.ApplicationServer.Caching Namespace
https://msdn.microsoft.com/en-us/library/microsoft.applicationserver.caching(v=azure.10).aspx
9. 20
Redis Cache
Cache
http://azure.microsoft.com/en-us/documentation/services/cache/
10
HTML5 Prefetch
9. 21
Link Prefetching
Link prefetching is a browser mechanism which utilizes
browser idle time to download or prefetch documents
that the user might visit in the near future
<link rel="prefetch" href="/Home/About">
Performance
9. 22
Three takeaways for web developers after two weeks of painfully slow internet
https://medium.com/@zengabor/three-takeaways-for-web-developers-after-two-weeks-of-painfully-slow-internet-9e7f6d47726e
11
Performance
9. 23
Performance
9. 24
12
9. 25
Performance
YSlow
YSlow analyzes web pages and suggests ways to
improve their performance based on a set of rules for
high performance web pages
Top Twelve Rules
1. Minimize HTTP Requests
4. Add an Expires or
a Cache-Control Header
5. Gzip Components
YSlow
http://developer.yahoo.com/yslow/
Performance
9. 26
CSS Sprites
http://alistapart.com/article/sprites
13
9. 27
Performance
9. 28
Performance
<link href="">
14
9. 29
Performance
Performance
9. 30
5. Gzip Components
Web clients indicate support for compression with the
Accept-Encoding header in the HTTP request
Accept-Encoding: gzip, deflate
15
Performance
9. 31
Performance
9. 32
16
Performance
9. 33
Performance
9. 34
17
Performance
9. 35
18
10. 1
Module 10
Using JavaScript and jQuery for
Responsive MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
10. 2
Contents
Exam Topic: Design and implement UI behavior
Implement client validation
Use JavaScript and the DOM to control application behavior
Extend objects by using prototypal inheritance
Implement the UI by using JQuery
Exam Topic: Reduce network bandwidth
Bundle and minify scripts (CSS and JavaScript)
Compress and decompress data (using gzip/deflate; storage)
Plan a content delivery network (CDN) strategy, for example, Windows Azure CDN
MOC Errata
Position 12-2694: debug=false will enable (NOT disable)
minification for any bundled file without a .min. file extension
10. 3
Optimization
Minification
Stripping whitespace and comments and unused functions and
using shorter variable and parameter names
(function(){console.log(10)})()
Compression
(function () { // firebrand
var apples = 10;
function neverUsed() {
console.log("never used");
}
console.log(apples);
})();
Optimization
10. 4
10. 5
Optimization
Release mode
<compilation debug="false" />
<script src="/bundles/bootstrap?v=2Fz3B0iizV2NnnamQFrxNbYJNTFeBJ2GM05SilbtQU1"></script>
10. 6
Optimization
to this
function StartController(n, t, i) { }
10. 7
Optimization
Compression Negotiation
Browser makes a request with this header to tell the
server what compression algorithms it understands
Accept-Encoding: gzip, deflate
Content-Encoding: deflate
Optimization
10. 8
10. 9
Optimization
HTTP Compression
What is gzip compression ratio?
It depends!
File
~120kb
Little or no compression
~2:1 compression
10. 10
jQuery
jQuery UI
A curated set of user interface
interactions, effects, widgets, themes
Interactions: Draggable, Droppable, Resizable,
Selectable, Sortable
Widgets: Accordian, Autocomplete, Button, Datepicker, Dialog,
Menu, Progressbar, Selectmenu, Slider, Spinner, Tabs, Tooltip
<div id="slider"></div>
$(function () {
$("#slider").slider();
});
$(function () {
$("#datepicker").datepicker();
});
10. 11
What Is It?
The Microsoft Ajax Library includes a rich framework to
simplify client programming
It was created for ASP.NET 3.5 and is included in any Web Forms
file that adds a ScriptManager
10. 12
10. 13
HTTP/2
What Is It?
HTTP/2
https://http2.github.io/
Changes to Bundling
10. 14
Exam Topic: none
Introducing Gulp, Grunt, Bower, and npm support for Visual Studio
http://www.hanselman.com/blog/IntroducingGulpGruntBowerAndNpmSupportForVisualStudio.aspx
11. 1
Module 11
Controlling Access to ASP.NET
MVC 4 Web Application
Developing ASP.NET MVC 4
Web Applications
11. 2
Slide
IIS
Authentication
Authorization
Forms Authentication
11
ASP.NET Membership
13
Impersonation
18
19
Custom Security
22
Token Formats
25
ASP.NET Identity
27
Exam Topic: Design and implement claims-based authentication across federated identity stores
Implement federated authentication by using Windows Azure Access Control Service
Create a custom security token by using Windows Identity Foundation
Handle token formats (for example, oAuth, OpenID, Google) for SAML and SWT tokens
11. 3
IIS
IIS Manager
11. 4
IIS
Application Pools
Classic means
act like IIS 6.0
that keeps IIS
and ASP.NET
separate rather
than integrated
Default identity
of the threads
running your app
11. 5
Authentication
IIS Authentication
Basic
Digest
Windows
Integrated
IE/Firefox auto-login
Use Forms for sites where a web page is used to login and users and
passwords are stored in a Membership provider such as SQL Server or
Active Directory
IIS Authentication
Anonymous
IUSR_computername
11. 6
Authentication
11. 7
Authorization
MVC Authorizing
To ensure users are authenticated
Anonymous users will be redirected to login view
[Authorize]
public ActionResult Create()
Authorization
11. 8
MVC Authorizing
If you apply Authorize to a whole class, you can still
allow anonymous for individual actions
[Authorize] // require all actions to authenticate (not allow anonymous)
public class ProductController : Controller
{
[AllowAnonymous] // allow anonymous just for this action
public ActionResult Index()
{
public ActionResult Display() // inherit from controller
{
// inherit from controller AND add additional requirements
[Authorize(Users="Mary,Omar", Roles="Admin")]
Roles value could be Windows
public ActionResult Edit()
Groups e.g. DOMAIN\Sales
{
11. 9
Authorization
Authorization
11. 10
11. 11
Authorization
if (User.IsInRole("Sales"))
Name
if (User.Identity.Name == "Fred")
if (Roles.IsUserInRole("John", "HR"))
Forms Authentication
11. 12
Configuring
Defaults for strings are shown, others are underlined
<system.web>
Cookie name
<authentication mode="Forms">
<forms name=".ASPXAUTH"
Change to MVC routes
loginUrl="login.aspx"
defaultUrl="default.aspx"
protection="[All|None|Encryption|Validation]"
timeout="30"
minutes
If true you must configure SSL certificate in IIS
path="/"
requireSSL="[true|false]"
slidingExpiration="[true|false]"
enableCrossAppRedirects="[true|false]"
cookieless="[UseUri|true|UseCookies|false|AutoDetect|UseDeviceProfile]"
domain=""
ticketCompatibilityMode="[Framework20|Framework40]">
<credentials>
<user name="Bob" password="secret"/>
</credentials>
forms Element for authentication (ASP.NET Settings Schema)
http://msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx
Forms Authentication
11. 13
FormsAuthentication Properties
Static read-only properties (set in .config)
IsEnabled, FormsCookieName, FormsCookiePath, RequireSSL,
SlidingExpiration, CookieDomain, CookieMode, DefaultUrl,
LoginUrl, Timeout
Methods
SetAuthCookie, GetAuthCookie: Creates an authentication
ticket for the supplied user name and adds it to the cookies
collection of the response
Encrypt, Decrypt: Creates a string containing an encrypted
forms-authentication ticket suitable for use in an HTTP cookie
RedirectFromLoginUrl, GetRedirectUrl: Redirects user back to
the originally requested URL or the default URL
SignOut: Removes the forms-authentication ticket from browser
FormsAuthentication Class
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.aspx
ASP.NET Membership
11. 14
Providers
SqlMembershipProvider in .NET 2.0 and later
Uses fixed schema for users and roles (aspnetdb.mdf by default)
Focused on traditional membership (user has a username and a
password), in OAuth/OpenID the user doesnt have a password
11. 15
ASP.NET Membership
SimpleMembershipProvider
SimpleRoleProvider simply implements the
RoleProvider abstract base class (from .NET 2.0) and
does not add anything more
ExtendedMembershipProvider abstract class inherits
from the core MembershipProvider abstract base class
Also added a new WebSecurity class which provides a nice
faade to SimpleMembershipProvider
11. 16
ASP.NET Membership
CreateNewRole
DeleteRole
FindUsersInRole
GetAllRoles
GetRolesForUser
IsUserInRole
RemoveUserFromRole
RemoveUserFromRoles
RemoveUsersFromRole
RemoveUsersFromRoles
11. 17
ASP.NET Membership
DeleteUser
FindUserByEmail
FindUserByName
Gets a collection of membership users for whom the email addresses contain the specified e-mail addresses
or user names to match
GeneratePassword
GetAllUsers
GetUserByEmail
Gets a user name for which the e-mail address for the
user matches the specified email address
UpdateUser
ValidateUser
using System.Web.Security;
if (Membership.ValidateUser("Fred", "secret"))
ASP.NET Membership
11. 18
Longest is:
GetTextEffectCharacterIndexFromTextSourceCharacterIndex
Impersonation
11. 19
11. 20
How to Authenticate Web Users with Azure Active Directory Access Control
http://azure.microsoft.com/en-gb/documentation/articles/active-directory-dotnet-how-to-use-access-control/
10
11. 21
Getting Claims
ClaimsIdentity class
Extends the IIdentity interface to incorporate functionality
needed to implement claims-based identity
For example, it adds a Claims property that can be enumerated
var identity = (ClaimsIdentity)User.Identity;
foreach (Claim claim in identity.Claims)
ClaimsIdentity Class
https://msdn.microsoft.com/en-us/library/system.security.claims.claimsidentity(v=vs.110).aspx
11. 22
Description
Type
A string (typically a URI) that contains the semantic information about the claim,
e.g., a claim with a type of GivenName represents a users first name
(http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname)
Value
ValueType
It is recommended that you use standard XML schema types in the ValueType
property to indicate how the Value property is meant to be serialized into and
deserialized from a string
Subject
The entity (typically the user who is requesting access to a resource) about
which the claim is asserted
Issuer
Claim Class
http://msdn.microsoft.com/en-us/library/system.security.claims.claim(v=vs.110).aspx
11
11. 23
ClaimTypes Class
https://msdn.microsoft.com/en-us/library/vstudio/system.identitymodel.claims.claimtypes(v=vs.110).aspx
Custom Security
11. 24
12
Custom Security
11. 25
ClaimsAuthorizationManager
.NET 4.5 ships with a claims-based authorization
infrastructure around the ClaimsAuthorizationManager
class
Claims-based authorization encourages you to have a clean
separation of business and authorization code and thats much
better than sprinkling role checks all over your code base
but the API is not very approachable, especially in the face of
modern application development like MVC or Web API
All the base APIs in .NET 4.5 allow using claims-based
authorization, you just have to write your own plumbing
Thinktecture.IdentityModel contains an authorization filter
called ClaimsAuthorizeAttribute to make the connection to
ClaimsAuthorizationManager (see link below for details)
Using Claims-based Authorization in MVC and Web API
http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/
Token Formats
11. 26
Supported in ACS
ACS can issue security tokens in the following formats
Security Assertion Markup Language (SAML) 1.1 and 2.0
<assertion id="_4fe09cda-cad9-49dd-b493-93494e1ae4f9"
issueinstant="2012-09-18T20:42:11.626Z"
version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
<issuer>https://test05.accesscontrol.windows.net/</issuer>
13
11. 27
Token Formats
SecurityTokenHandler
The SecurityTokenHandler class is the base class from
which all security token handlers derive
Windows Identity Foundation (WIF) ships the following
security token handlers out of the box:
EncryptedSecurityTokenHandler, KerberosSecurityTokenHandler,
MachineKeySessionSecurityTokenHandler,
MembershipUserNameSecurityTokenHandler,
RsaSecurityTokenHandler, Saml2SecurityTokenHandler,
SamlSecurityTokenHandler, SessionSecurityTokenHandler,
UserNameSecurityTokenHandler,
WindowsUserNameSecurityTokenHandler,
X509SecurityTokenHandler
SecurityTokenHandler Class
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler(v=vs.110).aspx
11. 28
ASP.NET Identity
14
ASP.NET Identity
11. 29
ASP.NET Identity
11. 30
Registering
When the user clicks the Register
button, the Register action of the
Account controller creates the user by
calling the ASP.NET Identity API
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
15
ASP.NET Identity
11. 31
Signing In
If the user was successfully created, she is logged in by
the SignInAsync method
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(
user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties()
{ IsPersistent = isPersistent }, identity);
}
ASP.NET Identity and OWIN Cookie Authentication are claimsbased system so the framework requires the app to generate a
ClaimsIdentity for the user using CreateIndentityAsync
ASP.NET Identity Stripped Bare - MVC Part 1
http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1
ASP.NET Identity
11. 32
Tutorial
MVC 5 with Google and Facebook authentication
This tutorial shows you how to build an ASP.NET MVC 5 web
application that enables users to log in using OAuth 2.0 or
OpenID with credentials from an external authentication
provider, such as Facebook, Twitter, Microsoft, or Google
For simplicity, this tutorial focuses on working with credentials
from Facebook and Google
Enabling these credentials in your web sites provides a
significant advantage because millions of users already have
accounts with these external providers
These users may be more inclined to sign up for your site if they
do not have to create and remember a new set of credentials
The tutorial also shows how to add profile data for the user, and
how to use the Membership API to add roles
Code! MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on
http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
16
12. 1
Module 12
Building a Resilient ASP.NET
MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
12. 2
Contents
Topic
Slide
Preventing Attacks
State Management
12
Protecting Data
29
Further Study
42
Preventing Attacks
12. 3
SQL Injection
Exploits of a Mom
http://xkcd.com/327/
Preventing Attacks
12. 4
SQL Injection
In which malicious code is inserted into strings that are
passed to an SQL database for parsing and execution
For example, this bad code reads a value posted from a web
form and concatenates it into a SQL statement
var city = Request.Form["ShipCity"];
var sql = "select * from OrdersTable where ShipCity = '" + city + "'";
SQL Injection
http://msdn.microsoft.com/en-us/library/ms161953.aspx
12. 5
Preventing Attacks
SQL Injection
http://www.gutizz.com/encoded-sql-injection/
http://www.blackhatlibrary.net/SQL_injection
Preventing Attacks
12. 6
12. 7
Preventing Attacks
12. 8
Preventing Attacks
Request Validation
ASP.NET validates requests for potentially dangerous
values (like JavaScript) automatically
Throws HttpRequestValidationException if it finds problem
[AllowHtml]
public string Contents { get; set; }
Preventing Attacks
12. 9
HttpRequest.Unvalidated
To disable request validation for a specific field in a
request (for example, for an input element or query
string value), check Request.Unvalidated when you get
the item
var rawComment = Request.Unvalidated.Form["comment"];
HttpRequest.Unvalidated Property
http://msdn.microsoft.com/en-us/library/system.web.unvalidatedrequestvalues.aspx
Preventing Attacks
12. 10
Requiring HTTPS
Use the RequireHttpsAttribute to prevent unsecured
HTTP requests from being sent to an action method
[RequireHttps] // applies to all actions in controller
public class SomeController
{
[RequireHttps] // applies to this action only
public ActionResult SomeAction()
12. 11
Preventing Attacks
Summary
Feature
Description
Anti-forgery tokens
Symmetric encryption
Asymmetric encryption
SQL parameters
12. 12
State Management
Server-side
Client-side
Overview
Technology
Lifetime
Encrypted
Shared?
Max.
Size
Always
Available
QueryString
Single request
No
Per user
1 KB
Cookies
In-memory: while
browser is running.
In-file: until cookie
cache is cleared or
cookie expires.
Per user
4 KB
ViewState &
ControlState
(Web Forms
only)
Not by default;
ViewStateEnc
ryptionMode:
Auto, Always, Never
Per user
n/a
Session1
While browser is
running (because it
stores session ID in
an in-memory cookie).
Not necessary
Per user
n/a
Application
While ASP.NET
application is running
(e.g. for months).
Not necessary
All users
n/a
Server affinity aka sticky sessions is a feature of load balancers that ensures a request from a
particular browser is always handled by the same server in a web farm meaning session state can stay InProc
1
State Management
12. 13
State Management
12. 14
State Management
12. 15
State Management
12. 16
(firstName=Tony) (border=blue)
State Management
12. 17
Query Strings
Typical query string in URL
http://search.microsoft.com/results?mkt=en-US&q=hello+world
State Management
12. 18
Application State
Application state is shared and used to store
information that is not user-specific
An instance of the HttpApplicationState class
State Management
12. 19
Application_End
Application is ending; use to free application resources
Application_Error
An unhandled error has occurred
Application_LogRequest
A request has been made; use to log information about requests
State Management
12. 20
StateServer
Stores session state in memory of a service called the ASP.NET
State Service; could be on same web server or another machine
Type must be serializable
SQLServer
Stores session state in a SQL Server database; session state must
be enabled on the database; type must be serializable
Slowest mode, but most recoverable
Off
<system.web>
<sessionState mode="Off" />
10
12. 21
State Management
12. 22
State Management
11
State Management
12. 23
State Management
12. 24
12
State Management
12. 25
Session_End
Raised when a session is abandoned or expires
but only when using InProc session mode
State Management
12. 26
Or a specified identity
<identity impersonate="true"
username="..." password="..." />
13
12. 27
State Management
Design Choices
Technology
PROs
CONs
Cookie
QueryString
ViewState
Session
Application
Simple
Cache
In-memory only
TempData
ViewData,
ViewBag
Simple
State Management
12. 28
machineKey Element
Controls tamper proofing and encryption of ViewState,
forms authentication tickets, and role cookies
For a single server the defaults are sufficient, but in a web farm
you must manually configure all servers to use the same keys
<machineKey validationKey="AutoGenerate,IsolateApps"
decryptionKey="AutoGenerate,IsolateApps"
validation="HMACSHA256" [SHA1|MD5|3DES|AES|HMACSHA256|HMACSHA384|HMACSHA512]
decryption="Auto" [Auto|DES|3DES|AES|alg:algorithm_name] />
14
Protecting Data
12. 29
Protecting Data
12. 30
15
Protecting Data
12. 31
SymmetricAlgorithm Properties
All symmetric algorithm implementations derive from
System.Security.Cryptography.SymmetricAlgorithm
Important properties
Mode: defaults to CipherMode.CBC (Cipher Block Chaining)
LegalKeySizes and LegalBlockSize: array of KeySize elements
Each has MaxSize and MinSize and SkipSize
Protecting Data
12. 32
SymmetricAlgorithm Methods
Important methods
CreateEncryptor(): creates the object that needs to be passed
to a CryptoStream
CreateDecryptor(): creates the object that needs to be passed
to a CryptoStream
GenerateIV(): re-generates a random IV
16
12. 33
Protecting Data
Managed
CryptoServiceProvider
Block Size
Key Size
Comment
DES
64 bit / 8 byte
56 bit / 7 byte
RC2
64 bit / 8 byte
40128 bit /
5-16 byte
(increments of 1)
Triple
DES
64 bit / 8 byte
128-192 bit /
16-24 byte
Rijndael
128-256 bit
(increments of
32 bit)
Aes
128 bit /
16 byte
In general, Triple DES with three independent keys has a key length of 168 bits (three 56-bit DES
keys), but due to the meet-in-the-middle attack, the effective security it provides is only 112 bits
2
12. 34
Protecting Data
using System.Security.Cryptography;
using System.Text;
17
12. 35
Protecting Data
Asymmetric Encryption
RSACryptoServiceProvider
Can encrypt, decrypt, hash and sign
Name comes from initials of three men who invented it
12. 36
Protecting Data
var
var
var
var
var
using System.Text;
clearText = "Hello, World!";
rsa = new RSACryptoServiceProvider();
clearBytes = Encoding.Unicode.GetBytes(clearText);
cryptoText = rsa.Encrypt(clearBytes, false);
xmlKey = rsa.ToXmlString(true); // export the key
18
12. 37
Protecting Data
12. 38
Protecting Data
19
12. 39
Protecting Data
Example
12. 40
Protecting Data
Public/Private Encrypt/Sign
Alice needs to send data to Bob securely
Alice must encrypt her data by using Bobs public key
Alices Data
Alices Encrypted
Alice must sign her encrypted data using her private key
Alices Encrypted
Alices Signed
Alices Data
20
12. 41
Protecting Data
Summary
To Do This
Use This
Rfc2898DeriveBytes (best)
PasswordDeriveBytes (deprecated)
AesManaged (best)
RijndahlManaged
RC2CryptoServiceProvider
TripleDESCryptoServiceProvider
DESCryptoServiceProvider (worst)
RSACryptoServiceProvider
DSACryptoServiceProvider
RNGCryptoServiceProvider
SHA512CryptoServiceProvider (best)
SHA256CryptoServiceProvider
SHA1CryptoServiceProvider
MD5CryptoServiceProvider (worst)
HMACSHA1CryptoServiceProvider
DSACryptoServiceProvider
Further Study
12. 42
Troy Hunt
About
Microsoft MVP for Developer Security, Pluralsight author and
international speaker, youll usually find Troy talking about web
security and The Cloud
21
Further Study
12. 43
.Net Havoc - Manipulating Properties of Dormant Server Side Web Controls, Shay Chen
https://vimeo.com/channels/44con2013/109380787
22
13. 1
Module 13
Using Windows Azure Web Services in
ASP.NET MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
13. 2
Contents
Exam Topic: Debug a Windows Azure application
Collect diagnostic information by using Windows Azure Diagnostics API Implement on demand vs. scheduled
Choose log types, for example, event logs, performance counters, and crash dumps
Debug a Windows Azure application by using remote debugging
New in Visual Studio 2013: Interact directly with remote Windows Azure websites using Server Explorer
Exam Topic: Design and implement the Windows Azure role life cycle
Identify and implement Start, Run, and Stop events
Identify startup tasks (IIS configuration [app pool], registry configuration, third-party tools)
13. 3
MOC Errata
Page 13-12
The MOC slide says
13. 4
Microsoft Azure
Description
ServiceDefinition.csdef
Defines:
- Endpoints for communicating between VMs
- Size of VM and upgrade domain count
- Modules for diagnostics, RDP, and so on
- Certificates
- Startup tasks and environment variables
- Configuration settings to load from .cscfg
ServiceConfiguration.cscfg
Configures:
- Number of instances of each type of VM
- Certificates
- Values of configuration settings
WebRole.cs, WorkerRole.cs
Web.config
13. 5
Microsoft Azure
Startup Tasks
(ServiceDefinition.csdef)
Microsoft Azure
13. 6
13. 7
Microsoft Azure
Run Method
The Run is considered the Main method for your
application
Overriding the Run method is not required; the default
implementation never returns
If you do override the Run method, your code should block
indefinitely
If your Run method returns, the
role is automatically recycled
by raising the Stopping event
and calling the OnStop method
so that your shutdown
sequences may be executed
before the role is taken offline
RoleEntryPoint.Run Method
https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.serviceruntime.roleentrypoint.run.aspx
Microsoft Azure
13. 8
Process.WaitForExit Method
http://msdn.microsoft.com/en-us/library/fb4aw7b8.aspx
13. 9
Microsoft Azure
(ServiceDefinition.csdef)
13. 10
Microsoft Azure
Diagnostics Logs
(ServiceDefinition.csdef)
ISO 8601:
Period Time 1 Minute
http://msdn.microsoft.com/en-us/library/gg593185.aspx
http://en.wikipedia.org/wiki/ISO_8601#Durations
Microsoft Azure
13. 11
Securing and authenticating azure service bus relay messages using a shared secret
http://acaseyblog.wordpress.com/2013/03/22/securing-and-authenticating-azure-service-bus-relay-messages-using-a-shared-secret/
WCF Services
13. 12
WCF Services
13. 13
Create a binding
var binding = new WSHttpBinding();
WCF Services
13. 14
13. 15
Data Contracts
<Order>
<OrderID>1</OrderID>
<BillTo>
<Street>High Street</Street>
<City>London</City>
<Country>UK</Country>
</BillTo>
<ShipTo>
<Street>High Street</Street>
<City>London</City>
<Country>UK</Country>
</ShipTo>
</Order>
Data Contracts
13. 16
Misc
13. 17
13. 18
14. 1
Module 14
Implementing Web APIs in
ASP.NET MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
14. 2
Contents
Exam Topic: none (but they are wrong!)
14. 3
14. 4
HTTP Method
Relative URI
GET
/api/orders
GET
/api/orders/id
Retrieve by custom
GET
/api/orders?category=category
POST
/api/orders
Update entity
PUT
/api/orders/id
Remove entity
DELETE
/api/orders/id
14. 5
Web API
Clients
Clients to Web API can be any language and platform
that can make HTTP requests
Best practice for .NET clients
Create your models in a separate Class Library project so they
compile to a DLL assembly and be given to .NET developers for
use with the HttpClient class
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:801/MyWebApiService");
var response = await client.GetAsync(@"api\person");
var person = await response.Content.ReadAsAsync<Person>();
14. 6
14. 7
14. 8
15. 1
Module 15
Handling Requests in ASP.NET
MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
15. 2
Contents
Topic
Slide
HTTP Modules
HTTP Handlers
12
SignalR
14
15. 3
Implement
this interface
with these
required methods
or inherit from
this class
MVC controller
IController
Execute
Controller
Action filter
IActionFilter
OnActionExecuting
OnActionExecuted
ActionFilterAttribute
Result filter
IResultFilter
OnResultExecuting
OnResultExecuted
ActionFilterAttribute
Route handler
IRouteHandler
GetHttpHandler
MvcRouteHandler
Route constraint
IRouteConstraint
Match
HttpMethodConstraint
HTTP handler
IHttpHandler
IsReusable, ProcessRequest
MvcHandler
HTTP handler
(asynchronous)
IHttpAsyncHandler
IsReusable, ProcessRequest,
BeginProcessRequest,
EndProcessRequest
n/a
SendAsync
HTTP module
IHttpModule
Init, Dispose
DelegatingHandler
Notes: Controllers and filters are covered in Module 4: Developing ASP.NET MVC 4 Controllers
Route handlers and constraints are covered in Module 7: Structuring ASP.NET MVC 4 Web Applications
HTTP handlers and modules are covered in this module.
HTTP Modules
15. 4
Implementing
HTTP handlers only process requests for file extensions
they are registered for; if you want to process all
requests, use an HTTP module instead
Create a class that implements IHttpModule
public class MyModule : IHttpModule
Implement Name property and Init method and add handlers for
any events you want to intercept
public void Init(HttpApplication a)
{
this.app = a;
this.app.BeginRequest += LogAllRequestsMethod;
15. 5
HTTP Modules
Configuring
HTTP module must be registered in .config
For IIS 6 or IIS 7 or later in Classic mode
<system.web>
<httpModules>
<add name="MyMod" type="MyNamespace.MyModule" />
15. 6
HTTP Modules
Ordering
Order modules are
processed is defined in
.config file
Order of events
(non-deterministic)
Order of events
(sequential)
BeginRequest
AuthenticateRequest
AuthorizeRequest
PreSendRequestHeaders
ResolveRequestCache
PreSendRequestContent
AcquireRequestState
Error
PreRequestHandlerExecute
PostRequestHandlerExecute
ReleaseRequestState
UpdateRequestCache
EndRequest
HTTP Handlers
15. 7
Members to implement
IsReusable property
Can the IHttpHandlerFactory object place the handlers in a
pool and reuse them (safe default is to return false)
ProcessRequest method
Processes the HTTP requests
Two methods
Code file (more effort, requires configuration)
Generic Handler (.ashx, no configuration)
HTTP Handlers
15. 8
HTTP Handlers
15. 9
HTTP Handlers
15. 10
Configure ASP.NET
<system.web>
<httpHandlers>
<add verb="*" path="*.chart"
type="MyHandler, MyHandlerAssembly" />
15. 11
HTTP Handlers
15. 12
Methods of Communication
Method
Description
MessageChannel
Web Sockets
Server-Sent Events
Web Workers
Methods of communication
http://html5doctor.com/methods-of-communication/
15. 13
using Microsoft.Web.WebSockets;
To use SignalR
Install the Microsoft ASP.NET SignalR NuGet package
Inherit from Hub
using Microsoft.AspNet.SignalR;
SignalR
15. 14
15. 15
SignalR
Communication
SignalR provides a simple
API for creating server-toclient remote procedure
calls (RPC) that call
JavaScript functions in
client browsers from
server-side .NET code
SignalR
15. 16
If JSONP is not configured and the connection is not crossdomain, WebSocket will be used if both the client and server
support it
If either the client or server do not support WebSocket, Server
Sent Events is used if it is available
If Server Sent Events is not available, Forever Frame is
attempted
If Forever Frame fails, Long Polling is used
SignalR
15. 17
Monitoring Transports
You can determine what transport your application is
using by enabling logging on your hub
$.connection.hub.logging = true;
16. 1
Module 16
Deploying ASP.NET MVC 4
Web Applications
Developing ASP.NET MVC 4
Web Applications
16. 2
Contents
Topic
Publishing
Slide
3
Web Deploy
12
Web.config Transformations
17
19
IIS
21
Web Architecture
24
Visual Studio
26
Publishing
16. 3
Publishing
16. 4
Connection Options
You can deploy to
Web Deploy (either directly or to a ZIP package)
FTP, File System, or FrontPage Server Extensions
Publishing
16. 5
Publishing
16. 6
File System
To deploy to the file system, enter the target path
Publishing
16. 7
Publish Output
When you click Publish button, your project will be rebuilt, Web.config transformed, and then published
Publishing
16. 8
Deployed Files
All C# source code is compiled into a single assembly
and deployed to the bin folder along with any other
dependent assemblies
16. 9
Web Deploy
Packages
IIS Settings
Application Pool
Authentication method
Error Handling
16. 10
Web Deploy
Publishing Pipeline
Build
Collect
Transform
Web Deploy
Package /
Publish
Build
Collect binary
and .pdb files
Transform
web.config
Create
package or
publish
Collect
references
Exclude files
Collect
content
Precompile
Collect SSL
Certificates
Create manifest
Custom extensions
16. 11
Web Deploy
IIS
Database
Provider
Database
Web Content
Provider
Web content
Parameters.xml
Web Deploy
Other
Other
Providers
Other
Providers
Providers
Package.zip
Your custom
Provider
COM
GAC
Custom Asset
16. 12
Description
csc, vbc
resgen
al
sn
Generate a strong name key pair (required for GAC deployment) and provides options for key
management, signature generation, and signature verification
gacutil1
ngen
net
regsvr32
regasm
Reads assembly metadata and adds the necessary entries to the registry, which allows COM
clients to create .NET Framework classes transparently
wsdl
svcutil
disco
ildasm
Intermediate Language (IL) Disassembler (or use ILSpy which can generate C# and VB source)
1Windows
Important .NET Framework 4.0 Command Line Tools You Must Know
http://www.devcurry.com/2011/02/important-net-framework-40-command-line.html
16. 13
Description
w3wp
An Internet Information Services (IIS) 6+ worker process runs Web applications, and is
responsible for handling requests sent to a Web Server for a specific application pool
aspnet_wp
ASP.NET applications using IIS 5 and earlier use this as their worker process
aspnet_regiis
Install or uninstall ASP.NET, encrypt and decrypt sections in Web.config, and many
other ASP.NET-related tasks
aspnet_regsql
Sets up ASP.NET features that can use SQL Server, e.g. session state, SQL cache
dependencies, profiles, membership, roles, and so on
aspnet_compiler
aspnet_merge
Combine and manage assemblies that are created by the ASP.NET compiler
aspnet_regbrowsers
Parses and compiles all system-wide browser definitions into an assembly and installs
the assembly into the global assembly cache
xsd
XML Schema Definition tool generates XML schema from classes in a runtime assembly
or common language runtime classes from XDR, XML, and XSD files
sgen
16. 14
gacutil
Command Line Switch
Description
gacutil /l
gacutil /l Firebrand.Library
gacutil /i [path]Firebrand.Library.dll
gacutil /u Firebrand.Library
gacutil /u Firebrand.Library,
Version=1.0.0.1,
Culture="de",
PublicKeyToken=45e343aae323ca
16. 15
16. 16
Web.config Transformations
16. 17
Web.Release.config
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ProductServer;..."
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
Web.config Transformation Syntax for Web Project Deployment Using Visual Studio
http://msdn.microsoft.com/en-us/library/dd465326(v=vs.110).aspx
Web.config Transformations
16. 18
Replacing Elements
Web.config
<customErrors defaultRedirect="Error.aspx" mode="RemoteOnly">
<error statusCode="500" redirect="ServerError.htm" />
Web.Debug.config
<customErrors defaultRedirect="DetailedError.aspx" mode="Off"
xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm" />
16. 19
16. 20
Directory is renamed
10
16. 21
IIS
16. 22
IIS
Classic
Integration
11
16. 23
IIS
Migrating
ASP.NET operates in Integrated mode by default
Because of the configuration unification, some applications may
require migration to operate properly in Integrated mode
Web Architecture
16. 24
Common Ports
Port
Description
21
22
Secure Shell (SSH) used for secure logins, file transfers (scp, sftp)
and port forwarding
23
25
53
79
Finger protocol
80
88
Kerberosauthentication system
443
666
12
Web Architecture
16. 25
Visual Studio
16. 26
File Properties
Build Action
None: file is not included in the project output group and is not
compiled in the build process e.g. documentation file
Compile: file is compiled into the build output e.g. code files
Content: file is not compiled, but is included in the Content
output group e.g. HTML files
Custom Tool
Used to transform files at design-time e.g. a dataset code
generator that reads an .xsd and generates .cs classes
File Properties
http://msdn.microsoft.com/en-us/library/vstudio/0c6xyb66(v=vs.100).aspx
13
A. 1
Appendix A
MeasureUp Errata
Developing ASP.NET MVC 4
Web Applications
A. 2
MeasureUp Errata
A. 3
MeasureUp Errata
A. 4
MeasureUp Errata
A. 5
MeasureUp Errata
A. 6
MeasureUp Errata
A. 7
MeasureUp Errata
A. 8
MeasureUp Errata
bufferQuotaInMB should be 1
A. 9
MeasureUp Errata
Duplicated answers!
BUT the correct answer is Append a salt value to the end of the password and then
hash the combined password and salt value. Only encrypt if the requirement
includes recoverable passwords.
A. 10
MeasureUp Errata
A. 11
MeasureUp Errata
A. 12
MeasureUp Errata
A. 13
MeasureUp Errata
A. 14
MeasureUp Errata
A. 15
MeasureUp Errata
Missing *
MeasureUp Errata
A. 16
According to MSDN there isnt a Federated option and you should use None to
activate the WSFederationAuthenticationModule (aka FAM) (see links below)
AuthenticationMode Enumeration
http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationmode(v=vs.110).aspx
B. 1
Appendix B
Exercises
Developing ASP.NET MVC 4
Web Applications
Exercise 1a
B. 2
Exercise 1b
B. 3
Exercise 2a
B. 4
Exercise 2b
B. 5
An exam detail page with exam number and title and how many
people have passed or failed that exam
Exercise 3
B. 6
Routes
In the Exercise 1 application define a custom route so
that
Customer/ALFKI maps to the existing Home/Details/ALFKI
Ensure that a match only happens if five letters are specified
Exercise 4
B. 7
Improving Performance
Improve the performance of the Exercise 1
applications home page by using
Response.Cache: to cache the response in the browser for 3
minutes
[OutputCache]: to cache the response on the server for 5
minutes
Cache: to cache the model for 10 minutes
Exercise 5
B. 8
Exercise 6
B. 9
Bundling
Write a JavaScript function for calculating factorials
and store it in Factorial.js
For example, Factorial(5) would return 120
5 x 4 x 3 x 2 x 1 = 120
Exercise 7
B. 10
Security
In the Exercise 1 application disable anonymous access
and display the logged on username in the navigation
bar
Exercise 8
B. 11
C. 1
Appendix C
Internationalization
Developing ASP.NET MVC 4
Web Applications
C. 2
Contents
Exam Topic: Plan and implement globalization and localization
Plan a localization strategy
Create and apply resources to UI including JavaScript resources
Set cultures
Create satellite resource assemblies
Internationalization
C. 3
What Is It?
Internationalization involves
Localizing the user interface (load any UI text from resource
assemblies) by setting the UICulture property of the thread
Globalizing the code (e.g. DateTime.Now.ToLongDateString())
by setting the Culture property of the thread
Internationalization
C. 4
For example,
Accept-Language: en-gb;q=0.8 , da , en;q=0.7
Internationalization
C. 5
Internationalizing MVC
There are two localization strategies
By setting the thread to dynamically loading resource strings in
views shared by all languages
By using different set of views for every language (and region)
Internationalization
C. 6
C. 7
Internationalization
@using Resources
Or use
@HttpContext.GetGlobalResourceObject("Shared", "Welcome")
Internationalization
C. 8
Internationalization
C. 9
Internationalization
C. 10
Right-to-Left Languages
When writing web pages in Web Forms or MVC, the best
way to make text flow from right to left is to use the
dir (direction) attribute
When the value is set on the html tag the page displays
as a right-to-left page and a vertical scrollbar appears
on the left side
<html dir="rtl">
D. 1
Appendix D
ASP.NET 5 and MVC 6
Developing ASP.NET MVC 4
Web Applications
D. 2
Versions
Year
Version
Version
New Features
2012
ASP.NET 4.5
MVC 4
Web API
Mobile support
Asynchronous support
70-486
2013
ASP.NET 4.5.1
MVC 5
Web API 2
Authentication filters
Override filters
ASP.NET Identity
SignalR 2
Bootstrap
Attribute routing
Unlikely
2015
ASP.NET 4.6
MVC 5.2.3
Web API 2.2
HTTP/2 support
Rosalyn compiler
2016
ASP.NET 5
MVC 6
(includes Web API)
Cross-platform (Windows,
Linux, Mac OS X)
EF7 support
D. 3
MVC 6
Unified model for MVC, Web API and Web Pages
Tag helpers let you use HTML helpers in your views by simply
extending the semantics of tags in your markup
Integration with Bower, Grunt, and Gulp
Manage NuGet packages with project.json
Removed dependency on Web.config
Introducing ASP.NET 5
http://weblogs.asp.net/scottgu/introducing-asp-net-5
ASP.NET 5 Documentation
http://docs.asp.net/en/latest/index.html
D. 4