MCSD Web Applications Asp Net Courseware PDF
MCSD Web Applications Asp Net Courseware PDF
1. 1
Module 1
Exploring ASP.NET MVC 4
Developing ASP.NET MVC 4
Web Applications
1. 2
Design the
application
architecture
Troubleshoot
and debug web
applications
Design the
user
experience
Develop the
user interface
Developing ASP.NET MVC 4 Web Applications
http://www.microsoft.com/learning/en/us/exam.aspx?ID=70-486
June 2013
155 minutes in total
55 questions in total
31 in main section
3 case studies
(6, 8, 10 questions)
Sep 2013 to Mar 2014
155 minutes in total
45 questions in total
22 in main section
3 case studies
(6, 7, 10 questions)
Time not an issue
Just as much configuration
and architecture as code
Official exam preparation guide does
not give percentages for each section
1. 3
Qs
10: Using JavaScript and jQuery for Responsive MVC 4 Web Applications
13: Using Windows Azure Web Services in ASP.NET MVC 4 Web Applications
45
1. 4
Labs
Follow the instructions at bottom of page 1-27 (position 3, 11014)
Allow NuGet to download missing packages during build
1. 5
1. 6
1. 7
Notes
The 70-486 exam is the hardest because it could ask a
question about almost any technology
ADO.NET, Entity Framework, LINQ, JavaScript, jQuery, CSS3,
WCF, Web API, Windows Azure, web architecture, Microsoft
Excel features, and so on
BUT the core of the exam is about ASP.NET MVC 4
1. 8
2. 1
Module 2
Designing ASP.NET MVC 4
Web Applications
Developing ASP.NET MVC 4
Web Applications
2. 2
Contents
Topic
Slide
MVC Architecture
Configuration
Intrinsic Objects
.axd Files
10
Internationalization
11
Future Reading
18
2. 3
MVC
Architecture
http://www.contoso.com/blog/edit/16
1
9
RouteTable
2
Controller
GetBlog(int)
Action1
Action
Result
Model
View
Domain Model
GetBlogs()
3
5
UpdateBlog
(Blog)
partial
classes and
metadata
ViewBag
ViewData
TempData2
CSDL
+ .cs
Entity
Data Model
MSL
SSDL
7
Partial View
1
2
2. 4
Configuration
Visual Studio
Or Web Site
IIS
\Windows\Microsoft.NET\
Framework64\v4.0.30319\Config
Configuration
2. 5
Why?
File-access security and permissions can be used to restrict
access to sections of configuration settings
Settings that are not used during application initialization (e.g.
connection strings) can be modified and reloaded without
requiring an application restart by using this attribute
<configSections>
<section name="pages" ... restartOnExternalChanges="false" />
Intrinsic Objects
2. 6
HttpContext Class
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx
Intrinsic Objects
2. 7
Intrinsic Objects
2. 8
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. 9
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
.axd Files
2. 10
Trace.axd: view the trace log for the last n requests; most
useful for Web Forms pages because they show ViewState and
page events
Internationalization
2. 11
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
2. 12
Internationalization
2. 13
Internationalizing MVC
There are two localization strategies to incorporate
different languages and cultures in ASP.NET MVC
By dynamically loading resource strings in all views
By using different set of views for every language and locale
Internationalization
2. 14
2. 15
Internationalization
In a View
@using MvcSite.Models
In Web.config
in Views folder
@SharedResources.Welcome
<pages>
<namespaces>
<add namespace="MvcSite.Models" />
Internationalization
2. 16
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">
2. 17
Internationalization
es
fr
en
es
fr
accept
aceptar
accepter
open
abrir
ouvrir
break
romper
casser
close/shut
cerrar
fermer
buy
comprar
acheter
pay
pagar
payer
cancel
cancelar
annuler
put
poner
poser
change
cambiar
changer
read
leer
lire
count
contar
compter
reply
responder
rpondre
cut
cortar
couper
send
enviar
envoyer
draw
dibujar
dessiner
start/begin
comenzar
commencer
explain
explicar
expliquer
translate
traducir
traduire
fill
llenar
remplir
turn off
apagar
teindre
find
encontrar
trouver
turn on
encender
allumer
finish
terminar
terminer
use
utilizar/usar
utiliser
go
ir
aller
wait
esperar
attendre
make/do
hacer
faire
write
escribir
crire
Future Reading
2. 18
ASP.NET MVC
Official Site for ASP.NET MVC
Tutorials, videos, samples, forum, books, open source
http://asp.net/mvc
Free MVC 4 Video Training from Pluralsight
http://www.asp.net/mvc/videos/pluralsight-buildingapplications-with-aspnet-mvc-4
Blogs
Phil Haack, http://haacked.com/
Scott Hanselman, http://www.hanselman.com/
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 Errata
Page 03-8 (position 5, 2677)
The MOC says
[AttributeUsage(AttributeTargets.Field)]
3. 4
MVC Models
Metadata Annotations
System.ComponentModel
System.Web.Mvc
System.ComponentModel.DataAnnotations
[DisplayFormat(HtmlEncode = false, NullDisplayText = "Unpaid",
DataFormatString = "{0:c}", ConvertEmptyStringToNull = true,
ApplyFormatInEditMode = false)]
// will not be included at all
public decimal Salary { get; set; }
[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. 5
MVC Models
Derived classes
DataType enumeration
Custom
Text
[DataType(DateType.Date)]
DateTime
Html
[Range(18, 65)]
Date
MultilineText
[RegularExpression(@"\d+")]
Time
EmailAddress
[Required(AllowEmptyStrings=false)]
Duration
Password
[StringLength(50)]
PhoneNumber
Url
Currency
ImageUrl
[StringLength(14, MinimumLength = 6,
ErrorMessage = "Password must be between 6 and 14 characters.")]
public string Password { get; set; }
MVC Models
3. 6
Custom Validation
Two techniques for custom validation
CustomValidationAttribute
Inherit from ValidationAttribute (see next slide)
MVC Models
3. 7
Custom Validation
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = false)]
public class ValidatePasswordLengthAttribute : ValidationAttribute
{ // public so they can be set with named parameters
public int MinimumCharacters { get; set; }
public int MaximumCharacters { get; set; }
public ValidatePasswordLengthAttribute(int minChars = 6) : base()
{
MinimumCharacters = minChars;
}
public override bool IsValid(object value)
{
var s = (value as string);
return ((s != null) && (s.Length >= MinimumCharacters)
&& (s.Length <= MaximumCharacters));
}
}
[ValidatePasswordLength(8, MaximumCharacters = 12)]
public string Password { get; set; }
MVC Models
3. 8
MVC Models
3. 9
Model Binders
There are five model binders built-in to ASP.NET MVC
DefaultModelBinder (most commonly used)
HttpPostedFileBaseModelBinder
ByteArrayModelBinder
LinqBinaryModelBinder
CancellationTokenModelBinder
MVC Models
3. 10
DefaultModelBinder
Maps a browser request to a data object
Provides a concrete implementation of a model binder
MVC Models
3. 11
MVC Models
3. 12
In a controller
To apply to a specific action argument
public ActionResult Edit(
[ModelBinder(typeof(FirstNameBinder))] string firstName,
[ModelBinder(typeof(AgeBinder))] int age) {
The Features and Foibles of ASP.NET MVC Model Binding
http://msdn.microsoft.com/en-us/magazine/hh781022.aspx
Entity Framework
3. 13
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
3. 14
3. 15
3. 16
3. 17
3. 18
4. 1
Module 4
Developing ASP.NET MVC 4
Controllers
Developing ASP.NET MVC 4
Web Applications
4. 2
Contents
Topic
Page 04-4
Slide
Action Filters
ActionResult
4. 3
Action Filters
4. 4
Action Filters
Action filter
OnActionExecuting
OnActionExecuted
Result filter
OnResultExecuting
OnResultExecuted
[MyCustomActionFilter]
[MyCustomResultFilter]
public ActionResult Index()
{
// fetch model
return View(model);
}
// response is returned
Exception filter
Only when an unhandled exception happens
4. 5
Action Filters
ActionFilterAttribute implements
IActionFilter: OnActionExecuting, OnActionExecuted
IResultFilter: OnResultExecuting, OnResultExecuted
ActionFilterAttribute inherits from FilterAttribute
Warning!
using System.Web.Mvc;
4. 6
ViewBag
ViewData is a dictionary of objects that is derived from
ViewDataDictionary and accessible using strings as keys
ViewData["Message"] = "Hello world!";
4. 7
ActionResult
Description
ContentResult
EmptyResult
FileResult
JavaScriptResult
Returns JavaScript
JsonResult
PartialViewResult
RedirectResult
RedirectToRouteResult
ViewResult
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
5. 5
MVC Views
@Model.Title
MVC Views
5. 6
5. 7
MVC Views
5. 8
MVC Views
5. 9
MVC Views
MVC Views
5. 10
MVC View
Add the partial view (RatingsDropDown.cshtml) in EditorTemplates
@Html.DropDownList("", new SelectList(new [] {
"Excellent", "Good", "Average", "Poor" }, Model))
5. 11
MVC Views
2
_ListOrders.cshtml
@Html.Partial("_ListOrders")
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. 12
MVC Views
Html.ActionLink
Creates an anchor tag with a path defined by a route
that calls an action method on a controller
Text to show
Action name
Route values
HTML attributes
5. 13
MVC Views
1
public class CustomerController : Controller
{
[ChildActionOnly]
public PartialViewResult ListOrders(Customer c)
{
List<Order> orders = GetOrders(c.CustomerID);
2
return PartialView("_ListOrders", orders);
@{ Html.RenderAction
("ListOrders", Model); }
Note
RenderAction returns
the results directly to
the response stream so
provides better
performance.
MVC Views
5. 14
ChildActionOnly Attribute
Designed for use with
Html.Action and Html.RenderAction
@Html.Action("GetMoreModelData")
MVC Views
5. 15
6. 1
Module 6
Testing and Debugging ASP.NET
MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
6. 2
Contents
Topic
Slide
Error Handling
Debugging
Health Monitoring
Testing
13
System.Diagnostics 24
.Contracts
Error Handling
6. 3
Error Handling
6. 4
Global Filters
Global filters are useful to set up global error handlers
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute
{
ExceptionType = typeof(DivideByZeroException),
View = "CustomException"
});
}
6. 5
Debugging
Configuring
Debugging for a web site is
controlled via two settings
In Machine.config, if deployment is
set to retail then debug and trace
output is disabled and custom
errors are always on
<system.web>
<deployment retail="true" />
Debugging
6. 6
Debugging
6. 7
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
Debugging
6. 8
Client-Side Script
By default, client-side script debugging is disabled in
Internet Explorer
Unselect the box to enable debugging
6. 9
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. 10
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
Health Monitoring
6. 11
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)
Health Monitoring
6. 12
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;
public class SampleWebBaseEvent : WebBaseEvent, IWebEventCustomEvaluator
{
public bool CanFire(WebBaseEvent e, RuleFiringRecord rule)
{
// return true when you want your rule to fire
IWebEventCustomEvaluator Interface
http://msdn.microsoft.com/en-us/library/system.web.management.iwebeventcustomevaluator.aspx
6. 13
Testing
Types of Tests
Test Level
Description
Unit
Integration
System
Acceptance
Regression
Performance
Load
Stress
Testing
6. 14
Testing
6. 15
Testing
6. 16
Testing
6. 17
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
The two parameters (expected, actual) refer to the same object
Assert Class
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert.aspx
Testing
6. 18
Testing
6. 19
Testing
6. 20
10
6. 21
Testing
Using shims to isolate your application from other assemblies for unit testing
http://msdn.microsoft.com/en-us/library/hh549176.aspx
6. 22
Testing
Ninject
http://code.google.com/p/autofac/wiki/FakeItEasy
http://www.ninject.org/
11
6. 23
System.Diagnostics.Contracts
using System.Diagnostics.Contracts;
System.Diagnostics.Contracts
6. 24
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
Contract Class
http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract(v=vs.110).aspx
12
7. 1
Module 7
Structuring ASP.NET MVC 4
Web Applications
Developing ASP.NET MVC 4
Web Applications
7. 2
Contents
Topic
Slide
SEO
Routing
MVC Areas
15
SEO
7. 3
SEO
7. 4
Robot Exclusion
Manage all robots.txt files from within IIS Manager
Modify robots.txt files from a GUI interface
7. 5
Routing
Default Route
Routing
7. 6
7. 7
Routing
Or like this
public ActionResult Index()
7. 8
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. 9
Routing
URL
Parameters
/query/select/bikes/onsale
queryname = "select"
queryvalues = "bikes/onsale"
/query/select/bikes
queryname = "select"
queryvalues = "bikes"
/query/select
queryname = "select"
queryvalues = null
Routing
7. 10
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. 11
Routing
7. 12
Routing
7. 13
Routing
7. 14
MVC Areas
7. 15
MVC Areas
7. 16
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. 17
MVC Areas
7. 18
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 Printing
Display Modes
Browsers
Exam Topic: Apply the user interface design for a web application
Create and apply styles by using CSS
Structure and lay out the user interface by using HTML
Implement dynamic page content based on a design
Exam Topic: Compose the UI layout of an application
Design layouts to provide visual structure
Implement master/application pages
8. 3
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>
CSS
8. 4
Media Queries
Media queries allow you to have different style sheets
for different scenarios
<link rel='stylesheet'
media='only screen and (max-width: 700px)'
href='css/narrow.css' />
<link rel='stylesheet'
media='only screen and (min-width: 701px) and (max-width: 900px)'
href='css/medium.css' />
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.
What is the difference between screen and only screen in media queries?
http://stackoverflow.com/questions/8549529/what-is-the-difference-between-screen-and-only-screen-in-media-queries
Display Modes
8. 5
using System.Web.WebPages;
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
DisplayModes in MVC 4
http://www.campusmvp.net/blog/displaymodes-in-mvc-4
Display Modes
8. 6
Browsers
8. 7
Browsers
8. 8
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
OutputCache
11
Caching Configuration
13
Performance
14
9. 3
Ajax.ActionLink
MOC code on page 09-4
Unnecessary to add [HttpGet]
Caching Overview
9. 4
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 needs two types of caching
9. 5
System.Web.Caching
Assignment
System.Web.Caching
9. 6
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. 7
System.Web.Caching
using System.Web.Caching;
9. 8
System.Web.Caching
SqlCacheDependency
Modify the web.config
using System.Web.Caching;
<caching>
<sqlCacheDependency enabled="true" pollTime="30000">
<databases>
<add name="Northwind" connectionStringName="NorthwindConnection"/>
9. 9
System.Runtime.Caching
9. 10
System.Runtime.Caching
Get("foo")
Get("foo")
Set("foo", "something")
Thread 2
Thread 1
System.Runtime.Caching
9. 11
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
OutputCache
9. 12
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
[OutputCache(Duration = 15)]
/Product/Detail/2
public ActionResult Detail(int id = 0) {
ViewBag.Message = "Page was cached at " + DateTime.Now;
return View(GetProduct(id));
9. 13
OutputCache
Configuring Caching
Duration (required)
VaryByParam
Location
CacheProfile
NoStore
SqlDependency
VaryByCustom
VaryByHeader
VaryByContentEncoding
Caching Configuration
9. 14
Downstream Caching
9. 15
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. 16
HttpCachePolicy.SetAllowResponseInBrowserHistory Method
http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setallowresponseinbrowserhistory(v=vs.110).aspx
9. 17
Downstream Caching
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. 18
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. 19
CSS Sprites
http://alistapart.com/article/sprites
Performance
9. 20
10
9. 21
Performance
<link href="">
9. 22
Performance
11
Performance
9. 23
5. Gzip Components
Web clients indicate support for compression with the
Accept-Encoding header in the HTTP request
Accept-Encoding: gzip, deflate
Performance
9. 24
12
Performance
9. 25
Performance
9. 26
13
Performance
9. 27
Performance
9. 28
14
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
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
Optimization
10. 5
Release mode
<compilation debug="false" />
<script src="/bundles/bootstrap?v=2Fz3B0iizV2NnnamQFrxNbYJNTFeBJ2GM05SilbtQU1"></script>
Optimization
10. 6
Minification Changes
As well as stripping whitespace and comments,
minification would change this
function StartController($scope, $location, $rootScope) { }
To this
function StartController(n, t, i) { }
System.Web.Optimization making function argument names stay the same for certain functions
http://stackoverflow.com/questions/13032721/system-web-optimization-making-function-argument-names-stay-the-same-for-certain
10. 7
Optimization
HTTP Compression
To enable gzip compression in .config for IIS
<system.webServer>
<httpCompression
directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>
10. 8
Optimization
HTTP Compression
What is gzip compression ratio?
It depends!
File
~120kb
Little or no compression
~2:1 compression
11. 1
Module 11
Controlling Access to ASP.NET
MVC 4 Web Application
Developing ASP.NET MVC 4
Web Applications
11. 2
Contents
Topic
Slide
Authentication
Authorization
Forms Auth.
ASP.NET Membership
Impersonation
22
23
Custom Security
25
Misc
28
11. 3
Authentication
Basic
mode="Windows"
Digest
Windows
Integrated
IE/Firefox auto-login
NTLM, Kerberos
ASP.NET authentication on
Anonymous
mode="Forms"
Use a MembershipProvider
mode="None"
Federated/claims-based
mode="Passport"
Pay Microsoft
IUSR_computername
Authorization
11. 4
MVC Authorizing
To ensure users are authenticated
Anonymous users will be redirected to login view
[Authorize]
public ActionResult Create() {
11. 5
Authorization
MVC Authorizing
If you apply Authorize to a whole class, you can still
allow anonymous for individual actions
[Authorize] // require all requests to authenticate
public class ProductController : Controller {
[AllowAnonymous] // disable authentication for this action
public ActionResult Index()
{
}
public ActionResult Display() // inherit from controller
{
}
[Authorize(Users="Mary,Omar", Roles="Admin")]
public ActionResult Edit()
{
}
}
11. 6
Authorization
if (User.IsInRole("Sales"))
IsAuthenticated (true/false)
Name
if (User.Identity.Name == "Fred")
Forms Authentication
11. 7
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. 8
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. 9
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
ASP.NET Membership
11. 10
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
ASP.NET Membership
11. 11
SimpleMembershipProvider
Now that we have created our users table we need to
wire it up to SimpleMembership so that
SimpleMembership knows what columns to use
Parameters of WebSecurity.InitializeDatabaseFile are
name of the database file
name of the table you are using for the users table
ASP.NET Membership
11. 12
SimpleMembershipProvider
To create a register view
Where the anonymous object represents the extra columns in
your users table
WebSecurity.CreateUserAndAccount(username, password, new {
FirstName = fname, LastName = lname, Email = email,
StartDate = DateTime.Now, Bio = bio});
11. 13
ASP.NET Membership
Table Schemas
SqlMembershipProvider
Universal Providers
ASP.NET Membership
11. 14
ASP.NET Membership
11. 15
ASP.NET Membership
11. 16
ChangePassword
ConfirmAccount(String)
CreateAccount
CreateUserAndAccount
GeneratePassword
ResetToken
Login/Logout
RequireRoles
ResetPassword
WebSecurity Class
http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity(v=vs.111).aspx
11. 17
ASP.NET Membership
CreateNewRole
DeleteRole
FindUsersInRole
GetAllRoles
GetRolesForUser
IsUserInRole
RemoveUserFromRole
RemoveUserFromRoles
RemoveUsersFromRole
RemoveUsersFromRoles
11. 18
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. 19
Longest is:
GetTextEffectCharacterIndexFromTextSourceCharacterIndex
11. 20
Impersonation
ASP.NET accesses resources using a specific account
Network Service (IIS 6.0), ApplicationPoolIdentity (IIS 7+)
10
11. 21
11. 22
Types Used
IClaimsIdentity
Extends the IIdentity interface to incorporate functionality
needed to implement claims-based identity e.g. Claims property
IClaimsIdentity Interface
http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.claims.iclaimsidentity.aspx
11
Custom Security
11. 23
Using HttpModules
An HTTP module is an assembly that is called on every
request that is made to your application
Can examine incoming requests and take action, so can perform
custom authentication or other security checks
Compare to HTTP handlers which are only called for registered
file extensions
Custom Security
11. 24
SimpleMembership and SimpleRole Providers for Oracle in ASP.NET MVC 4 Application Tutorial
http://www.devart.com/dotconnect/oracle/articles/extendedmembership-tutorial.html
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/
Miscellaneous
11. 26
Passwords
A study to find the top 25 leaked passwords of 2012 has
revealed too many people are still using password,
123456 and 12345678 for their login credentials
The average Web user maintains 25 separate accounts
but uses just 6.5 passwords to protect them, according
to a landmark study (PDF) from 2007
A PC running a single AMD Radeon HD7970 GPU can try
on average an astounding 8.2 billion password
combinations each second
Why passwords have never been weakerand crackers have never been stronger
http://arstechnica.com/security/2012/08/passwords-under-assault/
13
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
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
Preventing Attacks
12. 7
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()
State Management
12. 8
State Management
12. 9
State Management
12. 10
State Management
12. 11
Query Strings
Typical query string in URL
http://search.microsoft.com/results?mkt=en-US&q=hello+world
State Management
12. 12
Request Validation
ASP.NET validates requests for potentially dangerous
values (like JavaScript) automatically
Throws HttpRequestValidationException if it finds problem
The algorithm it uses is not documented for obvious reasons
State Management
12. 13
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
State Management
12. 14
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. 15
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. 16
12. 17
State Management
Session_End
Raised when a session is abandoned or expires
but only when using InProc session mode
12. 18
State Management
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
Custom, Off
<system.web>
<sessionState mode="Off" />
12. 19
State Management
State Management
12. 20
10
12. 21
State Management
Or a specified identity
<identity impersonate="true"
username="..." password="..." />
12. 22
State Management
Design Choices
Technology
PROs
CONs
Cookie
QueryString
ViewState
Session
Application
Simple
Cache
In-memory only
TempData
ViewData,
ViewBag
Simple
11
State Management
12. 23
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" [String=""
decryptionKey="AutoGenerate,IsolateApps" [String=""
validation="HMACSHA256" [SHA1="" | MD5="" | 3DES="" | AES="" | HMACSHA256=""
HMACSHA384="" | HMACSHA512="" | alg:algorithm_name="" decryption="Auto"
[Auto="" | DES="" | 3DES="" | AES="" | alg:algorithm_name=""] />
12
13. 1
Modules 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 IntelliTrace and Remote Desktop
Protocol (RDP)
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)
Review 20480.C.Cross.Domain.Requests
13. 3
MOC Errata
Page 13-12
The MOC slide says
Windows Azure
13. 4
Windows Azure
13. 5
Windows Azure
13. 6
13. 7
Windows Azure
Startup Tasks
You can use startup tasks to perform operations before
a role starts
Operations that you might want to perform include installing a
component, registering COM components, setting registry keys,
or starting a long running process
Startup tasks are defined in the ServiceDefinition.csdef file
<Startup>
<Task commandLine="Startup.cmd"
executionContext="limited" taskType="simple" >
<Environment>
<Variable name="MyVersionNumber" value="1.0.0.0" />
</Environment>
</Task>
</Startup>
13. 8
Windows Azure
void RoleEnvironment_Changing(
object sender,
RoleEnvironmentChangingEventArgs e)
{
Log(e.Changes);
e.Cancel = true;
WCF Services
13. 9
WCF Services
13. 10
Create a binding
var binding = new WSHttpBinding();
13. 11
WCF Services
13. 12
Data Contracts
[DataContract(IsReference=true)]
public class Address
Data Contracts
13. 13
14. 1
Module 14
Implementing Web APIs in
ASP.NET MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
14. 2
MOC Errata
Page 14-10
The MOC says NoAction in multiple sentences
It should say NonAction
[NonAction]
public void DoSomething()
{
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
15. 1
Module 15
Handling Requests in ASP.NET
MVC 4 Web Applications
Developing ASP.NET MVC 4
Web Applications
15. 2
Contents
Exam Topic: Design and implement a Web Socket strategy
Read and write string and binary data asynchronously (long-running data transfers)
Choose a connection loss strategy
Decide a strategy for when to use Web Sockets
Exam Topic: Design HTTP modules and handlers
Implement synchronous and asynchronous modules and handlers
Choose between modules and handlers in IIS
Exam Topic: Control application behavior by using MVC extensibility points
Control application behavior by using action results, viewengines, model
binders, and route handlers
Lab
Do NOT use the pre-release version of SignalR as described in
the lab, use the most recent version
HTTP Modules
15. 3
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 Init method and add handlers for any events you
want to intercept
public void Init(HttpApplication a)
{
this.app = a;
this.app.BeginRequest += LogAllRequestsMethod;
HTTP Modules
15. 4
Configuring
HTTP module must be registered in .config
For IIS 6.0 or IIS 7.0 in Classic mode
<system.web>
<httpModules>
<add name="MyMod" type="MyNamespace.MyModule" />
15. 5
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 Modules
15. 6
15. 7
HTTP Modules
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
Extending MVC
15. 8
16. 1
Module 16
Deploying ASP.NET MVC 4
Web Applications
Developing ASP.NET MVC 4
Web Applications
16. 2
Contents
Topic
Slide
Web Deploy
Web.config Transformations
11
IIS
13
Common Ports
16
Web Deploy
16. 3
Overview
For any question about deployment tools, the answer is
almost always use Web Deploy because
It works securely
It is powerful and flexible by changing the web publish pipeline
You can install SSL certificates using a custom target
Web Deploy
16. 4
Packages
IIS Settings
Application Pool
Authentication method
Error Handling
Production Settings
Release / Debugging
Connection Strings
16. 5
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. 6
Web Deploy
Parameters.xml
Web Deploy
Package.zip
IIS Provider
IIS
Database
Provider
Database
Web Content
Provider
Web content
Other
Other
Providers
Other
Providers
Providers
Your custom
Provider
COM
GAC
Custom Asset
16. 7
16. 8
16. 9
16. 10
Directory is renamed
Web.config Transformations
16. 11
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 Transformations
16. 12
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. 13
IIS
16. 14
IIS
Classic
Integration
16. 15
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
16. 16
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
A. 1
Appendix A
Whats New in Visual Studio 2013
and Updated Exam
Developing ASP.NET MVC 4
Web Applications
A. 2
Contents
Topic
SignalR
Slide
4
Filters
Browser Testing
10
ASP.NET Identity
11
Token Formats
17
Azure Caching
18
A. 3
Contents
Exam Topics: Test a web application
Create and run web tests (including using Browser Link)
Debug a web application in multiple browsers and mobile emulators
Exam Topics: Debug a Windows Azure application
Debug a Windows Azure application by using remote debugging
Interact directly with remote Windows Azure websites using Server Explorer
Exam Topics: Configure authentication
Configure ASP.NET Identity
Exam Topics: Design and implement claims-based authentication
across federated identity stores
Handle token formats (for example, oAuth, OpenID, Microsoft Account,
Google, Twitter, and Facebook) for SAML and SWT tokens
Exam Topics: Design a caching strategy
Implement Azure caching
SignalR
A. 4
A. 5
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
A. 6
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
A. 7
SignalR
Monitoring Transports
You can determine what transport your application is
using by enabling logging on your hub
$.connection.hub.logging = true;
A. 8
Filters
Authentication Filters
using System.Web.Mvc;
using System.Web.Mvc.Filters;
Filters
A. 9
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();
}
Filter Overrides in ASP.Net MVC 5
http://www.c-sharpcorner.com/UploadFile/ff2f08/filter-overrides-in-Asp-Net-mvc-5/
Browser Testing
A. 10
Browser Link
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
ASP.NET Identity
A. 11
ASP.NET Identity
A. 12
ASP.NET Identity
A. 13
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");
ASP.NET Identity
A. 14
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
The code above signs in the user by using the
AuthenticationManager from OWIN and calling SignIn and
passing in the ClaimsIdentity
ASP.NET Identity
A. 15
Components
Packages in green make up the ASP.NET Identity system
All the other packages are dependencies which are needed to
use the ASP.NET Identity system in ASP.NET applications
ASP.NET Identity
A. 16
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
Token Formats
A. 17
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>
A. 18
Implementing
Build highly responsive applications using a distributed
cache that scales independently from your application
using Microsoft.ApplicationServer.Caching;
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;
Cache
http://azure.microsoft.com/en-us/documentation/services/cache/