Anda di halaman 1dari 20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

barbarianmeetscoding
WebDev,UX&aPinchofFantasy
RSS
Search

AboutMe
Blog
Now
Videos
Projects
BestArticles
Archives
Books
Wiki
SubscribeRSS
SubscribeEmail

LearnJavaScript!
GetMyBook!!:)
RSS
Search

AboutMe
Blog
Now
Videos
Projects
BestArticles
Archives
Books
Wiki
SubscribeRSS
SubscribeEmail

Notesforthe70486ASP.NETMVCCertification
May12th,2015
ThisarticleispartofmypersonalwikiwhereIwritepersonalnoteswhileIamlearningnewtechnologies.Youarewelcometouseitforyourownlearning!
Hi!AsIwasstudyingforthe70486Icompiledabunchofnotesandlinksforthedifferentsectionsthatgointotheexam.IfindthatIlearnthingsbetterwhenIread
themandwritethemdownwithmyownwordsandexplanations.Mostofthenotesareasummary/paraphrasingoftheexamreferencebookanddocumentationsites
ontheinternet.Hopetheyhelp!
Thesearethetopicscoveredinthiscertification:

Designtheapplicationarchitecture(1520%)
Plantheapplicationlayers(BasicStuff)
Plandataaccess
TODO

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

1/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

TODO
READbasicsofEntityFramework
READbasicADO.NETstuff(DataAdaptersandDataReaders)
PlanforSOC:separationofconcern
AppropriateuseofMVCarchitecture
Choosebtwclientsideandserversideprocessing
Designforscalability

Designadistributedapplication
Integratingwebservices
TODO
**EXERCISE**CreatebasicWebAPIservice
**EXERCISE**ConsumeRESTserviceusing`HttpService`

Designahybridapplication(onpremisevsoffpremise)
TODOS
READ
UsingtheAzureServiceBusforCreatingHybridApps
SummaryofBindingsinAzureServiceBus
NetEventRelayBinding:Allowspublisherstobroadcastonewaymessagestomultiplesubscribers
BasicHttpRelayBinding:UsedtocommunicatewithservicesthatadheretoWSIbasicprofile1.1.ComparabletoWCFBasicHttpBinding
NetTcpRelayBinding:Efficientbidirectionalbinding.Supportsbothrelayedandhybridconnectionmodes.Therelayedconnectionmoderoutesalltraffic

throughtheservicebuswithnodirectconnectionbetweentheclientandtheservice.Thehybridconnectionhoweverbeginstheconnectinrelaymodeand
thenattempstoswitchtoadirectconnectionifpossible.ItiscomparabletotheWCFNetTcpBinding.
WebHttpRelayBinding:ItisusedtoeposeRESTlikeendpointstoclients.ItiscomparabletotheWCFWebHttpBinding.
Planforsessionmanagementindistributedenvironments
Asessionisstoredonaserverandisuniqueforauserscollectionofinteractionswiththeserver.ItisidentifiedbyauniquridentifiersessionIdthatcanbesent
fromthebrowsertotheservereitherinasacookieoraqueryparameter.
YoucanapproachsessionsinASP.NETMVCintwoways:eitherusesessionstostoresmallpiecesordata,orfollowthestatelessnessadvocatedbyMVC,forego
sessionsandsendalltheinformationneededfortheservertoperformanoperationontherequestitself.
Sessionmanagementindistributedenvironmentsisevenmoredifficultasawebsitemaybeservedfromdifferentserversordomains,andaservermaybeunaware
thatauserhaspreviouslyinteractedwithanotherserver(youneedawaytosynchronizesessionsindifferentmachines).Thatswhystatelessnessisevenmore
interestinginthesescenariosandweshouldfavortheuseofquerystrings,hiddenfieldsorothermechanismstotransferalltheinformationneeded.
Ifwestillwanttoprovidesupportforsessions,itisgoodtoknowthattherearethreemodesofsessionmanagementavailableinIIS:InProc,StateServerand
SQLServer(bothofthesearealsocalledOutProc).InProcisthedefaultsettinginwhichasessionisstoredinthewebserverslocalmemory(goodperformance,not
goodindistributedenvironments).WithStateServerthesessionstateisstoredwithinaseparateserverandsharedacrossallotherserverswhichaccessthestate
serverthroughaconnectionstring.SQLServermodeworksinasimilarfashiontoStateServerbutforthefactthatthesessionstateisstoredinaSQLserver
databaseandtheadditionalperformanceimpactofmakinganadditionaldatabasecall.
Someexamplesofsessionstatehandling:
1 <!
2 Exampleofapossiblesingleserverconfiguration.
3 Thesessionstateispersistedinmemoryonthewebserverthathoststhewebapplication.
4 Ifthisconfigurationweretobemaintainedinawebfarmscenarioausersessionstatewouldn'tbemaintainedwhenconnectingtoadifferentserver.
5
6 >
7 <sessionStatemode="InProc"/>
8
9 <!
10ExampleofpossibleconfigurationofstatemanagementwithinaWebFarm.
11Sessionstatepersistedinmemorywithinaserver.
12AllotherserverswithinaserverfarmcancontactthatserverviathestateConnectionString.
13Thecookieless="false"storesthesessionIdwithinthebrowsercookieswhereascookieless="true"usesthequerystring.
14>
15<sessionStatemode="StateServer"cookieless="false"stateConnectionString="someConnectionString"/>

PlanningWebFarms
Webfarmsaregroupsofwebserversthatsharetheloadofservingawebapplicationandhandlingwebrequests.SinceASP.NETMVCisbuiltwithseparationof
concernsisminditisverysuitedforwebfarmsscenarios.
Someoftheadvantagesinherenttowebfarmsare:
Highavailability:ifaserverinthefarmgoesdown,theloadbalancerredirectsincomingrequeststootherservers
Improvedperformance:sincetheloadbalancerreducestheloadeachserverhandles,hencedecreasingcontentionissues
Highscalability:asweaddmoreserverstothewebfarm
Itisimportanttonotethatwithinwebfarmconfigurationwecannotassumethatthesessionwillbeavailable,asdifferentuserrequestscanbehandledbydifferent
servers.Thiscanbesolvedeitherbyusingsessionaffinity(stickysessionswhereauserisservedbythesameserver)orusinganOutProcsessionmodelike
StateServerorSQLServer.

DesignandImplementtheAzureRoleLifeCycle
MicrosoftAzureisMicrosoftscloudcomputingplatformthatallowsyoutobuild,deployandmanageyourapplicationsandprovidesamyriadofservicestoease
development,applicationlifecyclemanagement,services,machinelearning,etc.
MicrosoftAzureoffersbothIaaS(infrastructureasaservice)andPaaS(platformasaservice)solution.VirtualMachines(IaaS)allowyoutohavecompletecontrol
overtheenvironmentinwhichyourapplicationswork.Webapps(formerlyknownasWebSitesPaaS)provideahigherlevelofabstractionoverVirtualMachines

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

2/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

overtheenvironmentinwhichyourapplicationswork.Webapps(formerlyknownasWebSitesPaaS)provideahigherlevelofabstractionoverVirtualMachines
andallowyoutoeasilyhostandscaleyourwebapplications.CloudServices(withroles)providesaPaaSsolutionthatisamiddlegroundbetweenwebappsand
VMsviaworkerandwebroles.
IdentifyStartupTasks(IISConfiguration[apppool]andregistryconfiguration)
MicrosoftAzurestartuptasksareusedtoperformactionsbeforearolestarts.Therearethreetypesofroles:Webroles,workerrolesandvirtualmachineroles.They
aresuitableindifferentcases:
webroles:usedtohostIISinAzure
workerroles:usedtohostmiddletierapplicationswithoutIIS
virtualmachineroles:whenwhatyouwanttodoismorecomplicatedthatjusthostingawebsiteonIISoramiddletierapplication.
StartupstasksareonlyavailableforWebandWorkerrolesandaredefinedwithinthetaskelementoftheServiceDefinition.csdeffile.Atypicalstartuptaskcould
betorunaconsoleapplicationorPowerShellscripts.Startuptaskshavethefollowingcharacteristics:
Youcanpassinformationtoataskbyusingenvironmentvariables
youcanreceiveinformationfromthembymakingthetasksavethatinformationondisk
Therunwhentheserverrebootsandeachtimearoleisrecycled
Theyhavetoendwithanerrorlevel0forthestartupprocesstocomplete,andiftheydonttheroledoesnotstart
TheprocessbywhicharolestartsinMicrosoftAzureisasfollows:
1.AroleinstaceismarkedasStartingandwillnolongerreceivetraffic
2.StartuptasksarethenexecutedaccordingtotaskType:
1.simpletasksareexecutedsynchronously
2.backgroundandforegroundtasksarestartedasync(inparallel)
3.TherolehostprocessisstartedandasiteiscreatedinIIS
4.ThetaskcallstheMicrosoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.OnStartmethod
5.TheroleinstanceismarkedasReadyandtrafficisroutedtoit
6.ThetaskcallstheMicrosoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.Runmethod
Someexamplesofcommonstartuptaskscanbe:
ConfiguringyourIISserverusingtheAppCmd.exetool
Adding/Modifyingregistryvariablesthroughascript
Wheneveryouwritestartuptaskstohandletheseconfigurationsyouhavetobeawarethattheymaybeexecutedseveraltimes,soaconfigurationmaybeapplied
twice,andwehavetobeextracarefulsothatthiseventwontaffectthestartupprocessnegatively.Additionally,MicrosoftAzurerolesarestateless,thismeans
thattheyarewipedcleaneverytimearolerestartssoyouhavetobereadytoaddallyourrolesetuptoStartuptasksandstoreinformationinexternalservicessuch
asAzureStorageandnotinthelocaldisk.
Finally,itisimportanttonotethatdeclaringtasksasbackgroundtasks(taskType="background")willpreventAzurefromwaitinguntilthestartcompletesbefore
completingtherolestartupprocess.Anexampleofsuchataskcouldbe:
1<Startup>
2<Taskcommandline="StartPerfMonitors.exe"
3executionContext="elevated"
4taskType="background"/>
5</Startup>

TODO
READIntroductionMicrosoftAzure
WATCHWindowsAzureLifecyclevideos
IdentifyandImplementStart,RunandStopEvents
OncethestartupprocesshascompletedsuccessfullytheroleitselfstartsitslifecycleandgoesthroughtheStart,RunandStopsteps.Youcansuscribetoeitherof
theseeventsifyouwanttoperformadditionaltasksbeforetherolestartsrunning,duringitslifetimeandwhenitisabouttobeterminated.
TheStarteventandtheStartuptasksareverysimilar:bothhavethesametimeout(ifyouarenotoutofeitherfunctiontherolestartupcontinues),theybothare
executedeverytimetheroleisrecycledandyoucanconfigurebothaheadoftherole.Howevertherearesignificantdifferencesbetweenthem:*Astartuptaskruns
inadifferentprocessthattheroleand,assuch,canbeexecutedwithadifferentprivilegelevel.*StatecanbesharedbetweentheOnStartmethod(thathandlesthe
Startevent)andtheRunmethodbecausetheyarebothpartofthesameAppDomain.*Astartuptaskcanbeconfiguredasynchronouslyasabackground/foreground
taskandrunparallelwiththerole
TosubscribetotheStarteventyoucanoverridetheOnStartmethod:
1publicclassWorkerRole:RoleEntryPoint{
2publicoverrideboolOnStart(){
3//dostuff
4returnbase.OnStart;
5}
6}

