Study notes for exam MCSD 70-486


Further Study material


MVC4 Content Map



1 Design the application architecture (15-20%). 4

1.1 Plan the application layers. 4

1.2 Design a distributed application. 11

1.3 Design and implement the Windows Azure role life cycle. 16

1.4 Configure state management. 18

1.5 Design a caching strategy. 23

1.6 Design and implement a WebSocket strategy. 29

1.7 Design HTTP modules and handlers. 33

2 Design the user experience (20-25%). 37

2.1 Apply the user interface design for a web application. 37

2.2 Design and implement UI Behavior. 38

2.3 Compose the UI Layout of an application. 43

2.4 Enhance application behavior and style based on browser feature detection. 45

2.5 Plan an adaptive UI layout. 47

3 Develop the user experience (15-20%). 50

3.1 Play for serach engine optimization and accessibility. 50

3.2 Plan and implement globalization and localization. 52

3.3 Design and implement MVC controllers and actions. 54

3.4 Design and implement routes. 57

3.5 Control application behavior by using MVC extensibility points. 60

3.6 Reduce network bandwidth. 61

4 Troubleshoot and debug web applications (20-25%). 64

4.1 Prevent and troubleshoot runtime issues. 64

Troubleshooting performance, security and errors. 64

4.2 Design an exception handling strategy. 67

4.3 Test a web application. 70

4.4 Debug a Windows Azure application. 72

5 Design and Implement Security (20 – 25%). 75

5.1 Configure authentication. 75

Authenticating users. 75

Microsoft Provider Pattern. 75

Authentication Protocols and Providers. 76

Enforcing authentication settings. 77

Choosing between Windows, Forms, and custom authentication. 78

Managing user session by using cookies. 78

Configuring membership providers. 79

WebSecurity. 79

SimpeRoleProvider. 80

Creating custom membership providers. 80

5.2 Configure and apply authorization. 83

Create Roles. 83

Authorize roles by using configuration. 83

Authorize roles programmatically. 84

Create custom role providers. 84

Implement WCF service authorization. 87

5.3 Design and implement claims-based authentication across federated identity stores. 88

Implement federated authentication using Windows Azure Access Control Service (ACS). 88

Create a custom security token by using Windows Indentity Foundation (WIF). 90

Handle token formats (OAuth, OpenID, LiveID, Facebook) for SAML and SWT tokens. 91

5.4 Manage data integrity. 92

Apply encryption to application data. 92

Apply encryption to configuration sections of application. 94

Sign application data to prevent tampering. 94

5.5 Implement secure site with ASP.NET. 95

Secure communication with SSL certificates. 95

Salt and hash passwords. 95

HTML encoding to prevent cross-site scripting attacks (XS / AntiXSS library). 97

Implement deferred validation and handle unvalidated requests. 97

Prevent SQL injection attacks. 97

Prevent cross-site request forgeries (XSRF) or Cross-Site reference forgery (CSRF). 97

Other Readings. 98

Introduction to ASP.NET Identity. 98

Easy Web App Integration with Azure. 99

C# Inheritance Overview.. 100

Configuration Settings (machine.config & web.config). 100





1 Design the application architecture (15-20%)


1.1 Plan the application layers

First determine what data needs to be captured. Then there are two ways for data access:

  1. ORM (Object Relational Mapper) – maps data into objects. Examples of ORM products are: NHibernate, Entity Framework and Linq-to-SQL
  2. Write you own access components – this might be necessary when data model might not fit or match the object model or if not working with completely relational database, such as NoSQL


Design Approaches / Entity Framework

Entity Framework and NHibernate development starts with the model first, then the database is created from those models. Entity Framework allows


  • Code First (from new or existing DB)

Code First starts with the data object classes (POCO) which then gets turned into the database schema.

Though Model and Code First approaches are good for initial database creation, maintenance can be problematic and Database first approaches are usually easier for these. Therefore after creation the database updates are usually pushed back to the code through the edmx file.


  • Model First

Model First is often used in new applications as these tend to also have new database schemas.

To create in VS à Add New à Data à ADO.NET Entity Data Model

On new space, add new entities with properties underneath them (table and field definitons)

Add relationships (association) between entities

Once model definition is complete, create the database by defining the database connection (SQL or wherever) which will generate the SQL scripts (with CREATE TABLE, etc.)

Models are .edmx files

Under it, there will class files (.cs) for each of the entities and the main Model.Context file (which implements DBContext)


  • Database First design approaches.

Added in similar way as model first à add new à data à ADO.NET entity model

But select the SQL datasource. This will auto-generate the edmx file and data models


Entity Framework relies on the DBContext which is abstract layer over the database to manage transactions. Since MVC is stateless, it cannot work with the default features of Entity Framework, and instead work with something else to get the control flow through DBContext. This can be done directly in the controllers or another abstraction layer.


There are two *.tt files in entity framework. The second contains the entity models. The first contains the context definitions which derives from DbContext




Temporary (or initial) data population done through code.


Repository Pattern

C# uses the repository pattern, which is abstraction layer between the data access layer and business logic layer. It allows business layer to not be coupled with the data access layer and thus allow any data connection. This helps with unit testing and using mock repositories.


Unit of Work Pattern

Combines multiple repositories into a single class so that interaction is done to the single class – but that class can be updating multiple data tables behind it.


Separation of Concerns (SoC)

Separation based on sections, concerns, based on purpose. Such as in N-Tier approach the different concerns are the UI, business logic, data access, database, etc. This is like loose coupling.


ASP.NET MVC is highly convention driven – meaning it is important on the directory structure, filenames, etc.



Handles the business logic; based on convention it is traditionally put in the models folder but depending on application size it can be put into its own assembly (project). Domain models are those that represent the middle tier, for example, the data objects in Entity Framework. View model is the data used in the presentation model, which is usually the aggregation of multiple classes into a single model. Input model are those from the client, and usually data binded in the model. Data binders map the form input data to the data and type of handling action’s parameters. For this work correctly, must follow the conventions, and names must be exactly the same (parameter names). Then the DefaultModelBinder, which implements IModelBinder, will map the input parameters to the model properties. To get the values the IModelBinder has methods like GetValue().



Async Controllers

In general, use synchronous pipelines when the following conditions are true:

  • The operations are simple or short-running.
  • Simplicity is more important than efficiency.
  • The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous action methods on CPU-bound operations provides no benefits and results in more overhead.

In general, use asynchronous pipelines when the following conditions are true:

  • The operations are network-bound or I/O-bound instead of CPU-bound.
  • Testing shows that the blocking operations are a bottleneck in site performance and that IIS can service more requests by using asynchronous action methods for these blocking calls.
  • Parallelism is more important than simplicity of code.

You want to provide a mechanism that lets users cancel a long-running request.


To convert a synchronous action method to an asynchronous action method involves the following steps:

  • Instead of deriving the controller from Controller, derive it from AsyncController. Controllers that derive from AsyncController enable ASP.NET to process asynchronous requests, and they can still service synchronous action methods.
  • Create two methods for the action. The method that initiates the asynchronous process must have a name that consists of the action and the suffix “Async”. The method that is invoked when the asynchronous process finishes (the callback method) must have a name that consists of the action and the suffix “Completed”. In the previous example, the News method has been turned into two methods: NewsAsync and NewsCompleted.

public class PortalController : AsyncController {    public void NewsAsync(string city) {         AsyncManager.OutstandingOperations.Increment();        NewsService newsService = new NewsService();        newsService.GetHeadlinesCompleted += (sender, e) =>        {            AsyncManager.Parameters[“headlines”] = e.Value;            AsyncManager.OutstandingOperations.Decrement();        };        newsService.GetHeadlinesAsync(city);    }     public ActionResult NewsCompleted(string[] headlines) {        return View(“News”, new ViewStringModel        {            NewsHeadlines = headlines        });    }}

The NewsAsync method returns void (no value in Visual Basic). The NewsCompleted method returns an ActionResult instance. Although the action consists of two methods, it is accessed using the same URL as for a synchronous action method (for example, Portal/News?city=Seattle). Methods such as RedirectToAction and RenderAction will also refer to the action method as News and not NewsAsync.

The parameters that are passed to NewsAsync use the normal parameter binding mechanisms. The parameters that are passed to NewsCompleted use the Parameters dictionary.

Replace the synchronous call in the original ActionResult method with an asynchronous call in the asynchronous action method. In the example above, the call to newsService.GetHeadlines is replaced with a call to newsService.GetHeadlinesAsync.


Note the following about asynchronous action methods:

If the action name is Sample, the framework will look for SampleAsync and SampleCompleted methods.

View pages should be named Sample.aspx rather than SampleAsync.aspx or SampleCompleted.aspx. (The action name is Sample, not SampleAsync.)

A controller cannot contain an asynchronous method named SampleAsync and a synchronous method named Sample. If it does, an AmbiguousMatchException exception is thrown because the SampleAsync action method and the Sample action method have the same request signature.


Filters for async actions

If you want to apply attributes to an asynchronous action method, apply them to the ActionAsync method instead of to the ActionCompleted method. Attributes on the ActionCompleted method are ignored.

Two new attributes have been added: AsyncTimeoutAttribute and NoAsyncTimeoutAttribute. These attributes let you control the asynchronous timeout period.


Working with the BeginMethod/EndMethod Pattern

If an asynchronous action method calls a service that exposes methods by using the BeginMethod/EndMethod pattern, the callback method (that is, the method that is passed as the asynchronous callback parameter to the Begin method) might execute on a thread that is not under the control of ASP.NET. In that case, HttpContext.Current will be null, and the application might experience race conditions when it accesses members of the AsyncManager class such as Parameters. To make sure that you have access to the HttpContext.Current instance and to avoid the race condition, you can restore HttpContext.Current by calling Sync() from the callback method.


If the callback completes synchronously, the callback will be executed on a thread that is under the control of ASP.NET and the operations will be serialized so there are no concurrency issues. Calling Sync() from a thread that is already under the control of ASP.NET has undefined behavior.


The ActionCompleted method will always be called on a thread that is under the control of ASP.NET. Therefore, do not call fSync() from that method.



Both the Web Forms and the Razor view engines are derived from the BuildManagerViewEngine

class, which is derived from the VirtualPathProviderViewEngine class. A common reason

for overriding or replacing the default view engine classes is to deviate from the conventionbased

design the standard view engines must follow. You can also write an HTML helper to

help you generate HTML inside views. An HTML helper is a class that helps you create HTML

controls programmatically.


ViewBag vs ViewData

Both are the same, just different annotation. ViewBag is C# 4.0 dynamic feature. Both are part of ControllerBase class and lives only for the current request. Example:




Partial and Layout Views

Both view types are reused. Layout provides a masterpage for overall layout. Partial views provide small windows inside single page. Note that view model in partial view should be that of it’s parent view.

Razor = @Html.Partial(“nameofpartialNoExtension”, model)


Client-side vs Server-side

Factors to take into account when considering client-side versus server-side are application

performance, user experience, and business requirements.



There are two primary ways that you can scale: horizontally or vertically.


With horizontal scaling, you scale by adding additional nodes to the system. With vertical scaling, you scale by adding resources to a single system. This typically involves adding central processing units (CPUs) or memory. It can also refer to accessing more of the existing resources on the system. Vertical scaling has its own architectural considerations as well. An application that scales on a single system might pay more attention to threading, input/output (I/O), garbage collection, and other design decisions that would help the application take better advantage of the additional memory or CPUs. By definition, however, a vertical scaling solution is limited. Theoretically, you can keep adding systems when scaling horizontally; however, you might run out of physical capability in a vertical solution if usage continues to grow.


Review Questions

  1. A (D infers the data would be manipulated at the Controller or View)
  2. B
  3. D (or C)
  4. C



1.2 Design a distributed application


Web Services

Basically, the frameworks provided by Microsoft to develop Web Services are:

  • XML Services based on SOAP.
  • Web services based on SOAP. These services were the evolution of the traditional ASMX services and basically they focused to separate the service itself from the transport protocol. That’s why you can expose the same service using several endpoints and therefore several protocols (TCP, HTTP, Named Pipes, MSMQ, HTTPS). This flexibility came with the configuration problem. One of the main complaints in the community about the WCF is the tedious and extensive configuration
  • WEB API. Based on HTTP not in SOAP. This new API is a new framework to create services. The main difference with the other two predecesors, is the fact that it’s based on HTTP and not on SOAP, therefore you can use several HTTP features like:
    • It contains message headers that are very meaningful and descriptive – headers that suggest the content type of the message’s body, headers that explain how to cache information, how to secure it etc.
    • use of verbs to define the actions (POST, PUT, DELETE..)
    • it contains a body that can be used to send any kind of content
    • It uses URIs for identifying both information paths (resources) and actions

WEB API is focused on writing services to expose them via HTTP (only on HTTP at the moment). If you want to expose your service using another protocol, then you should consider using WCF.


Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them. HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them. Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security. Uses basic protocol and formats such as HTTP, WebSockets, SSL, JQuery, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns. HTTP is request/response but additional patterns can be supported throughSignalRand WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas. There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET framework. Ships with .NET framework but is open-source and is also available out-of-band as independent download.


WCF – Query Interceptors


public Expression<Func<Entity,bool>> OnQueryFares()


return e => DataCheck(e);




WCF Messaging Patterns
One-Way: Client sends request and expects no response (not even an error msg). Similar to a void method, One-Way services does not support return values or output parameters. (IsOneWay = true)
Request-Reply: Client sends request and waits for a response. (IsOneWay = false)
Duplex: Two way message channel. The client sends a request and expects a response at some point in time. Suited for long running tasks. Two types exist: ServiceContract(client waits for response) and CallbackContract (client supplies an address for the server to send the response to).
Streaming: A buffered transfer holds the entire message i memory and the receiver can not read it until it is completely transferred. Processing of a streamed transfer can be started as soon as the first bytes of the message have been received. Buffered transfers use a IDuplexSessionChannel whereas streamed transfers use a IRequestChannel and a IReplyChannel.


WCF Instancing Mode

Per call

You want a stateless services.

Your service holds intensive resources like connection objects and huge memory objects.

Scalability is a prime requirement. You would like to have a scaled out architecture.

Your WCF functions are called in a single threaded model.

Per session

You want to maintain states between WCF calls.

You a scaled up architecture.

Light resource references.


You want share global data through your WCF service.

Scalability is not a concern.


Web API Demo – MVA Tutorial

Using MVC for a Web API / Web API 2 – similar HttpPost, Get, Delete, etc

Separate MVC API controller – can be automatically created from existing Web controllers – built into MVC

WebAPI is for Http services; RESTful services also do Http services so WebAPI is providing RESTful services (kind of) – WebAPI can return JSON or XML or media as well (binary, jpg, video, etc); WebAPI automatically handles the formatting – unlike MVC controllers would require manual setup of the return format type

MediaTypeFormatter / BufferedMediaTypeFormatter


Note: IE by default accepts JSON, whereas Chrome by default accepts XML; WebAPI is automatically handling this with the client and doesn’t need developer to figure that out.


SOAP / Simple Object Access Protocol = standards based access protocol (legacy), originally developed by Microsoft. Allows application logic accessible as services (not data like REST). Uses XML at the core of the messages. SOAP has built-in error handling, error messages are contained within the messages. Also SOAP doesn’t have to go over HTTP, can go over SMTP or many other protocols. It is fully matured and has many features that have been standardized (WS*).


REST / Representational State Transfer = REST goes over HTTP (required) and can do CRUD operations (GET, POST, PUT, DELETE). Doesn’t have to use XML, most use JSON. Lightweight compared to SOAP.



With SOAP, can change application state directly, no data exchange; it is like working with the application class/functions directly – example:


switchCategory(User, Old, New);


With REST, this would be a PUT or POST call.


WSDL / Web Services Description Language – an XML format that describes network services that operate on messages that can contain either data or procedure-oriented information. It’s the definition between client server and how they can communicate. The operations and messages are described abstractly and then bound to a concreate network protocol and message format to define an endpoint.


Using WSDL with SOAP enables platform independent data exchange (WSDL defines the connection and SOAP does the connection)


Consuming web services

To consume data from web service – use the HttpService class; Then use proxies created and exposed object set in models;  This is done in the controller. This uses WSDL


Hybrid Application = app hosted in multiple locations (like Azure, on premise, etc). Access may be controlled (private vs public); also a strategic option in expansion and extension. Two major patterns:

  1. Client-centric = client app determines where the service calls to make
  2. System-centric = a SOA service orented architecture approach – use of something like Windows AppFabric which will distribute service requests.



