Professional Documents
Culture Documents
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
plandataaccess?
http://www.windowsazure.com/enus/develop/net/fundamentals/in trotowindowsazure/
IfrastructureasaService(IaaS) PlatformasaService(PaaS)
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
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); }
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();
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 )
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 > "
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)
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
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 >
AsyncControllermedasyncTask<ActionResult>,await
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)
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]
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 >
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)
Asyncmodule(link):writeaasync/awaitmethod(hereWriteLogmessages)in themodule,registerlikethisininit():
HttpContext
Application Cache[]
DesigntheUserExperience Mvc.Controller HttpContext Request Response Server Session TempData[key] Headers Url
UserHostName HttpMethod
Session[key]HttpSessionState
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)
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){
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
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 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 :
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 >
SEO
alt=whenpurelydecorative arialabelledbyairadescribedby
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 " ) ;
GlobalFilters.Filters.Add(newLogFilterAttribute()) inheritfromActionFilterAttribute,implement
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
@Styles.Render
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
DebuginDebugbuilds,Traceinallbuilds
< 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
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
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>
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 >
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 >
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.
readuponazurelogging! DesignandImplementSecurity
Configureauthentication. Thisobjectivemayincludebutisnotlimitedto:authenticateusersenforceauthenticationsettings choosebetweenWindows,Forms,andcustomauthenticationmanageusersessionbyusingcookies
configuremembershipproviderscreatecustommembershipproviders
< 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
WCFServiceauthorization?
Security:Messagebasedortransportbased rolebasedauthorization
createcustomroleproviders?
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>
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 "
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 )
Web.configTransformations
Encoder.JavaScriptEncode,UrlEncode,HtmlEncode Sanitizer.GetSafeHtml,GetSafeHtmlFragment
< 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