Notethatifthesemethodreturnsfalsethestartupprocessoftherolewillstop.
AdditionallyyoucanoverridetheRunmethodtoruncodethatwillbeexecutedduringthelifetimeoftherole.WhentheRunmethodreturnssomethingtherole
terminationprocesswillstart.YoucanoverridetheOnEndtoperformcleanuptasksbutbeawarethatallprocessingwillbeterminatedwithin5minutesofthat
methodbeingcalled.
WebrolesalsoprovidetheApplication_StartmethodforinitializationlogicthatisrunimmediatelyaftertheroleOnStartmethod.
TODO
READmoreaboutWebandWorkerroles(probablytheintroductiontoAzurewillbeenough)
READabouttheRoleEntryPointmethods

ConfigureStateManagement
TODO:
READASP.NETStateManagementOverviewwhichincludesacompleteoverviewofallthewaysyoucanmanagestateinASP.NET
ChooseaStateManagementMechanism(InProcorOutProc)

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

3/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

ThefirstthingthatyouhavetothinkaboutwhenyouwanttoimplementastatemanagementmechanisminyourASP.NETMVCapplicationistoaskyourself
whetheryouwantstateornot.ASP.NETMVCisbuilttosupportthestatelessnessoftheweb,inwhicheachrequestprovidesalltheinformationanapplication
needstoperformanoperation,andwhichallowsserverstohandleasmanyconcurrentusersaspossiblesincetheresnoneedforlongrunningconnections,andto
freelyscaleyoursolutionasrequestsareindependentfromeachotherandcanbehandledbydifferentservers.
Thatbeingsaid,therearedifferentwaystomanagestatewithinyourASP.NETMVC4applicationeitherintheclientorintheserver:
usingtheCachewhichisamemorypoolstoredontheserverandsharedacrossusers.Itenablesyoutostorekeyvaluepairsandisessentiallyavailablewithin
anapplicatindomain.Ifplanningtousethissystemwithinawebfarmscenarioeachserverwouldneedtohaveacopyofthecache.
usingtheSession,thatisstoredontheserveranduniqueforeachuser.ItcanbeconfiguredtouseInProcorOutProcconfigurations(StateServer,SQLState),
oritcanbecustomizedbyinheritingfromSessionStateStoreProviderBaseandsettingtheconfigurationtoCustom.
withCookiesthataresmallpiecesofdatastoredintheuserbrowserandsenttotheserverineachrequest.Theyareindividualizedforaparticulardomainor
subdomainandcanbegivenanexpirationdate.CookiescanbeaccessedwithinyourASP.NETMVCapplicationintheHttpContext.Request.Cookiesand
HttpContext.Response.Cookiesproperties.
withintheQueryString,whichispassedaspartoftheURL.Thequerystringisnotpartoftheroutedataandcanbeaccessedvia
HttpContext.Request.QueryString[propertyName]propertyontheserverandinwindows.location.hrefinthebrowser.
insideContext.Items,whichisapartoftheHttpContextandlastonlythelifetimeofarequest.Theyaretypicallyusedtoaddinformationwithintherequest
viaHTTPmodules.(Forinstanceduringauthentication)
theProfilewhichisstoredinthedatabasewhenusingASP.NETMembershipandmaintainsinformationacrossmultiplesessions.Youcanaccessprofile
informationviaHttpContext.Profile["miscellaneousInformation"].
theapplicationstate
Whendecidingtherightstrategyweneedtothinkabout:
Usingclientsidestatemanagementprovidesamoreresponsiveexperiencetotheuserandsavessendingmorerequests/informationtotheserver.Atthesame
timeitcanmaketheapplicationmorecomplicatedwithconcernssuchashowtohandleseveralusersconcurrentlythesameinformationintheclient.
Thesizeoftheinformationbeingstoredisalsoimportantsincesomeapproacheshavelimitationsinthisregards(cookies,queryString).Largeamountsof
informationarebetterhandledwithasessionbackedbyaSQLserverdatabase.
PlanforScalability
Inanscalabilityscenariowhereyouwanttoaddadditionalserversacrossthebreadthofthewebapplication(horizontalscaling)sothateachserverhandleslessof
theoverallloadofthesystem,youcanuseanOutProcsessionmanagement(ServerStateorSQLServer)orgoforasessionlesssolution.
Ifyouwanttomanagestatewithasessionlesssolutionyoullneedtosendtherequiredinformationineveryrequest(withqueryparamsorhiddeninputfieldsfor
example).
TODO:
READASP.NETStateManagementRecommendations
UseCookiesorLocalStoragetoMaintainState
CookiesarethepredecessoroftheHTML5webstorageAPI(local/sessionstorage).Theyaresentbackandforthbetweenthebrowserandtheserverandhavea
limitedsizeof4KB.YoucanusethemwithinyourASP.NETMVCapplicationtopersistinformationbetweenrequests.Theyareoftenusedforstoringlogin
credentialsforauthenticationpurposes.
HTML5WebStorageconsistsoftwoAPIS:
localStorage:thatpersistsinformationforagivenwebapplicationacrossbrowsersessions
andsessionStorage:thatpersistsinformationuntilyouclosethebrowser(ortab)

Theinformationsavedinwebstorageisstoredintheclientbrowserandisnotsenttotheserver(unlikecookies).Youcansubscribetostorageevents.Browser
compatibilitymaybeanissuesincewebstorageisapartofHTML5anditisnotsupportedinolderbrowsers.
YoucandetectbrowsercapabilitiesintheserverbyusingtheRequest.BrowserpropertythatreturnsaHttpBrowserCapabilitiesobject.
ApplyConfigurationSettingsinWeb.Config
YoucanconfigurionASP.NETstatemanagementintheweb.config(ormachine.config)filesviathe<sessionState>elementunder<system.web>.Forinstance,for
anInProcconfiguration:
1<system.web>
2<sessionStatemode="InProc"
3cookieless="false"
4timeout="30"
5stateConnectionString="tcpip=127.0.0.1:42424"/>
6</system.web>

orforanOutProcStateServerconfiguration:
1<system.web>
2<sessionStatemode="StateServer"
3cookieless="false"
4stateConnectionString="tcpip=192.168.1.222:42424"/>
5</system.web>

TODO:
READmoreaboutASP.NETConfiguration
READmoreinformationaboutthesessionStateelement
ImplementSessionlessstate(forexample,usingtheQueryString)
ASP.NETMVCismeanttoembracethestatelessnessofthewebinwhichalltheinformationrequiredforhandlingarequestispartoftherequestitself.Handling
statewithouttheuseofasessioncanbedonethroughtheuseof:
cookies
querystring
hiddeninputforms
HTML5webstorage

DesignaCachingStrategy
http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

4/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

Cachingisafundamentalstrategyforimprovingtheperformanceofyourapplicationsbystoringfrequentlyusedinformationwithinhighspeedaccessmemory.
ImplementPageOutputCaching(performanceoriented)
ThebrowsercancacheanyHTTPGETrequestforapredefinedperiodoftimebasedontheresponseheaders.ASP.NETMVCallowsyoutosetupcachingwhen
servingyourpagesviaGETrequestsbothintheclientandtheserverviatheOutputCacheattribute:
1[OutputCache(Duration=60,VaryByParam="id",Location="ServerAndClient")]
2publicActionResultDetails(stringid){
3varcityDetails=repo.getCityDetails(id);
4returnView(cityDetails);
5}

ThisexamplewillgenerateHTTPheadersthatwilltellthebrowsertokeeptheresponseinitslocalcachefora60seconds.Sinceitisalsocachedintheserver,other
usersmakingasimilarrequestwillalsogetacacheversion(Location=ServerAndClient).ThesearesomeoftheparametersthatyoucanusetosetuptheOutputCache:
Duration:cachedurationinseconds
VaryByParam:storeadifferentversionoftheoutputbasedonaparametersenttotheactionmethod
Location:tellwherethecachingtakesplaceAny,Client,Downstream,Server,ServerAndClient,NoStore(nocaching)
Therearedifferentwaysinwecanperformcaching:
cachetheoutputofawhileactionmethodorcontroller(byusingtheOutputCacheattribute)
Donutcaching,inwhichwecachethesurroundingsandweservedynamicallypiecesofthewebsite.Thisisavailableoutoftheboxinwebforms,butin
MVCrequiresyoutoimplementyourownhelpertoaccesstheHttpResponse.WriteSubstitutionAPIthatprovidesthisfunctionalityinASP.NET
Donutholecaching,whereyoucachesmallpieceswithinawebsite.MVCallowsyoutodothisbycombiningtheChildActionOnlyandtheOutputCache
attributesandbyreferencingthechildviewvia@Html.Action("MyChildAction").
Distributedcaching,inscenarioswherewehaveadistributedsolution(webfarmorazure),weneedawaytohandledistributedcacheswhereallserverscan
havekeeplocalcacheswhilehavingaccesstoasharedcache.ThiscanbesolvedthroughWindowsServerAppFabricorMicrosoftAzureAppFabric.
TODO:
READOutputCacheAttributedocumentation
READImprovingPerformancewithOutputCaching
ImplementDataCaching
The.NETframeworkprovidesanotherwaytoperformserversidecaching,the.NET4CachingFrameworkwiththeObjectCacheandMemoryCacheAPIs.Youcan
usethistypeofcachingtointroduceacachinglayerbetweenyourdomainmodelandthedataaccesslayer.
TODO:
READCachinginthe.NETFramework
ImplementApplicationCaching
Toenableapplicationcachingyouneedtocreateamanifestfileforyourapplicationwhichdetailswhichresourcestocacheandwhichtoalwaysdeliverfromthe
serverbyusingtheCACHE,NETWORKandFALLBACKsections.Youneedtoreferencethisfilefromyourhtmlelement:
1<htmlmanifest="site.manifest">