Session Management

  1. For small data – control manually using sessions
  2. For large data or all else data – rely on ASP.NET which handles it all for you. ex Model Binding


Need to manage the sessionId in distributed systems. In IIS, there are 3 modes of session management:

  1. InProc = default – session info stored in the web server’s local memory. This has best performance but is not clusterable.
  2. StateServer = session info stored in memory on separate server. This server info needs to be setup in IIS. All IIS servers connecting to same session server can share the session info.
  3. SQLServer = same as state server but uses SQL Server. Can have some performance impacts.


Web Farms = servers sharing load of web request. Reduces load, increases availability, adds scalability. Adds complexity when working with sessions – so setup IIS as described above appropriately.

Review Questions

  1. Correct answers: B, C
  2. Incorrect: Although you would eventually be able to get a WCF REST services, it

would not be efficient.

  1. Correct: Using the Web API is a straightforward way to present REST services.
  2. Correct: Using ASP.NET MVC is another way to create a controller that will return


  1. Incorrect: An ASMX web service is SOAP-based, not REST-based.


  1. Correct answers: B, C
  2. Incorrect: Selecting Add Reference does not enable you to create a proxy.
  3. Correct: HttpService.Get gets the output of a REST service.
  4. Correct: Visual Studio creates a proxy for you from the WSDL at the site you select.
  5. Incorrect: A WCF proxy class needs endpoints and bindings. REST services do not

use, nor understand, WCF endpoints and bindings.


  1. Correct answers: C, D
  2. Incorrect: Both the web application and the database storage are being run from

within the company network. Although this is a distributed design, it is not a hybrid


  1. Incorrect: Both the web instance and the data repository are using Windows

Azure technology. This is not a hybrid app; it is a fully deployed Windows Azure


  1. Correct: Part of the application is being run in the Windows Azure environment;

the other part is being run in the corporate network environment.

  1. Correct: Part of the application is being run in the Windows Azure environment;

the other part is being run in the corporate network environment.



1.3 Design and implement the Windows Azure role life cycle


Windows Azure offers PaaS and IaaS

PaaS / Platform as a Service = cloud provides computing platform (OS, program execution environment (.Net), database, webserver)

IaaS / Infrastructure as a Service = cloud provides virtual machines


There are 3 types of solutions from Azure

  1. Virtual Machines = most control over environment (basically your own server); highly customizable, good for dev and testing; also good for disaster recovery
  2. Web Sites = good for simple web hosting; easy to deploy mvc apps
  3. Cloud Services = strictly PaaS,


Types of Roles in Azure

  1. Web = good for IIS / mvc web apps
  2. Worker = no web server; middle-tier apps
  3. VM = full control/customizable


Both Web and Worker roles can have startup tasks = such as register COM components, install components or set registry keys, etc. These are defined in the Task element, this is node in the Startup element of ServiceDefintion.csdef; can be console app or batch file that runs through PowerShell. Some tasks can be set to run as background, letting it complete later and Azure doesn’t wait for it.



File for Azure configuration – <ServiceDefinition … >

<?xml version=”1.0″ encoding=”utf-8″?>

<ServiceDefinition name=”MyServiceName” xmlns=””&gt;

<WebRole name=”WebRole1″ vmsize=”Medium”>


<Site name=”Web”>

Definitions are in WebRole and WorkerRole; Web Role examples:

  • EndPoints (HttpIn)
  • Certificates
  • Imports
  • LocalResources
  • Startup (Tasks, Environment Variable declarations, etc see below )

WorkerRole examples: (does the background processing of a WebRole)

  • ConfigurationSettings
  • Imports
  • Enpoints (tcp ports other than HTTP 80)



Cloud service configuration file; specifies the number of instances for each role; Not part of application but uploaded Azure as a separate file;



To deploy to Azure, solutions must be packaged using CSPack, part of Azure SDK. The resulting file is a *.cspkg file. This is done through VS but can be done manually with CSPACK as follows:

cspack [DirectoryName]\[ServiceDefinition]






Azure Startup <startup><tasks>…


<Task commandLine=”Startup.cmd” executionContext=”limited” taskType=”simple” >


<Variable name=”MyVersionNumber” value=”″ />




  1. The instance is marked as Starting. It will no longer receive traffic.
  2. Startup tasks are executed according to their taskType attribute:
  3. Simple tasks are executed synchronously.
  4. Background and foreground tasks are started asynchronously. This is in parallel

with the startup task.

  1. The role host process is started and the site is created in IIS.
  2. The task calls the Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.OnStart


  1. The instance is marked as Ready and traffic is routed to the instance.
  2. The task calls the Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint.Run method.

All this can be done in the AppCmd.exe. Below are available commands:

Object Description
Site Virtual site administration
App Application administration
VDir Virtual directories administration
Apppool Application pools administration
Config General configuration sections administration
Backup Management of server configuration backups
WP Worker process administration
Request Active HTTP request display
Module Server module administration
Trace Server trace log management Jump-Start-03-Windows-Azure-Lifecycle-Part-1 and Windows-Azure-Jump-Start-04-Windows-Azure-Lifecycle-Part-2


Implementing Start, Run and Stop events

OnStart and Startup tasks:

They both have the same time-out. If you are not out of either function, the execution of role startup continues.

■ ■They both are executed again if the role is recycled.

■ ■You can configure both to process ahead of the role.

Significant differences between the OnStart method and a startup task are these:

  • A startup task runs in a different process, which enables it to be at a different level of privilege than the primary point of entry. This is useful when you need to install soft­ware or perform another task that requires a different privilege level.
  • State can be shared between the OnStart method and the Run method because they both are in the same application domain (AppDomain).
  • A startup task can be configured as either a background or foreground task that runs parallel with the role.


MVC Jump Start Video – MVA – deploying to Azure

web.config transforms – set one for azure

Transforms specific to .Net apps


Thought Experiment


  1. When you need something to run the lifetime of the application, putting it into the override of the Run method is the best solution. It enables you to create a timer that fires an event every x minutes that you want to run the check.
  2. They both would work. The advantage to putting them in a worker process is that they can continue to function if the Web role has stopped for some reason. This is particu­larly useful if there are other non-web ways of getting information into the database, and you are still at risk for orphaned data.
  3. Provided that the processes are console applications, it should be relatively straightfor­ward to move them into methods that can be called from within startup process.


Review Questions

  1. Correct answer: B
  2. Incorrect: If the startup task fires an unhandled error, the role startup stops in a failure. The task will not complete successfully.
  3. Correct: The task will stop processing and return a non-zero value.
  4. Incorrect: The task will stop in error. The OnStop process will not run because the role will not get that far.
  5. Incorrect: The task will stop processing. It will not try to continue to run on a lower security setting.
  6. Correct answers: A, C, D
  7. Correct: AppCmd.exe enables the configuration of virtual sites.
  8. Incorrect: There is no capability to manage users in AppCmd.exe.
  9. Correct: AppCmd.exe supports the administration of general configuration sections.
  10. Correct: AppCmd.exe manages the support of applications.
  11. Correct answers: A, B, D
  12. Correct: Creating and running an application in parallel is what the Run method was designed to allow.
  13. Correct: The polling service is a good example of an activity in which the Run method enables a process to work independently of the main role.
  14. Incorrect: The error handling will be managed in the OnError event and will not involve the overridden Run method.
  15. Correct: Creating and running an application in parallel is what the Run method was designed to allow



1.4 Configure state management

Decide if state management is necessary. HTTP and MVC are stateless.


Web Forms use view state to handle important data in hidden fields. View state = construct that gathers pertinent information about the controls on a page and stores them in hidden form fields. These fields could to standard ASP controls or custom controls. Custom ASP controls can handle view state through ControlState.


MVC stores state info in the following:

  • Cache (server side) – memory pool on server
    • Key-value pairs that can be accessible any user or page in the application domain
    • In server farm, each server has own copy of the cache
  • Session (server side) – server side memory unique for each user
    • SessionStateStoreProviderBase inherit to create custom session provider that default session store cannot handle. For example, if trying to store state in an Oracle database, which is not built into MVC.
    • Done through IIS Manager
    • Should be for small amounts of data – lasts lifetime of session
  • Items (server side?) – part of HttpContext and lasts for lifetime of that request only
    • Property of HttpContext.Current.Items:

public IDictionary Items { get; }

  • Accessed as follows:

Context.Items[“MyObject”] = new object();

  • Single HTTP request only – very short term; since only alive for single pipeline of HttpHandler, it can be useful when used across HttpModules
  • Example – used in authentication by singtle module, results are made available through rest of request-response process
  • Profile (server side) – a database or session server
    • Part of memebership and Roles provider
    • Need to configure this provider in the Web.Config
    • Profile[“xxx”] part of Membership and Roles provider and configured through Web.config
  • Cookies (client side) – stored on client and passed with each HTTP request to server
    • Individualized to a domain or sub-domain; therefore it can be used across server farms; it is always return by the server back to the client.
    • Has expirations and size can impact http request
    • Cookies stay on client but send with all transactions; also stays specific to domain or sub-domain. Cookies are the predecessor of the newer HTML5 Web Storage (sessionSTorage or localStorage). Cookie size limit of 4kb.
    • Interface through HttpContext.Request.Cookies
  • Hidden Fields (client side) – hidden form fields passed along on each page
    • Best to store only small amounts of frequently changing data
  • QueryString (client side) – passed as part of URL
    • Appended to URL; anyone can see it and its not encrypted, even over HTTPS (since part of URL)
    • MVC does allow QueryString encryption though – not legible in the URL
    • Request.QueryString[“…”]



When going across server farms, need manage state carefully. Can use OutProc/StateServer, or a SQLServer session. This is a type of Session store in the list above.


Another option is to go sessionless. For example – authentication piggybacks off the HTTP Authroization header. This is set only once in the initial request.


HTML5 Web Storage

Came after cookes. This is an API to easily retrievable JavaScript objects in the browser memory for client-side use. Not all browsers are compatible with this (its part of HTML5). Can be implemented in two ways:

  1. sessionStorage
    1. Enables get/set on different pages as long as from same origin URL; objects persist as long as the browser window is not closed.
  2. localStorage
    1. unlike sessionStorage, objects persist beyond the window and browser lifetime; shared across multiple windows/explorers. Still must be the same origin URL though.


MVC does not offer specific methods for handling local storage – this can be done through jQuery instead. To work with it, use the following JavaScript:
You can also use this code:

window.localStorage.keyName = ‘valueToUse’;


This code sets an event listener:

window.AddEventListener(‘storage’, displayStorageEvent, true);


Session-State Modes – Configuration settings in Web.config <sessionState> node

ASP.NET supports following options for session data – each identified in the SessionStateMode enumeration.

  • In Proc (default) = stores session state in memory of web server


  • OutProc / StateServer = uses separate process – the state service – supports multiple web servers in farm (all communicate with each other through this state service process

This requires the state service to be running on the servers; (part of ASP.NET installation), aspnet_state.exe; this is configured in web.config as:



<sessionState mode=”StateServer”







  • SQLServer = use of SQL Server DB; support multiple web servers on farm. SQL server can be auto configured using the exe tool. Check link below for details.

<configuration>  <system.web>    <sessionState mode=”SQLServer”      sqlConnectionString=”Integrated Security=SSPI;data         source=SampleSqlServer;” />  </system.web></configuration>


  • Custom = custom storage provider

<configuration>  <connectionStrings>    <add name=”OdbcSessionServices”       connectionString=”DSN=SessionState;” />  </connectionStrings>   <system.web>    <sessionState mode=”Custom”      customProvider=”OdbcSessionProvider”>      <providers>        <add name=”OdbcSessionProvider”          type=”Samples.AspNet.Session.OdbcSessionStateStore”          connectionStringName=”OdbcSessionServices”           writeExceptionsToEventLog=”false” />      </providers>    </sessionState>  </system.web></configuration>


  • Off – disables session state



Implementing Sessionless State

Sessionless apps can handle AJAX callbacks in parallel rather than serial, which means multiple simultaneous calls from the client. If some state-type information is necessary, must pass some unique identifier from one request to the next. Some ways to do this:

  • Create identifier on server at initial request, then pass it at every request thereafter
  • Use hidden form fields to pass at every request
  • If using masterpage, can have it stored at that level for all child pages
  • Use sessionStorage or localStorage on the client side
  • Create identifier in the query string
  • Create identifier in the URL



State Management Recommendations


Client Side:

State management option Recommended usage
View state Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.
Control state Use when you need to store small amounts of state information for a control between round trips to the server.
Hidden fields Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue.

You can use a hidden field only on pages that are submitted to the server.
Cookies Use when you need to store small amounts of information on the client and security is not an issue.
Query string Use when you are transferring small amounts of information from one page to another and security is not an issue.

You can use query strings only if you are requesting the same page, or another page via a link.



Server Side

State management option Recommended usage
Application state Use when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session state Use when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Profile properties Use when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application.
Database support Use when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.



Application State

Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another.


The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class.


Example – The following code example shows how to reference a member of an object defined in theStaticObjects collection of application state. Notice that the label identifier defined in Global.asax is used as the variable name.

protected void Page_Load(Object sender, EventArgs e)


Label1.Text = MyInfo.Title;



Azure State Management

All new developments should use Azure Redis Cache for state management.

Note that InProc session state might be dangerous on Azure if in web farm


Other options:

  • Table storage

<sessionState mode=”Custom” customProvider=”TableStorageSessionStateProvider”>



<add name=”TableStorageSessionStateProvider”

type=”Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider” />




  • SQL Azure

<sessionState mode=”SQLServer”

sqlConnectionString=”Server=tcp:[serverName];Database=myDataBase;User ID=[LoginForDb]@[serverName];Password=[password];Trusted_Connection=False;Encrypt=True;”

cookieless=”false” timeout=”20″ allowCustomSqlDatabase=”true” />



  • Azure Caching

<sessionState mode=”Custom” customProvider=”AzureCacheSessionStoreProvider”>  <providers>    <add name=”AzureCacheSessionStoreProvider”          type=”Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache”          cacheName=”default” useBlobMode=”true” dataCacheClientName=”default” />  </providers></sessionState>




Thought Experiment


  1. There are many different ways that you could provision the servers. A typical approach would be to use two servers for SQL Server, with the data replicated between the servers. One of the servers would be the primary SQL server while the other would be the secondary, redundant fallback SQL server. Two other machines could be set up as a web farm to handle the web requests. A fifth server could be added to the web farm, or kept in reserve in case of a failure in either of the server blocks.
  2. There does not appear to be any real special cases for state management, so an Out­Proc solution in which IIS is configured to use SQL Server to manage sessions should be acceptable. This would enable the application to send requests to any server in the farm without a loss of state data. Typically, it is best to use the IIS built-in state man­agement systems where available because it frees your team from having to write code that might be redundant.
  3. It depends on the two servers that were lost. Using at least two servers for the data tier and the web tier should give you some contingency for hardware failures because it is rare that more than one server goes out at a time. However, if two servers are lost at the same time, the only real risk would be some downtime as you roll the fifth server in to replace one of the ones that was lost. The only real data loss might be if both servers in the database tier were lost, in which case it is likely that there will be some data loss. If you lose one in each tier, or even both web servers in the farm, you can provision the fifth server as a web server without any loss of data other than in those requests that the server was processing as it went down.


Review Questions


  1. Correct answers: C, D
  2. Incorrect: InProc does not support web farms as session items are stored only in the individual server’s memory.
  3. Incorrect: SQLServer is not available in the application stack. This means that us­ing the default SQLServer state is not possible.
  4. Correct: Using a shared state server across the web farm is an available option. Using a state server designates one server to maintain state for all the servers that connect to it.
  5. Correct: A custom session provider enables you to maintain state as necessary by doing the work in your custom code. It is generally used when you try to use a dif­ferent RDBMS system or when you do not want to use the default session database design.
  6. Correct answers: B, D
  7. Incorrect: localStorage is HTML5 and is not available in all browsers.
  8. Correct: Query string information is available across all browsers and is usable on both the client and server.
  9. Incorrect: Although ViewState is available in a form field on the page, it is en­crypted and cannot be used on the client side. It is also not used by many ASP.NET MVC 4 constructs.
  10. Correct: Cookies can be stored for a period of time on the client and be read from either client- or server-side operations.
  11. Correct answers: A, D
  12. Correct: Your application needs to manage whatever information might be re­quired to access the state management system.
  13. Incorrect: The HTTP headers are usually not used as part of state management.
  14. Incorrect: Because your application is sessionless, there is no need to manage ses­sion in the Web.config file.
  15. Correct: Your application needs to manage the passing of the identifier between requests.



1.5 Design a caching strategy

Caching to help improve performance
In the .NET Framework 3.5 and earlier versions, ASP.NET provided an in-memory cache implementation in the System.Web.Caching namespace. In previous versions of the .NET Framework, caching was available only in the System.Web namespace and therefore required a dependency on ASP.NET classes. In the .NET Framework 4, the System.Runtime.Caching namespace contains APIs that are designed for both Web and non-Web applications.


Caching Framework

Found in ObjectCache and MemoryCache objects within System.Runtime.Cachingassembly.


Output Caching

Can be done for controller or action; below example holds the output of Index() for 10 seconds. The caching is not garuanteed as if there are memory contension, it can be evicted and lost.

public class UserController : Controller


[OutputCache(Duration=3600, VaryByParam=”id”,

Location=OutputCacheLocation.Client, NoStore=true)]

public string GetName(int id)



Keywords to OutputCache attribute:

  • Duration (set to 0 to disable caching)
  • Location – where caching is done (Any, Client, Downstream, Server, ServerAndClient)


Member name Description
Any The output cache can be located on the browser client (where the request originated), on a proxy server (or any other server) participating in the request, or on the server where the request was processed. This value corresponds to the HttpCacheability.Publicenumeration value.
Client The output cache is located on the browser client where the request originated. This value corresponds to the HttpCacheability.Private enumeration value.
Downstream The output cache can be stored in any HTTP 1.1 cache-capable devices other than the origin server. This includes proxy servers and the client that made the request.
None The output cache is disabled for the requested page. This value corresponds to theHttpCacheability.NoCache enumeration value.
Server The output cache is located on the Web server where the request was processed. This value corresponds to the HttpCacheability.Server enumeration value.
ServerAndClient The output cache can be stored only at the origin server or at the requesting client. Proxy servers are not allowed to cache the response. This value corresponds to the combination of the HttpCacheability.Private and HttpCacheability.Server enumeration values.



  • VaryByParam – cache version based on param
    • Creates different cached versions, example above the cache is per Id only
  • NoStore – switch off caching


Cache Profile

Using the web.config – controls how all caching is done instead of having to write it out for each controller/action; also changes can be made without recompile

It is defined in the web.config:




<add name=”Cache1Hour” duration=”3600″ varyByParam=”none”/>




It is used in the controllers as attributes:

public class ProfileController : Controller



public string Index()



Donut Caching

Server side technology that caches entire page except dynamic content (the holes). Not supported by Razor but can be controlled through HttpContext. This is not well supported in MVC because most of this can be done using OutputCache with VaryByParam attribute.


Donut hole caching

Opposite of donut caching, it caches only the holes or specific areas of page, not the whole page

This is well supported in MVC through pChaildActionOnly] and very useful in partial views:

