You are on page 1of 16

Notes for Exam 70-486

Developing ASP.NET MVC


4 Web Applications
Note: these notes do not breach any agreement with microsoft. They were made ​before​ I
took the test (2012-10-08 which was four days after it was released). I passed the exam.
Some notes may be in swedish still, let me know if you find any. Drop me a line or mention
me on twitter (@Mellbourn) or Google+ (​klas@mellbourn.net​ ) if you find this guide useful. If
you want to improve the document, comment it and/or contact me for write access.
Many links are included below, but even more are at
http://www.delicious.com/mellbourn/70_-_486
I have also made ​notes for Exam 70-480: Programming in HTML5 with JavaScript and CSS3

Design the Application Architecture


● Plan the application layers.
○ This objective may include but is not limited to: plan data access; plan for separation of concerns;
appropriate use of models, views, and controllers; choose between client-side and server side
processing; design for scalability
■ plan data access?
● Design a distributed application.
○ This objective may include but is not limited to: design a hybrid application (on premise vs. off premise,
including Windows Azure); plan for session management in a distributed environment; plan web farms
■ http://www.windowsazure.com/en-us/develop/net/fundamentals/in
tro-to-windows-azure/
■ Infrastructure as a Service (IaaS)
■ Platform as a Service (PaaS)
● web role (runs in IIS, can communicate)
● worker role
● maintain state not in the roles, but in data management
○ sQL Database (ej SQL Server)
○ tables (Key/value store nosql)
○ Blobs (media)
■ Can be viewed as à Windows filé system
● Communication
○ Queue
■ short lived (less than 7days) more than 5GB
○ // Retrieve storage account from connection string
CloudStorageAccount​ storageAccount ​=​ ​CloudStorageAccount​.​Parse​(
​CloudConfigurationManager​.​GetSetting​(​"StorageConnectionString"​));

// Create the queue client


CloudQueueClient​ queueClient ​=​ storageAccount​.​CreateCloudQueueClient​();

// Retrieve a reference to a queue


CloudQueue​ queue ​=​ queueClient​.​GetQueueReference​(​"myqueue"​);

// Create the queue if it doesn't already exist


queue​.​CreateIfNotExist​();

// Create a message and add it to the queue


CloudQueueMessage​ message ​=​ ​new​ ​CloudQueueMessage​(​"Hello, World"​);
queue​.​AddMessage​(m
​ essage​);
// Peek at the next message
CloudQueueMessage​ peekedMessage ​=​ queue​.​PeekMessage​();
○ Service bus
■ (pub/sub)
■ when you need WCF
■ transactions, atomicity
■ FIFO (First-in-first-out)
● QueueDescription​ qd ​=​ ​new​ ​QueueDescription​(​"TestQueue"​);
qd​.​MaxSizeInMegabytes​ ​=​ ​5120​;
qd​.​DefaultMessageTimeToLive​ ​=​ ​new​ ​TimeSpan​(​0​,​ ​1​,​ ​0​);

// Create a new Queue with custom settings


string​ connectionString ​=
​CloudConfigurationManager​.​GetSetting​(​"Microsoft.ServiceBus.ConnectionString"​);
var​ namespaceManager ​=
​NamespaceManager​.​CreateFromConnectionString​(​connectionString​);

if​ ​(!​namespaceManager​.​QueueExists​("​ TestQueue"​))


{
namespaceManager​.​CreateQueue​(​qd​);
}
● QueueClient​ ​Client​ ​=
​QueueClient​.​CreateFromConnectionString​(​connectionString​,​ ​"TestQueue"​);
Client​.​Send​(​new​ ​BrokeredMessage​());
● BrokeredMessage​ message ​=​ ​Client​.​Receive​();
​Console​.​WriteLine​(​"Body: "​ ​+​ message​.​GetBody​<string>​());
​Console​.​WriteLine​(​"MessageID: "​ ​+​ message​.​MessageId​);
​Console​.​WriteLine​(​"Test Property: "​ ​+
message​.​Properties​["​ TestProperty"​]);

​// Remove message from queue