Amanifestfilecanlooklikethis:
1 #cachedentries
2 CACHE:
3 /favicon.ico
4 index.html
5 images/*
6
7 #resourcesthatarealwaysfetchedfromtheserver
8 NETWORK:
9 login.html
10
11#fallbacksifnetworkisnotavailable
12FALLBACK:
13login.htmlofflinelogin.html

ItneedstobeserverwiththeMIMEtypeoftext/cachemanifest.OnceanapplicationisusingAppCache,thebrowserwillfetchresourcesonlyif:
theusercleansthecache,
therearechangesinthemanifestfile,or
thecacheisupdatedprogrammaticallyviatheJSAPIs
TODO:
READabouttheAppCacheAPI
ImplementHTTPCaching
TODO:
READmoreaboutHTTPcachingdifferentheaders,statuscodesandflowsinvolved.MDNhasthebriefestsummary
ImplementAzureCaching
Anexampleoftheuserofazurecachingconfigurationinyourweb.configfileisshownbelow:
1
2
3
4
5

<system.web>
<!otherstuff>
<sessionStatemode="Custom"
customProvider="MyCacheSessionSateProvider">
<providers>

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

5/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

5 <providers>
6 <addname="MyCacheSessionStateProvider"
7 type="Microsoft.Web.....DistributedCacheSessionStateStoreProvider,..."
8 cacheName="myCache"
9 dataCacheClientName="default"
10applicationName="MyCacheSessionState"/>
11</providers>
12</sessionState>
13</system.web>
14<dataCacheClients>
15<dataCacheClientname="default">
16<autoDiscoverisEnabled="true"
17identifier="myapp.cache.windows.net"/>
18<securityPropertiesmode="Message"sslEnabled="false">
19<messageSecuirtyauthorizationInfo="secretkey"/>
20</securityProperties>
21</dataCacheClient>
22</dataCacheClients>

Wherethesessionstateishandledbyacustomsessionprovider(Azurecache)thatisadescribedintheproviderssection.
TODO:
READIntroductiontoAzurePerformanceandAzureCache
READOverviewofAzureCacheinMSDN

DesignandImplementaWebSocketStrategy
TraditionalwebcommunicationisdonethroughHTTPandthecommonrequest/responseflow,thisisgreatintermsofscalabilitybutitfallsshortinotherscenarios
likerealtimecommunicationandhighlyinteractiveapplications.
HTML5WebSocketsfillsinthegapforthisparticulartypeofusecasesandallowsforafullduplex,twowaycommunicationbetweenserverandclientandallows
tomaintainaconnectionbetweenbothparties(savingthetimenecessaryforestablishinganddisposingofconnections).Whenusingwebsockets,thebrowserdoes
anHTTPrequesttotheserverandanupgraderequesttoconverttoawebsocket,afterthat,allcommunicationsoccurinasingleTCPconnectionandallHTTP
relatedoverheads(likecreating/disposingconnections,headers,etc)areremoved.
ReadandWriteStringandBinaryDataAsync
IalreadylookedatthefrontendpartofHTML5websocketsintheHowtopassthe70480certificationblogpostandIhaveasmallwebsocketsarticleinthewiki.
Refertothosearticlesforsuchinformation.
YoucanmanagewebsocketcommunicationinthebackendbyusingthemanagedWebSocketsAPIandtheWebSocketobject.Ifyoudecidetobuildanapplication
thatisgoingtousewebsocketsyouwouldprobablywanttouseSignalRthatprovidesahigherlevelabstractionthatworkingwiththeWebSocketclass.Ifyou
wantedtogothispaththatgivesyoumorecontrol,youwouldneedtohaveawaytohandletheconnectionviaanHTTPhandleroranHTTPmodulesinceyouneed
toimplementtheupgraderequest:
1
2
3
4
5
6
7
8

//inanactionmethod
HttpContext.Current.AcceptWebSocketRequest(ChatWebSocket)
//Callback
publicasyncTaskChatWebSocket(AspNetWebSocketContext)
{
while(true)

9 {
10//dostuff
11//TODO:completethisexample
12}
13}

ItisalsoimportanttonotethattherearealsootheralternativestoWebSocketsthatareusedinolderbrowsers:
HTTPpolling:periodicalAJAXrequeststotheservertoemulatetheexistenceofacontinuousconnection.Verybandwithandserverusageintensive.
HTTPlongpolling:clientmakesanAJAXrequestandtheserverkeepstheconnectionopenuntilithasdatatoreturn.
TODO
READASP.NETWebSocketsAPIandWebSocketclass(howtoworkwithWebSocketinbackend).SeealsoWebSocketAPIinMSDN
EXPERIMENTWriteaWebSocketexample
ChooseaConnectionLossStrategy
Sincetheinternetisnotveryrealiableandconnectionscanbelost(moresowiththeuserofmobiledevices)itisimportanttohaveastrategyforhandlingthelostof
aWebSocketconnection:
handletheoncloseandonerrorevents
beabletohandleexceptionswhenattemptingtosendamessage
beabletorecreateaconnectionandresendmessages
establishmechanismsthatallowyoutoverifythattheotherpartyhasreceivedamessage
establishmechanismstohandlereceivingthesamemessagenumeroustimes
etc
DecideaStrategyforWhentoUseWebSockets
WebSocketsarespeciallysuitedfortwowaycommunicationwiththeserverwithminimaloverheadandnearrealtime.Bewareifyouaretargetingoldbrowsersor
iftherearenetworkentitiesthatmayblockthewebsockettraffic(forinstance,iftheyonlyallowHTTPtraffic).
ImplementSignalR
TODO
READmoreaboutSignalR
EXPERIMENT:BuildasmallexamplewithSignalR
UsingSignalRwiththeHubsAPI

YoucanimplementSignalRwithhubs.YoujustneedtocreateaclassthatinheritsfromHubandcreateapublicmethodthatwillbelateraccessiblefromaJavaScript

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

6/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

YoucanimplementSignalRwithhubs.YoujustneedtocreateaclassthatinheritsfromHubandcreateapublicmethodthatwillbelateraccessiblefromaJavaScript
proxy.Forinstance,thefollowinghubreceivescanreceiveamessageandbroadcastittoallbrowsersusingyourapplication:
1publicclassChat:Hub{
2publicvoidBroadcastMessage(stringmessage){
3Clients.All.showMessage(message);
4}
5}

ThiswillbeaccessibleviaJavaScript:
1varchat=$.connection.chat;
2chat.server.broadcastMessage($('.chatinput').val());
3
4//theclientcanreceivethemessagesvia
5chat.client.showMessage=function(message){
6$('.chatwindow__messages').append(message)
7}

Youcanusethe[HubName]attributetodefineadifferentnameforthehubthantheclassname,and[HubMethodName]tomodifyeachmethodname.

DesignHTTPModulesandHandlers
HTTPmodulesandhandlersallowdeveloperstointeractdirectlywiththeHTTPrequests.AnincomingrequestgetsprocessedbymultipleHTTPmodules(session,
authentication,etc)tobefinallyprocessedbyasingleHTTPhandlerbeforeflowingbackasaresponsetobeprocessedagainbythemodules.
ImplementAsyncandSyncModulesandHandlers
HTTPmodulesarecalledbeforeanHTTPhandlerisexecuted.Theyallowyoutointerceptormodifyeachrequest.Tocreateamoduleyouneedtoimplementthe
IHttpModuleinterface(Init(HttpApplication)andDisposemethods).ThewaythatyouinteractwithHTTPrequestsisbysubscribingtothedifferenteventsofthe
requestlifecyclethroughtheHttpApplicationclass.Youcanalsousethe<httpModule>configurationsectionintheWeb.configfile.
Httpmodulesareusefulhookuptotherequestpipelineeventsandrunlogicwheneventsareraised,andtoimplementcustommodulestoperformactionsthatwill
beinvokedforallrequestsbeinghandled.ManyoftheseeventscanbealsohandledinGlobal.asaxbuttheHttpModuleapproachprovidesbetterencapsulation,
separationofconcernsandcodereuse.
TheflowofarequestwithinanASP.NETMVCapplicationisasfollows:
1.Validation
2.URLmapping(definedwithintheUrlMappingsSectioninWeb.config)
3.eventsthatcanbehandledbyHTTPmodulesontherequest(security,caching,etc)
4.anHTTPhandlerhandlestherequestandgeneratesaresponse
5.eventsthatcanbehandledbyHTTPmodulesontheresponse(recaching,logging,etc)
HTTPhandlersontheotherhandsareusedtoprocessindividualendpointrequests,i.e.,specificURLswithinanapplication.Unlikeithappenswithmodules,
whereseveralmodulescansubscribetotheeventsoftherequestpipelineandperformtheirlogic,onlyoneHttphandlerisusedtohandlearequest.Tocustomize
ahandleryoucanimplementtheIHttpHandlerinterface(IsReusableandProcessRequest(HttpContext)methods)andusethe<httpHandler>sectionofthe
web.configtoconfigureit(selectwhichpath,verbandtypeofendpointsarehandledbythecustomhandler).
ASP.NET4.5letsyoueasilywriteasyncmodulesandhandlersbyusingtheasync/awaitpatternandTaskobjects.Theseasyncmodulesandhandlerswillnotstopor
affecttheprocessingofarequestasithappenswithsyncmodulesandhandlerswherethewholerequsetishandledbythesamethreadandwherelongrunning
problemscanaffectthethroughputofthewholeserver.
YoucaneasilyimplementasynchandlersbyextendingtheHttpTaskAsyncHandlerclassthatprovidestheProcessRequestAsync(HttpContext)method.
TODO
READUnderstandingtheMVCExecutionProcess(therequestpipeline)
READLifecycleofanASP.NETMVC5Application
READHTTPModulesandHandlersOverview.aspx)(RemembertoreviewHTTPmoduleevents)
READCustomHTTPModuleExample
READCreatinganAsynchronousHTTPHandler
READCreatingaSynchronousHTTPHandler
READaboutMVCmodules:UrlRoutingModule.aspx)
READaboutMVChandlers:MvcHandler,MvcHttpHandler.aspx)andMvcRouteHandler.aspx)(thisisanIRouteHandlerandnotanIHttpHandler)
EXPERIMENT:CreatecustomHTTPmodulesandhandlers
ASP.NETMVCHandlers

ThisisquotedfromMSDNMvcRouteHandlerRemarks.aspx):
ASP.NETMVCincludesthefollowinghandlertypes:
MvcHandler.ThishandlerisresponsibleforinitiatingtheASP.NETpipelineforanASP.NETMVCapplication.ItreceivesaControllerinstancefrom
theMVCcontrollerfactorythiscontrollerhandlesfurtherprocessingoftherequest.NotethateventhoughMvcHandlerimplementsIHttpHandler,it
cannotbemappedasahandler(forexample,tothe.mvcfilenameextension)becausetheclassdoesnotsupportaparameterlessconstructor.(Itsonly
constructorrequiresaRequestContextobject.)
MvcRouteHandler.ThisclassimplementsIRouteHandler,thereforeitcanintegratewithASP.NETrouting.TheMvcRouteHandlerclassassociatesthe
routewithanMvcHandlerinstance.AMvcRouteHandlerinstanceisregisteredwithroutingwhenyouusetheMapRoutemethod.Whenthe
MvcRouteHandlerclassisinvoked,theclassgeneratesanMvcHandlerinstanceusingthecurrentRequestContextinstance.Itthendelegatescontrolto
thenewMvcHandlerinstance.
MvcHttpHandler.Thishandlerisusedtofacilitatedirecthandlermappingwithoutgoingthroughtheroutingmodule.Thisisusefulifyouwanttomapa
filenameextensionsuchas.mvcdirectlytoanASP.NETMVChandler.Internally,MvcHttpHandlerperformsthesametasksthatASP.NETrouting
ordinarilyperforms(goingthroughMvcRouteHandlerandMvcHandler).However,itperformsthesetasksasahandlerinsteadofasamodule.This
handlerisnottypicallyusedwhentheUrlRoutingModuleclassisenabledforallrequests.
CustomHTTPHandlerExample

Youcanforinstance,createanhttphandlertohandlesomeimageextension*.gifbycreatingaImageProcessorclassthatimplementsIHttpHandlerandaddingthe
appropriateconfigurationinyourweb.configfile:
1 //Inyourcode

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

7/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

1 //Inyourcode
2 publicclassFunnyGifProcessor:IHttpHandler{
3 publicboolIsReusable{get{returntrue;}}
4 publicvoidProcessRequest(HttpContextcontext){//doprocessing;}
5 }
6
7 //inweb.config
8 <httpHandlers>
9 <addverb="*"path="*.gif"type="FunnyGifProcessor"/>
10</httpHandlers>
11//thismeans,handleanyrequestfora*.giffilewiththeImageProcessorHttpHandler

YoucannotuseRouteTable.Routes.MapRoutetomaparoutetoacustomHttpHandlerbecausetheseroutesonlyapplytotheMvcHttpHandler.
ChooseBetweenModulesandHandlersinIIS
HTTPhandlersallowyoutoinjectlogicbasedontheextensionofthefilenamerequested,theyareexecutedbasedoffileextensions,URLsandHTTPverbs.
HTTPmodulesareeventdrivenandinjectlogicbeforearesourceisrequested.
Somewaystodifferentiatewhentousewhich:
serverequestsforspecificURL/extensions=>Httphandler
appliestoallrequestsbasedonarbitraryrules=>Httpmodule
needinformationavailablepriortocallingtoMVCcode=>Httpmodule
handlespecificfilesdifferently=>Httphandler
HttpHandlervsHttpModuleSummary
HttpHandlerprocessesHTTPendpointsrequestswhereas,
HttpModulegivesyouaccesstotheHTTPpipeline,whichallowsittoinspectincomingrequestsandoutgoingresponsesbysubscribingtoevents.

Designtheuserexperience(2025%)
Applytheuserinterfacedesignforawebapp
CreateandApplyStylesUsingCSS
RefertotheCSSWikiandtothearticleonthe70480certification.
Theonlyadditionfromthatistoknowthatyoucanusethe@Style.RenderhelpertoincludestylesinyourMVCwebsite.
StructureandLayoutofaWebsiteUsingHTML
RefertothesemanticHTML5ElementsWikiandtothearticleonthe70480certification.
ImplementDynamicPageContentBasedonDesign
Dynamiccontentconsistsofcontentwithinapagethatcanchangebetweenvisitsbasedonarbitraryconditions(user,time,date,interactions,etc).
MVCusesprimarilytherazorsyntaxwithnumeroushelperstomanagedynamiccontent.HelpersaresnippetsofcodethatresultinHTMLelementsbeingrendered,
orthataffecthowthewholeHTMLoutputisgenerated.Someoftheseare:@Html.BeginForm,@Html.TextArea,@Html.TexBox,@Html.CheckBox,andtheirstrongly
typedrelatives@Html.TextAreaFor,@Html.TextBoxForthatletyouassociateinputelementstopropertiesofaModel(orViewModel).Forinstance:
1@Html.LabelFor(m=>m.Name)
2@Html.TextBoxFor(m=>m.Name)

ThiswillnotonlybindthevalueofthemodelwiththeHTMLelementsbutalsometadatasuchasvalidationthatwecanevenuseclientside.

DesignandimplementUIbehavior
ImplementClientValidation
AllthreecomponentsModel,ViewandControllertakepartinthevalidationofaMVCapplication.WithintheModelwedescribethevalidationrulesthatapplyto
eachpropertythroughtheuseofdataannotations(attributesintheDataAnnotationsnamespace).WithintheViewweuseHTMLhelperstobindHTMLelementsto
modelproperties,forinstance@Html.EditorForrendersthebestmatchingeditorforagivenproperty,@Html.ValidationMessageForrendersavalidationmessageif
needed,theycanalsobewiredupwithclientsidevalidation.WithintheControllerwehaveaccesstotheModelStatepropertywhichrepresentsthestateofthe
model(youcanchecktheIsValidpropertytofindoutwhetherornottherewerevalidationerrors).
YoualsohavethepossibilityofusingremotevalidationviatheRemoteattribute.Remotevalidationisusefulwhenyouneedtovalidateaconditionthatrequires
additionalinformationonlyavailableintheserver(likeaccesstodatathatisnotpresentintheclient).Inordertouseremotevalidationyouneedtodecoratea
propertywiththeRemoteattributeandpointittoanactionmethodwithinacontroller.Thisactionwillbetriggeredwhenthefieldisvalidatedintheclient:
1 //model
2 [Remote("IsUsernameAvailable","Validation")]
3 publicstringUserName{get;set;}
4
5 //actionwithinvalidationcontroller
6 publicJsonResultIsUsernameAvailable(stringusername){
7 //jarajara
8 //theAllowGetensuresthatiftheuseracceptsthevaluethevalidation
9 //willnotrunagain
10returnJson(true,JsonRequestBehavior.AllowGet);
11}

Youwillneedtoenableclientsidevalidationaswellwithintheweb.configfile:
1//intheweb.config
2<appSettings>
3<addkey="ClientValidationEnabled"value="true"/>
4<addkey="UnobstrusiveJavaScriptEnabled"value="true"/>
5</appSettings>

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

8/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

TODO
READaboutusingdataannotationsforvalidation
READabouttheattributesintheDataAnnotationnamespace
EXPERIMENTwithremotevalidation
UseJavaScriptandtheDOMtoControlApplicationBehavior
RefertotheHowtopassthe70480certificationarticlethatcontainsreferencestoarticlesabouthowtointeractwiththeDOMinjavascript.
ExtendObjectsbyUsingPrototypicalInheritance
AgainrefertotheHowtopassthe70480certificationarticlethatcontainsreferencestoJavaScriptOOP.AlsothisarticleonOOPinJavaScriptforC#developers
willbeuseful.
UseAJAXtoMakePartialPageUpdates
YoucanuseAJAXwithinMVCapplicationstoretrieve/senddatafrom/totheserverasynchronouslyeitherbyusingtheXMLHttpRequestAPIorlibrarieslikejQuery.
RefertotheHowtopassthe70480certificationarticlethatcontainsreferencestoAJAX,jQueryandtheXHRobject.
InadditiontoclientsideAJAXsupportandlibraries,MVCmakesiteasiertouseAJAXwiththeMvc.Ajaxnamespace.Forinstance,insteadoftheHtml.BeginForm
helperyoucouldusetheAjax.BeginFormhelper:
1@using(Ajax.BeginForm("BuyItem",newAjaxOptions{OnSuccess="onSuccess",OnFailure="onFailure"}))
2{
3//regularform
4}
5<script>
6//handleevents
7functiononSuccess(response){/*dosomething*/}
8functiononFailure(response){/*dosomething*/}
9</script>