[ChildActionOnly] [OutputCache(Duration=60)]

public ActionResult ProductsChildAction(){ … }


Distribution caching

In web farms, share the caching information between the application servers. Requires use of Windows Server AppFabric. Specifically the AppFabric Caching services. Each application server has the AppFabric Caching Service running which communicates with the other servers in the cluster to ensure caching information is contained.


Items being cached in AppFabric can also be serialized into .Net objects. This would be controlled by the client application. The service also handles timeout through synchronization (removing older cache objects).


AppFrabric also enables session maintenance as Session objects can be stored in the cache without any additional programmatic support. This allows new/other OutProc session storage types to session share, eliminating the need for a state server/SQL server.


Application Cache API (AppCache)

This is HTML5 specification that can use the local browser cache. Must create an application cache manifest, reference the manifest and configure it appropriate on what to do offline, etc. Main sections are CACHE, NETWORK, FALLBACK. Browser will fetch resource only when one of these cases

  1. User clears cache
  2. Manifest file changed
  3. Cache updated programmatically via JS


# Cached entries.







# Resources that are “always” fetched from the server.




button.png offline-button.png


Referenced as:

<html manifest=”site.manifest”>


HTTP Caching

Built into the HTTP protocol and handles own version of expiration calculation to determine responses to client. Such response codes are

  • 304 (not modified)
  • 305 (proxy redirect)
  • 4xx or 5xx (errors)


ETags = arbitrary token (typically a hash) that figerprints the contents of the file; if the fingerprints match then the cache is returned.


Cache Control = part of HTTP/1.1 specs – sets the max-age attribute which client uses to determine when to request for a new version of page


No-Store = indicates to not cache and always request new copy


No-Cache = don’t do client side cache without first checking back with the server;


Public / Private = if private it cannot be cached – ex. Logging into a bank account – whereas by default it would be considered public and cachable
Azure Caching




Legacy types:

  • Managed Cache Service
    • Retiring November 30, 2016
  • In-Role Cache


Azure Redis Cache

  • New caching that Azure uses to move away from previous caching mechanism
  • Up to 53GB with 99.99% SLA, premium tier offers up to 530GB and support clustering
  • Redis is PaaS
  • Redis cluster – number of shards for storage; shard = master/slave pair drives
  • Data Persistance – setup frequency of backup and select a storage account to use
  • Storage Key – primary key used to access the storage account
  • Virtual Network – the network that the cache will reside in. Can use one of VN used by other apps.



Thought Experiment


  1. There are several ways that caching could help this process. The first is to get the infor­mation from the database and store it in localStorage. That way you never need to call the server again unless the client realizes it does not have the information any more. You could also use donut caching or donut hole caching, whichever is more appropri­ate, to cache that area of the page where the information doesn’t change. If you assign a duration of 30 minutes, you decrease a lot of redundant database calls.
  2. Because the list of colors, sizes, and so on is the same for all users, you could store this information in a data cache layer in which the system will make only one call into the database every x minutes and will make that same set of returned information avail­able to all users of the system. This gives you an immediate performance gain across all users.



Review Questions


  1. Correct answers: A, D
  2. Correct: Page output caching will cache content at the client side to eliminate some of the required downloads. It is useful in a limited bandwidth environment. It can also be used in donut hole and donut caching scenarios for partial client-side caching.
  3. Incorrect: Application caching is an HTML5 feature, and it is unlikely that the older laptops will be able to support the feature.
  4. Incorrect: Data caching might decrease some server time, but with the limited number of users, it is unlikely that the data access would be an issue.
  5. Correct: HTTP caching will help response time even though there is not much a developer needs to do to implement the caching.


  1. Correct answers: B, C
  2. Incorrect: Although data caching can add some support in a highly dynamic situ­ation, it does not support the capability to have long-term caching.
  3. Correct: Donut hole caching provides the ability to cache parts of each page.
  4. Correct: Donut caching is another approach that gives the ability to cache parts of the application.
  5. Incorrect: AppFabric caching would provide some support in a highly dynamic situation, but it does not suit the need to store some of the page output.


  1. Correct answers: A, C, D
  2. Correct: Data caching with the appropriate timeout will enable the data needed for the reports to be stored so that the call to the database is not necessary.
  3. Incorrect: Although a page output caching would be useful, the short time frame of two minutes means that the cache will likely expire before the next user requests the page.
  4. Correct: A page output caching of four hours caches the output of the report for the whole morning and should eliminate the need for the report to be run a second time.
  5. Correct: AppFabric caching acts much like data caching to eliminate the need for additional calls to the database to generate the reports.



1.6 Design and implement a WebSocket strategy

HTML5 Web Sockets = new way of communication; instead of open/close per each connection (request/response), keeps a duplex (two-way) connection between client/server.

  • Messaging services


Reading and writing string and binary data

Some ways to communicate

  • HTTP Polling

Use of JS timer to send AJAX requests at schedule intervals; this is server-usage intensive

  • HTTP Long Polling

Server doesn’t respond to requests until data is ready – client just waits; can cause broken connections


WebSockets released with ASP.NET 4.5/MVC4 – includes new namespace System.Web.WebSockets; Requires use of delegates as ASP first tries to success handshake – then calles the delgate



Web sockets great when using in partial pages – particularly those areas using donut caching

Note that all users are not HTML5 compliant à can run server side check at System.Web.HttpBrowserCapabilities

  • Establish connection between both sides with hand shake
  • Requesting WebSocket server start to listen for communication
  • Transferring data


Choosing a lost connection strategy

This functionality must be on the client side – server cannot reach out to the client; Usually client can see broken connection when onclose or onerror exception is thrown; solution should be architected in a way to check if responses have stopped being received and handle it.


When to use WebSockets

Most common is web-messaging; live dashboard; anywhere when real-time updates needed;

WEbSockets do not have HTTP headers though sent as normal HTTP requests – some networks will filter this as malicious so those areas wont support WebSockets;


WebSockets vs SignalR

SignalR is Microsoft framework a layer above web sockets. It tries WebSocket first, if available. List or others it tries:

  • WebSockets
  • Server-send events (HTML5 feature where server sends message to browser)
  • Comet – forever frame (hidden iFrame that keeps active connection with server)
  • Long Polling – periodic requests from browser to server

WebSockets need to be enabled on the server


SignalR does the following:

  • Client to Server persistent connection over HTTP
  • Commonly for multi-user, real-time apps
  • Async to scale


SignalR will allow client/server to negotiate which protocol to use for communication. For example if they support web sockets, both would respond as “true” in the request body (JSON message) and return a HTTP 101.

HTTP response 101 – switching protocol


Redis – Azure’s inmemory cache system


Though Experiment


  1. The most common set of issues you would encounter when creating a solution that includes WebSockets is the nonuniversal support for HTML5. It is possible aspects of the company’s business still run on non-HTML5-compliant browsers. Other issues you could encounter include proxy servers, firewall filters, and other security systems that might look at nontraditional HTML communications as a threat.
  2. When following a traditional SoC route, the design should manage each different type of communication separately, even though it might be on the same page. This would give them the opportunity to change independently of each other, perhaps by moving to a different server or even starting to take the news feed from a third-party service directly.


  1. You need to create the server-side application that will be notified of news articles and send the information to the users. You also need to create a server-side applica­tion that will manage the instant messaging part of the application. Theoretically they could be the same application, but it would be prudent to design them in such a way that they could scale separately and independently.


Review Questions

  1. Correct answer: B
  2. Incorrect: In HTTP polling, the client sends a request to the server, and as soon as the response is returned, it sends a new request.
  3. Correct: In HTTP long polling, the client sends a request to the server, and the server holds it open until it either has something to return to the client or the con­nection times out.
  4. Incorrect: WebSockets are a way for two-way communication between the client and the server. The server does not hold onto the response.
  5. Incorrect: The request-response path is a traditional HTTP connection.
  6. Correct answers: A, D
  7. Correct: WebSockets can be used to pass information between the client and server.
  8. Incorrect: HTTP polling can provide the need, but the 1-minute refresh interval would not be efficient.
  9. Incorrect: HTTP long polling is not a valid strategy. The typical timeout on a single request is less than 15 minutes, and chaining multiple requests to get the 15-minute timespan is resource intensive.
  10. Correct: HTTP polling with 15-minute intervals is a valid way to get the informa­tion within the required time frame.
  11. Correct answer: B
  12. Incorrect: HTTP DELETE is not used to start the WebSocket connection; it is in­stead used to perform a delete on a discrete item.
  13. Correct: The first request to open a WebSocket connection is a standard HTTP GET. After the request is received, the browser sends a separate upgrade request.
  14. Incorrect: HTTP CONNECT converts the request connection to a transparent TCP/ IP tunnel.
  15. Incorrect: The upgrade request is sent after the server has responded to an HTTP GET request.




1.7 Design HTTP modules and handlers

HTTP Modules/handlers enable MVC4 developer to interact directly with HTTP requests; such as session and authentication modules


“HttpHandler is where the train is headed, HttpModule are stations along the way.”

An HttpModule will execute for every request to your application, regardless of extension, and is generally used for things like security, statistics, logging, etc. An HttpHandler is generally associated with a specific extension, and is used for things like RSS feeds, dynamic image generation or modification, and the like. HttpHandler is referred to as the “endpoint


Example: Check HttpContext.IsCustomErrorEnabled as


Synchronous and Asynchronous modules

Modules called before and after handlers; helps developer do following to requests:

  • Intercept
  • Participate
  • Modify

Must implement the System.Web.IHttpModule

  • Void Init(HttpApplication)
  • Void Dispose()

<httpModule> in web.config is responsible for configuring the HTTP module within the application
<add type=”[COM+ Class], [Assembly]” name=”[ModuleName]” />
<remove type=”[COM+ Class], [Assembly]” name=”[ModuleName]” />
<clear />


The custom HttpModule would implement IHttpModule and contain following signature methods
void Init(HttpApplication);
void Dispose();



General application flow per incoming request is:

Validation à URL mapping à set of events à handler à set of events


Can use global.asax to handle events but using the modules is better SoC and manages after handled by MvcHandler rather than before.


Async / Sync modules and handlers – should use async to avoid performance inefficiencies on server side;


Choosing between modules and handlers in IIS

Handlers = help inject preprocessing logic based on the extension of file name requested; when page requested it goes through HttpHandler

Can have custom HttpHandler (implement IHttpHandler) for each of the file types. Register the file types/handler in the web.config under <system.web><handlers>…
<add verb=”[verb list]” path=”[path/wildcard]” type=”[COM+ Class], [Assembly]” validate=”[true/false]” />
<remove verb=”[verb list]” path=”[path/wildcard]” />
<clear />


Modules = event-based and inject preprocessing logic before a resource is requested; the request pipeline emits lots of events (shown in table above table)


Use HTTP handler if working with specific URL (or if URL is the determining factor on what needs to be done); if need to support requests for only special type of URL. If want special files handled differently – use handler.

Use HTTP modules for any event-driven requirements; use if need support for every request, regardless of type or URL. If information available prior to calling MVC code; should be done in module.

To use custom HttpHandler, implement IHttpHandler and have following signature: (public class HelloWorldHandler : IHttpHandler)
void ProcessRequest(HttpContext);
bool IsReusable {get;}


See complete example in section 4.


More information


Thought Experiment


  1. Creating an HTTP handler is a relatively simple way to create a customized process to return XML or JSON return objects. Using it in a RESTful scenario is more compli­cated because there is no extension to also map the handler. You have to manage all requests without an extension and then filter the URL request to see what the appro­priate response would be.
  2. The AuthenticateRequest and AuthorizeRequest events are the traditional access points for authorization and authentication. You add the event handlers in the Init method and you have access to the entire HTTP Request in the module as it moves through the application stack.
  3. It would be a relatively responsive application, especially when comparing it to tradi­tional ASP.NET MVC applications. Because it would use its own custom handler, a lot of the overhead of MVC would be left out of the process.



Review Questions


  1. Correct answer: C
  2. Incorrect: The PostAuthorizeRequest event is thrown before the handler is mapped.
  3. Incorrect: You can handle the mapping of the request in the MapRequestHandler.
  4. Correct: You handle the mapping of the request in the MapRequestHandler.
  5. Incorrect: The ReleaseRequestState is thrown after the handler has completed.
  6. Correct answer: C
  7. Incorrect: object, EventArgs are the parameters used for the event handlers thrown during the startup process. The event handlers are assigned in the Init method.
  8. Incorrect: HttpApplication is the parameter used in the Init method.
  9. Correct: The ProcessRequest method takes the HttpContext parameter.
  10. Incorrect: There are no default methods that just accept an object parameter.
  11. Correct answer: C
  12. Incorrect: A module is not the best way to handle the request because it would have to deal with every HTTP request rather than just the image calls.
  13. Incorrect: Serving .htm and .html pages will not create watermarks on image files.
  14. Correct: Intercepting every request for .jpg and .png files is the easiest way to consistently add watermarks to the images.
  15. Incorrect: A module is not the best way to handle the request because it would have to deal with every HTTP request rather than just the image calls






2 Design the user experience (20-25%)

UI = user interface; UX = user experience


2.1 Apply the user interface design for a web application


Create and apply styles using CSS

Razor Engine:


The Razor engine parses the syntax to the following:

<link href=”/Content/site.css” rel=”stylesheet”/>

The _Layout.cshtml file is the base template for a Razor application, and Site.Master is the base template for an ASPX application. When using the Razor view engine, the <head> ele­ment is found in the Views\Shared\_Layout.cshtml file. If you are using the ASPX view engine rather than the Razor view engine, you can add the Styles.Render method to the Views\ Shared\Site.Master file.