message​.​Complete​();
● Design and implement the Windows Azure role life cycle.
○ This objective may include but is not limited to: identify and implement Start, Run, and Stop
events;identify startup tasks (IIS configuration [app pool], registry configuration, third-party tools)
■ http://brentdacodemonkey.wordpress.com/2011/09/24/leveraging-the-roleentrypoint-year-o
f-azure-week-12/
■ inherit ​RoleEntryPoint
■ public​ ​override​ ​bool​ OnStart()
● web role (which does not have to inherit RoleEntryPoint)
■ public​ ​override​ ​bool​ OnStop()
● must take a maximum of five minutes
■ public​ ​override​ ​void​ Run()
■ ServicePointManager​.DefaultConnectionLimit = 12;
■ RoleEnvironment​.Stopping +=
■ RoleEnvironment​.Changing += (service config changes)
■ We can optionally decide to restart our role instance by setting the
event’s​RoleEnvironmentChangingEventArgs​.Cancel property to true during the
Changing event
■ windows ​startup tasks
● for installation (webPI) registry settings, com components
● Simple ​(waits until finished before starting other), ​Background, Foreground
<ServiceDefinition>
<WebRole name=”WebRole1” vmsize=”Small”>
<Startup>
<Task commandLine=”Install.cmd” executionContext=”elevated” taskType=”background” />
</Startup>
<Sites>
<Site name=”Web”>
<Bindings>
<Binding name=”Endpoint1” endpointname=”Endpoint1”>

<Imports>
<Import moduleName=”Diagnostics” />
ServiceDefinition​.​csdef

<InputEndpoints>
<InputEndpoint name="HttpIn" port="80" protocol="http"/>
<InputEndpoint certificate="Certificate1" name="HttpsIn" port="443" protocol="https"/>
</InputEndpoints>
<InternalEndpoint name="InternalHttpIn" protocol="http"/>