AninterestingsideeffecttotakeintoaccountwhenrelyingonAJAXheavilywithinyourapplicationisitspossiblenegativeeffectsonwebcrawlersthatonlyparse
staticcontentwhichcouldaffectSEOorotherdeviceslikescreenreaderswhichcouldaffectaccesibility.
TODO
READmoreabouttheSystem.Web.Http.Ajaxnamespace
READ:HowtoloadcustomscriptswithdependenciesORdocsonASP.NETAJAX
READ:EnablingASP.NETAJAXscriptloaderforyourownscripts
EXPERIMENTwiththeAjaxhelpers
ImplementtheUIUsingJQuery
Referto70480ref,jQueryandjQueryUI.AlsocheckjQueryeffectsandjQueryUIeffects.

ComposetheUIlayoutofanapplication
ASP.NETMVCandtherazorviewengineprovidedifferentwaysinwhichwecancomposeandreusepiecesofUIinourwebapplications:partialviews,editorand
displaytemplates,layoutpagesandcustomhtmlhelpers.
Implementpartialsforreuseindifferentareasoftheapplication,
ThesimplestwayofUIreuseisbyusingpartialview.Youcaninsertapartialviewintoanotherviewbyusingthe@Html.Partialhelper.
@Html.Partialvs@Html.RenderPartial

TODO:
READPartialvsRenderPartial
DesignandimplementpagesbyusingRazortemplates(Razorviewengine)
RazortemplatesallowyoutoreusepiecesUIbydefiningtemplatesforeditingordisplayingspecificinformation(amodelorviewmodelforinstance).An
EditorTemplateisdisplayedwhenweusethe@Html.EditorForhelperonamodelpropertythatmatchestheEditorTemplatetype.Wedefinedthesuitabletypeinthe
viewitself:
1@modelMyApp.Cat
2@Html.TextBoxFor(m=>m.Name)
3@Html.TextBoxFor(m=>m.Color)
4@Html.TextBoxFor(m=>m.Race)

LikewiseyoucancreateaDisplayTemplatethatwillberenderedwhenusingthe@Html.DisplayForhelper.ForthesetemplatestobeusedbyMVCyouneedtoplace
theminspeciallocationswithinyourviewfolder:
1~/Views/ControllerName/EditorTemplates/TemplateName.cshtml
2~/Views/Shared/EditorTemplates/TemplateName.cshtml
3~/Views/ControllerName/DisplayTemplates/TemplateName.cshtml
4~/Views/Shared/DisplayTemplates/TemplateName.cshtml

TODO:
READmoreabouttherazorviewengine
Designlayoutstoprovidevisualstructure
MVCandrazorallowyoutocreatelayoutpagestodefinethehighlevelskeletonofyouwebsite(htmlelement,header,footer,etc).
1<html>
2<head>meta,styles</head>
3<body>

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

9/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

3<body>
4<header></header>
5<section>@RenderBody()</section>
6<aside></aside>
7<footer></footer>
8</body>
9</html>

Youusethe@RenderBodymethodtoindicaterazorwhereitshouldrendertheviewcontent.Layoutsalsoletyoudefinearbitraysectionsthatcanbelaterfilledby
otherviews.Youcandefinesectionsvia@RenderSection:
1@RenderSection("scripts",required:false);

Implementmaster/applicationpages
AlayoutcanbereusedbydifferentviewsbysettingtheLayoutpropertywithinaview(orsettingadefaultin_ViewStart.cshtml):
1@{
2Layout="~/Views/Shared/_Layout.cshtml";
3}

Enhanceapplicationbehaviorandstylebasedonbrowserfeaturedetection
Detectbrowserfeaturesandcapabilities
UsebrowserandfeaturedetectiontohandleinconsistenciesinHTML5browserimplementationviajQueryorModernizr.js,andwheneverabrowserdoesnthave
supportforafeaturethatyouwanttouse,provideafallback(likealinktoavideowhenabrowserdoesntsupportthevideotag).
Createawebapplicationthatrunsacrossmultiplebrowsersandmobiledevices
WhendevelopinganMVCappyouneedtounderstandthatyouwebapplicationneedstobeaccessiblefromarangeofdifferentdeviceswithdifferentformfactors.
Youcanhandlethisby:
usingdifferentviewsformobiledevices
usingmediaqueriesandtheviewportmetatag
MVCcandetectifthedeviceandrenderdifferentviews
usethirdpartylibrariesthatprovideconsistentstylesinmobiledeviceslikejQuerymobile,senchatouchorKendoUI.
YoucanfindinformationaboutthedifferenttypesofviewsupportedinVirtualPathProviderViewEngine.DisplayModeProviderwhichbydefaultcontainsmobileand
default(foreveryotherdevice).Mobilespecificviewscontainmobileintheirname(seeEdit.cshtmlversusEdit.Mobile.cshtml).Youcanevenaddnewdisplay
modesforotherspecificdevicestotheDisplayModeProvider(f.i.aniPad).Itwillexaminetherequests,findinformationabouttheuseragentandhelpchoosingthe
rightviewtorender.
TODO
READmoreaboutDisplayModeProvider
Enhanceapplicationbehaviorandstylebyusingvendorspecificextensions
BeforeCSSfeaturesarefullysupportedorpartoftheCSSstandardtheyareincorporatedinbrowserswithabrowserspecificprefix(suchaswebkitormozor
ms).Youmayneedtoincludesomeofthesedependingthebrowserversionsyouaretargeting.

PlananadaptativeUIlayout
Planforrunningapplicationsinbrowsersonmultipledevices(screenresolution,CSS,HTML)
Usemediaqueries
Orusedifferentlayoutsformobileanddesktop(_Layout.cshtmland_Layout.Mobile.cshtml)
UsejQuerymobilethatprovidesstylesandcontrolsspeciallydesignedformobiledevices
providessupportfortouchscreensandotherinputmethods,accessibility,gracefuldegradationwhenfeaturesarenotsupported,modularityandtheming.
Planformobilewebapplications
Useafrontendapproachwithmediaqueries
Useabackendapproachrenderingdifferentviewsbasedonthetypeofdevice(DisplayModeProvider)
1 //inGlobal.asaxApplication_Start
2 //weaddanewdisplaytypefortablets
3 //nowwecanuseViewName.Tablet.cshtmlto
4 //createtablespecificviews
5 varmodels=DisplayModeProvider.Instance.Modes;
6 vartabletMode=newDefaultDisplayMode("tablet")
7 {
8 ContextCondition=(c=>IsTablet(c.Request))
9 };
10displayModes.Add(tableMode);