Base template inherits from System.Web.Mvc.ViewMasterPage:

<%@ Master Language=”C#” Inherits=”System.Web.Mvc.ViewMasterPage” %>


Using HTML to structure and layout the user interface

HTML gives structure – CSS makes it look good

<div> = box/container with line breaks before and after

<span> = inline, no breaks


In HTML5, have fallback options. For example, <video> can fallback to flash:


<source id=”mp4_src” src=”video.mp4″ type=’video/mp4; codecs=”avc1.42E01E, mp4a.40.2″‘ />

<source id=”3gp_src” src=”video.3gp” type=’video/3gpp; codecs=”mp4v.20.8, samr”‘/>

<source id=”ogg_src” src=”video.ogv” type=’video/ogv; codecs=”theora, vorbis”‘ />

You need to install Java to play this file.




Dynamic page content based on design

Architect which work will be done by server and which done by client; MVC uses HTML helpers to manage dynamic content – code snippets in the view, examples:


These all recognized by the razor engine.


Thought Experiment


  1. The decision to use dynamic content can add functionality to the view to check for user information. The application decides what to display based on user information, which is what makes the content dynamic.
  2. Because HTML5 is not yet supported by all browsers, some elements might not be able to use certain styles, resulting in an experience different from what you expect. If you use HTML5-specific tags in your application, such as <audio> or <video>, you should have a fallback for displaying and managing the information.


Review Questions

  1. Correct answers: A, C
  2. Correct: Adding logic to the master page to determine the menu design enables your application to display a menu section that changes based on the area of the application the user is visiting.
  3. Incorrect: The master page does not have the capability to “look” into the content sections and select the first 40 characters.
  4. Correct: Referencing all style pages in a single place, the layout page, is an appropriate use.
  5. Incorrect: A master page does not control the design of the content being displayed.
  6. Correct answer: C
  7. Incorrect: It is unlikely that one or two styles will enable you to create the look and feel you want.
  8. Incorrect: Using a specific style for each element will limit your ability for style reuse.
  9. Correct: You should use general styles as much as possible. Achieving a certain look and feel means that you might have to create some specific styles, however.
  10. Incorrect: Although inline styling will give you the most, control over styling, it removes the possibility of code reuse. Design changes would be difficult to implement.
  11. Correct answers: B, D
  12. Incorrect: There is no need to create a dynamic website simply to replace the company logo.
  13. Correct: Displaying data from a database is an ideal reason to use a dynamic website.
  14. Incorrect: Linking to other pages outside of an application does not require a dynamic website.
  15. Correct: Personalization, or displaying information about the user on-screen, is an example of dynamic content.


2.2 Design and implement UI Behavior


Client Side Validations

Done in models; use of data annotation;

Data Annotations:

Required; RegularExpression; StringLength; DataType; Range; etc


In the Views, use the key constructs to apply model validation rules: *For; example:

Html.EditorFor; Html.ValidationMessageFor; Html.LabelFor; Html.EditorFor


In the controllers – check validations in the ModelState property of the base controller class:



Remote Validations

There are two parts:

  1. Server action that evaluates validity – client does AJAX call; use of validation-specific controller; Example below

In the model, must use the Remote attribute – System.Web.Mvc.RemoteAttribute; Also setup web.config to allow remote validation.


JS and DOM to control application behavior

The validation messages are actually JS that changes the innerHTML on validation error:


Extend Objects by using prototypal inheritance

JS is interpreted, prototype-based scripting language – does not have standard OO features like classes. When new object instantiated – creates copy based on prototype rather than building from constructor. Can do inheritance by having prototype on any object – thereby copying that object to its children. Each object from a prototype has the parent’s definition in that object’s constructor. Prototypes can be layered, one after another, each containing a higher ancestral copy.


The advantage of this is that each children contains the prototype of it’s parent so each object on the stack retains its own property values. This can save memory as definitions lower in the children will be referenced when defined and those properties not defined will be retrieved from it’s parents. Compared to other OO where each object is build as a standalone copy from its constructor.


Using AJAX for partial pages updates

Data received as XML or JSON.  Access the AJAX namespace here: System.Web.Mvc.Ajax


Implement the UI by jQuery and jQuery UI



Microsoft AJAX Framework

defineScripts allows you to specify a set of JS files that your site uses, and the dependencies between them e.g. jQueryUI has a dependency on jQuery. There’s an example here.

If you then use Sys.require to indicate that one of those scripts is used on a page, that script plus it’s dependencies will be downloaded in parallel, there’s an example of this at the bottom of the that page.

loadScripts accepts an array of paths to JS files, which are similarly downloaded in parallel, there’s some details here.



Though Experiment


  1. Use the jQuery date widget.
  2. You can convert from the list of buttons to tabs, keeping the look and feel the same. You can then preload the information by using the jQuery load function and place the information in the appropriate tab that represents what used to be a separate page. Taking this route preloads the page so that when a user selects a tab, the content has already been loaded.
  3. Use AJAX or jQuery to update the same page if the result is not found.


Review Questions

  1. Correct answer: C
  2. Incorrect: @Html.EditorFor only inserts data. The data is verified on the server side.
  3. Incorrect: @Html.ValidationMessageFor displays the validation message. There is no code included in this answer choice to validate the data.
  4. Correct: @Html.EditorFor, in combination with @Html.ValidationMessageFor, are used for client-side validation.
  5. Incorrect: @Html.LabelFor only displays labels for the items.
  6. Correct answer: B
  7. Incorrect: This approach will update the stockticker, but enabling and disabling the wizard buttons will not ensure that the base objects are saved.
  8. Correct: The best way to solve this issue is to use AJAX to do asynchronous calls to check the stock price as well as manage the save process through the wizard.
  9. Incorrect: This approach will update the stockticker, but enabling and disabling wizard buttons will not ensure that the base objects are saved.
  10. Incorrect: Data validation annotations will not meet any of the requirements.
  11. Correct answers: A, B, C, D
  12. Correct: You should build in validation to check that at least one field has been populated before saving an entry.
  13. Correct: Although the partner company has not provided any requirements, your company is responsible for data entry and therefore should ensure that the data passing through the application meets some minimum criteria.
  14. Correct: The application has many entry fields so it is difficult to predict when an entry hits a valid stage. However, you already know you have constraints on the data being input because of the size of the database columns in which you will be storing them. A MaxLength validator on each field would help ensure that there is no loss of data.
  15. Correct: Although either field in the form can be anything, they should have a maximum length limit imposed so the data does not exceed the size of the database column they will be stored in. You should also validate that neither field is empty.



2.3 Compose the UI Layout of an application


Implement partials for reuse in different areas of application

Simplest way of resuse is using partial layout in view;


Partial views should use the same model of the parent view it is being inserted into; if not – should use AJAX; having partial view use different model can cause problems by controller of parent view


Design and implement pages by using Razor templates

Reusuable UI layer – use of EditorTemplate vs DisplayTemplates

EditorFor = does both create and edit; this would be template used for editing

DisplayFor = for display only and should be used for viewing only


Design layouts to provide visual structure







Implement master/app pages

Inside master page – use the @RenderBody() for razor to load app data

Modernizr.js helps developers determine if browser is HTML5 compliant and work with compatibility issues


Thought Experiment

  1. Use AJAX or jQuery to load a partial view that lets you select users and view their information.
  2. Insert a login/logout partial view on top of the master layout. This partial view enables you to log in and log out from every screen in the application that uses that master layout page.


Review Questions

  1. Correct answer: B
  2. Incorrect: @Html.ActionLink creates a link but does not load a partial view.
  3. Correct: @Html.Partial loads a partial view.
  4. Incorrect: @RenderPage method inserts one complete page into another This is not what you are looking to do as you only want the partial view content to be displayed.
  5. Incorrect: @RenderBody inserts views on master layout pages.
  6. Correct answer: D
  7. Incorrect: The Value construct sets the display information in the element. In addi­tion, the field is not bound to the model.
  8. Incorrect: This will not validate or set the size requirement.
  9. Incorrect: This will make the input field display with a placeholder.
  10. Correct: This is the proper way to limit the size of a certain field that is being bound to the model.
  11. Correct answer: B
  12. Incorrect: @Html.ActionLink creates a clickable link and does not do anything to set the layout.
  13. Correct: Layout=”” loads the layout file to be used with that view.
  14. Incorrect: Layout=”Layout.WindowsPhone.cshtml“ points to an incorrect view folder.
  15. Incorrect: @Html.Partial loads. a partial view, but does not manage the layout being used by the page.




2.4 Enhance application behavior and style based on browser feature detection

HTML5 release for Interoperability Testing and Performance Phase – December 2012


Detect browsers features and capabilities

If certain HTML5 features missing or behave differently – must be corrected via addons in jQuery or Modernizer.js

In JS, can use userAgent – when not met, can fall back on different js/css versions

