You are on page 1of 16

NotesforExam70486 DevelopingASP.

NETMVC 4WebApplications
Note:thesenotesdonotbreachanyagreementwithmicrosoft.TheyweremadebeforeI tookthetest(20121008whichwasfourdaysafteritwasreleased).Ipassedtheexam. Somenotesmaybeinswedishstill,letmeknowifyoufindany.Dropmealineormention meontwitter(@Mellbourn)orGoogle+(klas@mellbourn.net)ifyoufindthisguideuseful.If youwanttoimprovethedocument,commentitand/orcontactmeforwriteaccess. Manylinksareincludedbelow,butevenmoreareat http://www.delicious.com/mellbourn/70__486 IhavealsomadenotesforExam70480:ProgramminginHTML5withJavaScriptandCSS3
DesigntheApplicationArchitecture

Plantheapplicationlayers. Thisobjectivemayincludebutisnotlimitedto:plandataaccessplanforseparationofconcerns appropriateuseofmodels,views,andcontrollerschoosebetweenclientsideandserverside processingdesignforscalability

plandataaccess?

Designadistributedapplication. Thisobjectivemayincludebutisnotlimitedto:designahybridapplication(onpremisevs.offpremise, includingWindowsAzure)planforsessionmanagementinadistributedenvironmentplanwebfarms

http://www.windowsazure.com/enus/develop/net/fundamentals/in trotowindowsazure/
IfrastructureasaService(IaaS) PlatformasaService(PaaS)

webrole(runsinIIS,cancommunicate) workerrole maintainstatenotintheroles,butindatamanagement

sQLDatabase(ejSQLServer) tables(Key/valuestorenosql) Blobs(media)

Communication

CanbeviewedasWindowsfilsystem

Queue

shortlived(lessthan7days)morethan5GB // 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(message); // Peek at the next message CloudQueueMessage peekedMessage = queue.PeekMessage();

Servicebus

(pub/sub) whenyouneedWCF transactions,atomicity FIFO(Firstinfirstout)

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();

DesignandimplementtheWindowsAzurerolelifecycle. Thisobjectivemayincludebutisnotlimitedto:identifyandimplementStart,Run,andStop eventsidentifystartuptasks(IISconfiguration[apppool],registryconfiguration,thirdpartytools)

http://brentdacodemonkey.wordpress.com/2011/09/24/leveragingtheroleentrypointyea rofazureweek12/ inheritRoleEntryPoint p u b l i c o v e r r i d e b o o l O n S t a r t ( )

w e b r o l e ( w h i c h d o e s n o t h a v e t o i n h e r i t R o l e E n t r y P o i n t ) m u s t t a k e a m a x i m u m o f f i v e m i n u t e s

p u b l i c o v e r r i d e b o o l O n S t o p ( )

p u b l i c o v e r r i d e v o i d R u n ( ) S e r v i c e P o i n t M a n a g e r . D e f a u l t C o n n e c t i o n L i m i t = 1 2 R o l e E n v i r o n m e n t . S t o p p i n g + = R o l e E n v i r o n m e n t . C h a n g i n g + = ( s e r v i c e c o n f i g c h a n g e s )

Wecanoptionallydecidetorestartourroleinstancebysettingthe eventsRoleEnvironmentChangingEventArgs.Cancelpropertytotrueduringthe Changingevent


windowsstartuptasks

S i m p l e (waitsuntilfinishedboforestartingother),B a c k g r o u n d ,F o r e g r o u n d < S e r v i c e D e f i n i t i o n > < W e b R o l en a m e = W e b R o l e 1 v m s i z e = S m a l l > < S t a r t u p > < T a s kc o m m a n d L i n e = I n s t a l l . c m d e x e c u t i o n C o n t e x t = e l e v a t e d t a s k T y p e = b a c k g r o u n d / > < / S t a r t u p > < S i t e s > < S i t en a m e = W e b > < B i n d i n g s > < B i n d i n gn a m e = E n d p o i n t 1 e n d p o i n t n a m e = E n d p o i n t 1 > < I m p o r t s > < I m p o r tm o d u l e N a m e = D i a g n o s t i c s / > 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"/>

forinstallation(webPI)registrysettings,comcomponents


Configurestatemanagement. Thisobjectivemayincludebutisnotlimitedto:chooseastatemanagementmechanism(inprocessand outofprocessstatemanagement,ViewState)planforscalabilityusecookiesorlocalstorageto maintainstateapplyconfigurationsettingsinweb.configfileimplementsessionlessstate(for example,QueryString)

sessionstate:inprocess,outofprocess,sqlservermode

< c o n f i g u r a t i o n > < s e s s i o n s t a t e m o d e = " s q l s e r v e r " c o o k i e l e s s = " f a l s e " t i m e o u t = " 2 0 " s q l c o n n e c t i o n s t r i n g = " d a t as o u r c e = M y S q l S e r v e r ; u s e ri d = A S P S t a t e ; p a s s w o r d = 1 G r 8 S t a t e " s e r v e r = " 1 2 7 . 0 . 0 . 1 " p o r t = " 4 2 4 2 4 " / > s q l c o n n e c t i o n s t r i n g = " d a t as o u r c e = 1 2 7 . 0 . 0 . 1 ; u s e r i d = < u s e ri d > ; p a s s w o r d = < p a s s w o r d > "