TODO
READaboutmediaquerieswhenuseddirectlyonhtmlelements(likeinlinewithmediaandviewportattributes,howdoesitwork?)

Developtheuserexperience(1520%)
SEOandaccesibility
SearchEngineOptimizationistheprocessofimprovingawebsiterankingonthelistofsearchresults.YoucanimproveSEOandaccesibilitybyusingthese
techniques:
UseanalyticaltoolstoparseHTML
YoucanusetheSearchEngineOptimizationToolkitthatrunsasanextensiononIISandhelpyoutoimproveyourSEOviarecommendations.Ifyoudonthave

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

10/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

YoucanusetheSearchEngineOptimizationToolkitthatrunsasanextensiononIISandhelpyoutoimproveyourSEOviarecommendations.Ifyoudonthave
accesstoIISyoucanuseBingorGoogleswebmastertools.TheW3CalsooffersHTMLandCSSvalidatorsthatyoucanuse.Yetanothertoolthatyoucanuseis
thePageInspectorinsideVisualStudio.
Viewandevaluateconceptualstructurebyusingplugsinforbrowsers
UsethewebdevelopertoolsonbrowserstoassessthequalityoftheHTMLyourASP.NETMVCrendersandensurethatitisformattedcorrectlyandthatHTML,
CSSandJavaScriptareclearlyseparatedtoallowcrawlersandscreenreaderstoeasilyparseyourwebsite.Youcanevenanalyzeyourwebsitesperformanceinterms
ofthespeedandnumberofHTTPrequests.
Writesemanticmarkup(HTML5andARIA)foraccessibility(forexample,screenreaders)
TheW3CintroducedWAIARIA(WebAccessibilityInitiativeAccessibleRichInternetApplications)asawaytoimprovetheaccessibilityofwebapplications.
TheWAIARIAprovidesadditionalcontexttoHTMLelementstomakethemmoreaccessiblethroughtheuseofnewARIAattributeswithinHTMLelements.
ARIAtriestoaddressaccesibilitybyimprovingkeyboardfocusandnavigation,relationships,managingdynamicchangesandtheroleofpresentation.Forinstance:
1<!adivdoesn'tprovidealotofsemantics,ariaallowsustoprovideadditionalinformationforaccessibilitypurposes>
2<divrole="application">
3...etc

MVCprovidesverylimitedsupportforARIAbutyoucancustomizeHTMLhelperstoincludeariaattributes.
TODO
READGettingStartedwithARIAatMDN
READWAIARIAOverviewatW3C

Planandimplementglobalizationandlocalization
Planalocalizationstrategy
Bydefaulttheculturesetontheserveristhedefaultcultureandcontentwillbereturnedtoallclientsinthiscultureiftheapplicationhasnotbeenglobalized.
Therearetwolevelsoflocalization,languageandlocale,languageisthehighestoneandrepresentsalanguagelikeEnglish(en),thenextoneislocalethatrepresents
alocationlikeUKorUS.WhenausermakesarequesttoawebapplicationthebrowserwillincludetheAcceptLanguageheaderwiththeuserlanguagepreferences
(AcceptLanguage:enUS,en;q=0,8).
Iftheapplicationhasbeenglobalized,itwillfirstwilltrytomatchthelocale(enUSforinstance)andifitisnotfoundwillfallbacktothelanguage(en)tosendthe
response.Inordertosupportthisfeature,theweb.configmustincludethefollowingconfiguration:
1<globalizationculture="auto"uiculture="auto"enableclientbasedculture="true"/>

ThistellsMVCtouseclientbasedcultureandloadtheappropriatecultureintheThread.CurrentThread.CurrentUICulturepropertyforthecurrentrequest(wonderin
theCurrentCultureisalsoset).
Themostcommonwaytohandlelocalizationistouseresourcefiles(.resx)whicharebasicallyxmlfilesthatcontainstringliterals,images,etc.Whenyouneedto
displaylocalizedcontentyoucanusetheResourceManagerhelperclassorthe@ResourcesrazordirectivetogetaresourceautomaticallyintheCurrentUICulture.
Resourcefilesarecompiledintosatelliteassembliesanddeployedwithyourapplication.
Anothersolutionistodefineculturespecificviewsbycreatingyourviewsinculturespecificfoldersandcreatingacustomactionfilter(overriding
OnActionExecuted)toselectthecorrectviewbasedonthecurrentUIculture.
TODO
READGlobalization,LocalizationeInternationalizationinMVC
READLanguagesandLocales
CreateandapplyresourcestoUI,includingJavaScriptresources
Youcaneithercreateasingleresourcesfileperlanguageorcreateseveralofthem(forbiggerapplications).YoucanaccessthesefilesviatheResourceManageror
usingthe@Resourcesdirective.
Youalsoneedtoglobalizeyourjavascriptcontent.Youcanusethejquery.globalizeprojectandthe$.global.preferCulture(language).Sincethecultureisnot
availablefromjavascript,youcansetitfromMVCvarlanguage="@Request.UserLanguages[0]".
TODO
READResxfilesinApp_GlobalResources
READabouttheResourcefilegeneratorthatletsyouturnxmlfilesintoresxfiles.
AccessingResourcesThroughMetadata

Youcanwritemetadataclassestoprovideadditionalmetadata(dataannotations)foryour(view)modelclasses(andusetheMetadataTypeattributetodecoratethe
modelthisalsoenablesyoutoextendmetadataforclasseswhichyoudonothavecontrolover).ApplyingtheDisplayattributeonthepropertiesletsyouspecify
thenameofaresourcefilethatcontainskeysandvaluesusedtoreplacethedisplaynameofaproperty:
1[Display(Name="Name",ResourceType=typeof(Resources.MyResources))]
2publicstringName{get;set;}

RemembernottousetheDisplayNameattributeinaglobalizationcontextsinceitdoesntallowyoutousearesource(onlystringliterals).
Setcultures
Althoughitisnicetouseaclientbasedculture,itisevenbetteriftheusercanpickherpreferredlanguageherself.Oncetheuserhasselectedalocale,wecansetuse
itbysettingtheCurrentUICulture:
1Thread.CurrentThread.CurrentUICulture=newCultureInfo("esES");

CurrentUiCulturevsCurrentCulture

Whenyouwanttomodifythecultureusedwithinyourapplication,sothatyoucanprovideculturespecificformatting,dates,numbers,currencyandresourcesyou

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

11/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

Whenyouwanttomodifythecultureusedwithinyourapplication,sothatyoucanprovideculturespecificformatting,dates,numbers,currencyandresourcesyou
mustsetthecultureinThread.CurrentThread:
Thread.CurrentThread.CurrentCulturemanagesformattingfordates,numbersandcurrencywhile,
Thread.CurrentThread.CurrentCultureUImanagestheloadingofresourcefiles.

Createsatelliteresourceassemblies
Therearetwomainwaystomanageyourresourcefiles.Youcancreateasingleassemblyforyourapplicationthatcontainsallresourcesembedded.Thisisagood
techniqueifyouonlyhaveafewlocales.Ifyouhavealotoflocalesoryourresourcefilesarebig,thenyoucanusesatellitesassembliesinstead.Satelliteassemblies
areassembliesthatonlycontainresourcesandwhichareonlyloadediftheyareneededbasedonthecurrentculture.
Thesuggestednamingforsatelliteassembliesis:resourcename.culture.resources.
Youcancreatesatelliteassembliesbyusingtheassemblylinker:
1al.exe/t:lib/embed:myresources.esES.resources/culture:esES/out:MyApp.esES.resources.dll

Afterthesatelliteassemblyisbeingcreated,youcanloaditusingtheResourceManagerwhentheuserlocaleisesES:
1ResourceManagerrm=newResourceManager("myresources",Assembly.GetExecutingAssembly());

TODO
READabouttheAssemblyLinker]thatletsyoulinkresourcestoanassembly.

DesignandimplementMVCcontrollersandactions
TODO
READGettingStartedWithASP.NETMVC
Applyauthorizationattributes,globalfilters,andauthenticationfilters
Certainattributes(filters)inASP.NETMVCexaminetherequests(HttpContextprimary)beinghandledbyaControllerorActionanddeterminerwhetherornotit
meetsspecificrequirements:
TheRequireHttpsAttributeensuresthatallcallsmadetoaControllerorActionaredoneviaHTTPS.
TheValidateAntiForgeryTokenAttributehelpsprotectyourformsagainstcrosssiterequestforgeriesbyensuringthereisasharedsecretvaluebetweenthe
formdatawithinahiddenfield,abrowsercookieandtheserver.
TheValidateInputAttributehelpstoavoidrisksofpotentiallydangerousinformationlikemaliciousscriptsbeingsenttotheserverbyremovingthiscontent.
Youcanselectfieldsthatwillnotbeincludedinthisvalidationprocessaswell[ValidateInput(true,Exclude="Content")].Additionallyyoucanalsousethe
[AllowHtml]withinamodelproperty.
YoucanusetheAuthorizeAttributetoforceausertoauthenticatewhenaccessingaControllerorAction.Youcanalsobemorespecificwhenusingthis
attributeandrequireaspecificrole(like[Authorize(Roles="Admin")]).
TheChildActionOnlyAttributeprotectsanactionmethodfrombeingcalledfromtheoutsideofyourMVCapplication.Whenanactionmethodisdecorated
withthisattributeyoullonlybeabletocallitviathe@Html.Actionand@Html.RenderActionmethodswithinarazorview.
TheHandleErrorAttributeletsyouhandleexceptionsthatmayoccurwithinanaction.Bydefault,MVCwilldisplaythe~/Views/Shared/Error.cshtmlview
whenanerroroccursinanactiondecoratedwith[HandleError],butyoucansettheExceptionType,View,Masterpropertiestocalldifferentviewswith
differentmasterpagesbasedonthetypeofexception.YoucanalsousetheOrderpropertytospecifytheorderinwhichseveraloftheseattributesare
evaluated.YoucanevencustomizeitbyoverridingtheOnExceptionmethodwithinagivencontroller.Uncaughtexceptionsbyeithertheattributeorthe
OnExceptionmethodcanbehandledbyoverridingtheApplication_ErrorinGlobal.asax.
TheActionFilterAttributeisanabstractclassthatyoucanusetoimplementyourowncustomactionfilters.Itprovidesfourmethodsthatyoucanoverrideto
hookintotheMVCpipeline:
OnActionExecuting:iscalledbeforetheactionisexecuted,itletsyouexaminetheHttpContextanddecidewhetherornottocontinue
OnActionExecuted:iscalledafteranactionisexecuted,itletsyouexaminetheresultanddeterminewhethersomethingneedstohappenatthatpointlike
overridingaview,etc.
OnResultExecuting:calledbeforetheactionresultfromtheactionisprocessed.
OnResultExecuted:calledaftertheactionresultisprocessedandbeforetheoutputisloadedintotheresponsestream
YoucanalsodefinewhetherornotanattributecanberunonlyonceormultipletimesbyusingtheAttributeUsageattributeusage
Youcanapplyalltheseattributesontheactionitself,onacontrollerwhereitappliestoallactionsorasaglobalfilter.Youcanregisterglobalfilterswithin
App_Start/FilterConfig.csandtheRegisterGlobalFiltersmethod:
1filters.Add(newRequireHttpsAttribute());
2filters.Add(newHandleErrorAttribute());