if ( navigator.userAgent.indexOf(“MSIE”)>0 ) {

@import url(ie7.css);



Another example – checking for window.addEventListener (legacy browsers wont support this, will use window.attachEvent) addEventListener = HTML5


HTML5 tags automatically fallback when not recognized by displaying the text within the tags:


<source src=”video.mp4″ type=’video/mp4′ />

<source src=”video.webm” type=’video/webm’ />

Download the video <a href=”video.mp4″>here</a>.



Create web applications that run across multiple browsers and mobile devices

Use different views for different devices; can detect this using “viewport”: <meta name-“viewport”>

<meta name=”viewport” content=”width=device-width”>

MVC4 allowed (or followed) using different views for different devices – MVC5 uses bootstrap instead


Index.cshtml vs Index.Mobile.cshtml


MVC4 also used @media queries (which is what bootstrap uses);


DisplayModeProvider = customized views per browser; done on the server side;

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode(“iemobile”){

ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf (“iemobile”, StringComparison.OrdinalIgnoreCase) >= 0)



Mobile device image formats:


Enhance application behavior and style by using vendor-specific extensions

Vendor specific browsers have vendor prefixes for CSS, example:


Thought Experiment


  1. The main way to manage this requirement is to use display mode providers, one for the iPads and the other for the Windows tablets. You must create a different set of views based on each device. Using the @media query is complicated because both types of devices are tablets with similar screen sizes. It is unlikely the viewport will be different for each.
  2. If you use the different views based off the display mode providers, you can design a completely different experience for users on each device. You can make different menus, use different colors—basically design completely different experiences.
  3. There are several problems with making the determination of functionality based on the type of the device being used. The first is that you lock in a user type to a device type; for example, a salesperson who breaks or loses his iPad could not work until he has another iPad. The second problem is that this kind of decision should really be by user type, not by device.



  1. Correct answers: B, C, E
  2. Incorrect: The -webkit- prefix is used for Google Chrome and Apple Safari.
  3. Correct: The -ms- prefix is used for Internet Explorer.
  4. Correct: The -o- prefix is used for the Opera browser.
  5. Incorrect: The -hp– prefix is used by Hewlett-Packard.
  6. Correct: The -moz- prefix is used for Mozilla Firefox.
  7. Correct answers: A, D
  8. Correct: Using JavaScript to query the userAgent gives you information about the type of browser being used by the client.
  9. Incorrect: The window.addEventlistener does not give any information on the browser being used by the client, but it can be used to see whether a browser is HTML5-compliant.
  10. Incorrect: The viewport <meta> tag gives access to the visible area of the device; it does not tell you anything about the device itself.
  11. Correct: The display mode provider performs some of the analysis of the HTTP request to try and determine what kind of browser made the request.
  12. Correct answer: B
  13. Incorrect: The viewport <meta> tag does not do any direction to views; it is strictly a client-side helper.
  14. Correct: Adding a DisplayModeProvider for each type of special view, such as IEMobile or IPad, informs the framework to use those views where the context condition is fulfilled.
  15. Incorrect: Putting logic into each action could be done, but it would be time-consuming and difficult to maintain. The DisplayModeProvider does the work for you in the background and eliminates the need for special code.
  16. Incorrect: The framework does not make any assumptions by itself; it only knows what to do based on configurations that it has been given.


2.5 Plan an adaptive UI layout


Plan for running apps in browsers of multiple devices (screen resolution, CSS, HTML)

Mobile devices can be as small as 2.5 inches or width of 60 inches on desktop

Can use @media queries; this challenge lies heavily in CSS


Also can use mobile friendly master pages; example:



jQuery Mobile (Install-Package jQuery.Mobile.MVC) will automatically create mobile-specific layouts for MVC apps

  • Flexibility and simplicity as it uses markup rather than JS
  • Support for touch screens
  • Acessbility
  • Graceful degratdaion
  • Modularity
  • Themes


This was all later replaced by bootstrap


Plan for mobile web apps

Can make a global change in the global.asax file’s Application_start() method

Put an DisplayModePRovider in there globally:


Having multiple views / master pages allows handling of different platforms but adds complexity and cost of maintenance



CSS viewport sets the dimissions of the page – this at minimum – can be used to set a page size more appropriate to the smaller mobile device size. More information about jQuery Mobile here:



Thought Experiment


  1. Two separate user groups—admin users and sales users—use two different types of devices to access the application. You can safely assume that admin users, or users from any desktop computer should have access to all functionality, whereas mobile device users need access to only a limited set of functionality. Therefore, you could start with separate, overridden views because they use different navigation schema. After you separate mobile users into their own template, you could use jQuery Mobile to create the UI while working in the mobile section of code.
  2. When developing a mobile app strategy, remember that mobile apps constantly evolve, and new mobile devices are available constantly. By using a jQuery Mobile approach without any specific templates for each mobile device, the framework makes many decisions for you. Adding supported devices should be almost free for the devel­oper, outside of testing efforts.



  1. Correct answers: A, B
  2. Correct: This allows for devices with a maximum width of 768 pixels.
  3. Correct: This allows for devices with a maximum width of 478 pixels in portrait view, such as tablets.
  4. Incorrect: The screen resolution is too large for a typical mobile device.
  5. Incorrect: The screen resolution is too large for a typical mobile device.
  6. Correct answers: A, D
  7. Correct: This installs all the necessary mobile packages.
  8. Incorrect: You need the additional views made for mobile calling the master layout.
  9. Incorrect: Just the views alone do not work; you need the master layout as well.
  10. Correct: All mobile views and mobile master layout ensure that the page will load accordingly.
  11. Correct answer: C
  12. Incorrect: Simply installing the jQuery Mobile package does not provide support for Android-specific browsers. It enables the application to use the package.
  13. Incorrect: By using @media queries and viewport, you can create an Android-readable website, but it won’t give an Android-specific UI.
  14. Correct: Additional views must be created or ported to fit the smaller layout.
  15. Incorrect: You do not have to modify the Web.config file.




3 Develop the user experience (15-20%)


3.1 Play for serach engine optimization and accessibility

SEO improved by:

  • Ensure clear consistent message within text on page
  • Ensure site is coded properly to facilitate search engine crawlers

WAI-ARIA – Web Accessibility Initiative-Accesssible Rich Internet Applications = set of descriptions on how to make active content more accessible


Use analytical tools to parse HTML

Different browsers display HTML differently – use the SEO Toolkit to examine HTML through IIS (must be downloaded)

Helps create sitemaps, robot exclusions (robot.txt), and analyze site or app
Analysis is what a crawler would see – number of links, download items, violations, etc:



Another tool is Bing Webmaster Tools (Microsoft)

  • Validates content and code for accessibility
  • Also evaluate keywords in page <head> for relevancy


Another tool is Webmaster Tools (Google)

Another is W3C – various tools


View and evaluate conceptual structure by using plugs-in for browsers

There are 3 major components of rendered HTML

  1. Content = text, images, videos, etc
  2. Presentation = styles
  3. Functionality = JS

Primary reason user visit site is for content and functionality


Use browser plugin tools to help check with content and functionality since it will have access to final rendered HTML. Example – IE developer tool


Write semantic markup (HTML5 and ARIA) for accessibility

W3C introduced WAI-ARIA for accessibility to disabilities.

Tags prefixes with “aria”

Also contains “roles”


Thought Review


  1. Run the IIS SEO Toolkit or a similar tool.
  2. When properly implemented, ARIA should not have any effect on search engine rank­ings. All markup occurs in attributes within the HTML elements.
  3. The Internet Explorer Developer Toolbar is one of several tools you can use to evalu­ate the performance of a website. With the toolbar, you can see every HTTP call made from the browser and determine how long each call takes.



  1. Correct answer: B
  2. Incorrect: Although the pages might contain unclosed HTML tags, the highly interactive nature of the site indicates that the content could be in script files, and therefore hidden from the search crawler.
  3. Correct: Text revealed by mouse-overs not being picked up by search engine crawlers indicates that content is being skipped.
  4. Incorrect: Broken links do not slow down a crawler.
  5. Incorrect: The presence of images does not affect the search engine crawler.
  6. Correct answer: B
  7. Incorrect: The IIS toolkit requires access to the server, and your charge is to per­form the assessment from outside the client’s network.
  8. Correct: The Internet Explorer F12 tool enables you view HTML and CSS code, which can help you detect structural problems or errors that might affect acces­sibility or SEO.
  9. Incorrect: The IIS Logging tab displays logs related to functioning of a website and also requires access to the server.
  10. Incorrect: The Bing Webmaster Toolkit requires access to the server to put a special file on to the file system so that Bing can tie a Webmaster account to a particular site.
  11. Correct answers: B, D
  12. Incorrect: The amount of text shouldn’t affect the amount of accessibility work to be performed. The work will be the same whether there is one word in the ARIA-compliant element or 100 words.
  13. Correct: Because ASP.NET MVC 3 HTML helpers are not ARIA compliant, you need to write custom HTML helpers or use a different process to create HTML forms.
  14. Incorrect: The number of controllers does not affect your need to make the ren­dered HTML ARIA compliant.
  15. Correct: Because many of the problems with accessibility are related to giving context to content, complex forms need a thorough review to ensure that labels and section context are provided for every element on the page.


3.2 Plan and implement globalization and localization

Globalization =

  1. Internationalization (I18N) = app supports multiple cultures
  2. Localization = translate data, labels, files, doco to enable any user to understand


Plan a localization strategy

Highest level of localization is language; second is locale;

Example – English UK vs US



HTTP request header contains Accept-Language HTTP Header – browser states its preferred language

GET http://localhost/HTTP/1.1 Connection: keep-alive Cache-Control: max-age=0 Accept-Language: en-US,en;q=0.8


On the server side must handle it by defining it in the <system.web>

<globalization culture=”auto” uiculture=”auto” enableclientbasedculture=”true”/>

Most easiest way to handle internationalization is through resource files – XML files containing strings, images, videos; call the ResourceManager;


Another way is to localize views; view for each local – control it through the Controller.OnActionExecuted


Create and apply resources to the UI including JS resources

Two ways to create and manage resource files:

  1. Use single resource file
  2. Use multiple files for each language, separating translatable content into smaller discrete files

For example – have a labels files for each locale – calling whichever needed


Using client side cultures (via JS)




A problem with client side localization is that the locale information must be first requested to the browser. Once browser gives information, client side localization would be more accurate way of providing the correct locale


var language = “@Request.UserLanguages[0]”;


Set cultures

Other than having the browser set the culture, can have the user do it directly with a link or drop down selection

Can manually set the culture for the thread processing the request

Thread.CurrentThread.CurrentUICulture = new CultureInfo(“es-MX”);


Create Satellite resource assemblies

Two ways to architect culturally aware applications:

  1. Create single assembly that contains all resources for the application (including translation files)
  2. Or use a satellite assembly that will be loaded by .NET

This would be loaded by the ResourceManager class



Mage.exe = manifest generation and editing tool for creating and editing app manifests

WinRes.exe = Windows Form Resource Editor for visual layout of Windows Form user interface

Lc.exe = License Compiler that reads text license file and complies them into binary

al.exe = Assembly Linker – generates modules or resource files


Though Experiment


  1. Using separate views to maintain translations would be problematic because there are more than 350 views to support the initial launch. Although translating a view is easier than translating a resource file, the creation and maintenance of the additional views would be a lot of additional work because the view gives context to the translator.
  2. Using jQuery in the context of AJAX requires some additional work because you have to add JavaScript globalization to the mix. Although you can use traditional resource files for any content created on the server side, you need to include the globalization package in your solution, have the appropriate translated versions of the culture file available, and provide enough information to the browser about the client’s culture so the JavaScript globalization features can determine which translated file to display.



  1. Correct answers: A, D
  2. Correct: Images that are being used for menus likely have text displayed on them. That text should be localized, and extra sets of buttons might have to be created.
  3. Incorrect: A company logo should not be changed because it provides brand awareness.
  4. Incorrect: Server error-logging messages are not seen by the user and are instead an internal item. You should keep them in the default language.
  5. Correct: Tooltips are supposed to give extra contextual help about the item the mouse hovers over. It is important to get them translated.
  6. Correct answer: A
  7. Correct: This is the correct way to insert resources into a view.
  8. Incorrect: The <div> tag cannot be used to insert resources into a view.
  9. Incorrect: This attempts to style the element, looking for a style named “resource.”
  10. Incorrect: Although this inserts resources into the view, it also adds Hello to the end of the header tag.
  11. Correct answer: D
  12. Incorrect: Manifest Generation and Editing Tool is for creation and editing of ap­plication manifests.
  13. Incorrect: Windows Form Resource Editor is a visual layout tool for the Windows Forms user interface.
  14. Incorrect: License Compiler reads text license files and compiles them into binary format.
  15. Correct: Assembly Linker generates modules or resource files.



3.3 Design and implement MVC controllers and actions

Controller manages the flow between user and app; with multiple controllers/actions, routes need to be used correctly;


Apply authorization attributes and global filters

HttpContext class


  • RequireHttpsAttribute
  • ValidateAntiForgeryTokenAttribute = protect from cross-site request forgeries
  • ValidateInputAttribute = no sql injection, checks for “<$” or “<!”
  • AuthroizeAttribute = Authorize (Roles = Admin, PowerUser)
  • ChildActionOnlyAttribute = these methods can only be called from Action or RederAction HTML extension
    • @Html.RederAction(“…”)
  • HandleErrorAttribute = how to handle exception in the method


<customErrors mode=”On” defaultRedirect=”GenericErrorPage.htm”>

<error statusCode=”500″ redirect=”/Error.htm” />




  • ActionFilterAttribute
    • Abstract class the class filters are built on; enables custom action filters:
      • OnActionExecuting
      • OnActionExecuted
      • OnREsultExecuting
      • OnResultExecuted


Implement action behaviors

Two approaches to determining the appropriate order of attributes:

  1. Rejecting filters – remove the general case first, then drill down to the specific cases
  2. Business importance – filter by the most important first


Implement action results

ActionResult = performs last set of coversions before returning to client; There are 9 action result helper methods:

The ViewResult and PartialViewResult is based off ViewResultBase (most common);

ContentResult is most flexible, allowing return of XML or PDF

FileResult returns binary – contains ContentType and FileDownloadName

JsonResult = serializes model before returning


Implement model binding

Model binding = two way mapping of request values to action method properties and parameters; several ways to do this:

  • Strongy typed binding = best for MVC, binds against model definition and incorporates input validation. On the client side user razor syntax *For; ex: @Html.TextboxFor(m =>
  • Weakly typed binding = if model is not attributed (no validation), then no performance benefits in using weakly typed binding; this is done: @Html.TextBox(“”);
    • Allows use of Bind attribute; this is beneficial in customizing what should/shouldnot be bound; use Exclude/Include;
    • Public ActionResult Login([Bind(Prefix=”login”)]LoginUser user)
    • Public ActionResult Save([Bind(Exclude=”Salary”)]Employee emp)
  • Value provider =
    • FormsValueProvider
    • QueryStringProvider
    • HttpFileCollectionValueProvider = file attachments returned in request
    • RouteDateValueProvider = routing data

Public ActionResult Save(FormCollection formColl) { Employee emp = new Employee(); If (TryUpdateModel(emp, formColl.ToValueProvider()) { UpdateModel(emp, formColl.ToValueProvider()); }



Thought Experiment


  1. Yes, the layout of the site can remain the same. You have to look at two areas: view and controller. The view needs the capability to display default placeholder information for nonregistered users. Use the controller to authenticate a user. Pass the information back to the view and show the required information for registered and logged-in us­ers. As long as the design is the same with some different options in a similar place for each type of user, the overall user experience is much the same.
  2. To allow for unauthenticated users to view, you need to ensure that there are no Authorize attributes set on the action. Anywhere authentication is needed, use the Authorize attribute to filter out unauthenticated users. You can even redirect the page to a login page so that a person with credentials can log in and post the information as needed.
  3. Although your roles are set up and you are correctly authenticated, if the information being returned misses required information, the model state is no longer valid. In that case, make sure that your model state is valid by manipulating the data before you insert the object.




  1. Correct answer: B
  2. Incorrect: Although this would solve the requirements, it is not the best way. It is better to run the RequireHttps filter first because it expends fewer resources than the Authorization filter.
  3. Correct: It filters out those users not on an SSL connection before performing the more resource-intensive authentication check.
  4. Incorrect: A custom action filter that performs both is more complicated to write than using the standard filters provided with ASP.NET MVC.
  5. Incorrect: A user can be authorized and not be connected over HTTPS. The two are independent and need to be treated as such.
  6. Correct answer: A
  7. Correct: The FileResult property was designed for this need.
  8. Incorrect: The product being distributed is a binary file and does not successfully transition to a string format.
  9. Incorrect: Creating a link to download the file through the application just postpones the decision until that link is clicked as it is still going through the application.
  10. Incorrect: Creating a link to download the file in an email just postpones the deci­sion until that link is clicked as it is still going through the application.
  11. Correct answer: D
  12. Incorrect: Although this could conceivably work, it has the misfortune of expect­ing manual mapping. It also uses the approach of a single model, and because the provided HTML input forms might change under you, it makes more sense to use two models so that the information your application controls is not affected.
  13. Incorrect: Although this would work, it uses the single model approach. Because the provided HTML input forms can change outside of your own release cycle, it makes more sense to use two models so that the information your application controls is not affected.
  14. Incorrect: You cannot weakly bind to the input fields provided from the third party because weakly-bound models imply that you have used an HTML helper to write the information, and you are just giving the helper a hint to the property it should map to in the model.
  15. Correct: The key is separating your data input fields from the provided input fields. You can strongly-bind to yours because you have full control over the rela­tionship between your model and your view, and can then use the ToValueProvider to merge the other model that is tied to the provided input fields.



3.4 Design and implement routes

Route = url to physical object on file system of web server


Define a route to handle a URL pattern

Routes can help with SEO

RouteCollection object à default handler is RegisterRoutes method, found in App_start/RouteConfig.cs



UrlParameter.Optional enum enables no parameters




new {controller=”Product”, action=”Details”},

new {productId = @”\d+” }




name: “NoDetails”,

url: “{controller}/{id}”,

defaults: new { controller = “Appointment”, action = “Details”, id = UrlParameter.Optional },

constraints: new { id = @”^[0-9]+$” }



Apply route constraints

Route constraint = filter that route must match

Constraints such as id = @”\d+” regex

The more constrain the route, the easier for route handler to identify the action to call


Ignore URL patterns

IgnoreRoute method to ignore some routes

routes.Ignore(“{*allhtml}”, new {allhtml=@”.*\.htm(/.*)?});

Example – can ignore specific files on the file system and instead have them accessible through controller actions that return a FileContentResult


Add custom route parameters

Customize specific controller/action parameters and routes, such as passing in optional parameters where on the controller it accepts it as nullable (when it not passed)


For multiple parameters

routes.MapRoute( name: “GeneralListDateRange”, url: “{controller} /List/{param1}/{ param2}/{ param3}”, defaults: new { controller = “Article”, param1= UrlParameter.Optional, param2= UrlParameter.Optional, param3= UrlParameter.Optional },);

  1. List the potentially contradictory routes
  2. Define and adhere to internal pattern of handling parameters


Define Areas

Area = portion of app where designer to separate normal set of MVC to separate functional groups in project file structure; physically and logically splits up the functionalities; Requires use of a AreaRegistration file



Thought Experiment


  1. You can split the site into areas. A staff area can be authenticated against the com­pany’s employee database. The customer area can display only products customers can purchase.
  2. If a certain product line is no longer available and still cached in the search engines, the route can be rewritten so that default controller and actions are called when the URL fits a certain type of request rather then causing a 404 error.
  3. When multiple products can be mapped to the same controller or action, additional routes can be mapped, and the same controller and/or action can be called for a dif­ferent URL request. For example, movies can be mapped to the DVD controller with a default action.



  1. Correct answer: B
  2. Incorrect: This is a default route; it accomplishes nothing.
  3. Correct: This is how you add an additional route and point to a different controller.
  4. Incorrect: The URL portion of the new route does not satisfy the question being asked.
  5. Incorrect: The URL portion of the new route is reversed.
  6. Correct answer: B
  7. Incorrect: SetItem adds an item to the collection. However, adding a route at the end of the collection does not solve the problem because it is being added as a route that should be matched.
  8. Correct: IgnoreRoute is the correct statement to use.
  9. Incorrect: Insert adds a new route to the collection for matching, but does not ignore pages.
  10. Incorrect: Remove removes a route from the table. More than likely, this is an implied mapping, so removing the DVD route does not stop the application from mapping the request to the same action.
  11. Correct answers: A, C
  12. Correct: Creating partial classes offers some relief to the problem that you are ex­periencing, although not as much as a more-functional separation such as offered by areas. You do not have to make any UI changes, however.
  13. Incorrect: You do not want or need to move any views or models. The code clutter is due to the small discrete actions that support your AJAX site.
  14. Correct: Your best move is to separate the AJAX components into an area. You would have to change all the calls to it, but you would achieve complete separa­tion of concern for AJAX calls.
  15. Incorrect: This would be too drastic a change. It would require a complete change, from deployment to testing, throughout the entire application stack.



3.5 Control application behavior by using MVC extensibility points


Implement MVC filters and controller factories

Four main filter types on controllers/actions:

  1. Authorization – System.Web.Mvc.IAuthorizationFilter
    1. OnAuthorization
  2. Action – System.Web.Mvc.IActionFilter
    1. OnActionExecuting
    2. OnActionExecuted
  3. Result – System.Web.Mvc.IResultFilter
    1. OnResultExecuting
    2. OnResultExecuted
  4. Exception – System.Web.Mvc.IExceptionFilter
    1. OnException


Controller factor for DI / IoC (Inversion of Control)

Implement the System.Web.Mvc.IControllerFactory

  • CreateController
  • ReleaseController
  • GetControllerSessionBehavior

This needs to be also defined in the Global.asax – Application_Start()

  • This is usually done by third party DI tool


Control application behavior by using action results, view engines, model binders and route handlers


Override ActionResult

  • Calls ExecuteREsult




Call Render method – part of IView; parameters = ViewContext and TextWriter


Model binders:

DefaultModelBinder (IModelBinder)

  • BindProperty


Route handlers:

Override MvcRouteHandler

  • GetHttpHandler method





  1. You can create themes by adding an additional custom view engine for the site and show the custom view engine on the test site.
  2. To execute a certain custom attribute, you need to create a custom action filter and run additional code within the OnActionExecuting method you have overridden in the custom action filter.
  3. Because every contingency has been reviewed, and the controller code is written cor­rectly, you should check the route. Make sure that additional parameter(s) are included because the code might be checking against parameters.



  1. Correct answer: D
  2. Incorrect: You should not have an AuthorizeAttribute on your login action, be­cause it ensures that users have to be authenticated before they log in. Users can never log in to the site.
  3. Incorrect: Because this filter is applied globally, it sends the email every time the user takes an action, rather than just once per visit.
  4. Incorrect: You should not have an AuthorizeAttribute on your login action because it ensures that users have to be authenticated before they log in. Users can never log in to the site.
  5. Correct: This is be applied only because the user is leaving the login section of the application, at which point you also know whether they have been authenticated.
  6. Correct answers: A, C
  7. Correct: Creating a globally applied action filter enables you to save the state of every action taken by the user while logged in to your site.
  8. Incorrect: By setting the AllowMultiple to false, you have configured the filter to be run only once during the lifetime of the application.
  9. Correct: By creating a globally applied action filter you have ensured that every action taken by the user will be logged.
  10. Incorrect: Because this is applied only to the AuthorizeAttribute, it logs only those actions where the user has to be logged in. That enables them to take actions that might not be logged.
  11. Correct answers: B, D
  12. Incorrect: This does not easily enable saving into the database because the color itself only implements the HTTP Get.
  13. Correct: This solution works because it combines the three discrete values into a single object on the model.
  14. Incorrect: Although this solution gets the value into the database appropriately, it does not fulfill the requirement that the model be able to use the color as a single value.
  15. Correct: Although it takes more work, using an approach of creating a model binder for the entire object, rather than just a part, successfully manages the need to have it in the model and in the database.



3.6 Reduce network bandwidth

Minimize amont of data sent over bandwidth; bundling and minification; reduce network hops


Bundle and minify scripts (CSS/JS)

Browsers limit number of concurrent connections to the same domain to 6. Bundling things together, minify them to make it smaller

Bundling – JS, CSS and custom bundles; being that things are all bundled together, there could be performance cost in finding things in the bundle, especially if large

Minificaiton – doesn’t have costs like bundling


Enable bundling by:

  • <compilation debug=”false”> in web.config
  • EbaleOptimizations = true in RegisterBundles of App_start/BundleConfig.cs (overrides web.config)


Compress and decompress data (using gip/deflate, storage)

Header tag: Accept-Encoding: gzip, deflate

Indicates browser can interpret gzip and deflate, which are compression types

IIS can detect this and automatically compress files before responding; no need to manage two different file types – IIS does it for you from the original file

Documents, large files – benefit most from compression


Compression can be done manually from MVC controller with FileResult; can also use ContentResult with CompressionStream (System.IO.Compression.GZipStream)


Plan on content delivery network (CDN) like Azure CDN

Content delivery network

Closer geographical location

For all mainstream JS, use CDN is faster – cached on routers


Thought Experiment


  1. You can create themes by adding an additional custom view engine for the site and show the custom view engine on the test site.
  2. To execute a certain custom attribute, you need to create a custom action filter and run additional code within the OnActionExecuting method you have overridden in the custom action filter.
  3. Because every contingency has been reviewed, and the controller code is written cor­rectly, you should check the route. Make sure that additional parameter(s) are included because the code might be checking against parameters.



  1. Correct answer: C
  2. Incorrect: Although you might be able to minimize the size of the files being downloaded, your browser cannot open and use those files.
  3. Incorrect: This approach minimizes the size of the files being sent to the client, but it also has a heavy cost on both server-side and client-side processing because the server tries to compress every file.
  4. Correct: This is an appropriate next step to try to compress the script and style files being sent to the client.
  5. Incorrect: IIS compression has not yet been tried. It makes more sense to try all other solutions before approaching a code rewrite.
  6. Correct answers: B, D
  7. Incorrect: Poor decisions in implementing bundling and minification can hurt performance rather than help it.
  8. Correct: Bundling every script into a single large file might decrease the effective­ness of concurrent downloading.
  9. Incorrect: You should keep scripts and CSS files separated for maximum effective­ness. They represent different aspects of the user experience, so a logical separa­tion, even on the client side, makes sense.
  10. Correct: Not separating scripts logically might lead to the user downloading scripts that will never be used. Although the download experience is maximized, it does not make sense to download unused scripts.
  11. Correct answers: B, C
  12. Incorrect: Bundling would create unreadable files because it would concatenate PDF files inappropriately.
  13. Correct: This solution causes more work on the client side to open and view the compressed content, but it provides a more responsive user experience.
  14. Correct: Moving the part of the site most affected by the new usage closer to the users increases their download speed and thus their perceived performance.
  15. Incorrect: Because local users have not noticed a reduction in performance, it is unlikely that adding more cycles at the server level would improve the responsive­ness of the application for remote users.



4 Troubleshoot and debug web applications (20-25%)

Debugging and Diagnostics are only available with Visual Studio Ultimate / Professional


4.1 Prevent and troubleshoot runtime issues

Performance analysis should be regular part of development process.

Troubleshooting performance, security and errors

The three types of errors to watch for:

  • Performance
  • Security
  • Runtime


Performance Wizards

Performance can be analyzed using the Visual Studio 2012 performance tool. Setup different profiling (process of analysis) methods; the following are available:

  • CPU Sampling (recommended) – shows work being done by app and impact against CPU; acts as initial check
  • Instrumentation – invasive check; for memory leak, disk I/O problems,
  • .NET Memory allocation = checks garbage collection, object handling in memory
  • Resource Contention – for multi-threaded, thread contention,


VS Profiler

VS2012 also provides profiler – performs complete trace and uses sampling. Generates a concise report; shows Hot Path which is the area that is using most resources or CPU processing;


Performance Monitor

A tool available on Windows Server (and desktops). Opened by running perfmon. This can monitor very specific parts of the server or .NET framework. Running the monitor itself can be resource intensive.


Troubleshooting Security Issues

Tend to be more on authentication and authorization.


Tracing logging and debugging

The process of saving the information is called logging. Tracing is a technique that enables you to analyze your application while it is running. You add tracing statements to your application during development, and you can use the output during both development and production. Plus, you can turn tracing on and off as needed without having to change code. Debugging is the process of analyzing results from various tools, like those mentioned previously, to determine problem areas in your application.


NLog and log4net are most popular logging tools. Logging usually captures based on criticality – Error, Info and Debug.



Tracing can be done through TraceListener (configured through web.config) which works with System.Diagnostics.TextWriterTraceListener. It writes out

Logging levels (by criticality)

  • Error
  • Warning
  • Info
  • Debug (verbose)

Turning <customErrors> off will display full errors (yellow page)

  1. <web>
  2. <customErrors mode=”Off” defaultRedirect=”Error” />

Tracing is handled different in *.cs files vs *.cshtml / *.aspx files



The HandleErrorAttribute is an attribute you can apply to actions, controllers, or globally that enables you to assign, as an attribute on the action, the relationship between a certain type of exception, and a view that will be used to display information about the error:

[HandleError(ExceptionType=typeof(System.IOException), View=”FileError”)]

Error handling can be done at controller level or global.ascx in Application_Error.



Code Contracts

Used to define preconditions, invariants and postconditions. Need to install Code Contract Editor for VS2012. This is managed by Microsoft Research

  • Pre-Conditions = conditions fulfilled before method execute

Contract.Requires( x != null );
Contract.Requires<ArgumentNullException>( x != null, “x” );

  • Invariants = conditions to not change during execution

Contract.Invariant ( this.y >= 0 );

Contract.Invariant ( this.x > this.y );

  • Post-Conditions = conditions that verified upon completion of method

Contract.Ensures( this .F > 0 );

Contract.EnsuresOnThrow<T>( this.F > 0 );

Extra: calling the end of code contract section: Contract.EndContractBlock();

If-then-throw statements Backward-compatible public preconditions
Requires All public preconditions.
Ensures All public (normal) postconditions.
EnsuresOnThrow All public exceptional postconditions.
Ensures All private/internal (normal) postconditions.
EnsuresOnThrow All private/internal exceptional postconditions.
EndContractBlock If using ifthenthrow style preconditions without any other contracts, place a call to EndContractBlock to indicate that all previous if checks are preconditions.

void IArray.RemoveAt(int index)


Contract.Requires(index >= 0);

Contract.Requires(index < ((IArray)this).Count);

Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) – 1);




Health monitoring

Build into ASP.NET that handles various events in application lifetime. It can be configured and customized through the web.config. Handles:

  • Application events = app start/stop; heartbeats during execution – Web.Managemetn.EventLogWebEventProvider
  • Security events = authentication/authorization
  • Appilcation errors = exceptions during execution

Can be added to web.config (sample found in the .net framework folder)

<healthMonitoring> …




  1. Several tools can help you maintain the integrity of your data. The first is parameter checking, in which you throw an ArgumentException. Another is the use of code con­tracts to perform a check on the values going into and coming out of the application.
  2. Several tools can give you an idea of what is happening with your data. You can’t de­pend solely on errors for the information you need because the data might be wrong without throwing errors. You can add helpful information to logging messages, as well as details on the parameters coming into a method and the return values out of the method. This information helps you understand problems in the system. You can also take the same approach with tracing.



  1. Correct answer: C
  2. Incorrect: CPU sampling will not provide assistance for the main problem of the application locking up.
  3. Incorrect: Memory analysis will not provide assistance for the main problem of the application locking up.
  4. Correct: Thread and resource profiling will give some understanding of what kind of actions are taking place that will cause a resource or thread to be blocked.
  5. Incorrect: Tracing information regarding when a web service starts and stops would be interesting. However, the problem is that the web service is called and never returns, so this logging information would not be complete or useful.
  6. Incorrect: A problem with security information would likely not cause the service to stop responding.
  7. Correct answers: B, C, D
  8. Incorrect: The Performance Wizard does not support management or identify data issues.
  9. Correct: Preconditional code contracts ensure that incorrect information is not submitted to a method. This helps eliminate the possibility of bad data.
  10. Correct: Postconditional code contracts ensure that incorrect information is not returned from a method. This helps eliminate the possibility of bad data.
  11. Correct: Invariant code contracts ensure that objects do not get to an invalid state. This helps eliminate the possibility of bad data.


  1. Incorrect: The Visual Studio profiler does not provide any support for managing or identifying data issues.


Correct answers: A, B

  1. Correct: Adding health monitors is an easy task. Determining which options pro­vide the information you need will be time-consuming because of the number of choices.
  2. Correct: Generic logging is a useful addition and can be added as items are refac­tored; it is not an all-or-nothing type of work.
  3. Incorrect: You can perform tracing on an ad-hoc basis as needed.
  4. Incorrect: Data collection in Performance Monitor is relatively simple. However, determining the most critical items to monitor can be time-consuming because there are hundreds of counters.



4.2 Design an exception handling strategy


In a layered architecture, should only handle exceptions in that layer. If a SQL exception is thrown at database layer, could be meaningless at other layers above so log it and perhaps instead throw a generic DatabaseException custom exception.


Handling Exceptions on multiple layers

SoC (separation of concern) can complicate error handling as need to determine where to do it. Keep focus on the current layer, only handle errors at that layer and don’t assume or try to handler other layers. For some fatal errors, like SQLException – needs to bubble up to user – but at the lower layer log it and throw a new exception that is more appropriate for user – like DatabaseException.


Displaying Custom Error pages using global.asax or custom HttpHandler through web.config

Two of the most common custom error pages – 404 page not found and a generic custom error page. These pages can be handled in the Global.asax file under Application_Start or Application_Error; the Application_Error() should log the error and call appropriate handler – such as a custom error handling controller. It can also be handled in the web.config in the <customErrors> section of the <system.web> area.


Common error pages: 400, 403, 404

Error pages for internal 500 errors – these usually should be caught through Exception Filters; OnException handlers; by default <customErrors> do not handle these due to being internal app error. To handle 500 errors, the <httpErrors errorMode=”detailed”> must be set.


Custom Http Handlers

Create custom HttpHandlers (like a handler for any *.sample page extensions) in the App_Code folder. Register them in the web.config

public class HelloWorldHandler : IHttpHandler


public HelloWorldHandler()



public void ProcessRequest(HttpContext context)


HttpRequest Request = context.Request;

HttpResponse Response = context.Response;

// This handler is called whenever a file ending

// in .sample is requested. A file with that extension

// does not need to exist.



Response.Write(“<h1>Hello from a synchronous custom HTTP handler.</h1>”);




public bool IsReusable




<add verb=”*” path=”*.sample” name=”HelloWorldHandler” type=”HelloWorldHandler” resourceType=”Unspecified”/>




First Chance Exception

Every exception starts as a first chance exception. Should be caught during development to be addressed. Select Common Language runtime Exceptions in the DEBUG Exceptions dialog under VS settings. It helps you find problems that might be mistakenly hidden, such as those handled by an empty catch block or those that are entirely mishandled.


First chance exception is a notification that allows observation of the exception only and cannot forward or handle the exception. Careful on use, as this itself throws an exception (FirstChanceException) and can get recursive leading to a StackOverflow.

HandleError Attribute – Exception Filters over Controllers and Actions

Exception filters implements IExceptionFilter
In the RegisterGlobalFilters file there is registration of HandleErrorAttribute added to filters

public static void RegisterGlobalFilters(GlobalFiltersCollection filters)


filters.Add(new HandleErrorAttribute());


Once registered, the exception filters can be used at controller level (or action level) like so:

[HandleError(Exception = typeof(DbException), View = “DatabaseError”)]

[HandleError(Exception = typeof(AppException), View = “ApplicationError”)]

public class ProductController
Note that HandleError/Exception Filter only catches HTTP 500 based errors – have to re-throw new exception if anything else needed:

public ViewResult Posts(string category)


if(_blogRepository.Category(category) == null)

throw new HttpException(404, “Category not found”);


return _blogRepository.Posts(category);



Extending HandleError

For custom excpetion handling

public class CustomHandleErrorAttribute : HandleErrorAttribute


private readonly ILog _logger;


public CustomHandleErrorAttribute()


_logger = LogManager.GetLogger(“MyLogger”);



public override void OnException(ExceptionContext filterContext)


if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)





HandleError vs Application_Error

Application_Error is outside the MVC context – bad for getting details of each request; however good place to put general application logging.



Error Logging Modules and Handlers – application wide error logging for ASP.NET




  1. You should treat exception handling as robustly as possible, regardless of the audience. It is a best practice to try to eliminate and/or remediate issues as soon as they happen.
  2. None of the information should be displayed in an error page outside of the devel­opment environment. Although these users are support staff for multiple applications, it is possible they are not fully accredited administrators across all the applications with which you are interfacing. You should treat logging and information display the same as if the users were not support staff. However, although you should not display the information in the UI to the user, you need to capture the necessary logging informa­tion to help technical staff troubleshoot issues.


Section Overview

B, C, B



4.3 Test a web application

Unit Testing is the process of creating re-runnable tests that validate a particular subset of functionality. Two important aspects of unit testing:

  • Test should thoroughly cover the area being tested
  • Positive and negative flows should be part of the test stack; as well as errors that might occur on lower stacks that might get bubbled and consumed in the segment currently testing.


Each assembly (project) should have its own unit test (project).


Arrange à Act à Assert


Use Microsoft.VisualStudio.TestTools.UnitTesting


Integration test

Testing between functionality points, such as data from database to controller or data logic and getting processed correctly. These tests can be more complicated due to I/O errors, etc. Need to persist the test data for these tests as multiple developers might be performing different tests.


Creating Mocks – Microsoft Fakes Framework

Use Fakes, provided in two different ways to perform test: shims and stubs.

Shim = small code that intercepts call to an assembly and returns mock object. For example, using a shim for DateTime.Now to control that date time. Example: Y2K bug testing – set date to 2000/1/1

Follow naming convention. Notice that DateTime.Now was converted to a call to ShimDateTime.NowGet, which shows how shim class names are composed by prefixing Fakes.Shim to the original type name and how Get is appended to any property getter.

Shims can affect performance since it is replacing code at runtime

Stub = code that replaces working class with limited subset of a mock class.

Stubs expect that your application is built as interface-driven rather than type-driven because stubs automatically provide an implementation of the interface you can work with as if it were a real object. Stubs requires a standard naming convention much like shims. For stubs, the names are transformed by putting Fakes.Stub in front of the interface name. Stubs ~ dependency injection

Use Shims to isolate assemblies that are not part of solution – use stubs to isolate components in the solution


public void TestCurrentYear()


int fixedYear = 2000;


// Shims can be used only in a ShimsContext:

using (ShimsContext.Create())


// Arrange:

// Shim DateTime.Now to return a fixed date:

System.Fakes.ShimDateTime.NowGet =

() =>

{ return new DateTime(fixedYear, 1, 1); };


// Instantiate the component under test:

var componentUnderTest = new MyComponent();


// Act:

int year = componentUnderTest.GetTheCurrentYear();


// Assert:

// This will always be true if the component is working:

Assert.AreEqual(fixedYear, year);




Load and Performance Testing

VS2012 Ultimate edition allows load and performance testing by using virtual servers. This is configured through the .webtest file. The .webtest allows for recording of the app for performance test. For load testing, there are 3 types:

  • Constant = sets constant number of users; could be unrealistic since the number of users starts immediately when test starts
  • Step = adds users incrementally based on following:
    • Initial user count
    • Max user count
    • Step duration
    • Step user count (number of users to add per step)
  • Goal-based = like step but sets final user count or CPU/memory usage (thereby showing capcity of users)
    • Gradual increase based on CPU and resource, can see performance over time
    • Gives indication of number of users capacity


Test Planning

There are 4 common test approaches:

  1. Smoke = light load; usually done right after deployment
  2. Stress = heavy load for long period of time;
  3. Performance = responsiveness of application; timed tests;
  4. Capacity Planning = testing with maximum users to see correctness of application;


Objective Review


  1. Correct answer: D Incorrect: There might very well be nonaction methods in a controller. Those methods should be tested as well.
  2. Incorrect: You should provide much more separation of your tests than using a single file for every unit test that applies to a controller.
  3. Incorrect: This is too much of a breakdown. The best relationship between con­trollers and the applicable unit tests is usually 1 to 1. However, a controller with a large number of methods working within the controller will not meet the 1-to-1 ratio. You should test nonaction methods in the controller as well.
  4. Correct: This solution provides for testing actions and nonactions as well as a good split of the tests per file.
  5. Correct answer: C Incorrect: Unit tests are designed to ensure that the functionality and logic of the application are correct. They do not work well when you need a performance-based analysis.
  6. Incorrect: Although this test will provide some useful and interesting information, running a constant load of 50 percent might not give you the information you need. More users could use the application at any point in time.
  7. Correct: Starting from a midlevel count of users and then increasing to the total number of possible numbers should give you an idea of what is happening during the day-to-day running of the application in production.
  8. Incorrect: Understanding the number of users required to reach 75 percent utilization of the CPU might be interesting, but it does not help you understand the users’ issue. They might be experiencing slowness due to memory utilization or threading contention that this approach will not be able to detect.
  9. Correct answer: C Incorrect: Running at a constant load, even at various levels of user count, will not efficiently give them the information that they need.
  10. Incorrect: Although this approach will give them interesting information and an understanding of the capacity of a server, it is based less on statistical information than on a subjective analysis of performance.
  11. Correct: This approach will give them an objective analysis of the amount of users a server can manage at a particular level of memory or CPU usage.
  12. Incorrect: This approach leaves out static pages. For a true test, you should exer­cise all parts of the application.



4.4 Debug a Windows Azure application

Azure has troubleshooting, debug and testing API and tools for cloud-based apps


Azure Diagnostics API (application programming interface)

Azure Diagnostics – tracing and debugging errors; watch performance issues; monitor system resources

Azure Roles are destroyed when app stops and created – which means all system logs are also destroyed if stored in that environment – should have these on separate storage


Azure Diagnostics; use the Microsoft.WindowsAzure.Diagnostics namespace that is part of the Azure SDK.


ServiceDefinition.csdef = add information to import the Azure Diagnostics module

ServiceConfiguration.cscfg = add information to allow diagnostic module to access databases or other business needs

Diagnostics.wadcfg = for event monitors, configure entries here on how to setup appropriate counters; this information will be downloaded to VS by On-Demand vs Scheduled; On-Demand approach = code within app, within role, or external app requests the transfer of diagnostics to Azure Storage account; Scheduled transfer = transfer done during configuration of log directory


Using Azure storage accounts – AttachStorageAcountRequest

A POST request method to attach storage account to a specified Media Services account. Successful operation returns HTTP204 (NoContent);


Method Request URI
POST https://endpoint//services/mediaservices/Accounts//StorageAccounts



public class AttachStorageAccountRequest



public string StorageAccountKey { get; set; }



public string StorageAccountName { get; set; }



public string BlobStorageEndPointUri { get; set; }





Choose log types (event, performance counters, crash dumps)

Can capture event logs, crash dumps, etc; Should consider performance impacts vs amount of logging detail; Also having too much logging can impact analysis.


Debug Azure using IntelliTrace and RDP (remote desktop)

Can be difficult analyzing through the cloud; but VS offers Azure emulation to do local analysis before deploy; install Azure SDK on VS.


Debugging in Azure can be done through:

  1. IntelliTrace – controlled through VS Ultimate; set project to Debug and during build – there is checkbox for IntelliTrace; Couple of options:
    1. Events only
    2. Events and Call info

The logs are stored in the Azure storage account – to review/request logs, must be downloaded locally through Windows Azure Compute note that is available on the Server Explorer in VS

  1. RDP = configured during publish process; enable rdp and requires authorization info; access is same as the intellitrace – done through VS Server Explorer – Windows Azure Compute node; rdp allows review of IIS logs, Windows event logs and other tasks.


IntelliTrace – VS Enterprise/Ultimate only


  • Record specific events
  • Debug errors that are hard to reproduce or that happen in deployment


  • Show past events
  • Call information with past events
  • Save Intellitrace session
  • Control the data that intellitrace collects







5 Design and Implement Security (20 – 25%)


5.1 Configure authentication

Authentication is process of determining whether users are who they say they are.


Authenticating users

There are two parts to authentication in ASP.NET MVC; both work in tandem to manage the authentication process

  • IIS
    • Challenge based = client must respond to server’s demand for credentials
      • Basic = windows accounts with Base64 encoding of actual password (very weak/insecure)
      • Digest = basic auth with hashing of password, better than basic as no actual pswd
      • Windows (NTLM) – includes impersonation, supports Kerberos, best for intranets
      • Client Certificate Mapping = Use of SSL with a cert from CA
    • Login redirection based = client sends login credentials to application without being requested by server
      • Forms authentication
    • A third category, though not really authentication is anonymous authentication or no authentication
  • .NET application framework.


Microsoft Provider Pattern

The provider pattern is a contract between an application programming interface (API) and the business logic/data abstraction layer. During request process – HttpModule analyzes and verifies the user information – then adds it to the HttpContext, which is available throughout the application. It is also put onto the System.Threading.Thread.CurrentPrincipal thread, however this and the HttpContext may not always be in sync as they are handled separately in the request process. You could sync the two after the authentication process by the following:

// Make sure the principals are in sync
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;


There are two interfaces that provide information about the security context of the user:

  • Security.Principal.IIdentity = interface contains info about the authenticated user (or whether they have been authenticated). At the base level it contains user’s name and if they have been authenticated. This can come from other Identity providers such as Google or Facebook.
  • Security.Principal.IPrincipal = interface contains info about user and user roles. This is usually specific to the app or domain. Multiple domains can have the same user Identity but each have different user Principals.

IPrincipal wraps the IIdenity  and as such, IIdentity is required for any user authentication/authorization.


The interfaces above can be implemented into several types, such as:

  • WindowsIdentity/WindowsPrincipal = for Active Directory and Windows store users
  • FormsIdentity/GenericPrincipal = forms authentication
  • GenericIdentity/GenericPrincipal = custom users


To check if user is authenticated, the follow two places can be checked:

  • CurrentPrincipal.Identity.IsAuthenticated
  • Current.User.Identity.IsAuthenticated


Authentication Protocols and Providers

Each default IIS authentication type fulfills different security need. Should try to use these instead of a custom or third-party one. The default IIS authentication types are:

  • Anonymous authentication – default for IIS7+. Uses another user or service account so anonymous users can impersonate file access. Can assign account to individual sites or application pool that runs the site. If the service account cannot access the file, then server will return Unauthorized The User object will be blank.
  • Basic authentication – supported by most browsers and servers; simple username and password transmission using Base64 encoding but not encrypted; Uesr accounts are defined either on the server or Active Directory.
  • Digest authentication – challenge-response mechanism to ensure credentials are not sent in clear text using a hash (though no encryption); this is possible with either Active Directory or server side accounts. (this is Basic Auth with hashed passwords); This is done in the following steps:
    • Server sends challenge to client
    • Client generates unique challenge value
    • Client creates hash of both the challenge and challenge value
    • Client returns hash to server
    • Server creates own version of hash to ensure it matches the one from client
    • Server creates new hash of the challenge and challenge values
    • Server sends new hash to client
    • Client calculates its own version of the hash to ensure it matches the one from server
  • Forms authentication – authentication and authorization without using Windows built-in security; instead developer creates it and after authentication, calls the Membership provider to setup authorization. The authentication session can be set at SetAuthCookie. (opposite to clear it is the FormsAuthentication.ClearAuthCookie)


Sample of C# code


public void Authenticate(string uname, string pass)


User user = dbContext.Users.First (x=>x.UserName.Equals(uname();

if (user != null && user.Password.Equals(EncryptHash(pass))


FormsAuthentication.SetAuthCookie(uname, false);

RedirectToAction(“Main”, “DashBoard”);


// unable to login

RenderView(“Index”, new LoginViewData


ErrorMessage = “Invalid credentials.”




  • Windows authentication – uses windows accounts, which can be done through two protocols listed below. But this only works through Windows broswers (or browsers that support the protocols) as the credential cache keeps this information. Therefore this provides SSO.
    • NTLM
    • Kerberos

Windows Auth is the default authentication provider – every user on the application is matched against the domain or local server by IIS.

  • Impersonation authentication – addin to windows auth that allows application to use the Windows identity provided by Windows auth. Typically, cannot access network files and resources using domain login, that’s still done through a service account. That can be changed using impersonation so that resource access is controlled by the domain user.

Note thought that impersonation only sets the System.Security.Principal WindowsIdentity object; the authentication process itself still done by windows auth, which fills the HttpContext.User property.


Sample of XML code



<identity impersonate=”true” />




  • Client Certificate authentication and IIS Client Certificate authentication – this is the most complex form of auth as it uses the server/client SSL certificates. It also requires that the client and server are in the same Active Directory domain and the user account must be in the AD.
  • Custom authentication – most cases should be able to use one of the default auth types, however, can use custom auth; must implement the IIdentity and IPrincipal interfaces; See example code for implementation:


public class CustomPrincipal : IPrincipal


public CustomPrincipal(CustomIdentity identity)


this.Identity = identity;


public IIdentity Identity { get; private set; }

public bool IsInRole(string role)


return true;



public class CustomIdentity : IIdentity


public CustomIdentity(string name)


this.Name = name;


public string AuthenticationType


get { return “Custom”; }


public bool IsAuthenticated


get { return !string.IsNullOrEmpty(this.Name); }


public string Name { get; private set; }



Enforcing authentication settings

Typically, authentication can be enforced using the AuthorizeAttribute-based class; a filter that can be applied to action, controller or even globally. These should be defined at the appropriate level but should not be defined in the web.config. Certain actions or methods can have AllowAnonymous attribute/filter set on it when it does not need authentication. To apply attribute at global level, can use following code (in the global.asax file??)

Sample of C# code

public static void RegisterGlobalFilters(GlobalFilterCollection filters)


filters.Add(new HandleErrorAttribute());

filters.Add(new AuthorizeAttribute());


The problem with global filter is that it will block even the login page. A work around for this is to create AllowAnonymous filter along the login action, or create a blocked-list, which is list of what is allowed and not allowed.


Another attribute to set is the RequireHttpsAttribute – which enforces use of HTTPS connection. This can be done at the global level as well in the global.asax file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)


filters.Add(new HandleErrorAttribute());

filters.Add(new AuthorizeAttribute());

filters.Add(new RequireHttpsAttribute());




Choosing between Windows, Forms, and custom authentication

To summarize above, the six types of authentication methods are:

  1. Anonymous – no auth
  2. Basic – windows user name and password sent in clear text
  3. Digest – basically Basic auth but the name and password are hashed
  4. Windows Auth – using Kerberos or NTLM (default)
  5. Client Certificate Mapping
  6. IIS Client Certificate


Forms authentication requires coding and possibly a database storing the user information. It gives more control over the authentication process as long as the auth token is set in the FormsAuthorization helper. There is also the SimpleMembership and WebSecurity helper classes to help with custom form authentications.


Managing user session by using cookies

Forms auth uses a cookie to manage the forms auth ticket, which is encrypted version of user name stored in cookie. This is an HTTP-only container for the ticket and cannot be manipulated on the client side. It is passed back to the server with every request and is used by server to identify previously logged-in authenticated user. Creating the FormsAuthentication ticket:

FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(





createPersistentCookie, // a Boolean indicating whether a cookie

// should be created on the user’s machine

String.Join(“;”,rolesArr) //user’s roles


// add cookie to response stream

string encTicket = FormsAuthentication.Encrypt(authTicket);

System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.

FormsCookieName, encTicket);


Other information can be stored in this ticket in the UserData property such as information on state, but should take into consideration that the ticket is available on the client side and though encrypted, the data could be accessible. The FormsAuthenticationToken object can store authentication information as well, but this is always passed back and forth in request/responses, so can affect performance.


Another option is to use session states, which keeps the user information on the server side. A cookie would still be used by the client but this cookie would only have SessionId and no more.


Configuring membership providers

Membership framework has existed since .Net 2.0 and revolved around users, roles and profiles. This requires user information being stored at some data source, ex SQL Server. The following is example config for using SqlMembershipProvider





<add name=”AspNetSqlMembershipProvider”












type=”System.Web.Security.SqlMembershipProvider, System.Web,

Version=, Culture=neutral />




Note that OAuth and OpenID don’t have user passwords and as such, require some extra work when used with membership provider. This has been improved with SimpleMembership = umbrella term for both SimpleMembership and SimpleRoles;



Provides security and authentication features; including ability to create user accounts, log users in and out, reset or change passwords and perform related tasks. This can be done from any table and it will take the given column field as the user Id and user Name.


WebSecurity.InitializeDatabaseConnection(string connectionString, string providerName,

string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)


WebSecurity is a wrapper over ExtendedMembershipProvider object; which is also implemented by the SimpleMembershipProvider (out of box class for MVC4). Note that WebSecurity cannot be used with standard MembershipPRovider object. Usually the only part of WebSecurity config used in SimpleMembership is the database connection string:

Sample of XML code


<add name=”DefaultConnection” connectionString=”ConnectionStringHere”

providerName=”System.Data.SqlClient” />



<add key=”TableName” value=”CustomLoginTable”/>

<add key=”IdColumn” value=”Id”/>

<add key=”UsernameColumn” value=”Username”/>



Note that the <provider> is “added” <providers> section, thereby indicating that multiple authentication providers can be utilized. For example, to use a Windows Auth first and then fall back on forms auth.


WebSecurity does not deal with roles. This is done through SimpleRolesProvider.



Implements part (not all) of the RoleProvider base class. Provides interface to define groups that users can be assigned to; can grant users to these groups; basic role functionality. If full functionality needed – use the default role provider.


Contains Name, Description, UserIdColumn, UserNameColumn, UserTableName, ApplicationName



There are no predefined roles; you can create any roles; User roles can be checked by: Roles.IsUserInRole


Creating custom membership providers

Putting code in the controller is bad practice, the code should be added with extensiblity points; this allow customization by overriding current functionality.


For Windows auth, can extend the ActiveDirectoryProvider and AuthorizeAttribute to customize how authentication and authorization are handled.


To customize FormsAuthentication – consider the two aspects:

  • FormsAuthentication class itself – does work to set auth ticket the first time
  • FormsAuthenticationModule – does all work for subsequent requests

The SEtAuthCookie method sets the ticket into a cookie. FormsAuthenticationModule is a HttpModule that looks for the cookie and ticket for all subsequent requests. It decrypts it and adds to the HttpContext of the request.


To customize membership provider, extend the MembershipProvider abstract class from System.Web.Security. This abstract class is derived from ProviderBase class of the System.Configuration.Provider.


Note that Membership is specific to an ApplicationName, this is to allow multiple applications to run against the same backend; but as such, user role definitons are specific to each application and must be defined appropriately with the ApplicationName. This can create multiple identical user names in the same physical database, but each with different ApplicationName. The full list of Required properties and members for creating a custom membership provider:




5.2 Configure and apply authorization

Authorization = process of giving user permissions to take an action on something, such as create, read, update, delete. This is usually done through roles; users come and go but roles remain the same.


Create Roles

ASP.NET membership is based on a provider model/framework where there are role providers; such as SqlRoleProvider which works with SqlMembershipProvider; or ActiveDirectoryMembershipProvider which also provides roles through Active Directory.


Active Directory based systems let role management be controlled through AD (not the app). Roles provide a way to group users together with similar authorization rules;


Authorize roles by using configuration

Can manage role authorization through the web.config so that redeploy/recompile is not necessary


Note that if using custom authorization through SimpleMembershipProvider with SimpleRole – this web.config is not available and instead must define the roles through InitializeDatabaseConnection()

public static void InitializeDatabaseConnection( string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)




This provides properties such as: ApplicationName, Passwords, Questions for Passwords, and UserIdColumn etc from ProviderBase class.


Generally – roles should be controlled through configurations rather than programmatically.


Authorize roles programmatically

Roles can be controlled programmatically through AuthorizeAttribute filters at the controller or action levels


Can also use [Authorize] without the roles definition which checks that the user is at least identified. Whenever these filters fail – the user will be automatically redirected to the default login page, which is controlled by framework. The default login page is defined in the StartupAuth.cs file (for MVC5).


Also – user roles can be checked at the RoleProvider level with IsUserInRole(..)

RoleProvider.GetRolesForUser, HttpContext.User.IsInRole, and RoleProvider.IsUserInRole.


Roles can also be controlled through WebSecurity à RequireRoles method; When user not in role, system generates a 401 and returning that error in an HttpResponse.

WebSecurity.RequireRoles(“Admin”, “OtherRole”);


Create custom role providers

Custom role providers might be needed when role information is coming from a non-standard database or data source.


Custom role providers can be created by extending the RoleProvider abstract class from System.Web.Security; RoleProvider abstract class inherits the ProviderBase abstract class from System.Configuration.Provider and therefore must implement the required members of ProviderBase class as well


System.Configuration.Provider.ProviderBase à System.Web.Security.RoleProvider à CustomRoleProvider


ProviderBase requires:

  • Initialize(name, NameValueCollection)
    • Sets up values and options from machine.config and web.config


RoleProvider requires:


A single RoleProvider is instantiated for all requests coming into the application; therefore the custom RoleProviders must be written to be thread-safe. Make sure there are no locking issues; don’t do database connections in the Initialize() method.


Role information stored in cookies should be encrypted, using the <machineKey> configuration element in the Machine.config. For web farms – ensure all servers have the same keys or ways to access the key to ensure it recognizes the roles.




Implement WCF service authorization

WCF – Windows Communication Foundation – requires authentication like everything else. Credentials must be passed in, whether it be the actual user’s credentials or a resource account – depending on what level of data access is needed. Note that authentication could be done against a client or a server – examples below:


ASP.NET MVC 5 Fundamentals (Pluralsight)

When using SQL server for the basic .Net membership provider, the following tables are created (if entity framework used, these are auto generated into corresponding entities)

  • AspNetRoles
  • AspNetUserClaims
  • AspNetUserLogins
  • AspNetUserRoles
  • AspNetUsers

The connectionString and provider information is found in the web.config


5.3 Design and implement claims-based authentication across federated identity stores

Federated security allows app to rely on another app/system (identity provider) to authenticate users; the provider forwards tokens to the app that contains claims.


Claims = information about the user, such as name, phone, etc


Implement federated authentication using Windows Azure Access Control Service (ACS)

ACS is a broker server that can go through Windows Live ID, Active Directory, Facebook, etc; ACS is not the identity provider but works with the providers to get whatever is needed from them. Basically – ACS is a STS (security token service) that builds, signs, and issues security tokens. ACS includes

  • Integration to WIF
  • Supports providers like Facebook, Microsoft, Yahoo, Google, etc
  • Supports Active Directory Federation Services (ADFS)
  • Supports OAuth, WS-Trust, WS-Federation
  • Supports various token formats like JWT (JSON Web Token), SAML (Security Assertion Markup Language) and SWT (Simple Web Token)
  • Provides web based management portal


Participants in ACS are:

  • RP; relying party – the MVC app
  • Client
  • Identity Provider
  • ACS

The Microsoft.Web.WebPages.OAuth abstracts the ACS process into two methods:

  • VerifyAuthentication (does steps 2 – 7 above)
  • Login



Windows Azure Authentication

See sample project


Create a custom security token by using Windows Indentity Foundation (WIF)

WIF is a framework for building identity-aware applications; abstracts the WS-Trust and WS-Federation protocols and provides APIs for building claims-aware systems. This is common for single-sign-on systems.


WS-Trust is a WS-* specification and OASIS standarad that provides extensions to WS-Security; WS-Federation is an extension to WS-Trust, it provides architecture for ensuring separation between the formats of the tokens and trust mechanisms; WS-Federation’s purpose is to provide common process for web clients and web services for identity operations.


WIF 4.5 has the following major features:

  • RP apps get claims model and API to access claims information
  • Identity delegation support, maintains identities across multiple boundaries
  • New identity and access tool for VS2012; can source from multiple IP (identity providers)


STS – security token service – builds, signs and issues security tokens according to the WS-Trust and WS-Federation protocols.


Claims sit higher than IIdentity and IPrincipal such that every principal class has a list of claims as one of it’s properties. The relationship is like so:

System.Security.Claims.ClaimsPrincipal (base)

  • Security.Principal
  • GenericPrincipal
  • Security.WindowsPrincipal
  • Web.Principal
  • RolePrincipal


Security tokens can be extended from SecurityTokens to create custom tokens. This occurs far less than having to create custom membership or role providers.





Handle token formats (OAuth, OpenID, LiveID, Facebook) for SAML and SWT tokens

SAML is XML based protocol that uses security tokens containing assertions or packets of information about the principal. Commonly used for single-sign-on, federated identity and web services security.


Asymmetric certificates are used to sign SAML tokens. This means clients cannot create their own tokens; also means that provider can do key rollover, revocation;. Allows token to be encrypted.


SWT (Simple Web Token) is another simpler object that unlike SAML is sign symmetric key. This is slowly being replaced by JWT where it uses JWS for signature (JSON Web Signature) and encryption with JWE (JSON Web Encryption).


WIF works with SAML security tokens through following handlers:





5.4 Manage data integrity

Managing the privacy, safety and integrity of data.

  • Encryption = transformation of readable text into illegible format that can be decoded only when appropriate key is provided to the system; a cipher algorithm is used for encryption (ciphertext);
  • Hashing = applying a formula to a string of text which produces a fixed length text that cannot be decrypted back into the original state; hashing identical texts results in identical hashes;
  • Salting = strengthening encryption or hash by adding a random string ot the original text; the salt value is only known to the system and therefore adds more randomness since decrypting to the original text is not enough
  • MD5 = popular hashing algorithim used before but problem is that two different texts can end up with same hash value; SHA (Secure Hash Algorithim) is the current and new hash algorithm, it has versions as it continues to evolve (SHA-0, SHA-3)
  • DES (Data Encryption Standard) = old symmetric-key algorithm that is no longer considered secure; replaced with AES (Advanced Encryption Standard)
  • Symmetric Encryption = using same key to encrypt and decrypt – useful when the enryptor and decryptor is the same.
  • Asymmetric Encryption = two different keys (public, private) for encypt / decrypt; uses RSA encryption algorithm (Rivest, Shamir, Adleman) which uses a product of two large prime numbers to do the encryption (plus a pseudorandom value) – these three values are what are used to decrypt later.
  • SSL (Secure Socket Layer) = uses asymmetric encryption


Apply encryption to application data

System.Security.Cryptography manages encryption/decryption; main base classes are AsymmetricAlgorithm and SymmetricALgorithm


Symmetric cryptopgraphy uses CryptoStream:


Asymmetric cryptography is done with RSACryptoServiceProvider


Both Symmetric/Asymmetric encryption follow these rules:

  • Use unique keys
  • Protect your keys
  • Ensure that keys are not with data
  • Configure keys to expire


Apply encryption to configuration sections of application

Two ways to encrypt in .NET Framework for configuration:

  • DPAPIProtectedConfigruationProvider – uses Windows Data Production API (DPAPI)
  • RsaProtectedConfigurationProvider – uses RSA encryption algorithm, should be used on server farms since the keys can be exported/imported


Use the aspnet_regiis.exe tool to encypt sections of web.config:

aspnet_regiis -pe “ConnectionStrings” -app “/MachineDPAPI” -prov “RsaProtectedConfigurationProvider”

-pe indicates which configuration section to encrypt, -app indicates the virtual path to the application that will be using the config file, and -prov is the name of the provider.


Also – ensure that the machineKey is present in the new web.config otherwise ASP.NET will not be able to decrypt it.


Decryption can be done with the same tool as follows:

aspnet_regiis -pd “ConnectionStrings” -app “/MachineDPAPI” -prov “RsaProtectedConfigurationProvider”


Sign application data to prevent tampering

Digital signature = is a mathematical scheme for demonstrating the authenticity of data;

Nonrepudiation = is ability to prove that authenticated party is the same party that took action


Application data can be signed to provide authenction, authorization and nonrepudiation. Ensures the communication between partners.


Digital signatures and encryption are both part of the AsymmetricAlgorithm class. Following shows the encypt/decypt processes:


5.5 Implement secure site with ASP.NET

Secure communications with SSL. Passwords should be encypted, hashed and salted.


Secure communication with SSL certificates

For SSL connections the web server requires an SSL certificate – public key cert – which usually comes from third-party source who is a Certificate Authority (CA). The browser downloads the public SSL cert (public key) and examines the expiration date and the CA that signed it. Browser will have internal list of trusted CA and if this key is trusted, it will proceed, otherwise prompt the user.


When requesting a cert, web server will put it’s public key in the CSR (Certificate Signing Request). It will also put its name and URL in the request, which is part of the public key. SSL is done through port 443 (HTTPS).


Within the app, SSL can be enforced (or checked) by the RequireHttps attribute. This can be done at controllers, actions, and the Global. Must register through GlobalFilters.


Salt and hash passwords

Hash = one way function of turning some text into a fixed-length encoded value that cannot be reversed back to the original text. There are 3 main ways to try breaking/cracking a hash:

  1. Brute-force attacks = using all possible combinations by trying random texts
  2. Dictionary attacks = uses a set of common passwords, phrases or other that scopes the attack
  3. Rainbow table attack = combination of brute-force and dicationary in that it takes a random set of text


To reduce vulnerabilities to attacks, adding a salt to the hash can greatly complicate the possibilities. A salt value should be at least as long as the output of the hashing function. Longer the salt, stronger the security.


Salts should be random values; one way to generate salt values is through CSPRNG Cryptographically Secure Pseudo-Random Number Generator.


Key-stretching = adds computational work to the hashing process (instead of just a salt). For example, PBKDF2 Password-Based Key Derivation Function 2 uses function Hash-based Message Autentication Code (HMAX) to be applied to the hash. It is applied more than once, perhaps 100 times, which makes it even more difficult to decipher.



HTML encoding to prevent cross-site scripting attacks (XS / AntiXSS library)

JS Injection attacks are when JS code is added to the query string or by finding a XSS scripting vulnerability. Example:


One way to prevent this in the view is by using Html helper classes like:

<% Html.Encode(review.Title) %>

This ensures text are encoded as HTML and not malicious code / scripts.


One the server side, this can also be done as follows (ensures text is encoded as HTML only)

public ActionResult Create(string message) {

var newEntry = new Entry();

newEntry.Message = Server.HtmlEncode(message);

newEntry.EntryDate = DateTime.Now;



return RedirectToAction(“Index”); }


Also available is the AntiXSS library. Available thorugh NuGet. Gains access to Microsoft.Security.Application.Encoder namespace and methods like HtmlAttributeEncode(). The AntiXSS library offers:

  • Increased Performance
  • Secure globalization = preventing attacks from different languages
  • Standards compliance
  • Encoding = HttpUtility.HtmlEncode,


AntiXSS takes an accepted-list approach where as .NET take blocked-list approach.


Implement deferred validation and handle unvalidated requests

Lazy request validation = Postpone validation until you are actually going to access and use the data; minimizes work done on server; JIT validation; this is by default in .NET 4.5


For older systems, or if trying to get the unvalidated data, this can be done through the HttpRequest. var s = context.Request.Unvalidated.Form[“some_value”];


Prevent SQL injection attacks

SQL injection is when SQL code is injected with query or elsewhere. To counter SQL attacks:

  • Always inspect data as it is being processed
  • Use type safe SQL parameters, example

SqlParameter param = adapter.SelectCommand.Parameters.Add(“@id”, SqlDbType.VarChar, 11);

Here the “@id” variable will be type checked before used and will throw exception if not in right format.


Another way is to use Entity Framer for Linq-to-Entities queuries.


  • Use restricted account when accesing database; or access via stored procedures only;
  • Do not bubble database errors to the user, this creates unnecessary exposure to database layer


Prevent cross-site request forgeries (XSRF) or Cross-Site reference forgery (CSRF)

XSRF / CSRF = hackers hitting specific url actions, can be done directly or indirectly through JS or HTML; example:



Can be blocked by using Antiforgery token; AntiForgeryToken method is an attribute on the action method:

This creates a hidden field and cookie with a server known token value. The the request doesn’t have this token, the server knows the request was not proper. The value is an RNG cryptography method of 128 bit string.

Authentication cookie (like from Forms Auth) is sent with every requrest from client to server, and these could be picked up by XSRF attacks. Malicious sites mimic target sites and stand in the way of the victim.

HTTP/1.1 200 OK
Date: Mon, 18 Jun 2012 21:22:33 GMT
X-AspNet-Version: 4.0.30319
Set-Cookie: .ASPXAUTH={authentication-token}; path=/; secure; HttpOnly;
{ Cache-Control, Content-Type, Location, Server and other keys/values not listed. }


Since this cookie is now saved by the browser, it will auto send it for any requests to the target site. If user is on another site that maliciously posts to the target site again with assumption that the auth-token is still there, the usr could be exposed. Such tokens need to be removed when the user leaves the site.


ASP.NET will auto synchronize session tokens to ensure users are coming in through the current session only. If the tokens don’t match, ASP.NET will not process the request. The AntiForgeryToken is another example of this.



Other Readings

Introduction to ASP.NET Identity


Originally in 2005 era apps used ASP.NET Membership – which stored user data in SQL databases. Today, this is uncommon as users usually login through other identity providers such as MSN, Facebook, Active Directory, etc. Membership did not support OWIN – which includes middleware to authenticate these other accounts supporting OAuth, JWT and CORS (Cross Origin Resource Sharing).


ASP.NET Simple Membership was 2010 release to help allow Membership use with these other identity providers, and it allows OWIN. Can work with existing ASP.NET Membership providers.


ASP.NET Universal Providers was developed to make Membership work with Azure SQL Database. This uses Entity Framework Code First – and still on top of Membership, though the databases were largely cleaned up.


ASP.NET Identity API has evolved to handle many different scenarios, old and new. It has the following capabilities:

  • One ASP.NET Identity system – can be used with all ASP.NET frameworks (MVC, web forms, web api, signalR, etc)
  • Ease of plugging in profile data about user
  • Persistence Control – still has SQL database access to store various user info
  • Role Provider – has been available since original Membership
  • Claims Based – supports claims
  • Social Login Providers
  • Azure Active Directory
  • OWIN integration
  • NuGet package





Easy Web App Integration with Azure


Setup an MVC app on Azure using OAuth to enable third-party authentication. The app would redirect to FB/Google/etc to let the identity provider do the user login / authentication – a token is then provided back to the app the app would trust from the provider.


External authentication is configured through AuthConfig.cs for MVC4 and in MVC5 it is in the StartupAuth.cs





C# Inheritance Overview

  • Derive classes vs implement classes
  • base keyword (Java = super)

Base classes are always left most class in class definition, all classes thereafter are implements

public class ColorCoOrds : CoOrds, ImplementClassA, ImplementClassB

  • Selecting Constructors
  • Overriding (virtual methods)

Can only override methods where in base it is marked virtual – cannot override in derive class base methods that are not virtual or base methods that are static

  • Abstract Methods

Contains zero implementation – must be implemented in derived class using override keyword

  • Abstract Classes

Can have partial implementations that needs to be implemented in derived classes (some methods may be abstract while others are not) à contains at least 1 abstract method; cannot be instantiated directly

  • Interfaces

Skeleton classes where everything is abstract – thereby everything must be implemented. Derived class does not need to use override keyword. Interfaces cannot have contsants or private data members, no constructors/destructors and no static members



Configuration Settings (machine.config & web.config)

Configuration involves everything from application settings such as database connections to security details and information about how errors should be handled. Files are XML based and two types:

  • config = (optional) specific to single app
  • config = (required) for all .NET apps to specific version


ASP.NET configurations are contained in <system.web> under <configuration>



The .NET Framework configuration functionality is fully extendable. There are two ways in which you can extend configuration:

  • Create a custom configuration section handler.
    For additional information about how to create custom ASP.NET configuration section handlers, click the article number below to view the article in the Microsoft Knowledge Base:

309045 HOW TO: Create a Custom ASP.NET Configuration Section Handler in Visual C# .NET

  • Use the<appSettings> section to store application specific data. For information on the syntax of the <appSettings> section, refer to the following topic in the .NET Framework SDK documentation:


To retrieve values from the <appSettings> section, use the following code in the .config file:

<add key=”MySetting” value=”Valuable Information” />
Then use the following code to retrieve the value:
NOTE: You must include the System.Configuration namespace to access appSettings.
Label1.Text = ConfigurationSettings.AppSettings[“MySetting”];




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s