Designacachingstrategy. Thisobjectivemayincludebutisnotlimitedto:implementpageoutputcaching(performanceoriented) implementdatacachingimplementHTTPcaching

Azureinmemorycashing

nugetpackage:azurecaching...

inyourcode: D a t a C a c h ec a c h e c a c h e . G e t ( n a m e ) c a c h e . A d d ( n a m e ,d a t a ) c a c h e . P u t ( n a m e ,d a t a )
[OutputCache(Duration,VaryByParam,VaryByContentEncoding, VaryByHeader,CacheProfile)]inactionorcontroller datacachingwithgoodoldCache[name] Cache.Add(key,value,CacheDependency,DateTime,TimeSpan, CacheItemPriority,CacheItemRemovedCallback)

Oldwayofcaching:System.Web.Caching

(CacheDependencycanpointoutfilepath)

Newwaystocachein.NET4System.Runtime.Caching ObjectCache//abstract,implementedby MemoryCache

Add,Set,Get,Remove

O b j e c t C a c h e c a c h e = M e m o r y C a c h e . D e f a u l t s t r i n g f i l e C o n t e n t s = c a c h e [ " f i l e c o n t e n t s " ] a s s t r i n g i f ( f i l e C o n t e n t s = = n u l l ) { C a c h e I t e m P o l i c y p o l i c y = n e w C a c h e I t e m P o l i c y ( ) p o l i c y . A b s o l u t e E x p i r a t i o n = D a t e T i m e O f f s e t . N o w . A d d S e c o n d s ( 6 0 . 0 ) L i s t < s t r i n g > f i l e P a t h s = n e w L i s t < s t r i n g > ( ) s t r i n g c a c h e d F i l e P a t h = S e r v e r . M a p P a t h ( " ~ " ) + " \ \ c a c h e T e x t . t x t " f i l e P a t h s . A d d ( c a c h e d F i l e P a t h )

p o l i c y . C h a n g e M o n i t o r s . A d d ( n e w H o s t F i l e C h a n g e M o n i t o r ( f i l e P a t h s ) ) / / F e t c h t h e f i l e c o n t e n t s . f i l e C o n t e n t s = F i l e . R e a d A l l T e x t ( c a c h e d F i l e P a t h ) c a c h e . S e t ( " f i l e c o n t e n t s " , f i l e C o n t e n t s , p o l i c y )

httpcaching

R e s p o n s e . C a c h e . S e t E T a g F r o m F i l e D e p e n d e n c i e s ( )/ / g e n e r a t e sE T a gn i c e ! R e s p o n s e . C a c h e . S e t V a l i d U n t i l E x p i r e s ( t r u e ) ;/ /i g n o r e c a c h e c o n t r o lh e a d e r se r r o n e u s l ys e n tb yb r o w s e r Response.Cache.SetExpires(DateTime.Now.AddYears(1) R e s p o n s e . C a c h e . S e t M a x A g e ( T i m e S p a n . F r o m S e c o n d s ( 6 0*1 0 ) / /s i m p l e rt h a ne x p i r ed a t e

o ri nc o n f i g : < s t a t i c C o n t e n t > < c l i e n t C a c h ec a c h e C o n t r o l M o d e = " U s e E x p i r e s " c a c h e C o n t r o l C u s t o m = " p u b l i c "h t t p E x p i r e s = " T u e ,0 1O c t2 0 3 0

0 1 : 0 1 : 0 1 ,G M T "/ >

o r < c l i e n t C a c h ec a c h e C o n t r o l M o d e = " U s e M a x A g e " c a c h e C o n t r o l M a x A g e = " 1 : 0 0 : 0 0 "c a c h e C o n t r o l C u s t o m = " p u b l i c "/ > < / s t a t i c C o n t e n t >

DesignandimplementaWebSocketstrategy. Thisobjectivemayincludebutisnotlimitedto:readandwritestringandbinarydataasynchronously (longrunningdatatransfers)chooseaconnectionlossstrategydecideastrategyforwhentouse WebSockets

AsyncControllermedasyncTask<ActionResult>,await

[ A s y n c T i m e o u t ( 1 5 0 ) ] [ H a n d l e E r r o r ( E x c e p t i o n T y p e=t y p e o f ( T i m e o u t E x c e p t i o n ) , V i e w=" T i m e o u t E r r o r " ) ]


publicasyncTask<ActionResult>PWGtimeOut(CancellationTokencancellationToken)

connectionlossstrategy?

Response.Closetocloseaconnectiononpurpose(avoidDOS)

strategyforwhentouseWebsockets (oldtech:longpolling)usewebsocketswhenlowlatencyisimportant(games,chat, realtime).Notethatyouneedtosupporthighconcurrency(manyopenwebsockets) var connection = new WebSocket('ws://h.com', ['soap', 'xmpp']); connection.onopen//event:nowyouareallowedtosend connection.onerror//event connection.Send(yourmessage)//orbinarybufferorblob //serversendingtobrowser: connection.onmessage = function(e) { console.log(e.data)

DesignHTTPmodulesandhandlers. Thisobjectivemayincludebutisnotlimitedto:implementsynchronousandasynchronousmodulesand handlerschoosebetweenmodulesandhandlersinIIS

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] BeginProcessRequest(context, callback, data) EndProcessRequest [do cleanup, e.g. throw exceptions]

IHttpAsyncHandler - returns response before done

p u b l i cc l a s sC u s t o m A s y n c H a n d l e r:H t t p T a s k A s y n c H a n d l e r { p u b l i co v e r r i d ea s y n cT a s kP r o c e s s R e q u e s t A s y n c ( H t t p C o n t e x t )

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
< s y s t e m . w e b > < h t t p H a n d l e r s > < a d d v e r b = " G E T , H E A D " p a t h = " * . N e w " t y p e = " M y H a n d l e r . N e w , M y H a n d l e r " / >

< s y s t e m . w e b S e r v e r >

< h a n d l e r s > < a d d . . . 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

I H t t p M o d u l e

I n i t ( H t t p A p p p l i c a t i o n )

a p p l i c a t i o n . B e g i n R e q u e s t+ = H t t p A p p l i c a t i o n

B e g i n R e q u e s t ,A u t h e n t i c a t e R e q u e s t , P o s t A u t h e n t i c a t e R e q u e s t , P r e R e q u e s t H a n d l e r E x e c u t e , P o s t R e q u e s t H a n d l e r E x e c u t e ,L o g R e q u e s t , E n d R e q u e s t

II7inintegratedmoderunsmanagedcodemodulesinaunifiedpiplinethatcan handleallrequests(notjustASP.NET)

Classicmoderegistration

< c o n f i g u r a t i o n > < s y s t e m . w e b > < h t t p M o d u l e s > < a d dn a m e = " H e l l o W o r l d M o d u l e " t y p e = " H e l l o W o r l d M o d u l e " / > < c o n f i g u r a t i o n > < s y s t e m . w e b S e r v e r > < m o d u l e s > < a d dn a m e = " H e l l o W o r l d M o d u l e " t y p e = " H e l l o W o r l d M o d u l e " / >

Integratedmoderegistration

Note:MvcApplicationinGlobal.asax.csinheritsfromHttpApplication,andcan thushandleallthesamerequests(butisnotasreusable)

justcreatemethodsnamedApplication_eventinglobal.asax: p u b l i cv o i dA p p l i c a t i o n _ L o g R e q u e s t ( o b j e c t s e n d e r ,E v e n t A r g se ) { H t t p A p p l i c a t i o nh t t p A p p l i c a t i o n= ( H t t p A p p l i c a t i o n ) s e n d e r ; D e b u g . W r i t e L i n e ( " l o g :"+ h t t p A p p l i c a t i o n . R e q u e s t . B r o w s e r . B r o w s e r ) ; }

Asyncmodule(link):writeaasync/awaitmethod(hereWriteLogmessages)in themodule,registerlikethisininit():


HttpContext

EventHandlerTaskAsyncHelperasyncHelper=new EventHandlerTaskAsyncHelper(WriteLogmessages) application.AddOnPostAuthorizeRequestAsync( asyncHelper.BeginEventHandler,asyncHelper.EndEventHandler)

Application Cache[]

Error Items[] RequestHttpRequest

Browser ContentEncoding []orParamswhichistheunionof


DesigntheUserExperience Mvc.Controller HttpContext Request Response Server Session TempData[key] Headers Url

Form[formvariables] Cookies QueryString

UserHostName HttpMethod

Response OutPutaTextWriter OutPutStreamaStreamforbinaryresponse CacheaCachePolicy Cookies Headers StatusCode

ServeraHttpServerUtility HtmlEnocde,UrlEncode HtmlDecode,UrlDecode MapPath Transferterminatesandexecutesanotherpage

Session[key]HttpSessionState

Mvc.ViewContext HttpContext Controller RouteData ViewData View(theIView) FormContext

Applytheuserinterfacedesignforawebapplication. Thisobjectivemayincludebutisnotlimitedto:createandapplystylesbyusingCSSstructureandlay outtheuserinterfacebyusingHTMLimplementdynamicpagecontentbasedonadesign DesignandimplementUIbehavior. Thisobjectivemayincludebutisnotlimitedto:implementclientvalidationuseJavaScriptandtheDOM tocontrolapplicationbehaviorextendobjectsbyusingprototypalinheritanceuseAJAXtomake partialpageupdatesimplementtheUIbyusingJQuery

http://phrogz.net/JS/classes/OOPinJS.html http://phrogz.net/JS/classes/OOPinJS2.html
C a t . p r o t o t y p e = n e w M a m m a l ( ) SuperCar.prototype=Object.create(Car.prototype)

ComposetheUIlayoutofanapplication. Thisobjectivemayincludebutisnotlimitedto:implementpartialsforreuseindifferentareasofthe applicationdesignandimplementpagesbyusingRazortemplates(Razorviewengine)designlayouts toprovidevisualstructureimplementmaster/applicationpages Enhanceapplicationbehaviorandstylebasedonbrowserfeaturedetection. Thisobjectivemayincludebutisnotlimitedto:detectbrowserfeaturesandcapabilitiescreateaweb applicationthatrunsacrossmultiplebrowsersandmobiledevicesenhanceapplicationbehaviorand stylebyusingvendorspecificextensions,forexample,CSS

detectbrowserfeaturesandcapabilities? injavascript

navigator.userAgent.indexOf("MSIE")>0
bettertodetectfeaturesandcapabilities

1. 2. 3. 4.
{

i f ( w i n d o w . a d d E v e n t L i s t e n e r ){ / / s u p p o r t s i f ( t y p e o fw i n d o w . a d d E v e n t L i s t e n e r! = = u n d e f i n e d )

if(Modernizr.fontface){

functionisCanvasSupported() var elem = document.createElement('canvas'); return!!(elem.getContext && elem.getContext('2d');

InHTML 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> Ifafeatureislackingyoucanuseshims(proprietartyemulator)orpolyfills(exact
HTML5apiemulator)

vendorspecificextensionstoCSS(oopacity=opacityforopera)


Mobile

moz webkit ms useallversionsandthenwithoutprefixtomakeitworkeverywhere

http://www.asp.net/mvc/tutorials/mvc4/aspnetmvc4mobilefeat ures
CSSmediaqueries

@ m e d i ao n l ys c r e e na n d( m a x w i d t h :8 5 0 p x ){
( s c r e e n a so p p o s e dt o p r i n t o r p r o j e c t i o n )

setviewportinlayout

< m e t an a m e = " v i e w p o r t "c o n t e n t = " w i d t h = d e v i c e w i d t h " >

. M o b i l ee . g .I n d e x . M o b i l e . c s h t m l o rI n d e x . i P h o n e . c s h t m li fy o ud o :

D i s p l a y M o d e s . I n s t a n c e . M o d e s . I n s e r t ( 0 ,n e wD e f a u l t D i s p l a y M o d e ( " i P h o n e " ) { C o n t e x t C o n d i t i o n=( c o n t e x t= >c o n t e x t . G e t O v e r r i d d e n U s e r A g e n t ( ) . I n d e x O f ( " i P h o n e " ,S t r i n g C o m p a r i s o n . O r d i n a l I g n o r e C a s e )> =0 ) } ) ;

H t t p C o n t e x t . R e q u e s t . B r o w s e r . I s M o b i l e D e v i c e HttpBrowserCapabilities.Name,Version,MajorVersion,JavaScript
InstallPackagejQuery.Mobile.MVC

usesd a t a r o l e s < d i vd a t a r o l e = " p a g e "d a t a t h e m e = " b " > < d i vd a t a r o l e = " h e a d e r " < d i vd a t a r o l e = " c o n t e n t " > < u ld a t a r o l e = " l i s t v i e w "d a t a i n s e t = " t r u e " > < l id a t a r o l e = " l i s t d i v i d e r " > N a v i g a t i o n < / l i >

PlananadaptiveUIlayout. Thisobjectivemayincludebutisnotlimitedto:planforrunningapplicationsinbrowsersonmultiple devices(screenresolution,CSS,HTML)planformobilewebapplications DeveloptheUserExperience

Planforsearchengineoptimizationandaccessibility. Thisobjectivemayincludebutisnotlimitedto:useanalyticaltoolstoparseHTMLviewandevaluate conceptualstructurebyusingplugsinforbrowserswritesemanticmarkup(HTML5andARIA)for accessibility,forexample,screenreaders

SEO

unique < t i t l e > foreachpage < m e t an a m e = d e s c r i p t i o n c o n t e n t = B r a n d o n sB a s e b a l l . .. urlswithwords,useasingleurlforapage(301tothecorrectone) easytonavigate(flathierarchy,withbreadcrumb) haveaSitemapfile(xmldescriptionofnavigation) rel=nofollowonlinksincomments

semanticmarkupHTML5 <article> <aside> <section> <figure><figcaption> <nav> <fieldset><legend>(groupbox) <labelfor=inputfieldid

semanticmarkupARIA roles:dialog,directory,grid,heading,main,menu,tree states&properties:ariaautocomplete,ariachecked,ariahaspopup landmarkroles:role=application,banner,form,main,navigation,search liveregions:alert,log,marquee

markregionswitha r i a l i v e = p o l i t e typeofupdate:relevant=additions ariabusy=trueduringupdates

alt=whenpurelydecorative arialabelledbyairadescribedby

Planandimplementglobalizationandlocalization. Thisobjectivemayincludebutisnotlimitedto:planalocalizationstrategycreateandapplyresources toUIincludingJavaScriptresourcessetculturescreatesatelliteresourceassemblies

avoidApp_GlobalResourcesandApp_LocalResourcesinMVC. usePublicResXFileCodeGenerator(togeneratpublic,testableresources) putfoo.fr.resx,foo.de.resxinanyfolder r e s g e nE x a m p l e . r e s o u r c e s . f r . t x t a l/ t : l i b/ e m b e d : E x a m p l e . f r . r e s o u r c e s/ c u l t u r e : f r / o u t : f r \ E x a m p l e . r e s o u r c e s . d l l folderstrukturfr\Example.resources.dll

< g l o b a l i z a t i o ne n a b l e c l i e n t b a s e d c u l t u r e = " t r u e " u i c u l t u r e = " a u t o "c u l t u r e = " a u t o " >


HTTPHeadercalled"AcceptLanguage"

i nj Q u e r y :

$ . g l o b a l . p r e f e r C u l t u r e ( t h e n$ . f o r m a tw o r k sw e l l :

$ . f o r m a t ( n e wD a t e ( 1 9 7 2 ,2 ,5 ) ," D " ) ;

DesignandimplementMVCcontrollersandactions. Thisobjectivemayincludebutisnotlimitedto:applyauthorizationattributesandglobalfilters implementactionbehaviorsimplementactionresultsimplementmodelbinding

GlobalFilters.Filters.Add(newLogFilterAttribute()) inheritfromActionFilterAttribute,implement

OnActionExecuting OnActionExecuted OnResultExecuting(afteractionexecutedbeforethereturnedresultisused) OnResultExecuted

Designandimplementroutes. Thisobjectivemayincludebutisnotlimitedto:definearoutetohandleaURLpatternapplyroute constraintsignoreURLpatternsaddcustomrouteparametersdefineareas AddAreaonsolution,createssubclassesofAreaRegistration public class HelpDeskAreaRegistration : AreaRegistration { public override string AreaName { get { return "HelpDesk"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "HelpDesk_default", "HelpDesk/{controller}/{action}/{id}", ControlapplicationbehaviorbyusingMVCextensibilitypoints. Thisobjectivemayincludebutisnotlimitedto:implementMVCfiltersandcontrollerfactoriescontrol applicationbehaviorbyusingactionresults,viewengines,modelbinders,androutehandlers

I g n o r e R o u t e

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.

subclassDefaultControllerFactoryandoverrideCreateController(requestcontext,name) tomapnametocontrollertype orimplementIControllerActivatorandoverrideCreate(context,type)

Reducenetworkbandwidth. Thisobjectivemayincludebutisnotlimitedto:bundleandminifyscripts(CSSandJavaScript) compressanddecompressdata(usinggzip/deflatestorage)planacontentdeliverynetwork(CDN) strategy,forexample,WindowsAzureCDN

minificationonlyturnedonfor< c o m p i l a t i o nd e b u g = " f a l s e "/ > (or BundelTable.EnableOptimizations=true

b u n d l e s . A d d ( n e wS c r i p t B u n d l e ( " ~ / b u n d l e s / j q u e r y " ) . I n c l u d e ( " ~ / S c r i p t s / j q u e r y { v e r s i o n } . j s " ) ) ; b u n d l e s . U s e C d n=t r u e ; / / e n a b l eC D Ns u p p o r t

/ / a d dl i n kt oj q u e r yo nt h eC D N v a rj q u e r y C d n P a t h= " h t t p : / / a j a x . a s p n e t c d n . c o m / a j a x / j Q u e r y / j q u e r y 1 . 7 . 1 . m i n . j s " ; b u n d l e s . A d d ( n e wS c r i p t B u n d l e ( " ~ / b u n d l e s / j q u e r y " , j q u e r y C d n P a t h ) . I n c l u d e ( " ~ / S c r i p t s / j q u e r y { v e r s i o n } . j s " ) ) ;

@Scripts.Render(~/bundles/jquery) newminifierscanbeloadedaspackages(ormadeusingimplementingIBundleTransform) WindowsAxuresellscustomizedCDNservice howdoyou(un)configuregzip

@Styles.Render

C o n t e n t E n c o d i n g :g z i p YoucancreatesuchstreamswithGZipInputStream,ZipInputStream(whenusing HttpWebResponse/HttpWebRequest.GetResponse()) TroubleshootandDebugWebApplications

Headers: A c c e p t E n c o d i n g :g z i p ,d e f l a t e

Preventandtroubleshootruntimeissues. Thisobjectivemayincludebutisnotlimitedto:troubleshootperformance,security,and errorsimplementtracing,logging(includingusingattributesforlogging),anddebugging(including IntelliTrace)enforceconditionsbyusingcodecontractsenableandconfigurehealthmonitoring (includingPerformanceMonitor)

DebuginDebugbuilds,Traceinallbuilds

Debug.Listeners.Add(newXmlWriterListener()) Debug.Indent() switchlevel4givesyouthemostlogging

< s y s t e m . d i a g n o s t i c s > < s w i t c h e s > < a d dn a m e = " G e n e r a l "v a l u e = " 4 "/ > < / s w i t c h e s > < t r a c ea u t o f l u s h = " t r u e "i n d e n t s i z e = " 2 " > < l i s t e n e r s > < a d dn a m e = " m y L i s t e n e r " t y p e = " S y s t e m . D i a g n o s t i c s . T e x t W r i t e r T r a c e L i s t e n e r ,
TraceSwitchs=newTraceSwitch(General,desc) Trace.WriteIf(s.TraceWarning,thiswrittenifvalue>=2)


EventLog

E v e n t L o g . C r e a t e E v e n t S o u r c e ( " M y S o u r c e " ," M y N e w L o g " ) ;

E v e n t L o gm y L o g=n e wE v e n t L o g ( ) ; m y L o g . S o u r c e=" M y S o u r c e " ; m y L o g . W r i t e E n t r y ( " W r i t i n gt oe v e n tl o g . " ) ;


createacategory

PerformanceCounters

P e r f o r m a n c e C o u n t e r C a t e g o r y . C r e a t e ( m y c a t e g o r y ) c r e a t ec o u n t e r
counter= n e wP e r f o r m a n c e C o u n t e r ( m y c a t e g o r y ,

c o u n t e r n a m e
adjustcounter

counter.Increment()//threadsafe counter.RawValue=

readcounter counter.NextValue,NextSample

Attributesforlogging:usingfilters?

O n A c t i o n E x e c u t i n g ( A c t i o n E x e c u t i n g C o n t e x t
context.ActionDescriptor.ControllerDescriptor.ControllerName

CodeContracts Contract.Requires<ArgumentException>(id>0) Contract.Requires(Contract.ForAll(customerIds,(id)=>id>0)) Contract.Ensures()postcondition Contract.Invariant(x!=0)//testedatendofpublicmethod Contract.AssumesameasContract.Assert

Healthmonitoringhttp://forums.asp.net/t/1027461.aspx <healthMonitoringenabled="true"> <providers> <addname="sqlProvider" type="System.Web.Management.SqlWebEventProvider" connectionStringName="appDB" buffer="false" bufferMode="Notification"/> </providers> <rules> <addname="lifeCycle" provider="sqlProvider" eventName="ApplicationLifetimeEvents"/> </rules> </healthMonitoring>

Intellitrace collectsiniTracefile decideeventstocollect,ifyouwanttocollectcallinformation. decidewhatmodulestocollectinformationabout IntellitraceSC.exelaunch/cp:collection_plan.ASP.NET.default.xml standalonecollectorcanbeinstalledtomonitorproduction

powershellintegratedStartIntelliTraceCollection

< M o d u l e L i s ti s E x c l u s i o n L i s t = " f a l s e " > < N a m e > P u b l i c K e y T o k e n : B 7 7 A 5 C 5 6 1 9 3 4 E 0 8 9 < / N a m e > < N a m e > F a b r i k a m F i b e r . W e b . d l l < / N a m e >

Designanexceptionhandlingstrategy. Thisobjectivemayincludebutisnotlimitedto:handleexceptionsacrossmultiplelayersdisplay customerrorpagesusingglobal.asaxorcreatingyourownHTTPHandlerorsetweb.configattributes handlefirstchanceexceptions

goodarticleonerrorhandling HandleErrorglobalfilterisregisteredinFilterConfig HandleErrordirectstotheShared\Error.cshtmlpageifcustomerrorsareon Error.cshtmlhasthemodelHandleErrorInfo,withpropertiesActionName, ControllerName,Exception specializederrorhandling: [HandleError(Exception=typeof(DbException),View=DbError)] HandleErrorsuppressesdefaulterrorlogging!

youshouldextendHandleErrorwithlogging

HandleErroronlycatches500errors(e.g.not404)andonlyinsidecontrollers Application_ErrorhandlesallerrorsbutknowsnaughtaboutMVC.ELMAHhasbestof bothworlds p r o t e c t e dv o i dA p p l i c a t i o n _ E r r o r ( o b j e c ts e n d e r ,E v e n t A r g se ) S e r v e r . G e t L a s t E r r o r ( ) < c u s t o m E r r o r sd e f a u l t R e d i r e c t = " h t t p : / / h o s t N a m e / a p p l / e r r o r S t a t u s . h t m " m o d e = " O n " > < e r r o rs t a t u s C o d e = " 4 0 4 "r e d i r e c t = " f i l e n o t f o u n d . h t m "/ > < / c u s t o m E r r o r s >

Testawebapplication. Thisobjectivemayincludebutisnotlimitedto:createandrununittests,forexample,usetheAssert class,createmockscreateandrunwebtests

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,
youcanbindtestdatatoadatabase youcanaddValidation Rule that requries Find Text youcanaddExtractionrulewithExtract Attribute Value to extract html attributes (class etc) youcancreateLoad Test

there you can select Avg Page Time counter node and select Add Threshold Rule.

DebugaWindowsAzureapplication. Thisobjectivemayincludebutisnotlimitedto:collectdiagnosticinformationbyusingWindowsAzure DiagnosticsAPIImplementondemandvs.scheduledchooselogtypes,forexample,eventlogs, performancecounters,andcrashdumpsdebugaWindowsAzureapplicationbyusingIntelliTrace andRemoteDesktopProtocol(RDP)

readuponazurelogging! DesignandImplementSecurity
Configureauthentication. Thisobjectivemayincludebutisnotlimitedto:authenticateusersenforceauthenticationsettings choosebetweenWindows,Forms,andcustomauthenticationmanageusersessionbyusingcookies

configuremembershipproviderscreatecustommembershipproviders

IIdentityisusernameandauthtype IPrincipalisiidentityandIsInRole,oftenusedforauthenticatingrole customprivider:inhertMembershipProvider

ValdiateUser() ResetPassword() MinRequiredPasswordLength RequiresQuestionAndAnswer

< m e m b e r s h i pd e f a u l t P r o v i d e r = " O d b c P r o v i d e r " u s e r I s O n l i n e T i m e W i n d o w = " 1 5 " > < p r o v i d e r s > < a d d n a m e = " O d b c P r o v i d e r " t y p e = " S a m p l e s . A s p N e t . M e m b e r s h i p . O d b c M e m b e r s h i p P r o v i d e r " c o n n e c t i o n S t r i n g N a m e = " O d b c S e r v i c e s " e n a b l e P a s s w o r d R e t r i e v a l = " t r u e " e n a b l e P a s s w o r d R e s e t = " t r u e " r e q u i r e s Q u e s t i o n A n d A n s w e r = " t r u e " w r i t e E x c e p t i o n s T o E v e n t L o g = " t r u e "/ > < / p r o v i d e r s > < / m e m b e r s h i p >

Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal) WindowsPrincipalmyPrincipal=(WindowsPrincipal)Thread.CurrentPrincipal

Configureandapplyauthorization. Thisobjectivemayincludebutisnotlimitedto:createrolesauthorizerolesbyusingconfiguration authorizerolesprogrammaticallycreatecustomroleprovidersimplementWCFserviceauthorization

WCFServiceauthorization?

Security:Messagebasedortransportbased rolebasedauthorization

IIdentity currentUser = ServiceSecurityContext.Current.PrimaryIdentity; if (Roles.IsUserInRole(currentUser.Name, "Member"))


InheritRoleProvider,implementmanyrequiredmethods

createcustomroleproviders?

CreateRole AddUsersToRole IsUserInRole(string,string)

Designandimplementclaimsbasedauthenticationacrossfederatedidentitystores. Thisobjectivemayincludebutisnotlimitedto:implementfederatedauthenticationbyusingWindows AzureAccessControlServicecreateacustomsecuritytokenbyusingWindowsIdentityFoundation handletokenformats(forexample,oAuth,OpenID,LiveID,andFacebook)forSAMLandSWTtokens

howtoimplementoauth,livied,fbetconyourmvcsite OAuthWebSecurity.RegisterTwitterClient OAuthWebSecurity.RegisterFacebookClient( appId:"",

appSecret:"") OAuthWebSecurity.RegisterMicrosoftClient OAuthWebSecurity.RegisterGoogleClien Claims: ClaimsPrincipalnowbaseclasstoWindowsPrincipal,GenericPrincipal,RolePrincipal Claimsarenotwhatthesubjectcanandcannotdo.Theyarewhatthesubjectisoris not.authenitcated/issuedbytheSecurityTokenService(STS)(akaIdentityprovider) AClaimobjecthasclaimT y p e ,V a l u e andV a l u e T y p e (givenname,klas,string) ClaimsaregroupedinaTokenthatissigned.SAML(SecurityAssertionMarkup Language)andSWT(SimplewebToken)areformats.RelayingParty(RP)istheusing website. BothClaimsPrincipalandCliamsIdentityhaveClaims,usetheprincipal C l a i m s P r i n c i p a l P e r m i s s i o n . C h e c k A c c e s s tocheckaccessincode C l a i m s A u t h e n t i c a t i o n M a n a g e r . A u t h e n t i c a t e canbesubclassedandimplemented tointerceptC l a i m s I d e n t i t y C o l l e c t i o n andmodifyit Youcanconfigureawebbasedapplicationwithacustomclaimsauthorizationmanager, aninstanceofaclassthatderivesfromtheC l a i m s A u t h o r i z a t i o n M a n a g e r class. Whensoconfigured,therequestprocessingpipelinepackagestheincoming C l a i m s P r i n c i p a l inanA u t h o r i z a t i o n C o n t e x t andinvokestheC h e c k A c c e s s methodonyourclaimsauthorizationmanager.C l a i m s P r i n c i p a l P e r m i s s i o n A t t r i b u t e canbeusedtoprotectcode

<applicationService> <claimsAuthorizationManager>

TheRPgetstheC l a i m s P r i n c i p a lp r i n c i p a l=H t t p C o n t e x t . C u r r e n t . U s e ra s C l a i m s P r i n c i p a l ; aFederatedProvider(FP)liesbetweenRPandIdentityProvidersandtransformsclaims inawaythatRPunderstands.WindowsAzureAccessControlService(ACS)isaFP HowtowritecustomtokensinWIFsubclassSecurityTokenHandlerand SecurityToken.Web.configinRPneedsa<microsoft.identityModel>with <federatedAuthetication>thatspecifiestheSTSused

Managedataintegrity. Thisobjectivemayincludebutisnotlimitedto:applyencryptiontoapplicationdataapplyencryptionto theconfigurationsectionsofanapplicationsignapplicationdatatopreventtampering

encryptdata

R i j n d a e l a l g = R i j n d a e l . C r e a t e ( ) a l g . K e y = K e y a l g . I V = I V c s = n e w C r y p t o S t r e a m ( m s , a l g . C r e a t e E n c r y p t o r ( ) , C r y p t o S t r e a m M o d e . W r i t e )

encryptconfigurationsections createkeys(exportableinCSP):

aspnet_regiispc"SampleKeys"exp

configuretousethem:

< c o n f i g P r o t e c t e d D a t a > < p r o v i d e r s > < a d dn a m e = " S a m p l e P r o v i d e r " t y p e = " S y s t e m . C o n f i g u r a t i o n . R s a P r o t e c t e d C o n f i g u r a t i o n P r o v i d e r , k e y C o n t a i n e r N a m e = " S a m p l e K e y s "

a s p n e t _ r e g i i sp e" c o n n e c t i o n S t r i n g s "a p p " / S a m p l e A p p l i c a t i o n "p r o v " R s a P r o t e c t e d C o n f i g u r a t i o n P r o v i d e r "

signapplicationdata? R S A C r y p t o S e r v i c e P r o v i d e rR S A a l g=n e wR S A C r y p t o S e r v i c e P r o v i d e r ( ) ; R S A a l g . I m p o r t P a r a m e t e r s ( K e y ) ; r e t u r nR S A a l g . S i g n D a t a ( D a t a T o S i g n , I n d e x , L e n g t h ,n e w S H A 1 C r y p t o S e r v i c e P r o v i d e r ( ) ) ; R S A a l g . V e r i f y D a t a ( D a t a T o V e r i f y ,S H A 1 C r y p t o S e r v i c e P o v i d e r ( ) ,S i g n e d D a t a )

ImplementasecuresitewithASP.NET. Thisobjectivemayincludebutisnotlimitedto:securecommunicationbyapplyingSSLcertificatessalt andhashpasswordsforstorageuseHTMLencodingtopreventcrosssitescriptingattacks (ANTIXSSLibrary)implementdeferredvalidationandhandleunvalidatedrequests,forexample,form, querystring,andURLpreventSQLinjectionattacksbyparameterizingqueriespreventcrosssite requestforgeries(XSRF)

turnoffvalidationonaction[ValidateInput(false)]onproperty[AllowHtml] deferredvalidation,meansthatavalueisnotvalidateduntilitisused AntiXSSlibrary


Web.configTransformations

Encoder.JavaScriptEncode,UrlEncode,HtmlEncode Sanitizer.GetSafeHtml,GetSafeHtmlFragment

< d e p l o y m e n tr e t a i l = " t r u e "/ >iM a c h i n e . C o n f i g


stngeravdebug,traceochcustomErrors=On

< c o n n e c t i o n S t r i n g s > < a d dn a m e = " M y D B " c o n n e c t i o n S t r i n g = " v a l u ef o rt h ed e p l o y e dW e b . c o n f i gf i l e " x d t : T r a n s f o r m = " S e t A t t r i b u t e s "x d t : L o c a t o r = " M a t c h ( n a m e ) " / > < / c o n n e c t i o n S t r i n g s > < s y s t e m . w e b > < c u s t o m E r r o r sd e f a u l t R e d i r e c t = " G e n e r i c E r r o r . h t m " m o d e = " R e m o t e O n l y "x d t : T r a n s f o r m = " R e p l a c e " > < e r r o rs t a t u s C o d e = " 5 0 0 "r e d i r e c t = " I n t e r n a l E r r o r . h t m " / > < / c u s t o m E r r o r s > < / s y s t e m . w e b >
x d t : L o c a t o r = ( C o n d i t i o n ( @ n a m e = o l d n a m e o r x d t : T r a n s f o r m = R e p l a c e | I n s e r t | I n s e r t B e f o r e ( x p a t h ) | I n s e r t A f t e r | R e m o v e | R e m o v e A l l | R e m o v e A t t r i b u t e s