TODO
READaboutAttributeUsage
MoreaboutErrorHandlingFromMSDN
AccessingExceptionDataintheView

TheMVCframeworkpassesinformationaboutanexceptiontotheerrorviewintheViewDataDictionaryobjectwhoseModelpropertyissettoaninstanceofthe
ExceptionContextclass.TheViewDatadictionarycontainsvaluesforthefollowingkeys:
ActionName.Theintendedactionmethod.
ControllerName.Theintendedcontroller.
Exception.Theexceptionobject.
EnablingCustomErrorHandling

ToenablecustomerrorhandlingforusebyaHandleErrorAttributefilter,addacustomErrorselementtothesystem.websectionoftheapplicationsWeb.configfile,
asshowninthefollowingexample:
1<system.web>
2<customErrorsmode="On"defaultRedirect="Error"/>
3</system.web>

HandlingErrorsintheErrorView

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

12/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

HandlingErrorsintheErrorView

Errorscanoccurintheerrorviewitself.Inthatcase,thedefaultASP.NETerrorpageisdisplayed.Toavoidthis,youcanconfiguretheapplicationtodisplayanerror
fileinthecustomErrorssectionoftheWeb.configfile,asshowninthefollowingexample:
1<system.web>
2<customErrorsmode="On"defaultRedirect="GenericErrorPage.htm">
3<errorstatusCode="500"redirect="/Error.htm"/>
4</customErrors>
5</system.web>

LimitationsoftheHandleErrorAttribute

Fromthisblogpost:
ItdoesnotcatchaHTTPexceptionotherthan500andbypassesalltheothers.
Itisnotabletocatchanexceptionraisedoutsideofcontrollers.
TheloggingofanexceptionisnotsupportedbytheHandleErrorattribute.
ItreturnsanerrorvieweveniftheerroroccurredinanAJAXclientcall.
TODO
READabouttheHandleErrorAttributeinMSDN(greatinformationhere)
Specifyanoverridefilter
WithMVC5youcanoverridefilters:
ASP.NETMVC5hasanewfeaturecalledFilterOverrides,whichallowsyoutoclearorreplacecertainfiltertypescreatedinhigherscopes.For
example,ifyoucreatedaglobalactionfilterorcontrolleractionfilter,youcouldoverridethosefiltersonacasebycasebasisatthecontrolleraction
level.Thisallowsyoutosetglobalorcontrollerfiltersthatapplyinalmostallcasesandjustoverridetheminthefew,specificplaceswherethosefilters
dontapply
Youcanusethesenewfilterstooverridefiltersinhigherscopes(theywillclearthepreviousfilters):
[OverrideActionFilters]
[OverrideAuthentication]
[OverrideAuthorization]
[OverrideExceptionFilters]
[OverrideResultFilters]

Andthenevenaddadditionalfiltersthatonlyapplytothatparticularaction.
TODO
READFilterOverridesinMVC5
READNewFilterOverridesinMVC5
ImplementActionBehaviors
ImplementActionResults
TheActionResultisthestandardresultofanaction.Theyarethefinishingactionstakenbyanapplication,thelaststepofhandlingtheHttpRequest,andresponsible
forwritingtheresultinformationbacktotheresponsestream.Therearedifferenttypes:
ContentResult
EmptyResult
FileResult
JavaScriptResult
JsonResult
PartialViewResult
RedirectResult
RedirectToRouteResult
ViewResult

TODO
READabouttheActionResultClassinMSDN
ImplementModelBinding
Modelbindingisthetwowaymappingbetweenrequestvaluesandactionmethodparametersandproperties.Therearedifferentwaysinwhichyoucanusemodel
binding:stronglytypedviews,weaklytypedbindingandthevalueprovider.TherearealsodifferentwaysinwhichyoucanaffectthedefaultbindingusingtheBind
attribute.
Ifyouusestronglytypedviewsthemodelbindercanuseallthemodelmetadatatohelprenderaviewandevenaddvalidationinformation.Whenthedatacomes
backfromthebrowserthebindercaneasilyparseitandverifywhetherornotthemodelisvalidpriortocallingtheactionmethod.
Thereareseveralstandardmodelbinders:
DefaultModerBinder:mapsabrowserrequesttoparametersandobjectproperties
LinqBinaryModelBinder:mapsabrowserrequesttoaLINQobject(what?xD)
ModelBinderAttribute:attributethatletsyouassociateamodeltypetoamodelbuildertype
ModelBinderDictionary:classthatcontainsallmodelbindersfortheapplicationlistedbybindertype

Youcanalsouseaweaklytypedapproachbyusingnonstronglytypedhtmlhelpers(@Html.TextBoxinsteadof@Html.TextBoxFor).TheBindattributeletsyou
providehintstohelpthemodelbinder(likeprefixesforproperties,blacklisting,whitelisting,etc).RefertomoreinformationaboutthisattributeinMSDN
Thereareotherscenarioswheremodelbindingisnotavailable,likeforinstance,whenathirdpartyispostinginformationtoanactionmethod.Inthesescenarios
youcanusevalueproviderstoeaseaccessingtotherequestinformation.Someoftheseare:
FormValueProvider
QueryStringProvider

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

13/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

QueryStringProvider
HttpFileCollectionProvider
RouteDataValueProvider

YoucanusetheTryUpdateModelmethodtousetheControllerscurrentvalueprovidertobindmodelpropertiesorevenprovideanspecificValueProviderasan
argument.
Thedifferencebetweenvalueprovidersandmodelbindersisthat:
Valueprovidersareresponsibleforaggregatingthevaluesthatarepartofthecurrentrequest,e.g.fromFormcollection,thequerystring,JSON,etc.
TheybasicallysayIdontknowwhataFirstNameisfororwhatyoucandowithit,butifyouaskmeforaFirstNameIcangiveyouwhatIhave.
Modelbindersareresponsibleforqueryingthevalueprovidersandbuildingupobjectsbasedonthoseresults.TheybasicallysayIdontknowwhere
directlytofindaFirstName,LastName,orAge,butifthevalueprovideriswillingtogivethemtomethenIcancreateaPersonobjectfromthem.
Sincemodelbindersarentlockedtoindividualsources(withsomenecessaryexceptions,e.g.HttpPostedFile),theycanbuildobjectsfromanaggregate
ofsources
TODO
READaboutwhatsthedifferencebetweenavalueproviderandamodelbinder
EXPERIMENTwithmodelbindersandvalueproviders

Designandimplementroutes
AnMVCrouteisadefinitionabouthowaURLcanbetranslatedintoanActionwithinController.
DefinearoutetohandleaURLpattern
RoutesarestoredinternallyinasingleRouteCollectionobject.YoucanaddroutestothiscollectionwithintheRegisterRoutesmethodwithinthe
App_Start\RouteConfig.csfile.TheRouteCollectionprovidestheMapRoutemethodthatyoucanusetoaddyourroutesbyusinganame,aurltemplate,defaultsand
constraints:
1routes.MapRoute(
2name:"Default",
3url:"{controller}/{action}/{id}",
4defaults:new{controller="Home",action="Index",id=UrlParameter.Optional}),
5constraints:new{id=@"\d+"});

TODO
READmoreaboutRoutinginMVC
READmoreaboutASP.NETRouting
Applyrouteconstraints
RouteconstraintsaddadditionalconstraintstotheroutingsystemwhenittriestomatchagivenURLtoaroute.Youcandefineconstraintsforeveryparameterusing
regularexpressions.Theexampleaboveconstraintstheidparametertoaninteger.
IgnoreURLpatterns
YoucanusetheIgnoreRouteandIgnoremethodstoignorecertainURLpatterns.Sincetheroutingengineevaluatesarouteatatime,youneedtoplacetheseignores
atthebeginning.
Anexampleofignoringroutes:
1routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
2routes.Ignore("{*allhtml},new{allhtml=@".*\.htm(/.*)?"});

TODO
READmoreaboutScenarioswhenroutingisnotapplied
Addcustomrouteparameters
Customrouteparametersprovideadditionalflexibilitywhenyouarecreatingtheroutesforyourwebapplication.Youcanusecustomrouteparameterstoyour
heartscontent:
1routes.MapRoute(
2name:"booksbyauthorandgenre",
3url:Books/List/{author}/{genre},
4defaults:
5new{author=UrlParameter.Optional,genre=UrlParameter.Optional}
6)

Defineareas
WhenyourMVCapplicationgrowsitisusefultocreatesubdivisiontohandleincreasingcomplexity.Awaytodothisisbycreatingareas.AnareainMVCisa
portionofanapplicationwithaseparatesetofcontrollers,viewsandmodelsintoseparategroupswithinthesolutionandfolderstructure.
WhenyoucreateanewareayougetanAreaRegistrationfilewhereyoucanspecifytheareaspecificroutingrules.Youcancommunicatebetweenareasbyadding
anareaparameterwithintheRouteValuesdictionary(likewhencreatingalink).

ControlapplicationbehaviorusingMVCextensibilitypoints
MVChasmanyextensibilitypointsthatyoucantakeadvantagetocustomizehowyourwebapplicationbehaves.
ImplementMVCfiltersandcontrollerfactories
TherearefourtypesoffiltersthatyoucanusetocustomizeyourMVCapplication:
Authorization:ImplementtheIAuthorizationFilterinterfaceandgetaccesstoauthenticationorothersecurityneedsorsecuritybasedevaluations.The
interfacehasasinglemethodOnAuthorizationthatiscallwhenauthorizationisrequired.Someexamplesaretoperformcustomauthentication,decide
whetherornotanactionisexecuted,etc.
Action:ImplementtheIActionFilterinterfaceandbeabletowraptheexecutionofanactionmethod.Someexamplesaretoprovideextrainfointotheaction

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

14/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

Action:ImplementtheIActionFilterinterfaceandbeabletowraptheexecutionofanactionmethod.Someexamplesaretoprovideextrainfointotheaction
method,inspectinformationcomingourofanaction,logging,cancelactionmethodexecution,overridingtheviewinwhichtorendertheresultsofanaction,
etc
Result:ImplementtheIResultFilterinterfaceandbeabletowraptheexecutionofanActionresults.Someexamplescouldbelogging,perfcountersbased
onviewrendering,etc
Exception:ImplementtheIExceptionFilterinterfaceandallowsforprocessingwhenanunhandledexceptionisthrownwithinanactionmethod.Itcoversthe
wholelifetimeofanaction(evenauthorization).IthasasinglemethodOnExceptionthatiscalledwhenanunhandledexceptionisthrownwithinanaction
method.Someexamplesofusagecouldbeloggingofexceptionsanderrors.
WheneveryoucreateafilteryoucandecorateitwiththeAttributeUsageattributetospecifyhowandwhenitcanbeapplied:
1[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple=false,Inherited=true)]

Thereisalsoawaytohavecontroloverhowcontrollersgetinstantiated.YoucandothatbyimplementingacustomControllerFactorybyimplementingthe
IControllerFactory(withthemethodsCreateController,ReleaseController,GetControllerSessionBehavior).Youcanregisteryourcontrollerfactorywithinthe
Application_Startmethod:
1ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));