● Configure state management.
○ This objective may include but is not limited to: choose a state management mechanism (in-process and
out of process state management, ViewState); plan for scalability; use cookies or local storage to
maintain state; apply configuration settings in web.config file; implement sessionless state (for example,
QueryString)
■ session state: in-process, out of process, sql server mode
● <configuration>
<sessionstate
mode="sqlserver"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=MySqlServer;
user id=ASPState;
password=1Gr8State"
server="127.0.0.1"
port="42424"
/>
● sqlconnectionstring="data source=127.0.0.1;user
id=<user id>;password=<password>"
● Design a caching strategy.
○ This objective may include but is not limited to: implement page output caching (performance oriented);
implement data caching; implement HTTP caching
■ Azure ​in memory caching
● nuget package: azure caching...
● in your code:
● DataCache cache
● cache.Get(name)
● cache.Add(name, data)
● cache.Put(name, data)
■ Old ​way of caching: System.Web.Caching
● [​OutputCache​(Duration, VaryByParam, VaryByContentEncoding,
VaryByHeader, CacheProfile)] in action or controller
● data caching with good old Cache[“name”]
● Cache.Add(key, value, CacheDependency, DateTime, TimeSpan,
CacheItemPriority, CacheItemRemovedCallback)
○ (CacheDependency can point out file path)
■ New ​ways to cache in .NET 4 System.Runtime.Caching
● ObjectCache // abstract, implemented by
● MemoryCache
○ Add, Set, Get, Remove
​ObjectCache ​cache = ​MemoryCache.Default​;
string fileContents = cache["filecontents"] as string;
if (fileContents == null)
{
​CacheItemPolicy ​policy = new CacheItemPolicy();
policy.AbsoluteExpiration =
DateTimeOffset.Now.AddSeconds(60.0);

List<string> filePaths = new List<string>();


string cachedFilePath = Server.MapPath("~") +
"\\cacheText.txt";
filePaths.Add(cachedFilePath);

policy.​ChangeMonitors.Add(new
HostFileChangeMonitor(​filePaths));

// Fetch the file contents.


fileContents = File.ReadAllText(cachedFilePath);

cache.​Set​("filecontents", fileContents, policy);



■ http caching
● Response​.​Cache​.​SetETagFromFileDependencies​() // generates
ETag nice!
● Response​.​Cache​.​SetValidUntilExpires​(​true​); // ignore
cache-control headers erroneusly sent by browser
● Response.Cache.SetExpires(DateTime.Now.AddYears(1)
● Response​.​Cache​.​SetMaxAge​(​TimeSpan​.​FromSeconds​(​60​ * ​10​)
// simpler than expire date
■ or in config:
■ <staticContent>
■ <clientCache cacheControlMode="UseExpires"
cacheControlCustom="public" httpExpires="Tue, 01 Oct 2030
01:01:01, GMT" />
■ or
■ <clientCache cacheControlMode="UseMaxAge"
cacheControlMaxAge="1:00:00" cacheControlCustom="public" />
■ </staticContent>
● Design and implement a Web Socket strategy.
○ This objective may include but is not limited to: 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
■ AsyncController ​med async Task<ActionResult>, await
● [​AsyncTimeout​(​150​)]
● [​HandleError​(​ExceptionType​ ​=​ ​typeof​(​TimeoutException​),
● ​View​ ​=​ ​"TimeoutError"​)]
● public async Task<ActionResult> PWGtimeOut(CancellationToken cancellationToken)
■ connection loss strategy?
● Response.Close to close a connection on purpose (avoid DOS)
■ strategy for when to use Web sockets
● (old tech: long polling) use websockets when low latency is important (games, chat,
realtime). Note that you need to support high concurrency (many open websockets)
● var​ connection = ​new​ ​WebSocket​('​ ws://h.com'​, [​'soap'​, ​'xmpp'​]);
● connection.onopen // event: now you are allowed to send
● connection.onerror // event
● connection.Send(‘your message”) // or binary buffer or blob
● // server sending to browser:
● connection.onmessage = ​function​(e) { console.log(e.data)
● Design HTTP modules and handlers.
○ This objective may include but is not limited to: implement synchronous and asynchronous modules and
handlers; choose between modules and handlers in IIS
■ HTTP handler ​is the process (frequently referred to as the
"endpoint") that runs in response to a request made to IIS 7.
● IHttpHandler
○ IsResuable [if pool ok]
○ ProcessRequest [produce output]
● IHttpAsyncHandler - returns response before done
○ BeginProcessRequest(context, callback, data)
○ EndProcessRequest [do cleanup, e.g. throw
exceptions]
■ public class CustomAsyncHandler : ​HttpTaskAsyncHandler
{
public override async Task ProcessRequestAsync(HttpContext)
● In IIS 6 you must map the extension to ASP.NET. Then
in the application, you must map the extension to the
custom handler. default .ashx
● In II7 you can configure it using the IIS manager or by
using config
<system.web>
<httpHandlers>
<add verb="GET, HEAD"
path="*.New"
type="MyHandler.New,MyHandler"/>
<system.webServer>
● <handlers>
● <add ...k
■ HTTP modules let you examine incoming and outgoing requests
and take action based on the request, events from the
HttpApplication object, many modules are called for each
request, but only one handler
● IHttpModule
○ Init(HttpAppplication)
■ application.BeginRequest +=
■ HttpApplication
● BeginRequest, AuthenticateRequest,
PostAuthenticateRequest,
PreRequestHandlerExecute,
PostRequestHandlerExecute, LogRequest,
EndRequest
● II7 in ​integrated​ mode runs managed code modules in a unified pipline that can
handle all requests (not just ASP.NET)
○ Classic ​mode registration
■ <configuration>
<system.web>
<httpModules>
<add name="HelloWorldModule"
type="HelloWorldModule"/>
○ Integrated ​mode registration
■ <configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule"
type="HelloWorldModule"/>
● Note: MvcApplication in Global.asax.cs inherits from HttpApplication, and can
thus handle all the same requests (but is not as reusable)
○ just create methods named Application_​event​ in global.asax:
○ public void Application_LogRequest(object
sender, EventArgs e)
○ {
○ HttpApplication httpApplication =
(HttpApplication)sender;
○ Debug.WriteLine("log: " +
httpApplication.Request.Browser.Browser);
○ }
● Async module (​link​): write a async/await method (here WriteLogmessages) in
the module, register like this in init():
○ EventHandlerTaskAsyncHelper asyncHelper = new
EventHandlerTaskAsyncHelper(WriteLogmessages);
○ application.AddOnPostAuthorizeRequestAsync(
○ asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler);
■ HttpContext
● Application
● Cache[]
● Error
● Items[]
● Request HttpRequest
○ Browser
○ ContentEncoding
○ [] or Params which is the union of
■ Form [form variables]
■ Cookies
■ QueryString
○ Headers
○ Url
○ UserHostName
○ HttpMethod
● Response
○ OutPut a TextWriter
○ OutPutStream a Stream for binary response
○ Cache a CachePolicy
○ Cookies
○ Headers
○ StatusCode
● Server a HttpServerUtility
○ HtmlEnocde, UrlEncode
○ HtmlDecode, UrlDecode
○ MapPath
○ Transfer - terminates and executes another page
● Session[“key”] HttpSessionState
■ Mvc.Controller
● HttpContext
● Request
● Response
● Server
● Session
● TempData[“key”]
■ Mvc.ViewContext
● HttpContext
● Controller
● RouteData
● ViewData
● View (the IView)
● FormContext
Design the User Experience
● Apply the user interface design for a web application.
○ This objective may include but is not limited to: 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
● Design and implement UI behavior.
○ This objective may include but is not limited to: implement client validation; use JavaScript and the DOM
to control application behavior; extend objects by using prototypal inheritance; use AJAX to make partial
page updates; implement the UI by using JQuery
■ http://phrogz.net/JS/classes/OOPinJS.html
■ http://phrogz.net/JS/classes/OOPinJS2.html
■ Cat.​prototype​ = ​new​ Mammal​()​;
■ SuperCar.prototype = Object.create(Car.prototype);
● Compose the UI layout of an application.
○ This objective may include but is not limited to: implement partials for reuse in different areas of the
application; design and implement pages by using Razor templates (Razor view engine); design layouts
to provide visual structure; implement master/application pages
● Enhance application behavior and style based on browser feature detection.
○ This objective may include but is not limited to: detect browser features and capabilities; create a web
application that runs across multiple browsers and mobile devices; enhance application behavior and
style by using vendor-specific extensions, for example, CSS
■ detect browser features and capabilities?
■ in ​javascript
● navigator.userAgent.indexOf(​"MSIE"​)>​0
● better to detect features and capabilities
○ if(window.addEventListener) { //supports
○ if(typeof window.addEventListener !== “undefined”)
● ​if​(Modernizr.fontface)​{
1. functionisCanvasSupported()
2. ​{
3. ​var​ elem = document.createElement('canvas');
4. ​return​!!(elem.getContext && elem.getContext('2d');
■ In HTML
1. <video>
2. ​<source​ src="video.mp4" type='video/mp4' ​/>
3. ​<source​ src="video.webm" type='video/webm' ​/>
4. ​<object​ type="application/x-silverlight-2"​>
5. ​<param​ name="source" value="http://url/player.xap"​>
6. ​<param​ name="initParams" value="m=http://url/video.mp4"​>
7. </object>
8. No native support, download the video ​<a​ href="video.mp4"​>​here</a>.
9. </video>
■ If a feature is lacking you can use ​shims ​(proprietarty emulator) or ​polyfills ​(exact HTML5
api emulator)
■ vendor specific extensions to CSS (-o-opacity = opacity for opera)
● -moz-
● -webkit-
● -ms-
● use all versions and then without prefix to make it work everywhere
■ Mobile
■ http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-4-mobile-feat
ures
■ CSS media queries
● @media only screen and (max-width: 850px) {
● (‘screen’ as opposed to ‘print’ or ‘projection’)
■ set viewport in layout
● ​ ame​=​"viewport"​ c
<meta​ n ​ ontent​="
​ width=device-width"​>
■ .Mobile e.g. Index.Mobile.cshtml
■ or Index.iPhone.cshtml if you do:
○ DisplayModes​.​Instance​.​Modes​.​Insert​(​0​,​ ​new​ ​DefaultDisplayMode​(​"iPhone"​)
○ {
○ ​ContextCondition​ ​=​ ​(​context ​=>​ context​.​GetOverriddenUserAgent​().​IndexOf
○ ​(​"iPhone"​,​ ​StringComparison​.​OrdinalIgnoreCase​)​ ​>=​ 0
​ ​)
○ });
■ HttpContext.Request.Browser.IsMobileDevice
● HttpBrowserCapabilities. Name, Version, MajorVersion, JavaScript
■ Install-Package jQuery.Mobile.MVC
● uses ​data-role​s
● <div data-role="page" data-theme="b">
<div data-role="header"
● <div data-role="content">
● <ul data-role="listview" data-inset="true">
<li data-role="list-divider">Navigation</li>
● Plan an adaptive UI layout.
○ This objective may include but is not limited to: plan for running applications in browsers on multiple
devices (screen resolution, CSS, HTML); plan for mobile web applications
Develop the User Experience
● Plan for search engine optimization and accessibility.
○ This objective may include but is not limited to: 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
■ SEO
● unique​ <title>​ for each page
● <meta name=”description” content=”Brandon’s Baseball.​..
● urls with words, use a single url for a page (301 to the correct one)
● easy to navigate (flat hierarchy, with breadcrumb)
● have a Sitemap file (xml description of navigation)
● rel=nofollow on links in comments
■ semantic markup HTML5
● <article>
● <aside>
● <section>
● <figure><figcaption>
● <nav>
● <fieldset><legend> (groupbox)
● <label for=”inputfieldid”
■ semantic markup ARIA
● roles: dialog, directory, grid, heading, main, menu, tree
● states & properties: aria-autocomplete, aria-checked, aria-haspopup
● landmark roles: role=application, banner, form, main, navigation, search
● live regions: alert, log, marquee
○ mark regions with ​aria-live=’polite’
○ type of update: ​relevant=”additions”
○ aria-busy=true ​during updates
● alt=”” when purely decorative
● aria-labelledby aira-describedby
● Plan and implement globalization and localization.
○ This objective may include but is not limited to: plan a localization strategy; create and apply resources to
UI including JavaScript resources; set cultures; create satellite resource assemblies
■ avoid App_GlobalResources and App_LocalResources in MVC.
■ use PublicResXFileCodeGenerator (to generat public, testable resources)
■ put foo.fr.resx, foo.de.resx in any folder
■ resgen Example.resources.fr.txt
■ al /t:lib /embed:Example.fr.resources /culture:fr
/out:fr\Example.resources.dll
■ folderstruktur ​fr​\Example.resources.dll
■ <globalization​ ​enableclientbasedculture="true"
uiculture="auto"​ ​culture="auto">
■ HTTP Header called "Accept-Language"
■ in jQuery:
● $.global.preferCulture(
● then $.format works well:
● $.format(new​ ​Date(1972, 2, 5), "D");
● Design and implement MVC controllers and actions.
○ This objective may include but is not limited to: apply authorization attributes and global filters; implement
action behaviors; implement action results; implement model binding
■ GlobalFilters.Filters.Add(new LogFilterAttribute())
■ inherit from ActionFilterAttribute, implement
● OnActionExecuting
● OnActionExecuted
● OnResultExecuting (after action executed before the returned result is used)
● OnResultExecuted
● Design and implement routes.
○ This objective may include but is not limited to: define a route to handle a URL pattern; apply route
constraints; ignore URL patterns; add custom route parameters; define areas
■ IgnoreRoute
■ Add Area ​on solution, creates subclasses of AreaRegistration
1. public​ ​class​ ​HelpDeskAreaRegistration​ ​:​ ​AreaRegistration
2. {
3. ​public​ ​override​ ​string​ ​AreaName
4. ​{
5. ​get
6. ​{
7. ​return​ ​"HelpDesk"​;
8. ​}
9. ​}
10.
11. ​public​ ​override​ ​void​ ​RegisterArea​(A
​ reaRegistrationContext​ context​)
12. ​ {
13. context​.​MapRoute​(
14. ​"HelpDesk_default"​,
15. ​"HelpDesk/{controller}/{action}/{id}"​,
● Control application behavior by using MVC extensibility points.
○ This objective may include but is not limited to implement MVC filters and controller factories; control
application behavior by using action results, viewengines, model binders, and route handlers
■ subclass DefaultControllerFactory and override CreateController(requestcontext, name) to
map name to controller type
■ or implement IControllerActivator and override Create(context, type)
● Reduce network bandwidth.
○ This objective may include but is not limited to: 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
■ minification only turned on for ​<compilation​ ​debug​=​"false"​ ​/> ​(or
BundelTable.EnableOptimizations = true
■ bundles​.​Add​(​new​ ​ScriptBundle​(​"~/bundles/jquery"​).​Include​(
■ ​"~/Scripts/jquery-{version}.js"​));

○ bundles​.​UseCdn​ ​=​ ​true​;​ ​//enable CDN support

○ ​//add link to jquery on the CDN
○ ​var​ jqueryCdnPath ​=
"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"​;

○ bundles​.​Add​(​new​ ​ScriptBundle​(​"~/bundles/jquery"​,
○ jqueryCdnPath​).​Include​(
○ ​"~/Scripts/jquery-{version}.js"​));

■ @Styles.Render
■ @Scripts.Render(“~/bundles/jquery”)
○ new minifiers can be loaded as packages (or made using implementing IBundleTransform)
○ Windows Axure sells customized CDN service
○ how do you (un)configure gzip
■ Headers:
■ Accept-Encoding: gzip, deflate
■ Content-Encoding: gzip
○ You can create such streams with GZipInputStream, ZipInputStream (when using
HttpWebResponse/HttpWebRequest.GetResponse())
Troubleshoot and Debug Web Applications
● Prevent and troubleshoot runtime issues.
○ This objective may include but is not limited to: troubleshoot performance, security, and errors;implement
tracing, logging (including using attributes for logging), and debugging (including IntelliTrace); enforce
conditions by using code contracts; enable and configure health monitoring (including Performance
Monitor)
■ Debug in Debug builds, Trace in all builds
● Debug.Listeners.Add(new XmlWriterListener())
● Debug.Indent()
● switch level 4 gives you the most logging
● <system.diagnostics>
<switches>
<add name="General" value="4" />
</switches>
<trace autoflush="true" indentsize="2">
<listeners>
<add name="myListener"
type="System.Diagnostics.TextWriterTraceListener,
● TraceSwitch s = new TraceSwitch(“General”, “desc”)
● Trace.WriteIf(s.TraceWarning, “this written if value >= 2”)
■ EventLog
● EventLog.CreateEventSource(​"MySource"​, ​"MyNewLog"​);
● EventLog myLog = new EventLog();
● myLog.Source = ​"MySource"​;
● myLog.WriteEntry(​"Writing to event log."​);
■ Performance Counters
● create a category
● PerformanceCounterCategory.Create(“mycategory”)
● create counter
● counter ​=
new PerformanceCounter(​“mycategory”,
“countername”
● adjust counter
○ counter.Increment() //thread-safe
○ counter.RawValue =
● read counter
○ counter.NextValue, NextSample
■ Attributes for logging: ​using filters​?
● OnActionExecuting(ActionExecutingContext
● context.ActionDescriptor.ControllerDescriptor.ControllerName
■ Code Contracts
● Contract.Requires<ArgumentException>(id > 0);
● Contract.Requires(Contract.ForAll(customerIds, (id) => id >0));
● Contract.Ensures() - postcondition
● Contract.Invariant( x != 0) // tested at end of public method
● Contract.Assume same as Contract.Assert
■ Health monitoring​ ​http://forums.asp.net/t/1027461.aspx
● <healthMonitoring enabled="true">
● <providers>
● <add name="sqlProvider"
● type="System.Web.Management.SqlWebEventProvider"
● connectionStringName="appDB"
● buffer="false"
● bufferMode="Notification" />
● </providers>

● <rules>
● <add name="lifeCycle"
● provider="sqlProvider"
● ​eventName="Application Lifetime Events"​ />
● </rules>
● </healthMonitoring>
■ Intellitrace
● collects in ​iTrace ​file
● decide ​events ​to collect, if you want to collect c​ all information​.
● decide what ​modules t​ o collect information about
● IntellitraceSC.exe launch /cp:collection_plan.ASP.NET.default.xml
● standalone collector can be installed to monitor production
○ powershell integrated ​Start-IntelliTraceCollection
● <ModuleList isExclusionList="false">
<Name>PublicKeyToken:B77A5C561934E089</Name>
<Name>FabrikamFiber.Web.dll</Name>
● Design an exception handling strategy.
○ This objective may include but is not limited to: handle exceptions across multiple layers; display custom
error pages using global.asax or creating your own HTTPHandler or set web.config attributes; handle first
chance exceptions
■ good article on error handling
■ HandleError global filter is registered in FilterConfig
■ HandleError directs to the Shared\Error.cshtml page if customerrors are on
■ Error.cshtml has the model ​HandleErrorInfo​, with properties ActionName, ControllerName,
Exception
■ specialized error handling:
■ [HandleError(Exception = typeof(DbException), View = “DbError”)]
■ HandleError ​suppresses ​default error logging!
● you should extend HandleError with logging
■ HandleError only catches 500 errors (e.g. not 404) and only inside controllers
■ Application_Error​ handles ​all​ errors but knows naught about MVC. ELMAH has best of
both worlds
■ protected void Application_Error(object sender, EventArgs e)
■ Server.GetLastError()
■ <customErrors defaultRedirect="http://hostName/appl/errorStatus.htm"
mode="On">
<error statusCode="404" redirect="filenotfound.htm" />
</customErrors>
● Test a web application.
○ This objective may include but is not limited to: create and run unit tests, for example, use the Assert
class, create mocks; create and run web tests
■ web tests​:
■ choose ​Web Performance and Load Test Project
■ ​Web Performance Test Recorder
■ Think Time​ can be modified
■ ​Expected response​ can be set
■ Web Performance Test Editor​,
■ you can bind test data to a database
■ you can add ​Validation Rule​ that requires ​Find Text
■ you can add Extraction rule with ​Extract Attribute Value​ to extract
html attributes (class etc)
■ you can create ​Load Test
■ there you can select ​Avg Page Time​ counter node and select
Add Threshold Rule​.
● Debug a Windows Azure application.
○ This objective may include but is not limited to: 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)
■ read up on azure logging!
Design and Implement Security
● Configure authentication.
○ This objective may include but is not limited to: authenticate users; enforce authentication settings;
choose between Windows, Forms, and custom authentication; manage user session by using cookies;
configure membership providers; create custom membership providers
■ IIdentity is username and authtype
■ IPrincipal is iidentity and IsInRole, often used for authenticating role
■ custom privider: inhert MembershipProvider
● ValdiateUser()
● ResetPassword()
● MinRequiredPasswordLength
● RequiresQuestionAndAnswer
■ <membership defaultProvider="OdbcProvider"
userIsOnlineTimeWindow="15">

<providers>

<add
name="OdbcProvider"

type="Samples.AspNet.Membership.OdbcMembershipProvider"
connectionStringName="OdbcServices"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
writeExceptionsToEventLog="true" />

</providers>
</membership>
■ Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
■ WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
● Configure and apply authorization.
○ This objective may include but is not limited to: create roles; authorize roles by using configuration;
authorize roles programmatically ; create custom role providers; implement WCF service authorization
■ WCF Service authorization?
● Security: Message based or transport based
● role based authorization
● IIdentity currentUser =
● ServiceSecurityContext.Current.PrimaryIdentity;
● if (​Roles​.IsUserInRole(currentUser.Name, "Member"))
■ create custom role providers?
● Inherit RoleProvider, implement many required methods
○ CreateRole
○ AddUsersToRole
○ IsUserInRole(string, string)
● Design and implement claims-based authentication across federated identity stores.
○ This objective may include but is not limited to: 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, LiveID, and Facebook) for SAML and SWT tokens
■ how to implement oauth, livied, fb etc on your mvc site
■ OAuthWebSecurity.RegisterTwitterClient
■ OAuthWebSecurity.RegisterFacebookClient(
■ appId: "",
■ appSecret: "");
■ OAuthWebSecurity.RegisterMicrosoftClient
■ OAuthWebSecurity.RegisterGoogleClien
■ Claims:
■ ClaimsPrincipal now base class to WindowsPrincipal, GenericPrincipal, RolePrincipal
■ Claims ​are not what the subject can and cannot do. They are what the subject is or is
not.authenitcated/issued by the Security Token Service (STS) (aka Identity provider)
■ A Claim object has claim ​Type, Value ​and V
​ alueType ​(givenname, “klas”, string)
■ Claims are grouped in a ​Token​ ​that is signed. SAML (Security Assertion Markup
Language) and SWT (Simple web Token) are formats. Relaying Party (RP) is the using
web site.
■ Both ClaimsPrincipal and CliamsIdentity have Claims, use the principal
■ ClaimsPrincipalPermission.CheckAccess ​to check access in code
■ ClaimsAuthenticationManager.Authenticate ​can be subclassed and implemented to
intercept ​ClaimsIdentityCollection ​and modify it
■ You can configure a web-based application with a ​custom claims authorization​ manager,
an instance of a class that derives from the ​ClaimsAuthorizationManager ​class. When
so configured, the request processing pipeline packages the incoming ​ClaimsPrincipal
in an ​AuthorizationContext ​and invokes the ​CheckAccess ​method on your claims
authorization manager. ​ClaimsPrincipalPermissionAttribute ​can be used to protect
code
● <applicationService>
<claimsAuthorizationManager>
■ The RP gets the ​ClaimsPrincipal principal = HttpContext.Current.User as
ClaimsPrincipal;
■ a ​Federated Provider ​(FP) lies between RP and Identity Providers and transforms claims in
a way that RP understands. Windows Azure Access Control Service (ACS) is a FP
■ How to write custom tokens in WIF​ - subclass ​SecurityTokenHandler ​and ​SecurityToken​.
Web.config in RP needs a <microsoft.identityModel> with <federatedAuthetication> that
specifies the STS used
● Manage data integrity.
○ This objective may include but is not limited to: apply encryption to application data; apply encryption to
the configuration sections of an application; sign application data to prevent tampering
■ encrypt data
● Rijndael ​alg = ​Rijndael​.Create();
alg.Key = Key;
alg.IV = IV;
cs = new ​CryptoStream​(ms, alg.CreateEncryptor(),
CryptoStreamMode​.Write);
■ encrypt configuration sections
■ create keys (exportable in CSP):
● aspnet_regiis -pc "SampleKeys" –exp
■ configure to use them:
<configProtectedData>
<providers>
<add name="SampleProvider"
type="System.Configuration.RsaProtectedConfigurationProvider, …
keyContainerName="SampleKeys"
■ aspnet_regiis -pe "connectionStrings" -app
"/SampleApplication" -prov
"RsaProtectedConfigurationProvider"
■ sign application data​?
■ ​RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
RSAalg.ImportParameters(Key);
return RSAalg.SignData(DataToSign,Index,Length, new
SHA1CryptoServiceProvider());
■ RSAalg.VerifyData(DataToVerify, SHA1CryptoServicePovider(), SignedData)
● Implement a secure site with ASP.NET.
○ This objective may include but is not limited to: secure communication by applying SSL certificates; salt
and hash passwords for storage; use HTML encoding to prevent cross-site scripting attacks (ANTI-XSS
Library); implement deferred validation and handle unvalidated requests, for example, form, querystring,
and URL; prevent SQL injection attacks by parameterizing queries; prevent cross-site request forgeries
(XSRF)
■ turn off validation on action [ValidateInput(false)] on property [AllowHtml]
■ deferred validation, means that a value is not validated until it is used
■ AntiXSS library
● Encoder.JavaScriptEncode, UrlEncode, HtmlEncode
● Sanitizer.GetSafeHtml, GetSafeHtmlFragment
■ <deployment retail="true" /> i ​Machine.Config
● turn off debug, trace and customErrors=”On”

Web.config Transformations
<connectionStrings>
<add name="MyDB"
connectionString="value for the deployed Web.config file"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
<system.web>
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
</system.web>
xdt:Locator=(Condition(@name=’oldname’ or …
xdt:Transform=”Replace|Insert|InsertBefore(xpath)|InsertAfter|Remove|RemoveAll|RemoveAttributes”

You might also like