AcommonusecaseofcreatingacustomcontrollerfactoryistoimplementDIandIoC.
TODO
READaboutcreatingcustomcontrollerfactories
EXPERIMENTwritingacustomactionfilters
EXPERIMENTwritingacustomcontrollerfactory
Controlapplicationbehaviorbyusingactionresults
Actionresultshandletheexecutionofaresultofanactionmethod,theyusuallydealwiththewayinwhichinformationisformattedpriorbeingsenttotheuser.You
cancreatecustomactionresultsbyinheritingtheActionResultandimplementingtheExecuteResult(ControllerContextcontext)method(youcanwritedirectlyto
theresponse(context.HttpContext.Response).Usagesofthiscouldbegeneratingpdffilesonthefly(PdfActionResult).
TODO
EXPERIMENTwritingacustomactionresult
Controlapplicationbehaviorbyusingviewengines
ViewenginesturnviewsandpartialviewsintoHTMLcode.Youcanoverrideoneoftheexistingengines(razororaspx)oryoucancreateacustomviewengineby
inheritingfromVirtualPathProviderViewEngine(andimplementingtheFindView,FindPartialView,CreateViewandReleaseViewmethods)ortheIViewEngine
interface:
overrideexistingviewenginestoadddebuginformation,orprovidemoreflexiblepathing.
createanewviewenginebyusingtheVirtualPathProviderViewEngineasastartingpointforbuildingaviewenginethatreliesonthe
VirtualPathProviderViewEngineclasstoaccessviewfilesandtosupportnewparsingprocesses.
createanewviewengienfromIViewEnginetosupportnewparsingprocessesorcustomizetheviewresolution.
WhenyoucreateacustomviewengineyoumayneedtocreateanewIViewimplementation(withhasaRender(ViewContext,System.IO.TextWritermethod)since
theworktorenderandsendpageinformationintotheresponseoccursinthecustomview.
TODO
READaboutcreatingacustomviewengineandview
EXPERIMENTwritingacustomviewengine
Controlapplicationbehaviorbyusingmodelbinders
Youcanusecustommodelbinderstomanipulatethewaydatasentwithinarequestismappedtoyouractionparameters.Forinstance,youcouldcreateacustom
modelbinderthatturnsthreefieldswithday,monthayearintoasingleDateTimeproperty.OryoucoulduseitasanAdapterbetweenathirdpartyformsubmission
andyourwebsitewheretheformsubmissionfieldnamesdontmatchwhatyourwebsiteexpects(itisusefulnottohavetochangeyourmodeltosupportotherUI
needs).
YoucanoverridethedefaultbinderbyinheritingfromDefaultModelBinderandoverridingtheBindProperty(ControllerContextcontContext,BindingContext
bindContext,PropertyDescriptionpropDesc)method.YoucanalsocreateacompletenewbinderbyimplementingtheIModelBinderinterfacewhichhasa
BindModelmethod.
YoucanregisteraclassasthedefaultmodelbinderintheApplication_Start:
1ModelBinders.Binders.DefaultBinder=newMyBinder();

oraddthemtothelistofallsupportedbinders(notethatintheexamplebelowthebinderappliestoaspecificmodeltype):
1ModelBinders.Binders.Add(typeof(MyViewModel),newMyBinder());

TODO
READaboutcreatingcustommodelbinders
EXPERIMENTcreatingcustommodelbinders
Controlapplicationbyusingroutehandlers
TherearedifferentwaysyoucancustomizehowroutesarehandledinMVC:
YoucanoverridetheprimaryroutehandlerMvcRouteHandleranditsGetHttpHandlermethod.Youcouldforinstance,translateurlpartsontheflytootherlanguages
toprovidebetterglobalizationsupport(byreadingthevaluesintheRequestContextandmodifyingtherequestcontextRouteDataaccordingly).Youneedtoregister
thecustomroutehandlerfortheapplicableroutes:
1routes.MapRoute(...routeinformation).RouteHandler=newMyRouteHandler()

AnotheroptionistocreateyourownroutehandlerbyimplementingtheIRouteHandlerinterfacewithitsGetHttpHandlermethod.Acommoncaseiswhenyouwant
touseyourownIHttpHandler.Toregisteracustomhandleryoullneedto:

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

15/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

touseyourownIHttpHandler.Toregisteracustomhandleryoullneedto:
1routes.Add("myNewroute",newRoute("myroute/{id}",newMyRouteHandler()));

TODO
READaboutcreatingcustomroutehandlers
EXPERIMENTcreatingcustomroutehandlers

Reducenetworkbandwidth
Bundleandminifyscripts(CSSandJavaScript)
Bundling:mergeresourcesintoasmallernumberoffilestominimizetheimpactofthelimitednumberofHTTPconnectionsperdomain(sothatthepage
rendersfaster)
Minify:reducethesizeofafiletosavebandwith(andalsoobfuscateasasideeffect)
Youcanenablebundlingandminificationbysetting<compilationdebug="false/>inyourweb.configorbyaddingBundleTable.EnableOptimizations=trueatthe
bottomoftheRegisterBundlesmethod.
TODO
READReviewbundlingandMinificationinMVC,JsMinifyandCSSMinify
EXPERIMENTwithbundlingandminification
Compressanddecompressdata(usinggzip/deflatestorage)
YoucancheckwhetherabrowsersupportscompressionbyreadingtheAcceptEncodingheader.Twocommoncompressionalgorithmsaregzipanddeflate.
CompressioncanbeenabledinIIS.
Planacontentdeliverynetwork(CDN)strategy(forexample,AzureCDN)
YoucanuseCDNtoputyourcontentnearertousersaroundtheworldandthusimproveperformance.Additionallythehelpyouoffloadstaticcontentfromyour
serverssotheycanfocusonrequestprocessing.
TODO
READmoreaboutAzureCDN
Miscnotes
Detectingbrowsercapabilitiesinthebackend

UsetheRequest.Browserproperty:
Request.Browser.IsMobileDevicereturnstrueformobiledevicesandallowstoservedifferentviewsforsmallerdevices.

Troubleshootanddebugwebapplications(2025%)
Preventandtroubleshootruntimeissues
Troubleshootperformance,security,anderrors
UsetheVisualStudioPerformanceWizardtoprofileyourrunningMVCapplication(alsomoreinformationindepthinMSDN:
UseCPUsamplingtolightweightmeasureCPUusage
UseInstrumentationtoautomaticallyinstrumateallassembliesandmeasureallfunctioncallsandtiming.Verydetailed
UseMemorysamplingtomeasureyourmemoryusagefromobjectcreationtoGC
UseResourceContentionDatatoinvestigateconcurrencyissuesinmultithreadenvironments
UsetheVisualStudioProfilertogetacompletetraceofallcallsmadewithinyourapplicationandallmemoryusedtoprocessthosecalls.Wherethewizard
concentratesonperformance,theprofilermonitorsallactivityanddocumentsit.Someinterestinginformationfromtheprofileris:cpucyclespersecond,hot
paththatdeterminesmostexpensivecodeapplicationpathandhighlightsproblematicfunctionsandshowsfunctionsdoingthemostindividualwork.
UsethePerformanceMonitorinWindowsServer(perfmon)tomonitoryourapplicationsinaproductionenvironment.Itprovideshundredsofmonitorsthat
letyougetabetterunderstandingofhowyourapplicationisperforming(evenASP.NETspecificones).
TODO
READBeginnersguidetoprofilingtools
READAnalyzingapplicationperformancewithprofilingtools
Implementtracing,logging(includingusingattributesforlogging),anddebugging(includingIntelliTrace)
Inordertodetect,troubleshootandfixproblemASP.NEToffersamyriadofwaystocaptureapplicationstateandsaveinformationoutsideofthesystem:
loggingistheprocessofsavinginformation.YoucanuseloggerssuchasNLogorLog4Netandusedifferentproviderstostorelogsindisk,webserviceora
databasewithdifferentlevelsofcriticalitysuchasError,WarningorInformation.
tracingisatechniquethatenablesyoutoanalyzeanapplicationwhileitisrunning.Youaddtracingstatementsindevelopmentandcanthenusethemindev
andproduction.Youcanactivate/deactivatetracingviaconfigurationwithoutneedingtochangethecode.Tracingisbuiltin.NETasapartofthe
System.Diagnosticsnamespace.
debuggingistheprocessoftroubleshootingaproblemusingvarioustoolstodeterminethecauseofaproblemandfixit.
Toconfiguretracingyouneedto:
1.createoneormoreTraceListenerswhichreceivetracingdataandcanstoreitindiskoradatabase.YoucanconfigureTraceListenersinthe
system.diagnosticssectionofyourweb.config.Thereareanumberofbuiltinlisteners:
TextWriterListener
EventLogTraceListener
DelimitedListTraceListener
XmlWriterTraceListener

2.WriteinformationtoalistenerusingTrace.WriteLine(orothermethodssuchasWrite,WriteIf,etc)
YoucaneasilylogerrorsautomaticallybyusingtheHandleErrorAttributeandoverridingtheOnExceptionmethodorusingacompletelycustomerrorfilter.Anerror
filterwillhandleerrorswithintheactionmethodandonattributesthatdecoratetheactionorthecontroller.Youcanalsohandleexceptionsatthecontrollerlevelby
overridingtheOnExceptionmethodofthecontroller.YoucanmanageerrorsattheapplicationlevelbyoverridingtheApplication_ErrormethodinGlobal.asax.

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

16/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

ANoteonHandlingExceptionsThrownonMissing*.htmlFiles(orotherfilesthatarenotpartofASP.NETlifecycle)

Missing*.htmlbypasstheASP.NETprocessingpipeline,inordertohandleexceptionsthrownwhen*.htmlfilesaremissingyoullneedtoimplementacustom
HttpHandler,youcannothandlethisexceptionsintheApplication_Errorevent,norwiththecustomErrorssectionoftheweb.configfile.
TODO:
READHowtoHandleApplicationLevelErrors
ANoteonExtractingHttpCodeFromanHttpException

YoucanaccesstheHTTPstatuscodefromaHttpExceptionbyusingtheGetHttpCode()methodandnotbyusingtheErrorCodewhichreturnstheHRESULTofthe
exception(32bitvalueassignedtoaspecificexception).
ANoteonCustomerrors

Ifyouwanttoshowexceptiondetailswhenanunhandledexceptionsoccurswithinabrowserisusedwithinthesameserverthathostsawebsitebutnotwhenthe
websiteisaccessedfromadifferentcomputeryoucanusethefollowingconfigurationinyourweb.configfile:
1<customErrorsmode="RemoteOnly"defaultRedirect="DefaultErrorPage.html">
2</customErrors>
3
4<!
5mode="Off"willalwaysshowexceptiondetails
6>

Youcanalsousespecificpagesforspecificstatuscodes:
1<customErrorsmode="RemoteOnly">
2<errorstatusCode="404"redirect="404.html"/>
3<errorstatusCode="500"redirect="500.html"/>
4</customErrors>

Enforceconditionsbyusingcodecontracts
TODO
READmoreaboutCodeContracts
EXPERIMENTwithCodeContracts
ANoteonCodeContracts

Rememberthatwhendefiningaclassthatdescribesacontracttobeappliedtoaninterfaceyouneedtousethe:
ContractClassForattributetodecoratetheclassthatdescribesthecodecontract
ContractClassattributetodecoratetheinterface

Forexample:
1
2
3
4
5
6
7

[ContractClass(typeof(MyContract))]
publicinterfaceIMyInterface{
publicvoidDo(stringsomething);
}
[ContractClassFor(typeof(IMyInterface))]
publicabstractclassMyContract:IMyInterface{

8 publicvoidDo(stringsomething){
9 Contract.Requires(!string.IsNullOrEmpty(something));
10}
11}

Enableandconfigurehealthmonitoring(includingPerformanceMonitor)
HealthmonitoringisapartofASP.NETthatisdesignedtohandletheloggingofeventswithinyourwebapplicationsuchas:*lifetimeevents:triggeredwhenan
applicationstartsorstops,etc*errors:raisedbyexceptionsorothererrors,*sercurityevents:likewhenaloginattemptfailsorunathorizedaccessisattempted*
etc.
Ithasthefollowingbenefits:*partofASP.NETandhasaccesstomoreeventthanmanythirdpartyproviders*followstheproviderframeworkwhichmeansthatit
canbeaddedtoyourwebapplicationviaconfiguration.Thismeansthatyoucanchangetheconfigurationasneededwithoutneedingtorecompileorredeploy,and
havedifferentconfigurationseasilyindevandprod.*hasmanybuiltinlogsourcesthatletyoustoreyourlogsinSQLserver,windowsevenlog,emailandmany
logformats*eachloggingeventcanbehandleddifferentlyviaconfiguration
Thesearethedifferentsectionsthatyoucanuseinyourweb.config:*<bufferModes>whereyoudefinehowlongeventsarebufferedbeforetheyarewrittentoa
provider*<providers>whereyoudefinetheproviderstousetowriteevents*<profiles>letsyouconfigurehoweventsgetlogged.Thissectioniscriticalin
limitingtheamountofinformationthatgetslogged*<rules>whereyoudefinetherelationshipbetweeneventsandproviders.Eventsthatarenotdefinedinthis
sectionarenotwrittentoanyprovider.*<eventMappings>whereyoudefinetheeventstolog(allevents,heartbeats,errors,allerrors,infrastructureerrors,processing
errors,etc)
Thecoolthingaboutthehealthmonitoringsystemisthat,sinceitisaprovider,youcanmanageitentirelyviaconfiguration.Ifyoudonthaveanyotherlogging
solutioninyourapplication,youcanimplementhealthmonitoringrightaway.
TODO
READmoreabouthealthmonitoringinASP.NET
READaboutloggingerrordetailswithhealthmonitoring
EXPERIMENTwithhealthmonitoring

Designanexceptionhandlingstrategy
Handleexceptionsacrossmultiplelayers
Displaycustomerrorpagesusingglobal.asaxorcreatingyourownHTTPHandlerorsetweb.configattributes
Handlefirstchanceexceptions

Testawebapplication

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

17/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

Testawebapplication
Createandrununittests(forexample,usetheAssertclass),createmocks
Createandrunwebtests,includingusingBrowserLink
Debugawebapplicationinmultiplebrowsersandmobileemulators
Browserlink

DebuganAzureapplication
CollectdiagnosticinformationbyusingAzureDiagnosticsAPIandappropriatelyimplementondemandversusscheduled
Chooselogtypes(forexample,eventlogs,performancecounters,andcrashdumps)
DebuganAzureapplicationbyusingIntelliTrace,RemoteDesktopProtocol(RDP),andremotedebugging
InteractdirectlywithremoteAzurewebsitesusingServerExplorer.
ANoteAboutTroubleshootingProblemsinAzureviaRDP

InordertoconnectdirectlytoAzureviaRDP(RemoteDesktopProtocol)youneedtouseapasswordprotectedcertificateandimporttheRemoteAccessonthe
servicedefinitionfileforeachservicethatshouldallowanRDPconnection.
TODO
READUsingRDPwithAzureRoles
READSetUpaRemoteDesktopConnectionforaRoleinAzure
READReviewASP.NETTracingOverView

Designandimplementsecurity(20%25%)
ConfigureAuthentication
Authenticateusers
Enforceauthenticationsettings
ChoosebetweenWindows,Forms,andcustomauthentication
Manageusersessionbyusingcookies
Configuremembershipproviders
Createcustommembershipproviders
ConfigureASP.NETIdentity

Configureandapplyauthorization
Createroles,authorizerolesbyusingconfiguration,authorizerolesprogrammatically,
Createcustomroleproviders
ImplementWCFserviceauthorization

Designandimplementclaimsbasedauthenticationacrossfederatedidentitystores
ImplementfederatedauthenticationbyusingAzureAccessControlService
CreateacustomsecuritytokenbyusingWindowsIdentityFoundation
Handletokenformats(forexample,oAuth,OpenID,MicrosoftAccount,Google,Twitter,andFacebook)forSAMLandSWTtokens

Managedataintegrity
Applyencryptiontoapplicationdata
Applyencryptiontotheconfigurationsectionsofanapplication
Signapplicationdatatopreventtampering

ImplementasecuresitewithASP.NET
SecurecommunicationbyapplyingSSLcertificates
Saltandhashpasswordsforstorage
UseHTMLencodingtopreventcrosssitescriptingattacks(ANTIXSSLibrary)
Implementdeferredvalidationandhandleunvalidatedrequests,forexample,form,querystring,andURL
PreventSQLinjectionattacksbyparameterizingqueries
Preventcrosssiterequestforgeries(XSRF)
ANoteonAuthenticationwithActiveDirectoryandaCustomLoginPage

IfyouwanttouseActiveDirectoryforauthenticationbutyouwanttoprovideacustomloginpage,thenyourbestchoiceistouseFormsauthenticationandaccess
ActiveDirectoyAPIstoauthenticateusers.IfyouwanttouseWindowsAuthenticationandhaveacustomlogingpagethenyoullneedtowriteacustomHTTP
modulewhichisamorecomplexroutetofollow.
ANoteAboutHowDigitalSigningWorks

Ifyouwanttoverifythatinformationwasnotmodifiednortamperedwithbeforeitarrivedtoyou,youneedtousethepublickeyoftheentitythatdigitallysigned
theinformation.Theentityitselfwillusetheprivatekeytosigntheinformationandguaranteeitsintegrity.Signingtheinformationinvolesgeneratingahashofthe
dataandthenencryptingthishashbyusingtheentitysprivatekey.Thereceivingendcanusethepublickeytodecrypttheencryptedhashandverifyitagainstthe
hashoftheinformation.Becausetheentitythatcreatesencryptsthehashistheonlyoneinpossessionoftheprivatekeythatcanencryptthedata,andbecauseitcan
onlybedecryptedusingthepublickey,thereceiverisassuredthattheinformationcomesfromtheoriginalentity.Bycomparingthehashesthereceivercanverify
whetherornottheinformationwastamperedwith.
ANoteAbouttheProperWayToStorePasswordsintheDB

Whenstoringpasswordsinthedatabaseyouwanttoappendasaltvalue(randomlygenerated)tothebeginning/endofthepasswordandthenhashthecombined
passwordandsalt.Thehashingprocessisaonewayoperationthatreducestheprobabilityofrevealingthepasswordifthedatabaseiscompromised.Byaddingthe
randomsaltvaluetothepasswordbeforehashingweintroduceadditionalcomplexitytopreventdictionaryattacksandavoiddisclosureviaduplicatedpassword
hasheswithinthedatabase.
TODO
READWritingSecureCodeatMSDN
TODO

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

18/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding
READHowtobuildaclaimsawareASP.NETMVCapplication
READConfigureAzureDiagnostics
READConfiguretheTraceListenerinaMicrosoftAzureApplication

(Bonus)MVC5andMiscStuff
MVC5
OWINandKatana
NewIdentityandSecurity
WebAPI2
READMVC5Attributerouting>asfarasIknowthisisnotpartoftheexam

MISC
READServiceBusbindingsinMSDN
READTroubleshootingAzureWebSitesinVisualStudio(attachdebugger)

References
Exam70486StudyGuide
Exam70486PageatMicrosoft.com
Exam70486ReferenceBook
MicrosoftAzureWebsite
MVA:ASP.NETMVC4JumpStart
PluralisgthMVC4andMVC5Fundamentals
May12th,2015

Comments

2Comments

BarbarianMeetsCoding.HackerzEdition

Share

Recommend 4

Login

SortbyOldest

Jointhediscussion
philipku 5monthsago

thisseemslikelotofstufftolearnfor70486.doyourecommendanybestwaytoefficientlydigintothisstuffinlesstime?

Reply Share

vintharas

Mod >philipku 5monthsago

HiPhilip!Trythefollowing:
1)Buytheexamrefbookandgetanoverviewofthecontentsoftheexam
2)Readonlyaboutthestuffyoudon'talreadyknoworhaveexperiencewith
3)Doapracticeexamusingserviceslikehttp://www.measureup.com/
Alternativeyoucangodirectlyto3)andlearnfromthequestionsthatyoufail.Buttheleastyoupreparethesmallerthechanceofsuccess.
Goodluck!:)

Reply Share

ALSOONBARBARIANMEETSCODING.HACKERZEDITION

IpublishedtheFirstVersionofJavaScriptmancyThe

BarbaricTipoftheWeek:BeMoreProductiveandGit

4comments9monthsago

16comments7monthsago

vintharasThankyouNathan!^_^Definitely!Itwouldbegreattogetyour

vintharasheheheIthinkIamalittleobsessedwithproductivityand

feedback!Dropme

makingthemostoutofmy

MasteringtheArcaneArtofJavaScriptMancyforC#

TheBasicIngredientsofJavaScriptMancy:An

7commentsayearago

7comments10monthsago

vintharasThearraycomprehensionsproposalwasabandonedinfavorof

vintharasHiKevYouareveryright!Thankyouforspottingitandyour

array

kindwords!:)

Subscribe

AddDisqustoyoursiteAddDisqusAdd

Privacy

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

19/20

7/4/2016

Notesforthe70486ASP.NETMVCCertificationBarbarianMeetsCoding

AboutJaime

Hi!I'mJaimeGonzlezGarcaandthisismyblog,playgroundandgardenofthoughtsandmusings.IamasuperpassionateSoftwareDeveloper,aloverofall
thingstechnology,abookwormandageek.That'sprettymuchwhatyou'llfindinthesepages.Cheers!

RecentPosts
DevTalkMonday:MasteringtheArcaneArtofJavaScriptmancyatDevsum2016
FunctionalProgramminginJavaScript
BarbaricTipoftheWeek:HowtoRecoveraLostCommitWithGit
MyTalkatDevsum2016andSomeInterestingJavaScriptLinks
ArgumentDestructuringandTypeAnnotationsinTypeScript

NowReading
ExamRef70486:
DevelopingASP.NETMVC4
Applications
ProgrammingJavaScript
Applications:
RobustWebArchitecture
withNode,HTML5
andmodernJS
libraries
FunctionalJavaScript:
IntroducingFunctional
Programmingwith
Underscore.js
GitHubRepos
vintharas.github.com
MyBlog!
angular2stepbystep04routing
Angular2codesamplesfortheblogpostAngular2StepbyStepRoutinghttp://www.barbarianmeetscoding.com/blog/2016/03/28/gettingstartedwith
angular2stepbystep4routing/
angular2stepbystep02refactoringtoservices
Angular2codesamplesfortheblogpostAngular2StepbyStepRefactoringtoServiceshttp://www.barbarianmeetscoding.com/blog/2016/03/26/getting
startedwithangular2stepbystep2refactoringtoservices/
angular2stepbystep01yourfirstcomponent
Angular2codesamplesfortheblogpostAngular2StepbyStepYourFirstComponenthttp://www.barbarianmeetscoding.com/blog/2016/03/25/getting
startedwithangular2stepbystep1yourfirstcomponent/
angular2stepbystep03yoursecondcomponentanddatabindings
Angular2codesamplesfortheblogpostAngular2StepbyStepYourSecondComponentandAngular2DataBindings
http://www.barbarianmeetscoding.com/blog/2016/03/27/gettingstartedwithangular2stepbystep3yoursecondcomponentandangular2databinding/

http://www.barbarianmeetscoding.com/wiki/aspnetmvc/aspnetmvccertification/

20/20

Anda mungkin juga menyukai