Sie sind auf Seite 1von 433

MCSD: SharePoint Applications

Para lograr la Certificación de Microsoft Certified Solutions Developer


(MCSD): la certificación de Aplicaciones de SharePoint debe tener una base
sólida de habilidades de programación web utilizando HTML5 con JavaScript
y ASP.NET MVC

Course 20480B - Programming in HTML5 with JavaScript and CSS3

Course 20486B - Developing ASP.NET MVC 4 Web Applications

Course 20488B - Developing Microsoft SharePoint® Server 2013 Core


Solutions

Course 20489B - Developing Microsoft® SharePoint® Server 2013


Advanced Solutions

Module 01: Exploring ASP.NET MVC 4

Module Overview
Microsoft ASP.NET MVC 4 y las otras tecnologías web del Framework .NET permite
crear y alojar aplicaciones web dinámicas, potentes, y extensibles. ASP.NET MVC 4
es compatible con el desarrollo ágil, basado en pruebas y los últimos estándares web
como HTML 5. Para crear aplicaciones web sólidas, es necesario estar familiarizado
con las tecnologías y productos de la pila web de Microsoft. También necesita saber
cómo funcionan las aplicaciones ASP.NET con IIS, Visual Studio, SQL Server,
Windows Azure, y base de datos SQL de Windows Azure para entregar páginas web
de acoplamiento a los visitantes del sitio. Para elegir un lenguaje de programación que
más se ajuste a un conjunto de requisitos de negocio, lo que necesita saber cómo
Modelo-Vista-Controlador (MVC) aplicaciones difieren de los otros modelos de
programación ASP.NET: Páginas Web y Web Forms.
La aplicación web que va a diseñar y desarrollar en los laboratorios de todo este curso
le ayudará a desarrollar aplicaciones web que cumplan con las necesidades del
negocio.

Objectives

Después de completar este módulo, el alumno será capaz de:

Describir el papel de ASP.NET en la pila de tecnologías web, y cómo utilizar


o
ASP.NET para crear aplicaciones web.
Describir los tres modelos de programación disponibles en ASP.NET: páginas web,
o formularios Web y MVC y seleccionar un modelo apropiado para un proyecto
determinado.
o Distinguir entre un modelo MVC, en MVC controlador, y una vista MVC.

Lesson 1 : Overview of Microsoft Web


Technologies
Antes de utilizar ASP.NET MVC 4, lo que necesita saber donde Microsoft ASP.NET
4.5 encaja en el contexto de toda la pila de tecnologías web de Microsoft. Usted debe
saber cómo en ASP.NET 4.5 estan alojados los sitios web en Internet Information
Server 8 (IIS) y Windows Azure, y cómo se ejecutan código de servidor en los
servidores web, y el código del lado del cliente en los navegadores web, para ayudar a
proporcionar un enriquecido y convincente contenido.

Lesson Objectives
Después de completar esta lección, usted será capaz de:

o Proporcionar una visión general de las tecnologías web de Microsoft


o Proporcionar una visión general de ASP.NET 4.5.
Proporcionar una visión general de las tecnologías web del lado del cliente, incluidas
o
las bibliotecas AJAX y JavaScript.
o Describir la función de IIS en la pila de tecnologías web de Microsoft.
o Describir la función de Windows Azure en la pila tecnologías web de Microsoft

Introduction to Microsoft Web Technologies


Microsoft ofrece una amplia gama de tecnologías que se pueden utilizar para crear
aplicaciones web ricas y publicarlos en intranets y en Internet. Además de publicar
aplicaciones web, puede utilizar estas tecnologías para desarrollar y alojar sitios web,
que se ejecutan código tanto en el servidor web y el navegador web del usuario.
.Developer Tools

Puede crear sitios web simples con texto e imágenes usando un editor de texto, como
el Bloc de notas.

Sin embargo, la mayoría de los sitios web requieren acciones complejas que se
realizarán en el lado del servidor, tales como operaciones de bases de datos, entrega
de correo electrónico, cálculos complejos, o de procesamiento de gráficos. Para crear
este tipo de sitios web complejos, altamente funcionales, y atractivas forma rápida y
sencilla, Microsoft ofrece las siguientes herramientas:

WebMatrix 2. Puede utilizar WebMatrix 2 para crear páginas HTML estáticas y


páginas dinámicas con ASP.NET, PHP, y Node.js. WebMatrix 2 es una herramienta
de desarrollo libre que se puede instalar mediante la descarga y el uso de la
Microsoft Web Platform Installer (Web PI) del sitio web de Microsoft. WebMatrix 2 le
o
permite desarrollar sitios web personalizados basados en aplicaciones web como el
Orchard, Umbraco CMS, y WordPress. El uso de WebMatrix 2, puede crear
aplicaciones ASP.NET páginas web, pero no ASP.NET Web Forms o aplicaciones
MVC.
Microsoft Visual Studio 2012. Puede utilizar Visual Studio 2012, un entorno de
desarrollo integrado (IDE), para crear aplicaciones personalizadas basadas en las
o tecnologías de Microsoft, independientemente de que estas aplicaciones se ejecutan
en la web, en los escritorios, en los dispositivos móviles, o mediante el uso de
servicios en la nube de Microsoft. Visual Studio 2012 cuenta con instalaciones ricos
para el diseño, codificación, depuración y cualquier aplicación web ASP.NET,
incluyendo aplicaciones MVC.
Microsoft Visual Studio Express 2012 para Web. Puede utilizar Visual Studio Express
2012 para Web para crear formularios web o aplicaciones web MVC. Esta es una
o herramienta gratuita que no incluye todas las características de Visual Studio 2012
ediciones. Sin embargo, se puede utilizar para crear sitios web completamente
funcionales MVC.

Hosting Technologies

Independientemente de la herramienta que se utiliza para construir una aplicación


web, debe utilizar un servidor web para alojar la aplicación web. Cuando los usuarios
visitan su sitio, el servidor host responde mediante la representación en HTML y
devolverla al navegador del usuario para su visualización. El centro de servicios puede
consultar una base de datos antes de que se construye el HTML, y el servidor host
puede realizar otras acciones como el envío de mensajes de correo electrónico o
guardar los archivos subidos. Es necesario para probar la funcionalidad de tales
acciones del usuario en un servidor web. Cuando se construye una aplicación web
utilizando Visual Studio 2012, puede utilizar Visual Studio Development Server, el
servidor web integrado para ejecutar la aplicación. Sin embargo, Visual Development
Server no puede albergar implementado aplicaciones web. Por lo tanto, cuando se
termine de construir la aplicación web y que quede listo para que los usuarios accedan
en una intranet oa través de Internet, debe utilizar un servidor web completamente
funcional, tales como:

Microsoft Internet Information Server 8. IIS es un alojamiento de sitios web de


tecnología avanzada. Puede instalar los servidores IIS en la red o el perímetro de la
red local, o emplear los servidores IIS alojados por un proveedor de servicios de
o Internet (ISP). IIS puede albergar cualquier sitio web ASP.NET, PHP, o Node.js.
Puede ampliar IIS para alojar sitios web grandes y ocupados mediante la
configuración de granjas de servidores que contienen múltiples servidores IIS, todos
los que tengan el mismo contenido.
Windows Azure. Windows Azure es una plataforma en la nube que ofrece servicios a
la carta para construir, desplegar, el host y administrar aplicaciones web a través de
o
los centros de datos gestionados por Microsoft. Cuando utiliza los servicios de
Windows Azure, tiene que pagar sólo por los datos que sirve a su sitio web. Además,
no necesita preocuparse por la construcción de una infraestructura escalable, ya que
Windows Azure añade automáticamente los recursos como su sitio web crece.

Note: Hay muchas otras tecnologías no son de Microsoft que puede utilizar
para alojar sitios web. El más popular, por ejemplo, es Apache. Apache se
ejecuta con mayor frecuencia en servidores Linux y que a menudo se
empareja con MySQL para gestionar bases de datos y PHP como un
framework de desarrollo web basado en servidor. Esta configuración se
refiere a menudo como la pila web Linux Apache MySQL PHP (LAMP) .

Note: Windows Azure y IIS pueden alojar sitios web escritas en ASP.NET,
PHP, o Node.js. servidores web Apache se pueden utilizar para alojar una
serie de tecnologías web del lado del servidor, incluyendo PHP, Node.js, y
Python, pero los servidores web Apache no se pueden utilizar para alojar
sitios web ASP.NET.
La mayoría de los sitios web requieren una base de datos para gestionar datos tales
como los detalles del producto, la información del usuario, y temas de discusión. Se
puede elegir entre las siguientes tecnologías de Microsoft para gestionar sus datos:

Microsoft SQL Server 2012. SQL Server 2012 es un servidor de base de datos de
alta calidad que se puede utilizar para alojar cualquier base de datos desde la más
sencilla hasta la más compleja. SQL Server se puede ampliar hasta apoyar a
o
grandes bases de datos y un gran número de usuarios. Se pueden construir grandes
cluster de SQL Server para garantizar la mejor disponibilidad y fiabilidad. Muchas de
las organizaciones más grandes del mundo confían en SQL Server para alojar datos.
Base de datos SQL de Windows Azure. Base de datos SQL es una plataforma de
base de datos en la nube y una parte de Windows Azure. El uso de bases de datos
SQL, se puede implementar la base de datos y pagar sólo por los datos que se
o
utiliza. Usted no necesita preocuparse por la gestión de su infraestructura de base de
datos porque la base de datos se amplía hasta automáticamente a medida que crece
su sitio web. .

Microsoft ofrece una amplia gama de tecnologías que se pueden utilizar para crear
aplicaciones web ricas y publicarlos en intranets y en Internet. Además de publicar
aplicaciones web, puede utilizar estas tecnologías para desarrollar y alojar sitios web,
que se ejecutan código tanto en el servidor web y el navegador web del usuario.
Code Execution Technologies

El código que se escribe en una herramienta de desarrollo debe ejecutarse en uno de


dos lugares:

En el servidor web. Este código tiene acceso completo a la potencia del servidor web
o y las bases de datos que se le atribuye. Se puede acceder a la base de datos de
forma rápida, enviar mensajes de correo electrónico, y hacer que las páginas web.
En el navegador web del usuario. Este código responde rápidamente a las acciones
o del usuario, tales como clics del ratón, pero es más limitado en lo que puede lograr
sin interactuar con el servidor web.

Es necesario utilizar diferentes tecnologías para ejecutar código del lado del servidor y
el código del lado del cliente.

Server-Side Execution
Microsoft ASP.NET 4.5 es un entorno web del lado del servidor que ejecuta código
.NET de servidor que se escribe en Visual Studio 2012 o WebMatrix 2. El código de
acceso a la base de datos, hace que las páginas HTML, y los devuelve al navegador
web. El modelo de programación MVC es una parte de ASP.NET 4.5. Otras
tecnologías del lado del servidor incluyen PHP y Node.js.

Client-Side Execution

La mayoría de los navegadores web pueden ejecutar código escrito en el lenguaje


JavaScript. Este código es enviado al navegador como texto dentro de una página
HTML representado o en un archivo .js aparte. Debido a que JavaScript es local en el
navegador, que puede responder muy rápidamente a las acciones del usuario, como
hacer clic, apuntando, o arrastrando.

Muchas librerías JavaScript están disponibles para acelerar el desarrollo de códigos


del cliente. Por ejemplo, la popular librería jQuery hace que sea sencillo para acceder
a los elementos de página y manipularlos al cambiar su estilo o contenido. Cuando se
utiliza este tipo de bibliotecas, puede escribir funciones en unas líneas que de otro
modo requerirían cientos de líneas de su propio código JavaScript.

Las aplicaciones ASP.NET también pueden utilizar la tecnología (AJAX) Asynchronous


JavaScript y XML en el equipo cliente. Puede utilizar AJAX para actualizar una
pequeña sección de una página HTML, en lugar de recargar toda la página desde el
servidor. Tales actualizaciones de la página parciales ayudan a hacer páginas web
más sensible y atractivo.

Question: Si desea animar un elemento de página, por ejemplo, el desvanecimiento


en este, le escribe el código del lado del servidor o del lado del cliente?

Puede utilizar ASP.NET 4.5 para desarrollar sitios web dinámicos con bases de datos,
muy funcionales y escalables que utilizan código del lado del cliente y del lado del
servidor.

Se pueden crear muchos tipos de sitio web con ASP.NET 4.5, por ejemplo, portales de
Internet, sitios de compras en línea, blogs y wikis.

Esta separación del modelo, ver y código del controlador asegura que las aplicaciones
MVC tienen una estructura lógica, incluso para los sitios más complejos. También
mejora la capacidad de prueba de la aplicación. En última instancia, ASP.NET MVC
permite un mayor control sobre el código HTML generado que cualquiera de las
páginas web o Web Forms.
The ASP.NET API

Sea cual sea el modelo de programación que elija, usted tiene acceso a las clases de
la API de ASP.NET. Estas clases están incluidas en el .NET Framework en espacios
de nombres dentro del espacio de nombres System.Web y se pueden utilizar para
implementar rápidamente las funcionalidades del sitio web comunes, tales como:

Configuración. El uso de archivos Web.config, puede configurar la aplicación web,


con independencia del modelo de programación. archivos Web.config son archivos
XML con etiquetas específicas y atributos que el tiempo de ejecución de ASP.NET
o
4.5 acepta. Por ejemplo, puede configurar las conexiones de bases de datos y
páginas de error personalizados en el archivo Web.config. En el código, puede
acceder a la configuración a través del System.Web.Configuration namespace
Autenticacion y autorizacion. Muchos sitios web requieren que los usuarios iniciar
sesión introduciendo un nombre de usuario y contraseña, o proporcionando
información adicional. Puede utilizar los proveedores de pertenencia de ASP.NET
para autenticar y autorizar a los usuarios, y restringir el acceso a contenido. También
o
es posible construir páginas que permiten a los usuarios registrar una nueva cuenta,
restablecer una contraseña, recuperar una contraseña perdida, o realizar otras
tareas de gestión de cuentas. proveedores de pertenencia pertenecen al
System.Web.Security namespace.
El almacenamiento en caché. ASP.NET puede tomar algún tiempo para hacer una
página web complejo que puede requerir varias consultas de bases de datos o
llamadas a servicios web externos. Puede utilizar el almacenamiento en caché para
mitigar este retraso. ASP.NET almacena en caché una página representada en la
memoria, de modo que pueda volver a la misma página de peticiones de los usuarios
o posteriores sin tener que hacer de nuevo desde el principio. De manera similar, los
objetos de .NET Framework también pueden almacenar en caché. Se puede acceder
a las páginas en caché mediante el namespace System.Runtime.Caching y
configurar las memorias caché en Web.config

Compiling ASP.NET Code

Debido a que el código de servidor ASP.NET utiliza el .NET Framework, debe escribir
código en un lenguaje de programación .NET administrado como C # o Visual Basic.
Antes de ejecutar el código, debe ser compilado en código nativo de modo que la CPU
del servidor puede procesarlo. Este es un proceso de dos etapas:

Compilación a MSIL. Cuando se construye un sitio web en Visual Studio, el


compilador de ASP.NET crea archivos .dll con todo el código compilado en lenguaje
1.
intermedio de Microsoft (MSIL). Este código es a la vez independiente del lenguaje
que utilizó para escribir la aplicación y la arquitectura de CPU del servidor.
La compilación a código nativo. Cuando se solicita una página por primera vez, el
2. Common Language Runtime (CLR) compila MSIL en código nativo para la CPU del
servidor.

Este proceso de compilación de dos etapas permite que los componentes escritos en
diferentes idiomas para trabajar juntos y permite a muchos errores que se detecten en
tiempo de compilación. Tenga en cuenta, sin embargo, que las páginas pueden tomar
más tiempo para hacer la primera vez que se solicitan después de un reinicio del
servidor. Para evitar este retraso, puede pre-compilar el sitio web.

Cuando se utiliza el modelo de compilación por defecto, los retrasos pueden surgir
cuando el primer usuario solicita una página. Esto se debe a que ASP.NET debe
compilar la página antes de servir al navegador. Para evitar este tipo de retrasos y
para proteger el código fuente, el uso de pre-compilación. Cuando se pre-compila un
sitio, todos los archivos de ASP.NET, incluyendo controladores, vistas y modelos, se
compilan en un único archivo .dll.

Question: ¿Cuál de los tres modelos de programación le parece proporciona el


máximo control sobre el código HTML y JavaScript que se envía al navegador?

Client-Side Web Technologies


Originalmente, en ASP.NET y tecnologías similares como PHP, todo el código
corriendo en el servidor web. Este enfoque es a menudo práctico porque el
servidor web por lo general tiene acceso inmediato a la base de datos y más
potencia de procesador y la memoria de un ordenador cliente típico. Sin
embargo, en este enfoque, cada acción del usuario requiere un viaje de ida y
vuelta entre el cliente y el servidor web, y la mayoría de las acciones requieren
una recarga completa de la página. Esto puede tomar un tiempo considerable.
Para responder con rapidez y proporcionar una mejor experiencia de usuario,
puede complementar código del lado del servidor con código de cliente que se
ejecuta en el navegador web.

JavaScript
JavaScript es un lenguaje de programación simple que tiene una sintaxis similar a C #,
y es apoyado por la mayoría de los navegadores web. Un lenguaje de script no se
compila. En su lugar, un motor de secuencia de comandos interpreta el código en
tiempo de ejecución para que el navegador web puede ejecutar el código.

Note: Además de JavaScript, VBScript es compatible con Internet Explorer.


Hay también otros lenguajes de script, pero JavaScript con el apoyo de
prácticamente todos los navegadores web. Esto no es cierto para cualquier
otro lenguaje de programación. A menos que su público objetivo es muy
limitada y tiene control sobre el navegador utilizado por sus usuarios, se
debe utilizar JavaScript debido a su apoyo casi universal
Usted puede incluir código JavaScript en las páginas ASP.NET, con independencia del
modelo de programación que elija. JavaScript es un lenguaje de gran alcance, pero
puede requerir muchas líneas de código para lograr efectos visuales o llame a
servicios externos. bibliotecas de scripts contienen funciones de pre-construidos de
JavaScript que ayudan a poner en marcha acciones comunes que usted puede desear
llevar a cabo en el código del lado del cliente. Se puede utilizar una biblioteca de
scripts, en lugar de construir todo su propio código JavaScript desde el principio;
utilizando una biblioteca de scripts ayuda a reducir el tiempo y esfuerzo de desarrollo.

Los diferentes navegadores interpretan de manera diferente JavaScript. Al desarrollar


un sitio de Internet, usted no sabe lo que los navegadores utilizan los visitantes del
sitio. Por lo tanto, se debe escribir código JavaScript que funciona en torno a la
compatibilidad del navegador.

jQuery

jQuery es una de las bibliotecas más populares de JavaScript. Proporciona funciones


elegantes para interactuar con los elementos HTML en su página y con hojas de estilo
en cascada (CSS) estilos. Por ejemplo, puede localizar todos los elementos <div> en
una página web y cambiar su color de fondo usando una sola línea de código. Para
lograr el mismo resultado mediante el uso de JavaScript sólo tiene que escribir varias
líneas de código y un bucle de programación. Por otra parte, el código que escriba
puede ser diferente para diferentes navegadores. Usando jQuery, es más fácil escribir
código para responder a las acciones del usuario y crear animaciones simples. jQuery
también se ocupa de las diferencias navegador. Puede utilizar jQuery para llamar a
servicios web en equipos remotos y actualizar la página web con los resultados
devueltos.

El proyecto jQuery también incluye otras dos librerías JavaScript que se extienden a la
biblioteca jQuery base de:
jQuery UI. Esta biblioteca incluye un conjunto de widgets que se pueden utilizar para
ayudar a construir una interfaz de usuario. Hay selectores de fecha, hiladores,
o cuadros de diálogo, cuadros de texto de autocompletar, y otros widgets. También
puede aplicar temas a sus widgets jQuery UI para integrar sus colores y estilos con
el sitio web de la marca.
jQuery Mobile. Esta biblioteca hace que sea fácil para proporcionar una interfaz de
usuario para dispositivos móviles como teléfonos y tabletas. Se representa HTML
mediante el uso de una mejora progresiva. Por ejemplo, el uso de jQuery Mobile,
o puede mostrar ricos, controles avanzados en dispositivos móviles avanzados como
los teléfonos inteligentes con pantallas de gran tamaño, mientras que se puede
visualizar una interfaz de usuario más simple con la misma funcionalidad para más
viejos dispositivos móviles con pantallas más pequeñas.

Note: Hay muchas otras librerías JavaScript como Prototype, Enyo, Ext y Dojo
Toolkit. Si encuentra alguno de estos más adecuado para una tarea en
particular, o si usted tiene experiencia en el desarrollo de aplicaciones web
mediante el uso de ellos, puede incluirlos en sus páginas ASP.NET, en lugar
de jQuery.

jQuery.

AJAX

AJAX es una tecnología que permite a los navegadores para comunicarse con
los servidores web de forma asincrónica utilizando el objeto XmlHttpRequest
sin actualizar la página por completo. Puede utilizar AJAX en una página para
actualizar una parte de la página con los nuevos datos, sin necesidad de
recargar la página entera. Por ejemplo, puede utilizar AJAX para obtener los
últimos comentarios realizados en un producto, sin actualizar toda la página del
producto.

AJAX es una abreviatura de JavaScript asíncrono y XML. AJAX se implementa


completamente en JavaScript y ASP.NET 4.5, de forma predeterminada, se
basa en la librería jQuery para gestionar las solicitudes y respuestas AJAX. El
código se ejecuta de forma asíncrona, lo que significa que el navegador web no
se congela mientras espera una respuesta desde el servidor AJAX.
Inicialmente, los desarrolladores utilizan XML para dar formato a los datos
devueltos por el servidor. Más recientemente, sin embargo, los desarrolladores
utilizan JavaScript Object Notation (JSON) como un formato alternativo a XML.

Question: ¿Se puede pensar en los problemas que puedan surgir si se incluye
la biblioteca jQuery con cada página de la aplicación?

Internet Information Server 8.0

Cada sitio web debe estar alojado en un servidor web. Un servidor web recibe
solicitudes de contenido Web desde navegadores, se ejecuta ningún código del
lado del servidor, y devuelve páginas web, imágenes y otros contenidos.
HTTP se utiliza para la comunicación entre el navegador y el servidor web.

Internet Information Server 8.0 es un servidor web que puede escalar desde un
pequeño sitio web que se ejecutan en un único servidor web a un gran sitio
web que se ejecuta en un varias granjas de servidores web. Internet
Information Server 8.0 está disponible con Windows Server 2012.

Internet Information Server 8.0 Features

Internet Information Server 8.0 está estrechamente integrado con ASP.NET


4.5, Visual Studio 2012 y Windows Server 2012. Incluye las siguientes
características:
Protocolos de despliegue. Implementar el protocolo Web avanzada, que está
integrado en Visual Studio 2012, gestiona automáticamente el despliegue de
o una página web con todas sus dependencias. Alternativamente, se puede
utilizar el protocolo de transferencia de archivos (FTP) para implementar el
contenido.
Gestión centralizada Granja Web. Cuando se ejecuta un sitio web grande,
puede configurar una granja con balanceo de carga de muchos servidores de
o IIS escalar a grandes tamaños. herramientas de administración de IIS que sea
fácil de desplegar sitios a todos los servidores de la comunidad y administrar
sitios después del despliegue.
Caché de alto rendimiento. Puede configurar ASP.NET para hacer un uso
óptimo del caché de IIS para acelerar las respuestas a las solicitudes de los
o usuarios. Cuando IIS sirve una página o de otros contenidos, se puede
almacenar en caché en la memoria para que las peticiones idénticas
posteriores se pueden servir más rápido.
Autenticación y seguridad. IIS admite los estándares más comunes para la
autenticación, incluyendo la autenticación de tarjeta inteligente y la
autenticación integrada de Windows. También puede utilizar Secure Sockets
o
Layer (SSL) para cifrar las comunicaciones sensibles a la seguridad, como
las páginas de inicio de sesión y las páginas que contienen números de
tarjetas de crédito.
ASP.NET Support. IIS es el único servidor web que es totalmente compatible
o
con ASP.NET.
Otras tecnologías del lado del servidor. Puede alojar sitios web
o
desarrollados en PHP y Node.js en IIS.

Scaling Up IIS

Un solo servidor web tiene escalabilidad limitada, ya que está limitada por la
velocidad del procesador, la memoria, la velocidad del disco, y otros factores.
Por otra parte, los servidores web individuales son vulnerables a fallos de
hardware y cortes. Por ejemplo, cuando un solo servidor web está en línea, su
sitio web no está disponible para los usuarios.

Puede mejorar la escalabilidad y la flexibilidad de su sitio web por lo aloja en


una granja de varios servidores. En este tipo de granjas de servidores, muchos
servidores comparten el mismo nombre de servidor. Por lo tanto, todos los
servidores pueden responder a las peticiones del navegador. Un sistema de
balanceo de carga como s Windows Network Load Balancing o un sistema
basado en hardware como Riverbed Cascade, distribuye las solicitudes de
manera uniforme entre los servidores de la granja de servidores. Si falla un
servidor, otros servidores están disponibles para responder a las solicitudes, y
por lo tanto, la disponibilidad de la página no se interrumpe. servidores IIS
están diseñados para trabajar en este tipo de granjas de servidores e incluyen
herramientas avanzadas de gestión para la implementación de la gestión de los
sitios y servidores miembro.

Perimeter Networks

Los servidores web IIS, entre ellos, a menudo se encuentran en una red
perimetral. Una red perimetral tiene un segmento de red que está protegida de
Internet a través de un servidor de seguridad que valida y permite realizar
peticiones HTTP entrantes. Un segundo servidor de seguridad, que permite las
solicitudes sólo desde el servidor web, separa la red perimetral de la red
interna de la organización. servidores de apoyo, tales como servidores de
bases de datos, por lo general se encuentran en la red interna de la
organización.

En esta configuración, los usuarios de Internet pueden acceder al servidor IIS


para páginas de solicitud y el servidor IIS pueden llegar al servidor de base
para ejecutar consultas. Sin embargo, los usuarios de Internet no pueden
acceder al servidor de base de datos o cualquier otra computadora interna
directamente. Esto evita que usuarios malintencionados ejecuten ataques y
garantiza un alto nivel de seguridad.

IIS Express
Internet Information Server 8.0 Express no proporciona todas las
características de Internet Information Server 8.0 en Windows Server 2012.
Por ejemplo, no se puede crear granjas de servidores con equilibrio de carga
mediante el uso de Internet Information Server 8.0 Express. Sin embargo,
tiene todas las características necesarias para albergar ricos ASP.NET 4.5
sitios web y otros sitios web en un único servidor. Internet Information Server
8.0 Express se incluye con Windows 8. También se puede instalar en
Windows Server 2012, Windows Server 2008, Windows 7 y Windows Vista
SP1 y después por descargar y utilizar el Instalador de plataforma web (Web
PI).

Other Web Servers


Apache es un servidor web popular no es de Microsoft y hay otras
alternativas, como Nginx. Apache se puede instalar en equipos con Windows
server o cliente de Windows para alojar sitios web durante el desarrollo o para
despliegues de producción. Sin embargo, Apache no puede alojar sitios web
ASP.NET.

Visual Studio Development Server

Visual Studio 2012 incluye un servidor web integrado, Visual Studio


Development Server. Cuando se abre una página web en modo de depuración,
Visual Studio Development Server se inicia y se aloja su sitio. Si cierra el
navegador o detiene la depuración, Visual Studio Development Server se
detiene automáticamente. Visual Studio Development Server no puede alojar
sitios para la producción y no proporciona toda la funcionalidad disponible en
Internet Information Server 8.0 Express. Por ejemplo, no se puede configurar
el cifrado SSL en Visual Studio Development Server.

Question Si quería alojar un sitio ASP.NET que había escrito para la prueba
sencilla por un pequeño equipo de desarrolladores, ¿cuál de los servidores
web precedentes usaría como anfitrión?

Windows Azure
Windows Azure es una parte de los servicios de nube de Microsoft para alojar
los sistemas críticos de negocio.

Cuando se ejecuta el código en Windows Azure, el código se ejecuta en los


servidores en Data Center administrados por Microsoft en diversos lugares del
mundo. Tiene dos ventajas principales al usar Windows Azure para albergar y
desplegar la aplicación web:

Escalado flexible: A medida que las necesidades de su aplicación web y base


de datos crecen, los recursos del servidor adicionales se asignan
o automáticamente. No es necesario planificar para granjas de servidores o
sistemas de balanceo de carga, porque éstos están integrados en Windows
Azure.
Precios flexibles: Con Windows Azure, se puede elegir un modelo de
precios de pago por you-go, lo que significa que usted sólo paga por los
o datos que se utiliza. Esto hace que Windows Azure muy rentable para los
sitios web pequeños. También hace que los costes previsibles para grandes
sitios web.

Puede usar Windows Azure para albergar la siguiente:


Sitios web. Puede alojar un sitio web completo en Windows Azure.
Windows Azure es compatible con los sitios web desarrollados en
o
ASP.NET, PHP, o Node.js. También puede implementar sitios web a
Windows Azure directamente desde Visual Studio 2012 o WebMatrix 2.
Web services. A web service no incluye una interfaz de usuario como una
página web. En su lugar, se compone de un conjunto de métodos que se
o pueden llamar, de otro software. Puede llamar a servicios web desde
dispositivos móviles, aplicaciones de escritorio y de código del sitio web que
se ejecuta en el lado del cliente o en el lado del servidor.
Databases. Cuando utiliza Internet Information Server 8.0 para alojar un
sitio web, puede utilizar SQL Server para almacenar la base de datos web.
o Cuando aloja un sitio web en Windows Azure, puede utilizar base de datos
SQL, que es un servicio de base de datos basada en la nube basado en SQL
Server, para alojar su base de datos.
Virtual servers. Puede provisionar de servidores virtuales enteras en
Windows Azure para ejecutar el software de back office crítica para el
o negocio o el uso de los servidores virtuales como entornos de prueba. Los
servidores virtuales en Windows Azure pueden ejecutar Windows Server o
Linux.
Mobile services. Si desarrolla aplicaciones para dispositivos móviles, tales
como teléfonos y tabletas, puede usar Windows Azure para albergar los
o servicios que las sustentan. Tales servicios pueden proporcionar
almacenamiento de preferencias de usuario, almacenamiento de datos y otras
funciones.
Media services. Cuando se utiliza Windows Azure para albergar medios
tales como audio y video, que está disponible automáticamente para muchos
o
tipos de dispositivos, como ordenadores, teléfonos móviles y tabletas, y se
codifica en varios formatos, tales como MP4 y formatos de Windows Media.

Question: ¿Cómo saben los visitantes del sitio si su sitio está alojado en
Windows Azure o servidor IIS?

Lesson 2: Overview of ASP.NET 4.5


ASP.NET 4.5 le ayuda a crear sitios web dinámicos que utilizan código del
lado del cliente y del lado del servidor. Además, con ASP.NET 4.5, usted no
está limitado a un solo estilo de programación; En su lugar, se puede elegir
entre tres diferentes modelos de programación: páginas web, formularios Web
y MVC. Estos modelos de programación diferentes unos de otros, y tienen sus
propias ventajas y desventajas en diferentes escenarios. ASP.NET también
proporciona muchas características que se pueden utilizar,
independientemente del modelo de programación que elija.

Lesson Objectives
Después de completar esta lección, usted será capaz de:

o Describe the Web Pages programming model.


o Describe the Web Forms programming model.
o Describe the MVC programming model.
Determinar si se debe construir páginas web, formularios web o aplicaciones
o
web MVC, basado en las necesidades del cliente.
Describir las características que se pueden utilizar en todas las aplicaciones
o
ASP.NET, independientemente del modelo de programación elegido.

Web Pages Applications

Páginas Web es el modelo de programación sencillo que se puede optar por


construir una aplicación web en ASP.NET. Puede utilizar páginas Web para
crear un sitio web de forma rápida y con pocos conocimientos técnicos. No es
un archivo único asociado a cada página web que los usuarios pueden
solicitar. Para cada página, se escribe HTML, el código del lado del cliente, y
el código del lado del servidor en el mismo archivo .cshtml. El símbolo @ se
utiliza para distinguir el código del lado del servidor de HTML y JavaScript.
Cuando los usuarios solicitan la página, el tiempo de ejecución de ASP.NET
compila y ejecuta el código del lado del servidor para representar HTML y
devuelve el HTML en el navegador web para su visualización.

Note: Si desea escribir código de servidor en Visual Basic, utiliza los archivos
.vbhtml, en lugar de archivos .cshtml.

Puede utilizar cualquiera de Visual Studio 2012 o WebMatrix 2 para crear


aplicaciones de páginas web. ASP.NET 4.5 incluye la versión 2.0 de páginas
Web.

El ejemplo de código siguiente muestra HTML y código C # en parte de un


archivo de páginas Web. El código muestra los datos del objeto de elemento,
que es una clase del modelo MVC.

A Web Pages Code Example

<h2>Special Offers</h2>

<p>Get the best possible value on Northwind specialty foods by taking

advantage of these offers:</p>

@foreach (var item in offers) {

<div class="offer-card">

<div class="offer-picture">

@if (!String.IsNullOrEmpty(item.PhotoUrl)){

<img src="@Href(item.PhotoUrl) alt="@item.Title"/>

</div>

</div>

El modelo de programación de páginas Web tiene las siguientes ventajas:

o Es fácil de aprender
o Se proporciona un control preciso sobre el HTML representado.
o Puede ser escrito en WebMatrix 2 o Visual Studio 2012.

El uso de un sitio Web Pages tiene algunas desventajas:

Proporciona control sobre las direcciones URL que aparecen en la barra de


o
direcciones.
Grandes sitios web requieren un gran número de páginas, cada una de las
o
cuales deben ser codificados de forma individual.
No hay separación de la lógica de negocio, la lógica de entrada, y la interfaz
o
de usuario.

Question: ¿Por qué deberían los desarrolladores web que tenga que tomar el
control de las direcciones URL que aparecen en la barra de direcciones del
navegador cuando visita un sitio Web Pages?

Web Forms Applications

Web Forms es otro modelo de programación que se puede elegir en


ASP.NET. WebMatrix 2 no es compatible con formularios web, por lo que
debe utilizar Visual Studio 2012 para desarrollar una aplicación Web Forms.
Una aplicación Web Forms se caracteriza por controles, que se pueden
arrastrar desde la caja de herramientas de Visual Studio en cada página web.
Este método de crear una interfaz de usuario se parece el método usado en
aplicaciones de escritorio.

Web Forms Controls

ASP.NET proporciona una amplia variedad de controles altamente


funcionales que se monten en los formularios web. Después de agregar un
control a una página, puede escribir código para responder a eventos de
usuario. Por ejemplo, puede utilizar el código en un evento de clic de botón
para procesar la entrada de un usuario en un formulario. Los controles
proporcionados incluyen:

Los controles de entrada, tales como cuadros de texto, botones de opción y


o
casillas de verificación.
Controles de la pantalla, como cuadros de imagen, mapas de imágenes y
o
rotadores de anuncios.
Controles de visualización de datos, tales como vista grillas, vista form, y
o
graficos.
Los controles de validación, que comprueban los datos introducidos por el
o
usuario.
o Los controles de navegación, tales como menús y vistas de árbol.

También puede crear sus propios controles personalizados para encapsular


funcionalidad personalizada.

Web Forms Code Files

En una aplicación de formularios Web, HTML y control de marcado se


almacena en archivos con la extensión .aspx. Del lado del servidor de código
C # se suele escribir en un archivo .cs asociado llamado un archivo de código
subyacente. Por ejemplo, una página llamada Default.aspx por lo general tiene
un archivo de código subyacente llamada Default.aspx.cs.

Del mismo modo, cuando se escribe controles personalizados, almacenar


HTML y marcado de control en un archivo .ascx. Un control de llamada
personalizada Control.ascx tiene un archivo de código subyacente llamada
personalizada Control.ascx.cs.

Web Forms también pueden contener archivos de clase que tienen la


extensión .cs.

Note: Si se escribe el código del lado del servidor en Visual Basic, archivos
de código subyacente tienen una extensión .vb, en lugar de una extensión .cs.

Binding Controls to Data


En Web Forms, puede visualizar fácilmente los datos mediante binding
controls a las fuentes de datos. Esta técnica elimina la necesidad de colocar a
través de las filas de datos y construir pantallas línea por línea. Por ejemplo,
para enlazar un control de grilla a una tabla de base de datos SQL Server, se
arrastra un control de origen de datos de SQL en el Web Form, y utilizar un
cuadro de diálogo para obligar a la vista de cuadrícula a la fuente de datos.
Cuando se solicita la página, ASP.NET se ejecuta la consulta en el origen de
datos y fusiona las filas devueltas de datos con la página de formularios Web.

Advantages and Disadvantages of Web Forms

El modelo de programación Web Forms tiene las siguientes ventajas:

Usted puede diseñar su página visualmente mediante el uso de controles de


o
servidor y Vista Diseño.
Se puede utilizar una amplia gama de controles altamente funcionales que
o
encapsulan una gran cantidad de funcionalidad.
Se pueden visualizar los datos sin tener que escribir muchas líneas de código
o
del lado del servidor.
La interfaz de usuario en el archivo .aspx se separa de entrada y lógica de
o
negocio en los archivos de código subyacente.

El uso de un sitio Web Forms tiene algunas desventajas:

El ciclo de vida de la página Web Forms ASP.NET es una capa de


abstracción a través de HTTP y puede comportarse de forma inesperada.
o
Debe tener una comprensión completa de este ciclo de vida, para escribir
código en los eventos correctos.
o Usted no tiene control preciso sobre el marcado generado por los controles
del lado del servidor.
Los controles pueden añadir grandes cantidades de marcado y la información
o de estado a la página HTML presentado. Esto aumenta el tiempo necesario
para cargar las páginas.

Question: ¿Por qué deberían los desarrolladores web que preocuparse por el
marcado y el estado de la información que los controles ASP.NET Web
Forms se suman a una página HTML presentado?

MVC Applications

MVC es otro modelo de programación disponibles en ASP.NET. aplicaciones


MVC se caracterizan por una fuerte separación de la lógica de negocios,
código de acceso a datos y la interfaz de usuario en modelos, controladores y
vistas. ASP.NET MVC 4.5 incluye la versión 4.0.

No se puede utilizar WebMatrix para crear aplicaciones en MVC.

Models
Cada sitio presenta información sobre los diferentes tipos de objetos a los
visitantes del sitio. Por ejemplo, el sitio web de una editorial puede presentar
información sobre libros y autores. Un libro incluye propiedades tales como el
título, un resumen, y el número de páginas. Un autor puede tener propiedades
tales como un nombre, un apellido y una breve biografía. Cada libro está
vinculado a uno o más autores.

Cuando se escribe una página web MVC para una editorial, debe crear un
modelo con una clase de libros y una clase para los autores. Estas clases del
modelo incluirían las propiedades descritas y pueden incluir métodos tales
como "comprar este libro" o "ponerse en contacto con este autor". Si los libros
y autores se almacenan en una base de datos, el modelo puede incluir el
código de acceso a datos que puede leer y modificar los registros.

Los modelos son clases .NET personalizados y código almacenados en


archivos .cs.

Views

Cada sitio web debe hacer las páginas en HTML que el navegador puede
mostrar. Esta representación se completa con Vistas. Por ejemplo, en el sitio
de publicación, una vista puede consultar los datos del modelo del libro y
hacerlo en una página web para que el usuario pueda ver los detalles
completos. En las aplicaciones de MVC, se crea Vistas de la interfaz de
usuario.

Las vistas son páginas que almacenan marcado HTML y código C # en


archivos .cshtml. Esto significa que son como las páginas Web, sino que
incluye sólo el código de interfaz de usuario. Otra lógica se separa en modelos
y controladores.

Controllers

Cada sitio web debe interactuar con los usuarios cuando hacen clic en los
botones y enlaces. Controladores responden a las acciones del usuario, cargar
datos de un modelo, y lo pasan a una vista, por lo que va a hacer que una
página web. Por ejemplo, en el sitio de publicación, cuando el usuario hace
doble clic en un libro, él o ella espera para ver los detalles completos de ese
libro. El controlador libro recibe la solicitud del usuario, carga el modelo de
libro con el libro de identificación correcto, y lo pasa al libro Detalles Ver, lo
que hace que una página web que muestra el libro. Controladores de
implementar lógica de entrada y enlaza los Modelos a la vista correcta.

Los controladores son NET clases que heredan de la clase


System.Web.Mvc.Controller y el código se almacena en archivos .cs.

Advantages and Disadvantages of MVC

El modelo de programación MVC tiene las siguientes ventajas:

Vistas permiten al desarrollador tomar el control preciso del HTML que se


o
representa.
Se puede utilizar el motor de enrutamiento para tomar el control preciso de
o
la URL.
La lógica de negocio, la lógica de entrada, y la lógica de la interfaz de
o
usuario se dividen en modelos, controladores y vistas.
técnicas de pruebas unitarias y Test Driven Development (TDD) son
o
posibles.

El uso de un sitio de MVC tiene algunas desventajas:

MVC es potencialmente más compleja de entender que las páginas web o


o
formularios web.
MVC forza a que se separen de sus preocupaciones (modelos, vistas y
o
controladores). Algunos programadores pueden encontrar este desafío.
No se puede crear visualmente una interfaz de usuario arrastrando los
o
controles en una página.
Debe tener una comprensión completa de HTML, CSS y Javascript para
o
desarrollar Vistas.

Question: Cuando un usuario realiza una solicitud para un determinado


producto en su catálogo de productos, cual componente recibe la solicitud en
primer lugar: un modelo, un controlador o una vista?
Discussion: ASP.NET Application Scenarios

Los siguientes escenarios describen algunos requisitos para los sitios web. En
cada caso, discutir qué modelo de programación que se elija para implementar
la funcionalidad requerida.

Database Front-End
Su organización tiene su propio sistema de gestión de relaciones con los
clientes que almacena los datos en una base de datos SQL Server. Su equipo
de desarrolladores escribió la interfaz de usuario en Visual Studio 2012 como
una aplicación de escritorio. Los directores ahora requieren que todos los
equipos deben ser capaces de acceder a la aplicación, incluso cuando la
aplicación cliente de escritorio no está instalado. Debido a que todos los
equipos tienen un navegador, se ha decidido a escribir una aplicación web en
ASP.NET para permitir esto.

E-Commerce Site
Usted es un consultor para una organización de software de gran tamaño. Se le
ha pedido al arquitecto un sitio de comercio electrónico que permitirá a los
clientes navegar por el catálogo completo de los paquetes de software,
descarga los paquetes, y la compra de licencias. La empresa cuenta con un
amplio equipo de desarrolladores que están familiarizados con la
programación orientada a objetos .NET. La política de la empresa es utilizar
Test Driven Development para todo el software.

Website for a Small Charitable Trust


Su amigo trabaja para una organización benéfica y le pide consejo sobre un
sitio web. Su amigo no tiene ningún presupuesto para contratar a un consultor,
pero ha creado sitios web mediante el uso de Microsoft FrontPage. Su amigo
quiere incluir una base de datos de mercancía que los visitantes del sitio
pueden navegar y comprar.

Caracteristica Compartidas de ASP.NET

ASP.NET también incluye una serie de características que están disponibles


independientemente del modelo de programación que se utiliza. Esto significa
que si usted está familiarizado con estas características de trabajo con páginas
web o formularios web, su conocimiento puede ser usado en aplicaciones
MVC también.

Configuration

Al configurar un sitio ASP.NET, puede controlar cómo se manejan los


errores, cómo el sitio se conecta a bases de datos, cómo se valida la entrada
del usuario, y muchos otros ajustes. Puede configurar los sitios ASP.NET
mediante la creación y edición de archivos Web.config. El archivo
Web.config en la carpeta raíz de su sitio se configura todo el sitio, pero se
puede anular esta configuración en los niveles más bajos mediante la creación
de archivos Web.config en las subcarpetas.

Los archivos Web.config son archivos XML con un conjunto de elementos y


atributos que el tiempo de ejecución de ASP.NET acepta.
An Example Web.config File

<?xml version="1.0" encoding="utf-8"?>

<configuration>

<appSettings>

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"

/>

<add key="webpages:Version" value="2.0.0.0" />

<add key="webpages:Enabled" value="false" />

<add key="PreserveLoginUrl" value="true" />

<add key="ClientValidationEnabled" value="true" />

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

</appSettings>

<connectionStrings>

<add name="ApplicationServices"

connectionString="Data Source=

.\SQLEXPRESS;Integrated Security=SSPI;

AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"

providerName="System.Data.SqlClient"/>

</connectionStrings>

<system.web>

<customErrors mode="RemoteOnly" defaultRedirect="~/Error.html" />


<authentication mode="Forms">

<forms loginUrl="~/Account/Login" timeout="2880">

</forms>

</authentication>

<pages>

<namespaces>

<add namespace="System.Web.Helpers" />

<add namespace="System.Web.Mvc" />

<add namespace="System.Web.Mvc.Ajax" />

<add namespace="System.Web.Mvc.Html" />

<add namespace="System.Web.Routing" />

<add namespace="System.Web.WebPages" />

<add namespace="System.Web.Optimization"/>

</namespaces>

</pages>

</system.web>

</configuration>

Si necesita acceder a los valores de configuración en tiempo de ejecución en


su código .NET del lado del servidor, puede utilizar namespace
System.Web.Configuration.

Authentication
Muchos sitios web identifican a los usuarios a través de la autenticación. Esto
se hace generalmente mediante la solicitud y la comprobación de las
credenciales como un nombre de usuario y contraseña, aunque la
autenticación se puede hacer mediante el uso de métodos más sofisticados,
tales como el uso de tarjetas inteligentes. Algunos sitios requieren que todos
los usuarios se autentiquen antes de que puedan acceder a cualquier página,
pero es común permitir el acceso anónimo a algunas páginas y requieren
autenticación sólo a los contenidos sensibles o de suscripción.

ASP.NET es compatible con varios mecanismos de autenticación. Por


ejemplo, si está utilizando Internet Explorer en un equipo con Windows,
ASP.NET puede ser capaz de utilizar la autenticación de Windows integrada.
En este mecanismo, la cuenta de usuario de Windows se utiliza para
identificar al usuario. Cuando se construye sitios de Internet, no se puede estar
seguro de que los usuarios tienen Windows, un navegador compatible o una
cuenta accesible, por lo que a menudo se utiliza la autenticación de
formularios. Autenticación de formularios es apoyado por muchos
navegadores y puede ser configurado para comprobar las credenciales contra
una base de datos, servicio de directorio, u otros almacenes de cuentas de
usuario.

Membership and Roles

En muchos sitios de Internet, por ejemplo, Facebook y Twitter, los usuarios


pueden crear sus propias cuentas y establecer las credenciales. De esta
manera, su sitio puede soportar un gran número de miembros sin requerir una
enorme cantidad de esfuerzo administrativo porque los administradores no
crean cuentas.

En ASP.NET, un proveedor de membresía o Membership Provider es un


componente que implementa las funciones de administración de cuentas de
usuario. Varios proveedores de pertenencia son compatibles con ASP.NET,
como el membership Provider SQL, que utiliza una base de datos SQL para
almacenar cuentas de usuario. También puede crear un Membership Provider
de suscripciones personalizado, que hereda de uno de los proveedores por
defecto, si usted tiene requisitos únicos.
Cuando se tiene más de unos pocos usuarios, es posible que desee agruparlas
en roles con diferentes niveles de acceso. Por ejemplo, puede crear una
función "Gold Members" que contiene las cuentas de usuario con acceso a las
mejores ofertas especiales. Los proveedores de roles de ASP.NET le permiten
crear y llenar papeles con el mínimo de código personalizado.

Puede habilitar el acceso a las páginas en su sitio web para las cuentas de
usuario individuales o para todos los miembros sociados a un rol. Este proceso
se conoce como la autorización.

State Management – Gestionar Estados

Los servidores web y navegadores web se comunican a través de HTTP. Este


es un protocolo sin estado en el que cada solicitud está separado de las
solicitudes antes y después de ella. Cualquier valor de las solicitudes
anteriores no se recuerda de forma automática.

Sin embargo, cuando se crea una aplicación web, debe preservar los valores
de frecuencia a través de múltiples peticiones de página. Por ejemplo, si un
usuario introduce un producto en un carrito de compra, y luego hace clic en
"Check Out", se trata de una petición web separada, pero el servidor debe
preservar el contenido de ese carro de compra; de lo contrario, el carro de
compra se vaciará y el cliente no va comprar nada. ASP.NET ofrece varios
lugares donde puede almacenar dichos valores o información de estado a
través de múltiples peticiones.

Caching

Una página ASP.NET se construye dinámicamente por el tiempo de ejecución


de ASP.NET en el servidor web. Por ejemplo, en una aplicación de páginas
Web, el tiempo de ejecución debe ejecutar el código C # en la página HTML
para hacer que esto retorne al navegador. Ese código C # puede realizar
operaciones complejas y requieren mucho tiempo. Puede ejecutar varias
consultas en una base de datos o llamar a los servicios en servidores remotos.
Puede mitigar estos retardos de tiempo mediante el uso de caché de ASP.NET.

Por ejemplo, puede utilizar la caché de páginas ASP.NET para almacenar la


versión procesada de una página solicitada habitualmente en la memoria del
servidor web. La primera página de su catálogo de productos puede ser
solicitada a cientos o miles de veces al día por muchos usuarios. Si se
almacena en caché la página en la memoria la primera vez que se hace, el
servidor web puede servir a la mayoría de usuarios muy rápidamente, sin
consultar el servidor de base de datos y construcción de la página desde el
principio.

Question: ¿Se puede pensar en otras facilidades que puedan necesitar todas
las aplicaciones ASP.NET, independientemente del modelo de programación
que utilizan?

Lesson 3: Introduction to ASP.NET MVC 4


Usted necesita saber cómo los modelos, vistas y controladores trabajan juntos
para representar HTML, y cómo la estructura de aplicaciones MVC determina
la visualización de la información en un proyecto de Visual Studio 2012.
Puede examinar las nuevas características de MVC 4, incluido en ASP.NET
4.5, para crear aplicaciones ricas y atractivas.

Lesson Objectives
Después de completar esta lección, usted será capaz de:

o Describir los modelos, vistas y controladores.


Explora las características principales de una aplicación Web ASP.NET
o
MVC 4 en Visual Studio.
o Describir las nuevas características de ASP.NET MVC 4.

Models, Views, and Controllers


Modelos representan los datos y la lógica de negocio que acompaña, los
controladores interactúan con las peticiones del usuario e implementar la
lógica de entrada, y vistas a construir la interfaz de usuario. Examinando
cómo una solicitud de usuario es procesado por ASP.NET MVC 4, se puede
entender cómo los flujos de datos a través de modelos, vistas y controladores
antes de ser enviado de vuelta al navegador.

Models and Data

Un modelo es un conjunto de clases de .NET que representa los objetos


manipulados por su sitio web. Por ejemplo, el modelo para una aplicación de
comercio electrónico puede incluir una clase de modelo del producto con
propiedades tales como la identificación del producto, número de parte,
número de catálogo, nombre, descripción y el precio. Al igual que cualquier
clase de .NET, las clases del modelo pueden incluir un constructor, que es un
procedimiento que se ejecuta cuando se crea una nueva instancia de esa clase.
También puede incluir otros procedimientos, si es necesario. Estos
procedimientos encapsulan la lógica de negocio. Por ejemplo, puede escribir
un procedimiento de publicación que marca el producto como listos para la
venta.
La mayoría de los sitios web almacenan información en una base de datos. En
una aplicación MVC, el modelo incluye código que lee y escribe los registros
de base de datos. ASP.NET MVC trabaja con muchos marcos de acceso a
datos diferentes. Sin embargo, el marco más utilizado es la versión de Entity
Framework 5.0.

Controllers and Actions

Un controlador es una clase .NET que responde a las peticiones del navegador
Web en una aplicación MVC. Por lo general hay una clase controlador para
cada clase del modelo. Controladores incluyen acciones, que son métodos que
se ejecutan en respuesta a una petición del usuario. Por ejemplo, el
controlador del producto puede incluir una acción de compra que se ejecuta
cuando el usuario hace clic en el botón Añadir al carro de la aplicación web.

Controladores heredan de la clase base System.Web.Mvc.Controller.


Acciones normalmente devuelven un objeto System.Web.Mvc.ActionResult.

Views and Razor

Una vista es, por defecto, un archivo .cshtml o .vbhtml que incluye tanto el
formato HTML y el código de programación. Un motor de vista interpreta
archivos de vista, se ejecuta el código del lado del servidor, y representa
HTML al navegador web. Razor es el motor vista por defecto en ASP.NET
MVC 4, pero ASP.NET MVC 4 también soporta el motor de vista de ASPX.
Además, puede instalar motores de vista alternativos, tales como Spark y
NHaml. El motor de vistas Razor identifica el código del lado del servidor
mediante la búsqueda de el símbolo @, como el siguiente ejemplo de código
se muestra.

Las siguientes líneas de código son parte de una vista ASP.NET MVC 4 y
usan la sintaxis Razor. El símbolo @ delimita código del lado del servidor.

Part of a Razor View

<h2>Details</h2>

<fieldset>

<legend>Comment</legend>
<div class="display-label">

@Html.DisplayNameFor(model => model.Subject)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Subject)

</div>

<div class="display-label">

@Html.DisplayNameFor(model => model.Body)

</div>

<div class="display-field">

@Html.DisplayFor(model => model.Body)

</div>

</fieldset>

A menudo, la vista muestra las propiedades de una clase del modelo. En el


ejemplo de código anterior, Subject property y Body property se incorporan a
la página.

Request Life Cycle

El ciclo de vida de solicitud comprende una serie de eventos que suceden


cuando una petición web se procesa. Los pasos siguientes ilustran el proceso
que siguen las aplicaciones MVC para responder a una petición de usuario
típico. La solicitud se refiere a los detalles de un producto con el ID "1":

The user requests the web address:


1.
http://www.adventureworks.com/product/display/1
2. The MVC routing engine examines the request and determines that it should
forward the request to the Product Controller and the Display action.
The Display action in the Product Controller creates a new instance of the
3.
Product model class.
The Product model class queries the database for information about the
4.
product with ID “1”.
The Display action also creates a new instance of the Product Display View
5.
and passes the Product Model to it.
The Razor view engine runs the server-side code in the Product Display
6. View to render HTML. In this case, the server-side code inserts properties
such as Title, Description, Catalog Number, and Price into the HTML.
7. The completed HTML page is returned to the browser for display.

Question: Si quería escribir algo de código que hace que los datos de su
catálogo de productos en una tabla HTML, se colocaría ese código en un
modelo, una vista, un controlador, o una función de JavaScript?

Demonstration: How to Explore an MVC Application


In this demonstration, you will see how to use a sample photo sharing
application to explore the structure of an MVC website.

Demonstration Steps
In the Solution Explorer pane of the PhotoSharingSample – Microsoft
Visual Studio window, expand PhotoSharingSample, and then note that
1.
the PhotoSharingSample application does not have the default.htm, the
default.aspx, or the default.cshtml files to act as a home page.
In the Solution Explorer pane, under PhotoSharingSample, expand
2.
Controllers, and then click HomeController.cs.
In the HomeController.cs code window, locate the following code.

Public ActionResult Index()

3.
{

return View();
}

Note: This code block represents an action that will return a view called
Index.
4. In the Solution Explorer pane, expand Views, and then expand Photo.
5. In the Solution Explorer pane, under Photo, click Index.cshtml.
In the Index.cshtml code window, locate the following code.

<h2>@ViewBag.Title</h2>

<p>
6.
@Html.ActionLink(“Create New”, “Create”)

</p>

Note: This code block represents the View that renders the home page.
On the toolbar of the PhotoSharingSample – Microsoft Visual Studio
7.
window, click Internet Explorer.
In the http://localhost:<yourportnumber>/ window, note that the default
8.
home page is displayed.
9. On the taskbar, click the Microsoft Visual Studio icon.
In the PhotoSharingSample – Microsoft Visual Studio window, in the
10. Solution Explorer pane, expand App_Start, and then click
RouteConfig.cs.
In the RouteConfig.cs code window, locate the following code.

routes.MapRoute(

name: "Default",

11.
url: “{controller}/{action}/{id}",

Note: This code block represents the default route that forwards requests
to the specified controller.
12. On the taskbar, click the Internet Explorer icon.
In the Address bar of the Windows Internet Explorer window, type the
URL http://localhost:<yourportnumber>/home/index, and then click the
13. Go to button.
Note: The browser window displays the Home page of the
http://localhost:<yourportnumber>/home/index web application.
14. On the taskbar, click the Microsoft Visual Studio icon.
In the PhotoSharingSample – Microsoft Visual Studio window, in the
15.
Solution Explorer pane, expand Models, and then click Photo.cs.
In the Photo.cs code window, locate the following code.

[Required]

16.
public string Title { get; set;}

Note: This code block represents the Title property for a photo stored in
the application.
In the Solution Explorer pane, under Controllers, click
17.
PhotoController.cs.
In the PhotoController.cs code window, locate the following code.

18. public class PhotoController : Controller

Note: This code block represents that the PhotoController class inherits
the System.Web.MVC.Controller base class.
In thePhotoController.cs code window, locate the following code.

public ActionResult Details

(int id = 0)

19. {

Photo photo = db.Photos.Find(id);

if (photo == null)

{
return HttpNotFound();

return View("Details", photo);

Note: This code block represents the Details action of the Photo
Controller.
In the Solution Explorer pane, expand Views, expand Photo, and then
20.
click Details.cshtml.
In the Details.cshtml code window, locate the following code.

21. <h2>"@Model.Title"</h2>
Note: The Razor view engine runs this code and renders the Photo Title
property that you viewed in the model.
22. On the taskbar, click the Internet Explorer icon.
In the Address bar of the Windows Internet Explorer window, type
http://localhost:<yourportnumber>/photo/details/2, and then click the
23. Go to button.
Note: The photo with ID 2 is displayed in the browser window. Note that
the title of the photo is rendered at the top.
24. In the Windows Internet Explorer window, click the Close button.
In the PhotoSharingSample (Running) – Microsoft Visual Studio
25.
window, click the Close button.
New Features of ASP.NET MVC 4

ASP.NET MVC 4 incluye varias características nuevas, tales como la Web


API de ASP.NET, características móviles, modos de visualización,
controladores asíncronos, OAuth y OpenID apoyo y la paquetización y la
minimización.

Web API de ASP.NET. La Web API de ASP.NET hace que sea fácil crear un
conjunto de servicios web que puedan responder a las peticiones del
navegador mediante el uso de verbos HTTP simples, tales como GET, POST
o y DELETE. El uso de la API de Web, se puede construir los web services
back-end que una aplicación web específica del cliente puede llamar. La
creación de aplicaciones web mediante el uso de páginas HTML específicas
para el cliente y la API de Web es una alternativa al uso de ASP.NET MVC.
Características móviles. A medida que los teléfonos inteligentes y las
tabletas se vuelven omnipresentes, debe asegurarse de que su sitio web
muestra bien en todos los tamaños de pantalla, resoluciones, profundidades
o de color, y así sucesivamente. ASP.NET MVC 4.0 incluye varias nuevas
funciones para hacer esto más fácil. Por ejemplo, la biblioteca de scripts
jQuery Mobile hace una rica interfaz de usuario para navegadores de
teléfonos inteligentes, pero los controles más sencillos para los modelos más
antiguos de teléfonos. Puede utilizar la nueva plantilla de proyecto móvil que
utiliza jQuery Mobile para crear sitios específicamente para dispositivos
móviles. Alternativamente, se puede añadir puntos de vista específicos para
dispositivos móviles a su proyecto MVC.
Los modos de visualización. Los modos de visualización permiten
seleccionar fácilmente un punto de vista basado en el navegador web que
hizo la solicitud. Los modos de visualización ayudan render HTML para
o dispositivos móviles y que se pueden utilizar para mostrar contenido en los
navegadores de escritorio inusuales. Cuando se agrega un modo de
visualización para un navegador en particular, sustituir los puntos de vista,
opiniones plantilla, y vistas parciales que se utilizan para representar HTML.
Controladores asíncronos. Por lo general, una acción de controlador hace
de forma sincrónica. Si la acción se lleva mucho tiempo para funcionar, el
usuario tiene que esperar porque la acción utiliza un solo hilo. Con acciones
o
asíncronas, puede llamar a un método de larga duración en un hilo separado
y esperar a que se devuelvan los resultados. Esto permite una acción para
completar y responder al usuario antes de que se entreguen los resultados.
Compatibilidad con los estándares de OAuth y OpenID. El uso de las
normas de OAuth y OpenID para identificar a los usuarios conectados a la
aplicación web a través de Internet, puede llamar a los servicios de un sitio
de terceros para comprobar las credenciales de un usuario. Usted puede
o
confiar en la identidad verificada por el sitio externo y, a continuación,
utilizarlo para autorizar el acceso a los recursos internos. El uso de estas
tecnologías, se puede, por ejemplo, que los usuarios puedan acceder a los
recursos internos, conectándose con su cuenta de Windows Live.
Agrupación y minimización. Cuando un navegador solicita una página web,
el servidor vuelve a menudo a la página con una hoja de estilo en cascada y
uno o más archivos JavaScript. ASP.NET MVC 4.0 puede agrupar estos
archivos separados en un solo archivo para aumentar la eficacia de la
o respuesta. También puede minimizar estos archivos, mediante la eliminación
de espacios en blanco, acortando los nombres de variables, y la realización
de otras acciones que ahorran espacio. Esto ahorra tiempo en las descargas y
ambos recursos del servidor y del lado del cliente, y hace que su aplicación
web más rápido.
Question: ¿Quieres animar a los desarrolladores reutilizar los datos de su
página web en mashups (aplicaciones hibridas) con los mapas de Bing. ¿Cuál
de las nuevas características de MVC 4 usaría para hacer esto posible?

Module 02: Designing ASP.NET MVC 4 Web


Applications

Module Overview
Microsoft ASP.NET MVC 4 es un modelo de programación que puede utilizar
para crear aplicaciones web potentes y complejas. Sin embargo, todos los
proyectos de desarrollo complejos y grandes proyectos, en particular, puede
ser difícil y complejo para entender completamente. Sin una comprensión
completa de los efectos de un proyecto, no se puede desarrollar una solución
eficaz al problema del cliente. Usted necesita saber cómo identificar un
conjunto de necesidades de negocio y planificar una aplicación web MVC
para satisfacer esas necesidades. El plan de proyecto que se crea asegura que
las partes interesadas comprendan sus necesidades y comunica la
funcionalidad de la aplicación web, su interfaz de usuario, la estructura y el
almacenamiento de datos a los desarrolladores que se va a crear. Al escribir un
plan detallado y exacto del proyecto, se puede asegurar que las características
de gran alcance de MVC se utilizan con mayor eficacia para resolver los
problemas de negocio de un cliente.

Objectives

After completing this module, you will be able to:

Planificar la arquitectura general de una aplicación web MVC 4 y considerar


o
aspectos tales como la administración del estado.
Planificar los modelos, controladores y vistas que se requieren para poner en
o
práctica un conjunto de requisitos funcionales.

Lesson 1 : Planning in the Project Design Phase


Antes de que usted y su equipo de desarrolladores planea una aplicación web
Modelo-Vista-Controlador (MVC) o escribir ningún código, debe tener un
conocimiento profundo de dos cosas: el problema de negocio que está
tratando de resolver y los componentes de ASP.NET que le puede utilizar para
construir una solución. Antes de diseñar una arquitectura de aplicaciones web
y su base de datos, usted debe saber cómo identificar los requerimientos que
los usuarios potenciales de una aplicación web tienen.

Lesson Objectives
After completing this lesson, you will be able to:

o Describir los distintos modelos de desarrollo de proyectos.


Describe cómo recopilar información acerca de los requisitos del proyecto
o
en la construcción de MVC 4 aplicaciones web.
Determinar los requisitos funcionales y problemas de negocios en la
o
construcción de aplicaciones web
Explicar cómo planificar el diseño de base de datos al crear una aplicación
o
web.
o Describir las posibles arquitecturas de aplicaciones distribuidas.
Describir las opciones para la planificación de la administración del estado
o
en una aplicación web.
Describir las opciones para la planificación de la globalización y la
o
localización de una aplicación web.
o Determinar los aspectos críticos del diseño de aplicaciones web.

Project Development Methodologies


Desarrollo de una aplicación web o aplicación de intranet es a menudo un
proceso complejo que involucra muchos desarrolladores en diferentes equipos
que realizan diversas funciones. Para organizar el proceso de desarrollo y
asegurarse de que todo el mundo en un proyecto trabaja en conjunto, se puede
utilizar una amplia gama de metodologías de desarrollo. Estas metodologías
de desarrollo describen las fases del proyecto de desarrollo, los roles de las
personas toman, los entregables que concluyen cada fase, y otros aspectos del
proyecto. Debe elegir una metodología de desarrollo en una etapa temprana en
un proyecto. Muchas organizaciones tienen una metodología estándar que
usan siempre para el desarrollo del proyecto.

Algunas metodologías de desarrollo de proyectos incluyen el modelo de


cascada, el modelo de desarrollo iterativo, el modelo de prototipos, el modelo
de desarrollo ágil de software, programación extrema, y el desarrollo basado
en pruebas.

Waterfall Model

The waterfall model is an early methodology that defines the following phases
of a project:

o Feasibility analysis. In this phase, planners and developers study and


determine the approaches and technologies that can be used to build the
software application.
Requirement analysis. In this phase, planners and analysts interview the
o users, managers, administrators, and other stakeholders of the software
application to determine their needs.
Application design. In this phase, planners, analysts, and developers record a
o
proposed solution.
Coding and unit testing. In this phase, developers create the code and test
o
the components that make up the system individually.
Integration and system testing. In this phase, developers integrate the
o
components that they have built and test the system as a whole.
Deployment and maintenance. In this phase, developers and administrators
o
deploy the solution so that users can start using the software application.

The waterfall model classifies the development project into distinct phases
with a clear definition of deliverables for each phase. The model also
emphasizes the importance of testing. However, the customer does not receive
any functional software for review until late in the project. This makes it
difficult to deal with changes to the design in response to beta feedback or
manage altered circumstances.

Iterative Development Model

When you use an iterative development model, you break the project into
small parts. For each part, you perform the activities related to all the stages of
the waterfall model. The project is built up stage by stage, with thorough
testing at each stage to ensure quality.

In an iterative project, you can perform corrective action at the end of each
iteration. These corrections might reflect a better understanding of the
business problems, insightful user feedback, or a better understanding of the
technologies that you used to build the solution. Because requirements are
added at the end of each iteration, iterative projects require a great deal of
project management effort and frequently feature an overrun of planned
efforts and schedule.

Prototyping Model
The prototyping model is suitable for a project where you begin with a few or
meagerly defined business requirements. This situation occurs when the
customers or stakeholders have only a vague understanding of their needs and
how to solve them. In this approach, developers create a simplified version of
the software application, and then seek feedback from stakeholders. This
feedback on the prototype is used to define the detailed requirements, which
developers use in the next iteration to build a solution that matches the needs
of stakeholders to better help them perform their jobs.

After two or more iterations, when both stakeholders and developers reach a
consensus on the requirements, a complete solution is built and tested. The
prototyping model, however, can lead to a poorly-designed application
because at no stage in the project is there a clear focus on the overall
architecture.

Agile Software Development Model

The waterfall model, iterative development model, and prototyping model are
based on the premise that business requirements and other factors do not
change from the beginning to the end of the project. In reality, this assumption
is often invalid. Agile software development is a methodology designed to
integrate changing circumstances and requirements throughout the
development process. Agile projects are characterized by:

Incremental development. Software is developed in rapid cycles that build


o
on earlier cycles. Each iteration is thoroughly tested.
Emphasis on people and interactions. Developers write code based on what
o
people do in their role, rather than what the development tools are good at.
Emphasis on working software. Instead of writing detailed design
o documents for stakeholders, developers write solutions that stakeholders can
evaluate at each iteration to validate if it solves a requirement.
Close collaboration with customers. Developers discuss with customers and
o
stakeholders on a day-to-day basis to check requirements.
Extreme Programming

Extreme programming evolved from agile software development. In extreme


programming, the preliminary design phase is reduced to a minimum and
developers focus on solving a few critical tasks. As soon as these critical tasks
are finalized, developers test the simplified solution and obtain feedback from
stakeholders. This feedback helps developers identify the detailed
requirements, which evolve over the project life cycle.

Extreme programming defines a user story for every user role. A user story
describes all the interactions that a user with a specific role might perform
with the completed application. The collection of all the user stories for all
user roles describes the entire application.

En la programación extrema, los desarrolladores a menudo trabajan en


parejas. Un desarrollador escribe el código y el otro desarrollador revisa el
código para asegurarse de que utiliza las soluciones simples y se adhiere a las
mejores prácticas. desarrollo basado en pruebas es una práctica fundamental
en la programación extrema.

Additional Reading: For more information about the extreme programming


model, go to http://go.microsoft.com/fwlink/?LinkID=288945&clcid=0x409.

Test Driven Development

In test-driven development (TDD), developers write test code as their first


task in a given iteration. For example, if you want to write a component that
stores credit card details, you begin by writing tests that such a component
would pass. These may be whether it checks the number formats correctly,
whether it writes strings to a database table correctly, or whether it calls
banking services correctly. After you define the tests, you write the
component to pass those tests.

In subsequent iterations, the credit card tests remain in place. This ensures that
if you break the credit card functionality, perhaps by refactoring code or by
adding a new constructor, you find this out quickly because the tests fail.

En Microsoft Visual Studio 2012, puede definir un proyecto de prueba, dentro


de la misma solución que el proyecto principal, para almacenar y ejecutar
pruebas unitarias. Después de escribir las pruebas, puede ejecutar ellos
individualmente o en grupos después de cada cambio de código. Dado que los
proyectos tienen el modelo MVC, ver y código del controlador en archivos
separados, es fácil para crear pruebas unitarias para todos los aspectos del
comportamiento de la aplicación. Esta es una de las principales ventajas de la
MVC sobre páginas Web y Web Forms.

Unified Modeling Language

The Unified Modeling Language (UML) is an industry standard notation to


record the design of any application that uses object-oriented technology.
UML is not a development model. Rather, UML diagrams are often used for
planning and documenting application architecture and components, across all
project development methodologies. When you use UML to design and record
an application, you create a range of diagrams with standard shapes and
connectors. These diagrams can be divided into three classes:

Behavior diagrams. These diagrams depict the behavior of users,


o
applications, and application components.
Interaction diagrams. These diagrams are a subset of behavior diagrams that
o
focus on the interactions between objects.
Structure diagrams. These diagrams depict the elements of an application
o that are independent of time. This means they do not change through the
lifetime of the application.

Question: What aspects of agile software development and extreme


programming might be of concern to customers? What aspects might reassure
them?
Gathering Requirements – Recolecccion reuerimientos

Cuando se pone en marcha un proyecto, que necesita una visión de la


solución. La visión a menudo puede ser vago y requieren una investigación en
profundidad antes de poder añadir detalles y asegurarse de que los requisitos
de todas las partes interesadas están cubiertas por la aplicación web que se
genera. Estos requisitos pueden ser de dos tipos:

Requerimientos funcionales. Estos requisitos describen cómo se comporta la


aplicación y responde a los usuarios. Requisitos funcionales son a menudo
llamados requisitos de comportamiento. Ellos incluye:

User interface requirements. These requirements describe how the user


o ▪ interacts with an application.
Usage requirements. These requirements describe what a user can do with

the application.
Business requirements. These requirements describe how he application

will fulfill business functions.
Requerimientos técnicos. Estos requisitos se describen las características
o técnicas de la aplicación y se refieren a la disponibilidad, la seguridad o el
rendimiento. Estos requisitos son a veces llamados los requisitos no
funcionales o no comportamentales.

Por lo general, se reúnen los requisitos de las partes interesadas, tales como
entrevistas a usuarios, administradores, otros promotores, miembros de la
junta, los responsables del presupuesto, y jefes de equipo. Cada uno de estos
grupos tendrá un conjunto diferente de prioridades que la aplicación necesita
para cumplir.

Usage Scenarios and Use Cases – Escenarios y casos de uso

Un método común mediante el cual se puede construir un conjunto de


requisitos de interfaz de usuario, los requerimientos del negocio, y los
requisitos de uso es pedir a los usuarios lo que van a hacer con la aplicación
web que se genera. Puede grabar estas acciones como escenarios de uso y
casos de uso.

Un escenario de uso es un ejemplo específico del mundo real, con los nombres
y valores de entrada sugeridas, de una interacción entre la aplicación y un
usuario. El siguiente es un ejemplo sencillo:

1. Roger Lengel clicks the Add Photo link on the main site menu.
Roger provides the input, RogerL, in the User name box and the password
2.
in the Password box to authenticate on the site.
3. Roger types the title, Sunset, for the photo.
4. Roger browses to the JPEG file for his new photo.
5. Roger clicks the Upload button.
The web application stores the new photo and displays the photo gallery to
6.
Roger.

Un caso de uso es similar a un escenario de uso, pero es más generalizada.


Los casos de uso no incluyen nombres de usuario o valores de entrada. Ellos
describen varias rutas de una interacción, que depende de lo que el usuario
proporciona como entrada o otros valores. El siguiente es un ejemplo sencillo:

1. The user clicks the Add Photo link on the main site menu.
2. If the user is anonymous, the logon page is shown and the user provides
credentials.
3. If the credentials are correct, the CreatePhoto view is displayed.
4. The user types a title.
5. The user specifies the photo file to upload.
6. The user optionally types a description for the photo.
7. The user clicks the Upload button.
The web application stores the new photo and displays the photo gallery to
the user.
8.
Note: Similar to verbal descriptions, you can use UML Use Case diagrams
to record the use cases for your web application.

Mediante el análisis de los escenarios de uso y casos de uso, se puede


identificar los requisitos funcionales de todos los tipos. Por ejemplo, a partir
del caso de uso anterior, se puede identificar el requisito siguiente interfaz de
usuario: La página web que permite a los usuarios crear una nueva foto debe
incluir título y la descripción cuadros de texto, un control de entrada de
archivo para el archivo de fotografía, y un botón de Cargar para guardar la
foto.

Agile Requirements Modeling

En un modelo de cascada tradicional o modelo de desarrollo iterativo, los


desarrolladores y analistas investigan y registran los requisitos técnicos y
funcionales precisos y detallados en una fase inicial del proyecto, que no
cambian más tarde. Por el contrario, en un proyecto basado en el modelo de
desarrollo ágil, los desarrolladores reconocen que los requisitos pueden
cambiar en cualquier momento durante el desarrollo. Por lo tanto, el análisis
de requisitos se caracteriza por lo siguiente:

Initial requirement modeling. In the initial design phase, developers


o identify and record a few broad use cases in an informal manner without full
details.
Just-in-time modeling. Before writing code that implements a use case, a
developer discusses it with the relevant users. At this point, the developer
o adds full details to the use case. In an agile development project, developers
talk to users and other stakeholders at all times, and not just at the beginning
and end of the project.
Acceptance testing. An acceptance test is a test that the application must
pass for all stakeholders to accept and sign off the application. When you
o
identify a functional requirement, you can also specify a corresponding
acceptance test that must be run to ensure that the requirements are met.

User Stories in Extreme Programming

En los proyectos de programación extremas, los desarrolladores realizan


análisis de requisitos aún menos funcional en el inicio del proyecto, en
comparación con otros modelos de desarrollo. Crean historias de usuario, en
lugar de casos de uso o escenarios de usuario. Una historia de usuario, es muy
amplio ejemplo de una interacción entre la aplicación y el usuario, y se afirma
a menudo en una sola frase como ilustra el siguiente ejemplo:

o Users can upload photos and give new photos a title and a description.

User stories contain just the minimal details to enable developers to estimate
the effort involved in developing it. Extreme programmers discuss each user
story with stakeholders just before they write code to implement each user
story.

Question: If a customer asks you to ensure 95% availability, is this a


functional requirement or a technical requirement?
Planning the Database Design – Planeando Diseño BD

Cuando usted tiene una buena comprensión de los requisitos funcionales y


los requisitos técnicos de la aplicación web propuesto, puede empezar a
diseñar la implementación física de la aplicación. Uno de los objetos físicos
más importantes para planificar es una o más bases de datos. Aunque no
todas las aplicaciones web utilizan bases de datos para el almacenamiento de
información, que son un objeto subyacente de la mayoría de los sitios y los
utilizarán en la mayor parte de sus proyectos.

Logical Modeling – Modelado Logico

Puede comenzar el diseño de los datos a un alto nivel mediante la creación de


diagramas UML modelo de dominio y diagramas (LDM) Logical Data Model
– Modelo Logica de Datos.

Un diagrama de modelo de dominio, también conocido como un modelo


conceptual de datos, muestra los objetos conceptuales de alto nivel que
gestiona la aplicación web. Por ejemplo, en una aplicación web de comercio
electrónico, el modelo de dominio incluye los conceptos de los clientes,
carritos de compra, y los productos. El modelo de dominio no incluye detalles
de las propiedades de cada concepto tiene, pero muestra las relaciones entre
conceptos. Utilice el modelo de dominio para grabar sus conversaciones
iniciales con las partes interesadas.

En esencia, una LDM es un diagrama de modelo de dominio con los detalles


adicionales añadidos. Puede utilizar diagramas de LDM para rellenar más
detalles, como las propiedades y tipos de datos, por los conceptos que se han
definido en el modelo de dominio. Tenga en cuenta que los objetos de la LDM
no corresponden a las tablas en la base de datos. Por ejemplo, el objeto carrito
de la compra puede mostrar los datos de la base de datos tanto del cliente y
tablas de la base del producto.

Physical Database Structure

Usted debe considerar los siguientes objetos de base de datos en su plan de


proyecto:

Tables. These are the fundamental storage objects in a database. When you
define a table, you need to specify the columns that each table has. For each
column, you must define a data type such as integer, string, usually the
o nvarchar type in SQL Server, or date and time. You should also define the
primary key for the table—the value of this column uniquely identifies each
record and is essential for defining the relationships with records in other
tables.
Views. These are common presentations of data in tables and are based on
o queries. For example, a view can join two tables, such as a products table
and a stock levels table.
Stored procedures. These are common sequences of database operations that
you define in the database. Some operations are complex and might involve
o
a complex transformation of the data. You can define a stored procedure to
implement such a complex routine.
Security. You need to consider how the web application will authenticate
o with the database server and how you will authorize access to each database
table.

En UML, un modelo de datos físico es un diagrama que representa las tablas,


columnas, tipos de datos y las relaciones entre tablas.
Working with Database Administrators

A veces, el equipo desarrollador tiene control total sobre la base de datos que
subyace a la aplicación web. Esto sucede, por ejemplo, cuando la organización
es pequeña o cuando la aplicación web tiene un servidor de base de datos
independiente que no tienen datos críticos para el negocio. Sin embargo, en
las organizaciones más grandes o en proyectos donde las bases de datos
almacenan información crítica del negocio, puede haber un equipo de
administradores de bases de datos (DBA). Estos administradores de bases
suelen ser muy experto en el diseño de bases de datos y administración, y su
trabajo es para asegurar la integridad de datos en base a la política de
almacenamiento de datos de la organización.

Si su base de datos de proyecto es administrado por el equipo de DBA, es


esencial para comunicarse bien con ellos. Es necesario consultar con los
DBAs para sus necesidades. A menudo, imponen una serie de requisitos
técnicos que otras partes interesadas pueden no entender. Como crear y
desplegar la aplicación web, los administradores de bases son responsables de
la creación de bases de datos en los servidores o clusters adecuados y asignar
permisos. DBA son contribuyentes importantes en la entrega de la aplicación
web.

Database Design in Agile Development and Extreme


Programming

El desarrollo ágil y la programación extrema se caracterizan por una cantidad


relativamente pequeña de planificación y documentación inicial, y reconocen
que los requisitos son susceptibles de cambiar en todo el proyecto de
desarrollo. Si está trabajando mediante el uso de estas metodologías de
desarrollo, sólo se va a crear modelos de dominio durante la fase inicial de
planificación de su proyecto. No se desarrollan LDMs o modelos de datos
físicos hasta que escribir código que implementa los requisitos funcionales.
Durante la fase de desarrollo, se discuten los requisitos con los usuarios y los
DBAs y crean LDMs y modelos de datos físicos justo antes de escribir el
código.

En el desarrollo ágil y la programación extrema, el diseño de la base de datos


cambia a lo largo del proyecto hasta la implementación. Por lo tanto, los
desarrolladores deben ser capaces de alterar la base de datos cuando sea
necesario sin consultar a los DBAs o cumplir con las políticas de datos
complejos. Por esta razón, se debe utilizar una base de datos independiente
alojada en un servidor de desarrollo dedicado.

En algunos casos, el proyecto de desarrollo trabaja con una base de datos que
ya existe. Por ejemplo, puede estar desarrollando una aplicación web que
presenta y edita la información de la base de datos empleado de la compañía
en la intranet. En tales casos, la base de datos no cambia como se desarrolla el
código, pero los requisitos funcionales y técnicas todavía puede cambiar.
Debería copiar la base de datos a un servidor de base de datos de desarrollo
aislado para asegurar que su código en desarrollo no modifica erróneamente
los datos críticos para el negocio.

Question: You want to implement a shopping cart in your web application.


How many logical data models are required? How many database tables are
required?

Planning for Distributed Applications


For small web application with less user traffic levels, you can choose to host
all the components of your web application on a single server.

However, as your web application grows, a distributed deployment, in which


different servers host separate components of the application, is often used.
Distributed web applications often use a layered architecture:

Presentation layer. Components in this layer implement the user interface


o and presentation logic. If you are building an MVC web application, views
and controllers make up your presentation layer.
Business logic layer. Components in this layer implement high-level
o business objects such as products, or customers. If you are building an MVC
web application, models make up your business logic layer.
Data access layer. Components in this layer implement database access
operations and abstract database objects, such as tables, from business
objects. For example, a product business object may include data from both
o the Products and StockLevels database tables. If you are building an MVC
web application, models often make up both business logic and data access
layers. However, with careful design and coding practices, it is possible to
refactor code to separate these layers.
o Database layer. This layer has the database itself.

If you implement such a layered architecture in your web application, you can
host each layer on separate servers. Often, for example, the presentation layer
is hosted on one or more IIS servers, the business logic and data access layers
are hosted on dedicated middle-tier servers, and the database is hosted on a
dedicated SQL Server. This approach has the following advantages:

You can specify server hardware that closely matches each role. For
o example, a server that hosts business logic components requires good
memory and processing resources.
You can dedicate multiple servers to each role to ensure that a single server
o
failure does not cause an interruption in service.
Only the web servers must be on the perimeter network. Both middle-tier
o servers and database servers can be protected by two firewalls without direct
access from the Internet.
Alternatively, you can host middle-tier layers and databases on a cloud
o
service, such as Windows Azure.

Communication Between Layers

Cuando un solo servidor aloja todos los componentes de una aplicación web,
la presentación, lógica de negocio y componentes de acceso a datos de corre
en un proceso simple en la memoria del servidor web. La comunicación entre
los componentes no es un problema. Sin embargo, al ejecutar diferentes capas
en diferentes servidores, debe tener en cuenta dos factores:

o ¿De qué manera cada capa intercambiar información y mensajes?


¿De qué manera cada servidor se autentica y tiene comunicaciones seguras
o
con otros servidores?

La comunicación de la información y la seguridad se lleva a cabo de


diferentes maneras entre las diversas capas:

Entre el servidor web y el navegador capa de presentación. En cualquier


aplicación web, el navegador web, donde la capa de presentación se ejecuta,
se comunica con el servidor web mediante el protocolo HTTP. Si se requiere
o
autenticación, a menudo se lleva a cabo mediante el intercambio de
credenciales de texto sin formato. También puede utilizar Secure Sockets
Layer (SSL) para cifrar esta comunicación sensible.
Entre el servidor web y el servidor de nivel intermedio. Los mecanismos de
comunicación y seguridad que se utilizan para la comunicación entre el
servidor web y el servidor de nivel intermedio depende de la tecnología que
se utiliza para construir los componentes de lógica de negocios:

Web Services: Si implementa objetos de negocio y clases de acceso a datos


o como servicios web, los componentes de la capa de presentación se
comunican con los servicios web mediante el uso de HTTP. Se puede

realizar la autenticación mediante el protocolo Kerberos que es una parte
de la autenticación integrada de Windows o mediante texto sin formato
cifrado con SSL.
Windows Communication Foundation (WCF) services: Si implementa

objetos de negocio y clases de acceso a datos como servicios de WCF, se
puede elegir entre dos mecanismos de alojamiento. Puede alojar los
servicios WCF dentro de IIS, en cuyo caso, HTTP es el mecanismo de
transporte y SSL es el mecanismo de seguridad. También puede organizar
los servicios de WCF dentro de un servicio de activación de procesos de
Windows (WAS), en cuyo caso, se puede utilizar TCP, Microsoft Message
Queuing (MSMQ), o canalizaciones con nombre como mecanismo de
transporte.
Entre servidor de nivel intermedio y de base de datos. El servidor de nivel
intermedio envía consultas T-SQL en el servidor de base de datos, que
autentica la base de datos mediante el uso de las credenciales necesarias
o que a menudo se incluyen en la cadena de conexión.

Note: Web services and WCF services are covered in detail in Course
20487A: Developing Windows Azure and Web Services.

Question: ¿Cuáles son las ventajas de escribir componentes de nivel medio


como WCF services y no a los servicios web?

Planning State Management – Planificacion Gestiòn de


Estados
En el desarrollo de aplicaciones, el estado de la aplicación se refiere a los
valores y la información que se mantienen a través de múltiples operaciones.
Protocolo de transferencia de hipertexto (HTTP) es fundamentalmente un
protocolo sin estado, lo que indica que no tiene ningún mecanismo para
retener la información de estado a través de múltiples peticiones de página.
Sin embargo, hay muchos escenarios, como el siguiente, que requieren un
estado a ser preservado:

Preferencias de usuario. Algunos sitios web permiten a los usuarios


especificar las preferencias. Por ejemplo, una aplicación web para compartir
o fotos podría permitir a los usuarios elegir un tamaño preferido para las fotos.
Si esta información se pierde preferencia entre solicitudes de páginas, los
usuarios tienen que volver a aplicar continuamente la preferencia.
Identidad del usuario. Algunos sitios autentican usuarios para proporcionar
acceso a contenido exclusivo solo a sus miembros. Si la identidad del
o
usuario se pierde entre solicitudes de páginas, el usuario debe volver a
introducir las credenciales para cada página.
Carritos de compra. Si el contenido de un carro de compras se perdió entre
o las solicitudes de página, el cliente no puede comprar nada de su aplicación
web.

En casi todas las aplicaciones web, almacenamiento de estado es un requisito


fundamental. ASP.NET ofrece varios lugares donde puede almacenar
información de estado, y las formas simples de acceso a la información de
estado. Sin embargo, debe planear el uso de estos mecanismos con cuidado. Si
utiliza la ubicación incorrecta, es posible que no sea capaz de recuperar un
valor cuando se espera. Por otra parte, la mala planificación de la
administración del estado frecuentemente da como resultado a un pobre
rendimiento.

En general, se debe tener cuidado con el mantenimiento de grandes cantidades


de datos de estado, ya sea porque consume la memoria del servidor, si se
almacena en el servidor, o se relentiza la transferencia de la página web en el
navegador, si está incluido en una página web. Si necesita almacenar los
valores de estado, se puede elegir entre almacenamiento de estado del lado del
cliente o de almacenamiento de estado del lado del servidor.
Client-Side State Storage – Almacenamiento Lado Cliente
Cuando se almacena la información de estado en el cliente, se garantiza que
los recursos del servidor no se utilizan. Sin embargo, debe tener en cuenta que
toda la información del estado del lado del cliente debe ser enviado entre el
servidor web y el navegador web, y este proceso puede ralentizar el tiempo de
carga de página. Utilice almacenamiento de estado del lado del cliente sólo
para pequeñas cantidades de datos:

Cookies son pequeños archivos de texto que puede pasar al navegador para
almacenar información. Una cookie puede almacenarse:

En la memoria del ordenador cliente, en cuyo caso, se conserva la



información sólo para una única sesión de usuario.
En la unidad de disco duro del ordenador del cliente, en cuyo caso, se

conserva la información a través de múltiples sesiones.

La mayoría de los navegadores pueden almacenar cookies sólo hasta 4.096


bytes y permitir sólo 20 cookies por sitio web. Por lo tanto, las cookies se
pueden utilizar sólo para pequeñas cantidades de datos. Además, algunos
usuarios pueden deshabilitar las cookies para fines de privacidad, por lo que
no deben confiar en las cookies para funciones críticas.

Query strings. Un query string es la parte de la URL después del signo de


interrogación y, a menudo se utiliza para comunicar los valores del
formulario y otros datos al servidor. Puede utilizar la query string para
preservar una pequeña cantidad de datos de una solicitud de página a otra.
Todos los navegadores son compatibles con las cadenas de consulta, pero
algunos imponen un límite de 2.083 caracteres en la longitud de la URL. No
se debe colocar ninguna información sensible en las query string, ya que es
visible para el usuario, cualquiera que vigile la sesión, o cualquier
monitoreo de tráfico web.

Note: In ASP.NET Web Forms applications, View State, Control State, and
Hidden Fields can be used to store state information in the rendered HTML
that the server sends to the client. These mechanisms are not available in
MVC web applications because they do not use Web Forms controls.
Server-Side State Storage – Almacenamiento lado Servidor

La información de estado que se almacena en el servidor consume recursos


del servidor, por lo que debe tener cuidado de no uso excesivo
almacenamiento de estado del lado del servidor o ariesgarse a un bajo
rendimiento.

Los siguientes lugares almacenar información de estado en la memoria del


servidor:

TempData. Esta es una ubicación de almacenamiento de estado que se puede


utilizar en aplicaciones MVC para almacenar valores entre una petición y
otra. Puede almacenar valores mediante su inclusión en la colección
o TempData. Esta información se conserva sólo una única solicitud y está
diseñado para ayudar a mantener los datos a través de una redirección página
web. Por ejemplo, se puede utilizar para pasar un mensaje de error a una
página de error.
Application State. Esta es una ubicación de almacenamiento de estado que se
puede utilizar para almacenar los valores para el tiempo de vida de la
aplicación. Los valores almacenados en el Application State se comparten
entre todos los usuarios. Puede almacenar valores mediante su inclusión en
el Application Collection. Si se reinicia el servidor web o la aplicación web,
o los valores se destruyen. El procedimiento Application_Start () en el archivo
Global.asax es un lugar apropiado para inicializar los valores de estado de la
aplicación. Application State no es un lugar apropiado para almacenar los
valores específicos del usuario, tales como preferencias, porque si almacena
una preferencia en el estado de la aplicación, todos los usuarios comparten la
misma preferencia, en lugar de tener su propio valor único.
Session state. The Session collection almacenan información por el tiempo
de vida de sesión de un navegador y los valores aquí almacenados son
específicos de una única sesión de usuario; que no se puede acceder por
otros usuarios. Por defecto, si se reinicia el servidor web o la aplicación web,
o
los valores se destruyen. Sin embargo, puede configurar ASP.NET para
almacenar estado de sesión en un servidor de base de datos o estado. Si hace
esto, el estado de sesión puede ser preservada en los reinicios. El estado de
sesión está disponible tanto para usuarios autenticados y usuarios anónimos.
De manera predeterminada, el estado de sesión utiliza cookies para
identificar a los usuarios, pero se puede configurar ASP.NET para almacenar
el estado de sesión sin necesidad de utilizar las cookies.

Si decide utilizar estas localizaciones de memoria del servidor, asegúrese de


que se estima el volumen total de datos de estado que pueden ser necesarios
para todos los usuarios al mismo tiempo que se esperan de manejar. Los
valores del estado de la aplicación se almacenan sólo una vez, pero los valores
de estado de sesión se almacenan una vez por cada usuario concurrente.
Especificar el hardware de servidor que puede manejar fácilmente esta carga,
o mover los datos del estado en las posiciones basadas en unidades de disco
duro del servidor siguiente.

Las propiedades de perfil. Si su sitio utiliza un proveedor de perfil


ASP.NET, puede almacenar las preferencias del usuario en los perfiles. Las
o
propiedades de perfil se conservan en la base de datos de miembros, por lo
que se mantendrán incluso si se reinicia la aplicación web o servidor web.
tablas de bases de datos. Si su sitio utiliza una base de datos subyacente,
como la mayoría de los sitios lo hacen, puede almacenar información de
estado en sus tablas. Este es un buen lugar para almacenar grandes
volúmenes de datos de estado que no se pueden colocar en la memoria del
o
servidor o en el equipo cliente. Por ejemplo, si desea almacenar un gran
volumen de información de estado específica de la sesión, se puede
almacenar un valor de ID simple en la colección de sesión y utilizarlo para
consultar y actualizar un registro en la base de datos.

Recuerde que los datos de estado es sólo una forma de información que una
aplicación ASP.NET ubica en memoria del servidor. Por ejemplo, el caché
deben compartir memoria con los datos del estado.

Question: Usted muestra a los visitantes de su sitio web una selección de


países. Cuando van a seleccionar un estado, que desea redirigir a una página
que muestra un mapa de ese estado. Usted no utilizará el nombre del país
elegido que el usuario ha seleccionado después de esto. Qué lugar se debe
utilizar para almacenar el nombre del país elegido?
Planning Globalization and Localization

La Internet es una red internacional, y, a menos que esté seguro de que la


audiencia de su aplicación web habla un solo idioma, debe asegurarse de que
todo el mundo puede leer su contenido. A limitar el potencial audiencia del
sitio si se procesa sólo las páginas en Inglés. El proceso por el cual se hace
una aplicación web disponible en varios idiomas se llama globalización o
internacionalización. El proceso por el cual se hace una aplicación web
disponible en un idioma específico y la cultura se llama localización.

Managing Browsers for Languages and Regions

Hay un conjunto internacionalmente reconocido de códigos de idioma que


especifican una cultura en Internet. Estos códigos están en dos partes:

1. The language. For example, English is “en”, and Russian is “ru”.


The region. This specifies regional variations within a language and affects
spellings and formats. For example, in United States English, “Globalize” is
2.
correct and dates are written in mm/dd/yy format, whereas in British
English, “Globalise” is correct and dates are written in dd/mm/yy format.

The full language and region code for United States English is “en-US” and
the full language and region code for British English is “en-UK”.
El idioma preferido que los usuarios elijan está disponible como el código de
idioma en la cabecera HTTP del navegador del usuario. Este es el valor que
responda a, con el fin de globalizar su sitio. Alternativamente, se puede
proporcionar un control, tales como una lista desplegable, en la que los
usuarios pueden elegir su idioma preferido. Este es un buen ejemplo de un
usuario de las preferencias que se pueden almacenar en el estado de la sesión.

Using Resource Files


Cuando el usuario especifica un idioma preferido y región, debe responder por
la prestación de páginas para que la cultura. Un método para proporcionar una
respuesta localizada es utilizar archivos de recursos para insertar texto en el
idioma apropiado en la página en tiempo de ejecución. Un archivo de recursos
es un simple diccionario de términos en una lengua dada. Para cada término
en el archivo, es necesario especificar un nombre, un valor, y, opcionalmente,
un comentario. El archivo tiene una extensión .resx. El nombre del archivo
también incluye el código de lenguaje que los recursos se aplican a. Por
ejemplo, si se crea un archivo de recursos para una vista llamada, Índice, que
los valores almacenados en el español de Chile, sería el nombre del archivo,
Index.es-CL.resx.

Los archivos de recursos también pueden tener una cultura neutra. Esto
significa que el archivo se aplica a cualquier región en una lengua dada. Por
ejemplo, el archivo se aplica Index.es.resx términos españoles,
independientemente del código de región que se ha elegido.

También debe crear archivos de recursos predeterminados correspondientes,


sin ningún código de idioma en el nombre del archivo, como Index.resx. Estos
archivos se utilizan cuando no se especifica un idioma preferido.

Cuando se utiliza archivos de recursos para localizar un sitio, cada vista se


aplica, sin importar el idioma que prefiera. Debe insertar código extra Razor
en la vista con el fin de tomar valores de texto desde un archivo de recursos.
Esto puede reducir la legibilidad de los archivos de vista porque todo el texto
representado viene de archivos de recursos. Sin embargo, el apoyo a nuevos
lenguajes es más fácil, ya que sólo se necesita agregar un nuevo archivo de
recursos para cada idioma que puede ser creado por un traductor profesional.

Using Separate Views

Algunos desarrolladores prefieren utilizar conjuntos de vistas independientes


y paralelos para cada código de idioma soportado. Si utiliza este enfoque,
debe insertar código en los controladores para detectar el idioma preferido que
el usuario ha especificado. A continuación, puede utilizar este valor para
representar la vista correcta.

Cuando utiliza vistas separadas para globalizar y localizar un sitio, las vistas
son más legibles, ya que la mayoría del texto y las etiquetas permanecen en el
archivo de vista. Sin embargo, debe crear archivos de vista, lo que requiere
que usted o los miembros de su equipo sean competentes en el idioma de
destino.

Question: Which language do you consider would be appropriate to specify


in the default resource file?

Lesson 2: Designing Models, Controllers, and


Views
Modelos, controladores y vistas son los componentes fundamentales de una
aplicación web MVC 4. En un sitio complejo, pueden existir cientos de
modelos, vistas y controladores. Necesita administrar estos objetos y
planificar bien su aplicación, de modo que sea fácil administrar la
organización y la estructura interna durante el desarrollo. Un plan completo
asegura que detecte cualquier código incorrecto y depure problemas
rápidamente.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe how to design models.


o Describe how to design controllers.
o Describe how to design views.
Designing Models

Una actividad fundamental en el proceso de diseño de MVC es el diseño de un


modelo. Cada clase de modelo dentro del modelo representa un tipo de objeto
que administra su aplicación. No puede planificar controladores y vistas hasta
que entienda la estructura y el diseño del modelo.

Identifying Model Classes and Properties

Los casos de uso, los escenarios de uso o las historias de usuarios que reunió
durante la fase de análisis del proyecto deberían permitirle determinar las
clases de modelo que necesita crear. Cada clase de modelo tiene un rango de
propiedades. Por ejemplo, considere el siguiente ejemplo de caso de uso
compartido anteriormente.

1. The user clicks the Add Photo link on the main site menu.
If the user is anonymous, the logon page is shown and the user provides
2.
credentials.
3. If the credentials are correct, the CreatePhoto view is displayed.
4. The user types a title.
5. The user specifies the photo file to upload.
6. The user optionally types a description for the photo.
7. The user clicks the Upload button.
The web application stores the new photo and displays the photo gallery to
8.
the user.

Este ejemplo incluye los siguientes objetos, cada uno de los cuales requiere
una clase de modelo:

User. The User model class must include properties to store credentials, such
o
as the user name and the password.
Photo. The Photo model class must include the Title and Description
o
properties.

Other use cases similarly help you add new model classes or new properties to
the User and Photo model classes.

Domain Model and Logical Data Model Diagrams


Puede utilizar diagramas de modelo de dominio y diagramas de modelo de
datos lógicos (LDM) para analizar la información que gestiona su sitio web y
sugerir un modelo de datos físicos o un diseño de base de datos. Puede volver
a estos diagramas para planificar clases de modelo. Cada objeto en su modelo
de dominio o LDM diagrama debe implementarse como una clase de modelo
MVC. El diagrama del modelo de dominio incluye no sólo los nombres de
esas clases, sino también el diagrama LDM, si ha creado uno, con nombres de
propiedades y tipos de datos.

Relationships and Aggregates

Al identificar las clases de modelo que implementará en su sitio web, también


debe considerar las relaciones entre ellos. Por ejemplo, en el caso de uso de la
aplicación de intercambio de fotos de ejemplo, cada foto está asociada a uno y
sólo a un usuario. Esto se conoce como una relación uno a uno. Sin embargo,
cada usuario puede crear varias fotos. Esto se conoce como una relación uno-
a-muchos.

Los diagramas de modelo de dominio y los diagramas LDM incluyen


relaciones tales como vínculos entre objetos. Los números en los extremos de
cada enlace muestran si la relación es uno-a-uno, uno-a-muchos o muchos-a-
muchos.
Los agregados imponen más límites al comportamiento de las clases de
modelos y aclaran las relaciones. Por ejemplo, en una aplicación para
compartir fotos, una foto es creada por un solo usuario. Otros usuarios pueden
hacer comentarios múltiples en cada foto. Si un usuario elimina una foto,
todos los comentarios de esa foto también deben eliminarse de la base de
datos. Sin embargo, el usuario que creó la foto no debe borrarse con la foto
porque puede agregar otras fotos o comentarios en el sitio. En este caso, los
comentarios y las fotos deben colocarse en un agregado, pero los usuarios
deben estar fuera de los agregados. La foto es la "entidad raíz" del agregado.
Esto significa que al eliminar una foto se eliminan todos los comentarios
asociados, pero al eliminar un comentario no se suprime la foto asociada.

Entity Framework

Entity Framework es un marco de asignación de objetos relacional (ORM)


para aplicaciones basadas en .NET Framework. Un marco de ORM vincula
las tablas de la base de datos y las vistas contra las clases que un desarrollador
puede programar mediante la creación de instancias o métodos de llamada.
Entity Framework ha sido parte de ADO.NET desde .NET Framework 3.5.

Cuando utiliza Entity Framework en su aplicación web MVC, enlaza tablas y


vistas con las clases de modelo que ha planificado. No es necesario escribir
código SQL para consultar o actualizar tablas de base de datos porque Entity
Framework lo hace para usted. Entity Framework está bien integrado con el
lenguaje Language Integrated Query (LINQ).

Si planea utilizar Entity Framework para el acceso a datos, debe decidir cómo
se creará la base de datos durante la fase de planificación:

Database-First. Utilice Entity Framework en el modo de base de datos


cuando tenga una base de datos preexistente con la que trabajar. Esto puede
suceder porque ya tiene datos de un sistema anterior o porque un DBA ha
diseñado la base de datos para usted. También puede elegir este modo si está
familiarizado con la creación de bases de datos en una herramienta de
o
administración de bases de datos, como Microsoft SQL Server Management
Studio. Cuando utilice este modo, deberá especificar la cadena de conexión
de la base de datos. Entity Framework se conecta a la base de datos y
examina el esquema de la base de datos. Crea un conjunto de clases para su
uso para el acceso a datos.
Model-First. Utilice Entity Framework en el modo de model-first cuando no
tiene una base de datos preexistente y prefiera diseñar su modelo en Visual
Studio. Puede usar la herramienta Diseñador de entidades para nombrar,
o
configurar y vincular las clases de modelo. Esto crea archivos XML que
Entity Framework utiliza tanto para crear clases de modelo como para crear
la base de datos con sus tablas y relaciones.
Code-First. Utilice Entity Framework en el modo de código primero cuando
no tenga una base de datos preexistente y prefiera diseñar completamente
sus modelos en código C #. Su código debe incluir objetos DBContext y
o
DBSet, que corresponden a la base de datos y a sus tablas. Cuando ejecuta la
aplicación por primera vez, Entity Framework crea la base de datos para
usted.

Design in Agile and Extreme Programming

Agile and Extreme Programming projects are characterized by short design


phases in which data models are not completed. Instead, a simple design, with
little detail, is created and developers fill in details as they build code by
continuously discussing requirements with users and other stakeholders.

In an MVC project, this means that you identity the model names and
relationships during the design phase. You can record these on a Domain
Model UML diagram. However, you can leave details such as property names
and data types to be finalized in the development phase, along with the
complete LDM diagrams.

Entity Framework lets you work in the Agile or Extreme Programming styles.
For example, the framework can update the database when the model changes.
Alternatively, the framework can update the model when the database
changes. Entity Framework can perform these updates in any Entity
Framework mode.

Designing Controllers
En una aplicación web de ASP.NET MVC, los controladores son clases
basadas en .NET Framework que heredan de la clase base
System.Web.Mvc.Controller.

Implementan la lógica de entrada-esto significa que reciben entrada del


usuario en forma de solicitudes HTTP y seleccionan tanto el modelo y la vista
correctos para usar, como para formular una respuesta.

Identify Controllers and Actions

En una aplicación web ASP.NET MVC, normalmente hay un controlador para


cada clase de modelo.

Convencionalmente, si la clase del modelo se llama "Photo", el controlador se


llama "PhotoController".

Si sigue esta convención en su diseño, puede utilizar el comportamiento de


encaminamiento predeterminado de MVC para seleccionar el controlador
adecuado para una solicitud.
Sin embargo, para cada controlador puede haber muchas acciones, cada
acción se implementa como un método en el controlador y normalmente
devuelve una vista. A menudo requieren acciones separadas para los verbos de
solicitud GET y POST HTTP. Similar al diseño de un modelo, puede
identificar las acciones a escribir en cada controlador examinando los casos de
uso que recopiló durante el análisis. Por ejemplo, considere el siguiente caso
de uso compartido anteriormente.

1. The user clicks the Add Photo link on the main site menu.
If the user is anonymous, the logon page is shown and the user provides
2.
credentials.
3. If the credentials are correct, the CreatePhoto view is displayed.
4. The user types a title.
5. The user specifies the photo file to upload.
6. The user optionally types a description for the photo.
7. The user clicks the Upload button.
The web application stores the new photo and displays the photo gallery to
8.
the user.
Ya ha identificado las clases de modelo de Photo y user de este caso de uso.
Adhiriéndose a la convención MVC, debe crear un PhotoController y un
UserController. El caso de uso muestra que se necesitan las siguientes
acciones para cada controlador.

Controller Action Description

Photo AddPhoto The AddPhoto action for GET requests


(GET) creates a new instance of the Photo model
class, sets default values such as the created
date, and passes it to the correct view.

AddPhoto The AddPhoto action for POST requests


(POST) calls the Photo model class methods to save
the photo values to the database and
redirects the browser to the DisplayGallery
action.
Controller Action Description

DisplayGallery The DisplayGallery action for GET


(GET) requests displays all the photos stored in the
database.

User Logon (GET) The Logon action for GET requests


displays a view that an anonymous user can
enter credentials into.

Logon (POST) The Logon action for POST requests


checks user credentials against the
membership database. If the credentials are
correct, the Logon action authenticates and
redirects the user to the originally requested
page.

Design in Agile and Extreme Programming

Similar to the design of models, you will only make generalized plans for
controllers during the design phase of an Agile Development or Extreme
Programming project. Because you have identified the model classes
necessary, you can plan the required controllers. However, you should specify
only a few actions at this stage.
Designing Views

La interfaz de usuario es un componente vital de cualquier sistema, ya que es


la parte que los usuarios, los responsables del presupuesto y otras partes
interesadas ven e interactúan con ellos. Los usuarios están más interesados en
obtener esta parte de la aplicación correcta y con frecuencia tienen más que
decir acerca de su diseño. Como desarrollador, tiene la oportunidad de
impresionar a sus usuarios mediante el diseño y la implementación de una
interfaz de usuario sofisticada, lo que puede dar lugar a más negocios.

En una ASP.NET MVC Web aplication, la interfaz de usuario se crea


mediante vistas de construcción.

Views, Template Views, and Partial Views

Hay una relación de muchos a uno entre controladores MVC y vistas. Por
ejemplo, un controlador puede utilizar una vista para mostrar una sola foto,
otra vista para mostrar varias fotos y una tercera para permitir a los usuarios
subir fotos nuevas. Cada vista corresponde a una página web que la aplicación
puede mostrar al usuario, aunque puede mostrar datos diferentes. Por ejemplo,
la vista PhotoDetails puede mostrar diferentes fotos, dependiendo del
parámetro ID que se le pasa.

A medida que planifica vistas, también debe considerar partes de la interfaz de


usuario que aparecen en todas las páginas. Por ejemplo, es posible que el
logotipo de la empresa, el menú principal del sitio, los enlaces a información
legal y los controles de inicio de sesión aparezcan en cada página. Puede
colocar estos componentes de interfaz de usuario en una vista de plantilla para
crear una apariencia coherente entre las páginas.

Note: Template views in ASP.NET MVC web applications perform the same
role as master pages in ASP.NET Web Forms applications.

Algunos componentes de la interfaz de usuario no aparecen en todas las


páginas, pero se vuelven a utilizar en varias páginas. Por ejemplo, los
comentarios pueden mostrarse en una sola visualización de fotos, en la galería
o en otras páginas. Mediante la creación de una vista parcial, puede crear un
elemento de interfaz de usuario reutilizable que puede aparecer en muchas
ubicaciones de esta manera, sin duplicar el código.

Creating Wireframes

Una técnica común para discutir y planificar la interfaz de usuario para su


aplicación es crear diagramas wireframe. Estos son diseños simplificados que
muestran dónde aparecerán los elementos en las páginas web finales. Están
destinados a comunicar a los usuarios las partes funcionales esenciales de la
interfaz de usuario, pero no incluyen gráficos, logotipos o colores. No es
necesario crear un modelo wireframe para cada vista de la aplicación, pero
solo para las más importantes.

Puede comenzar un diagrama wireframe dibujándolo en una pizarra, en


conversación con un usuario. Muchas herramientas están disponibles para
crear versiones más formales; por ejemplo, Microsoft Visio tiene excelentes
capacidades de dibujo de wireframe.

Design in Agile and Extreme Programming

No se diseñan muchas partes de la interfaz de usuario durante las fases


iniciales de los proyectos de desarrollo agiles o de programación extrema. En
su lugar, diseñar vistas y vistas parciales en estrecha consulta con los usuarios
durante la fase de desarrollo. Esto se aplica incluso a la vista de plantilla que
muestra los componentes comunes de la interfaz de usuario, aunque es
probable que la vista de plantilla sea uno de los primeros componentes de
interfaz de usuario diseñados y creados. Se creará la vista de plantilla durante
las iteraciones tempranas de la fase de desarrollo del proyecto.

Module 03: Developing ASP.NET MVC 4 Models


Module Overview
La mayoría de las aplicaciones web necesitan interactuar con diversos tipos de
datos u objetos. Una aplicación de comercio electrónico, por ejemplo, ayuda a
administrar productos, carros de compras, clientes y pedidos. Una aplicación
de red social puede ayudar a administrar usuarios, actualizaciones de estado,
comentarios, fotos y vídeos. Un blog se utiliza para administrar entradas de
blog, comentarios, categorías y etiquetas. Cuando se escribe una aplicación
web MVC, se crea un modelo MVC para modelar los datos de la aplicación
web. Dentro de este modelo, se crea una clase de modelo para cada tipo de
objeto. La clase de modelo describe las propiedades de cada tipo de objeto y
puede incluir lógica de negocio que coincida con los procesos empresariales.
Por lo tanto, el modelo es un bloque de construcción fundamental en una
aplicación MVC y un buen lugar para comenzar cuando se escribe código.
Los modelos interactúan con el almacén de información que subyace a su
sitio, que suele ser una base de datos. Por lo tanto, es necesario comprender
técnicas y tecnologías de acceso a datos para escribir modelos. En este
módulo, verá cómo crear el código para los modelos y acceder a los datos
mediante Entity Framework y LINQ.

Objectives

After completing this module, you will be able to:

Agregue un modelo a una aplicación MVC y escriba código en él para


o
implementar la lógica empresarial.
Cree una nueva base de datos de SQL Azure para almacenar datos para la
o
aplicación web.
Lesson 1 : Creating MVC Models
Un modelo MVC es una colección de clases de .NET Framework. Cuando se
crea una clase de modelo, se definen las propiedades y los métodos que se
adaptan al tipo de objeto que describe la clase de modelo. Puede describir
estas propiedades en el código para que MVC pueda determinar cómo
procesarlas en una página web y cómo validar la entrada del usuario. Debe
saber cómo crear y describir modelos y cómo modificar la forma en que MVC
crea instancias de clase de modelo cuando ejecuta la aplicación web.

Lesson Objectives
After completing this lesson, you will be able to:

o Describir cómo crear modelos MVC y desarrollar una lógica empresarial.


Use el display y editar con data annotations para asignar atributos a vistas y
o
controladores.
o Validar entrada del usuario con data annotations.
o Descibir modelos binders.
o Describir modelo extensibility.
o Añadir un modelo a una MVC 4 web application.

Developing Models
Cada sitio web presenta información sobre varios tipos de objetos. En su
aplicación web, debe definir clases de modelo para estos objetos.

Cuando implementa un requisito funcional en su aplicación web, normalmente


comienza creando una clase de modelo. La clase de modelo probablemente se
revisará al crear el controlador y las vistas para el modelo y, posteriormente,
durante las iteraciones que se produzcan durante el proyecto. Si sigue el
modelo de Desarrollo Agile o Programación Extrema, comienza con un
simple entendimiento de la clase, quizás su nombre y algunas propiedades.
Luego, discute con los usuarios y agrega detalles a la clase de modelo
planificada con el conjunto completo de propiedades y sus relaciones con
otras clases. Al desarrollar el modelo, puede referirse a casos de uso o
historias de usuarios para asegurarse de que estos detalles del modelo son
correctos.

Cuando crea que entiende completamente los requisitos de un modelo, puede


escribir clases de modelo para implementar los requisitos. Las siguientes
líneas de código ilustran cómo crear una clase de ejemplo de modelo llamada
Photo.

Example Model Class


public class Photo

public int PhotoID { get; set; }

public string Title { get; set; }

public byte[] PhotoFile { get; set; }

public string Description { get; set; }

public DateTime CreatedDate { get; set; }

public string Owner { get; set; }

public virtual ICollection<Comment> Comments { get; set; }

Observe que la clase de modelo no hereda de ninguna otra clase. Además,


observe que ha creado propiedades públicas para cada propiedad en el modelo
e incluye el tipo de datos, como entero o cadena en la declaración. Puede crear
propiedades de sólo lectura omitiendo el set; palabra clave.

La clase Photo incluye una propiedad llamada Comments. Esto se declara


como una colección de objetos Comments e implementa un lado de la
relación entre fotos y comentarios.

Las siguientes líneas de código ilustran cómo puede implementar la clase de


modelo de Comment.

Comment Model Class

public class Comment

{
public int CommentID { get; set; }

public int PhotoID { get; set; }

public string UserName { get; set; }

public string Subject { get; set; }

public string Body { get; set; }

public virtual Photo Photo { get; set; }

Observe que la clase Comment incluye una propiedad PhotoID. Esta


propiedad almacena el ID de la Photo que el usuario comentó y enlaza el
comentario a una sola foto. Además, observe que la clase Comment incluye
una propiedad Photo, que devuelve el objeto Photo al que se refiere el
comentario. Estas propiedades implementan el otro lado de la relación entre
fotos y comentarios. Las instancias de clases de modelo suelen crearse en una
acción de controlador y se pasan a una vista para mostrar.

El siguiente ejemplo de código muestra cómo una acción de controlador


puede crear un nuevo objeto photo de la clase de modelo de photo y pasarlo
a la vista Display view.

Instantiating a Photo in a Controller Action

Photo newPhoto = new Photo();

newPhoto.Title = "This is an Example Photo";

newPhoto.Owner = User.Identity.Name;

newPhoto.CreatedDate = DateTime.Today;

return View("DisplayView", newPhoto);


En la vista Display, puede renderizar la propiedad Title de una foto utilizando
el objeto Model en el código Razor que escribe, como se muestra en el
siguiente código.

Rendering a Property from a Model Class

<div id="photo-title">

@Model.Title

</div>

Usando Display y Edit Data Annotations en


Propiedades

Las clases de modelo suelen especificar tres atributos para cada propiedad:

o El nombre de la propiedad, for example, Title


o El tipo de dato de la propiedad, for example, String
Nivel de acceso de la propiedad for example, the get and set keywords to
o
indicate read and write access
Además, mediante el uso de atributos, puede proporcionar metadatos
adicionales para describir las propiedades de ASP.NET MVC. El tiempo de
ejecución de MVC utiliza estos metadatos para determinar cómo procesar
cada propiedad en vistas para mostrar y editar. Estos atributos se denominan
visualización y edición de anotaciones.

Por ejemplo, los nombres de propiedad en C # no pueden contener espacios.


En una página web representada, es posible que desee incluir espacios en una
etiqueta de propiedad. Por ejemplo, es posible que desee representar una
propiedad denominada CreatedDate con la etiqueta Fecha de creación. Para
proporcionar a MVC esta información, puede utilizar la anotación
DisplayName.

Cuando usa MVC, puede indicar cómo desea que se nombre una propiedad en
una vista utilizando la anotación DisplayName, como ilustran las siguientes
líneas de código.

Configurando la Anotacion DisplayName

[DisplayName("Created Date")]

public CreatedDate { get; set; }

Si tiene una propiedad DateTime, puede utilizar mostrar y editar anotaciones


de datos para informar a MVC el formato en el que desea que se muestre la
propiedad.

En las siguientes líneas de código, la propiedad CreatedDate es un DateTime


y la anotación de datos DisplayFormat se utiliza para indicar a MVC que
sólo deben mostrarse los valores de día, mes y año.

Setting the DataType and DisplayFormat

[DisplayName("Created Date")]

[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yy}",

ApplyFormatInEditMode = true)]

public DateTime CreatedDate { get; set; }

Todas las anotaciones de datos que se proporcionan con ASP.NET MVC 4 se


incluyen en el namespace System.ComponentModel.DataAnnotations.

Additional Reading: To read more about all the data annotations provided
with MVC 4, see
http://go.microsoft.com/fwlink/?LinkID=288949&clcid=0x409

Question: In the code on the slide, how can you recognize the display and
edit annotations and distinguish them from other code?

Validacion de ingreso de Usuario con Data


Annotations
Puede utilizar anotaciones de datos en modelos MVC para establecer criterios
de validación para la entrada de usuario. Validación de entrada es el proceso
por el cual MVC comprueba los datos proporcionados por un usuario o una
solicitud web para asegurarse de que está en el formato correcto. El siguiente
ejemplo muestra un formulario de página web que recopila información del
usuario:

o Name. This is required input. The user must enter some data in this field.
o Height. This must be an integer between 0 and 400.
Email Address. This is required input. The value entered must be a valid
o
email address.

En el ejemplo siguiente, cuando el usuario envía el formulario, desea que


MVC cree una nueva instancia del modelo Person y lo use para almacenar los
datos en la base de datos. Sin embargo, desea asegurarse de que los datos son
válidos antes de ser almacenados.

Para asegurarse de que los datos son válidos, puede definir la clase de modelo
Person utilizando las siguientes líneas de código.
Using Validation Data Annotations

public class Person

public int PersonID { get; set; }

[Required]

public string Name { get; set; }

[Range(0, 400)]

public int Height { get; set; }

[Required]

[RegularExpression(".+\\@.+\\..+")]

public string EmailAddress { get; set; }

Las anotaciones Required, Range, StringLength y RegularExpression


implementan validación de entrada en MVC. Si los usuarios no introducen
datos que cumplan los criterios especificados para cada propiedad, la vista
muestra un mensaje de error estándar que solicita al usuario que introduzca los
datos correctos. En el ejemplo anterior, puede ver que el usuario debe ingresar
un Name y una altura o Height entre 0 y 400. Para la propiedad
EmailAddress, el usuario debe ingresar un valor que coincida con la
expresión regular. La expresión regular en el ejemplo es una expresión simple
que requiere un símbolo @ y un punto.

Para especificar el mensaje de error que el usuario ve cuando los datos no son
válidos, puede utilizar la propiedad ErrorMessage en las anotaciones de
datos de validación, como ilustra el siguiente código.

Setting a Validation Error Message


[Required(ErrorMessage="Please enter a name.")]

public string Name { get; set; }

Note: You will see how to ensure that the validation error message is
displayed in a view.

Additional Reading: For more examples of validation data annotations see


http://go.microsoft.com/fwlink/?LinkID=288950&clcid=0x409

Additional Reading: For more information about the regular expressions that
you can use to check user input, see
http://go.microsoft.com/fwlink/?LinkID=288951&clcid=0x409

Question: You want to ensure that users enter a password that is longer than
six characters. How should you do this by using a validation data annotation?

What Are Model Binders?

Un model binder es un componente de una aplicación ASP.NET MVC que


crea una instancia de una clase de modelo, basada en los datos enviados en la
solicitud desde el navegador web. ASP.NET MVC incluye un model binder
predeterminado que satisface las necesidades de la mayoría de las aplicaciones
web. Sin embargo, debe saber cómo funciona el conector de modelo
predeterminado con otros componentes para utilizarlo correctamente.
Además, puede elegir crear un model binder personalizado para situaciones
avanzadas.

Que hace Model Binder?

Un model binder asegura que los datos correctos se envían a los parámetros en
un método de acción del controlador. Esto permite a MVC crear instancias de
clases de modelo que satisfagan la solicitud del usuario. El model binder por
defecto, por ejemplo, examina tanto la definición de los parámetros de acción
del controlador como los parámetros de solicitud para determinar qué valores
de petición se pasarán a qué parámetro de acción.

Este proceso de model binder o vinculador puede ahorrar a los desarrolladores


mucho tiempo y evitar muchos errores de tiempo de ejecución inesperados
que surgen de parámetros incorrectos. MVC incluye un model binder por
defecto con lógica sofisticada que pasa parámetros correctamente en casi
todos los casos sin código personalizado complejo.

El Controlador Action Invoker y Model Binder por defecto

Para entender el proceso predeterminado model binding por defecto, considere


la siguiente solicitud desde un navegador web:

http://www.adventureworks.com/product/display/45

Esta solicitud identifica tres aspectos:

La clase de modelo que interesa al usuario. El usuario ha solicitado un


o
producto.
La operación a realizar en la clase de modelo. El usuario ha solicitado que se
o
muestre el producto.
La instancia específica de la clase de modelo. El usuario ha solicitado que se
o
muestre el producto con ID 45.

La petición es recibida por un objeto denominado el invocador de la acción


del controlador. El invocador de acción del controlador del tiempo de
ejecución MVC llama a una acción del controlador y le pasa los parámetros
correctos. En el ejemplo, el invocador de acciones llama a la acción Display
en el controlador de Product y pasa la ID "45" como un parámetro a la
acción, para que se muestre el producto correcto.

La clase ControllerActionInvoker Es el invocador de acción por defecto.


Este invocador de acciones utiliza model binder para determinar cómo se
pasan los parámetros a las acciones.

Como el Model Binder por defecto pasa los Parametros

En una aplicación MVC predeterminada, sólo hay un model binder para que
utilice ControllerActionInvoker. Este enlace es una instancia de la clase
DefaultModelBinder. El model binder por defecto pasa los parámetros
utilizando la lógica siguiente:

El vinculador o binder examina la definición de la acción a la que debe


1. pasar los parámetros. En el ejemplo, el vinculador o binder determina que
la acción requiere un parámetro entero llamado PhotoID.
El vinculador o binder busca valores en la solicitud que se pueden pasar
como parámetros. En el ejemplo, el binder busca enteros porque la acción
requiere un entero. El binder busca valores en las siguientes ubicaciones, en
orden:

Form Values. Si el usuario rellena un formulario y hace clic en un botón


a.
de envío, puede encontrar parámetros en la colección Request.Form.
Route Values. Dependiendo de las rutas que haya definido en su
2. aplicación web, el modelo binder puede ser capaz de identificar los
b.
parámetros en la URL. En la URL de ejemplo, "45" se identifica como un
parámetro por la ruta MVC predeterminada.
Query Strings. Si la solicitud del usuario incluye parámetros nombrados
c. después de un signo de interrogación, puede encontrar estos parámetros
en la colección Request.QueryString
Files. Si la solicitud del usuario incluye archivos cargados, éstos se
d.
pueden utilizar como parámetros.
Observe que si hay valores de formulario y valores de ruta en la solicitud, los
valores de formulario tienen prioridad. Los valores de cadena de consulta sólo
se utilizan si no hay valores de formulario y no hay valores de ruta disponibles
como parámetros.

Model Extensibility

La arquitectura MVC ha sido diseñada para proporcionar extensibilidad para


que los desarrolladores puedan adaptar la arquitectura a requisitos inusuales o
únicos. Por ejemplo, el invocador de acciones predeterminado,
ControllerActionInvoker, puede ser reemplazado por su propio invocador de
acción si desea implementar su propia lógica de invocación.

Dos maneras en las que puede ampliar el manejo MVC de los modelos MVC
son crear data annotations personalizadas y model binders personalizados.

Validacion Personalizada de Data Annotations

Puede utilizar anotaciones de datos para indicar a MVC cómo validar los
datos que un usuario ingresa en un formulario o pasa en query strings. Los
cuatro atributos de validación incorporados en MVC 4, Required, Range,
StringLength y RegularExpression, son muy flexibles. Sin embargo, en
algunas situaciones, como los ejemplos siguientes, puede que desee ejecutar
algún código de validación personalizado:

Ejecución de una comprobación de almacén de datos. Desea comprobar los


o datos introducidos con datos que ya se han almacenado en la base de datos o
en otro almacén de base de datos.
o Comparación de valores. Desea comparar dos valores introducidos entre sí.
Comprobaciones Matemáticas. Desea calcular un valor a partir de los datos
o
introducidos y comprobar que el valor es válido.

En estas situaciones, puede crear una validación personalizada data


annotation. Para ello, crea una clase que hereda de la clase
System.ComponentModel.DataAnnotations.ValidationAttribute.

Las siguientes líneas de código ilustran cómo crear una validación


personalizada de data annotation.

Creating Custom Validation Data Annotation

[AttributeUsage(AttributeTargets.Field)]

public class LargerThanValidationAttribute : ValidationAttribute

public int MinimumValue { get; set; }

//Constructor

public LargerThanValidationAttribute (int minimum)

MinimumValue = minimum;

//You must override the IsValid method to run your test


public override Boolean IsValid (Object value)

var valueToCompare = (int)value;

if (valueToCompare > MinimumValue)

return true;

else

return false;

Después de haber creado un atributo de datos de validación personalizado,


puede utilizarlo para anotar una propiedad en su modelo, como ilustran las
siguientes líneas de código.

Usando una Validacion Personalizada de Data Annotation

[LargerThanValidationAttribute(18)]

public VoterAge { get; set; }

Custom Model Binders

El controlador predeterminado action invoker recibe solicitudes y llama a la


acción correcta en el controlador adecuado para cumplir con la solicitud. El
action invoker por defecto utiliza los model binders para identificar los
parámetros en la solicitud y los pasa a los parámetros correctos en la acción.
Este mecanismo garantiza que las cadenas de consulta, los valores de ruta, los
valores de formulario y los archivos subidos estén disponibles para que la
acción funcione.

El model binder por defecto es sofisticado y flexible, pero a veces, puede que
desee personalizar su comportamiento para pasar parámetros de una manera
inusual. Puede hacerlo creando un Model binder personalizado y registrándolo
con el tiempo de ejecución MVC.

Las siguientes líneas de código muestran cómo crear un Model Binder


personalizado sencillo para pasar parámetros de la colección de formularios
mediante la implementación de la interfaz IModelBinder.

A Simple Custom Model Binder

public class CarModelBinder : IModelBinder

public object BindModel (ControllerContext controllerContext,

ModelBindingContext bindingContext)

//Get the color for the car from the request form

string color =

controllerContext.HttpContext.Request.Form["color"];

//Get the brand for the car from the request form

string brand=

controllerContext.HttpContext.Request.Form["brand"];

//Create a new instance of the car model


Car newCar = new Car();

newCar.color = color;

newCar.brand = brand;

//return the car

return newCar;

El ejemplo de código supone que tiene una clase de modelo en su aplicación


MVC denominada Car. También supone que cualquier solicitud de un objeto
Car incluye valores de color y marca (Brand) en la colección de formularios.
Esta situación puede ser manejada fácilmente por el model binder
predeterminado. Sin embargo, este ejemplo demuestra cómo los model
binders pueden localizar valores desde el contexto de la solicitud y pasar esos
valores a las propiedades correctas en el modelo. Puede agregar código
personalizado para implementar funcionalidad adicional.

Additional Reading: You can see more examples of custom model binders at
the following locations:

o http://go.microsoft.com/fwlink/?LinkID=288952&clcid=0x409
o http://go.microsoft.com/fwlink/?LinkID=288953&clcid=0x409

Question: You want to ensure that when a user types a value into the Car
Model Number box when adding a new car to the website, the text entered is
not already used by another car in the database. Would you use a custom
validation data annotation or a custom model binder for this?

Lesson 2: Working with Data


Todas las aplicaciones web presentan información y casi todas las
aplicaciones web requieren un almacén de datos para esa información. Al
convertir páginas web utilizando datos de un almacén de datos, puede crear
una aplicación web que cambie continuamente en respuesta a la entrada de
usuarios, acciones administrativas y eventos de publicación. El almacén de
datos suele ser una base de datos, pero otros almacenes de datos se utilizan
ocasionalmente. En aplicaciones MVC, puede crear un modelo que
implemente lógica de acceso a datos y lógica negocio. Como alternativa,
puede separar la lógica de negocio, en clases de modelo, de la lógica de
acceso a datos, en un repositorio. Un repositorio es una clase que un
controlador puede llamar para leer y escribir datos desde y hacia un almacén
de datos. El Framework .NET incluye el Entity Framework y las tecnologías
LINQ, que hacen que el código de acceso a datos sea muy rápido de escribir y
fácil de entender. Además, verá cómo crear un sitio web basado en bases de
datos en MVC.

Lesson Objectives
After completing this lesson, you will be able to:

o Conectar una aplicación a una base de datos para acceder y almacenar datos.
o Describir las características del Entity Framework.
o Utilice LINQ para escribir consultas para seleccionar, filtrar y agrupar datos.
Cree clases de modelo independientes y correspondientes clases de
o
repositorio utilizando el código de Entity Framework.
o Explicar cómo acceder a los datos en modelos y repositorios.

Connecting to a Database
La mayoría de los sitios web utilizan una base de datos para almacenar datos
dinámicos. Al incluir estos datos en páginas HTML procesadas, puede crear
una aplicación web dinámica con contenido que cambia con frecuencia. Por
ejemplo, puede proporcionar páginas web administrativas que permitan a los
empleados de la compañía actualizar el catálogo de productos y publicar
noticias. Los productos y elementos se almacenan en la base de datos. Tan
pronto como se almacenan, los usuarios pueden verlos y leerlos. Los
empleados no necesitan editar HTML o volver a publicar el sitio web para que
sus cambios sean visibles.

Algunos sitios web pueden almacenar datos en otras ubicaciones, como un


servicio de directorio, pero las bases de datos son el almacén de datos más
utilizado.

ADO.NET and Databases

Cuando crea aplicaciones .NET Framework, incluidas las aplicaciones web


MVC, puede utilizar la tecnología ADO.NET para acceder a las bases de
datos. Las clases de ADO.NET están contenidas en el namespace ADO.NET
System.Data. admite una amplia gama de bases de datos utilizando diferentes
proveedores de datos. Por ejemplo:

Microsoft SQL Server. Este es un servidor de base de datos líder en la


o industria de Microsoft. ADO.NET incluye el proveedor SqlClient para todas
las bases de datos de SQL Server.
Microsoft SQL Server Express. Esta es una versión gratuita de SQL Server
que incluye una amplia gama de funcionalidad de base de datos y es muy
o flexible. Algunas capacidades avanzadas, como el clustering de bases de
datos, no son posibles con SQL Express. El proveedor SqlClient se utiliza
para SQL Express.
Microsoft SQL Server Compact. Esta versión de SQL también es gratuita y
o utiliza archivos .sdf para almacenar datos en el disco duro. ADO.NET
incluye el proveedor SqlServerCe para las bases de datos de SQL Compact.
Oracle Databases. Este es un servidor de base de datos ampliamente
o utilizado. ADO.NET incluye el proveedor OracleClient para todas las bases
de datos de Oracle.
o OLE DB. Este es un estándar al que se adhieren muchas bases de datos
diferentes. ADO.NET incluye el proveedor OleDb para todas las bases de
datos OLE DB.
ODBC. Este es otro estándar más antiguo que muchas bases de datos
diferentes se adhieren a. ADO.NET incluye el proveedor Odbc para todas
o
las bases de datos ODBC. En general, debe utilizar un proveedor de OLE
DB, si está disponible, en lugar de un proveedor de ODBC.

También puede utilizar proveedores ADO.NET de terceros para acceder a


otras bases de datos.

Cloud Databases

La base de datos de una aplicación web se encuentra normalmente en el


mismo servidor que la propia aplicación web o en un servidor de base de datos
dedicado en el mismo sitio físico. Sin embargo, si tiene una conexión a
Internet rápida y fiable, puede considerar utilizar una base de datos en la nube.
Además, si ha elegido alojar una aplicación Web en la nube, una base de datos
en la nube es una solución de almacenamiento lógico. El servicio de base de
datos en la nube de Microsoft se denomina SQL Database y forma parte de
Windows Azure.

Windows Azure SQL Database tiene las siguientes ventajas:

Databases run in Microsoft data centers with the best connectivity and
o
reliability.
o Microsoft guarantees up to 99% uptime.
You do not need to build and maintain your own database servers or employ
o
database administrators.
o You can scale up the databases very easily.
o You pay only for the data that you use and distribute.

You can use Windows Azure SQL Database with ADO.NET by using the
SqlClient provider.

Connecting an MVC Web Application to a Database

Para utilizar ADO.NET y conectarse a una base de datos, debe agregar dos
elementos a su aplicación:
o Adicionar una reference a el namespace System.Data.
Agregue una cadena de conexión al archivo Web.config. Esta cadena
o especifica el proveedor, la ubicación de la base de datos, las propiedades de
seguridad y otras propiedades dependiendo del proveedor.

El siguiente marcado muestra cómo agregar una cadena de conexión a


Web.config para conectarse a una base de datos de SQL Express denominada
PhotoSharingDB utilizando las credenciales en las que se ejecuta la aplicación
web.

Connecting to SQL Express

<connectionStrings>

<add name="PhotoSharingDB"

connectionString="Data Source=.\SQLEXPRESS;Initial

Catalog=PhotoSharingDB;" +

"Integrated Security=SSPI"

providerName="System.Data.SqlClient"/>

</connectionStrings>

La siguiente cadena de conexión se conecta a una base de datos en Windows


Azure SQL database.

Connecting to Windows Azure SQL Database

<connectionStrings>

<add name="PhotoSharingDB"

connectionString="Server=tcp:example.database.windows.net,1433;Databas

e=PhotoSharingDB;"
+ "User ID=Admin@example;Password=Pa$$w0rd;Trusted_Connection=False;"

+ "Encrypt=True;Connection Timeout=30;PersistSecurityInfo=true"

providerName="System.Data.SqlClient"/>

</connectionStrings>

La etiqueta <connectionStrings> debe aparecer dentro de la etiqueta


<configuration>, después de la etiqueta <configSections>.

Additional Reading: The MVC web application templates in Microsoft Visual


Studio 2012 include ADO.NET references so you need not add them.
However, you must add connection strings. Some of the templates, such as
the Internet site template, include SQL Server Express membership
databases with connection strings.

The Entity Framework

Analice las bases de datos ejecutando consultas Transact-SQL. Puede elegir


crear y ejecutar consultas Transact-SQL en su código ADO.NET. Sin
embargo, ADO.NET incluye el Entity Framework-esta tecnología le permite
leer y escribir datos y desde una base de datos utilizando clases y objetos.
Entity Framework es un marco de asignación de objetos relacional (ORM).
Un marco ORM asigna las tablas y columnas encontradas en una base de
datos a los objetos y sus propiedades que se pueden llamar desde el código
.NET.

Entity Framework Workflows

La forma en que utiliza Entity Framework en su aplicación depende de la


forma en la que desea crear su base de datos. Los tres flujos de trabajo de
Entity Framework disponibles son database-first, model-first, and code-first:

Database First. Puede utilizar el database-first workflow cuando tiene una


base de datos preexistente o si prefiere crear una nueva base de datos
definiendo tablas, columnas, vistas y otros objetos de esquema de base de
datos. En este flujo de trabajo, Entity Framework examina la base de datos y
o
crea un archivo XML con una extensión .edmx denominada archivo de
modelo. El archivo de modelo describe las clases con las que podrá trabajar,
en código. Puede ajustar el modelo utilizando un diseñador en Visual Studio
y escribiendo código en contra de las clases de Entity Framework.
Model First. Puede utilizar el flujo de trabajo de model-first cuando todavía
no tiene una base de datos y prefiere diseñar su modelo utilizando una
herramienta de modelado de ORM. En este flujo de trabajo, crea el archivo
.edmx en el diseñador de Visual Studio y, a continuación, escribe código en
o contra de las clases de modelo generadas por el diseñador. Cuando ejecuta la
aplicación, Entity Framework crea las tablas y columnas de la base de datos
para admitir el modelo. En este flujo de trabajo, Visual Studio también
puede crear una cadena de conexión para usted e insertarla en Web.config,
en función de la base de datos que especifique.
Code First. Puede utilizar el flujo de trabajo de código primero si prefiere
crear un modelo escribiendo clases de .NET Framework. En este flujo de
o trabajo, no hay ningún archivo de modelo. En su lugar, se crean clases de
modelo en C # o Visual Basic. Al ejecutar la aplicación, Entity Framework
crea la base de datos.

Adding an Entity Framework Context

Cuando utiliza Entity Framework en el flujo de trabajo de código primero,


debe asegurarse de que el marco de trabajo crea la base de datos correcta y las
tablas para almacenar las clases de modelo. Para ello, cree una clase que
hereda la clase Entity Framework DbContext. Utilizará esta clase en los
controladores cuando desee manipular datos en la base de datos. Dentro de
esta clase, agregue una propiedad DbSet <> para cada tabla de base de datos
que desea que Entity Framework cree en la nueva base de datos.

El código siguiente muestra cómo agregar un contexto de Entity Framework a


su modelo.

An Entity Framework Context Class

public class PhotoSharingDB : DbContext

public DbSet<Photo> Photos { get; set; }

public DbSet<Comment> Comments { get; set; }

En el ejemplo anterior, Entity Framework busca una cadena de conexión con


el nombre, PhotoSharingDB, para que coincida con el nombre de la clase
DbContext. Entity Framework crea la base de datos en la ubicación que
proporciona la cadena de conexión y crea dos tablas en la nueva base de datos:

Photos: Esta tabla tendrá columnas que coinciden con las propiedades de la
o
clase modelo Photo.
Comments: Esta tabla tendrá columnas que coinciden con las propiedades
o
de la clase de modelo Comment.

Question: You have a Microsoft Visio diagram, which a business analyst


created that shows all the model classes for your web application and their
relationships. You want to re-create this diagram in Visual Studio. Which
Entity Framework workflow should you use?

Using an Entity Framework Context


Ahora que ha definido Entity Framework context y las clases modelo, puede
utilizarlas en controladores MVC para pasar datos a las vistas para su
visualización.

El siguiente código muestra cómo utilizar el contexto Entity Framework en un


controlador para pasar una sola foto o una colección de fotografías a las vistas.

Using an Entity Framework Context in a Controller

public class PhotoController : Controller

//Creating a reference to the Entity

Framework context class

private PhotoSharingDB db = new PhotoSharingDB();

//This action gets all the photos in the database and passes them

to the Index view


public ActionResult Index()

return View("Index", db.Photos.ToList());

//This action gets a photo with a particular ID and passes it to

the Details view

public ActionResult Details(int id = 0)

Photo photo = db.Photos.Find(id);

if (photo == null)

return HttpNotFound();

return View("Details", photo);

Utilizar Inicializadores para poblar bases de datos

Si está utilizando el flujo de trabajo de código primero o modelo primero,


Entity Framework crea la base de datos la primera vez que ejecuta la
aplicación y los datos de acceso. La base de datos permanecerá vacía si ha
creado el esquema de base de datos pero no lo ha completado con filas de
datos.

Puede utilizar una clase de inicializador para poblar la base de datos con datos
de ejemplo. Esta técnica asegura que haya datos de muestra con los que
trabajar, durante el desarrollo.

Las siguientes líneas de código muestran cómo crear una clase de inicializador
que añade dos objetos Photo a la tabla Fotos de la base de datos.
An Example Entity Framework Initializer

public class PhotoSharingInitializer : DropCreateDatabaseAlways

<PhotoSharingDB>

//Override the Seed method to populate the database

protected override void Seed(PhotoSharingDB context)

//Create a list of Photo objects

var photos = new List<Photo>

new Photo {

Title = "My First Photo",

Description = "This is part of the sample data",

UserName = "Fred"

},

new Photo {

Title = "My Second Photo",

Description = "This is part of the sample data",

UserName = "Sue"

};
//Add the list of photos to the database and save changes

photos.ForEach(s => context.Photos.Add(s));

context.SaveChanges();

Después de haber creado un inicializador, debe asegurarse de que se ejecuta


agregando una línea de código al archivo Global.asax en el método
Application_Start, como ilustra el siguiente ejemplo.

Running the Initializer in Global.asax

protected void Application_Start()

//Seed the database with sample data for development. This code

should be removed for production.

Database.SetInitializer<PhotoSharingDB>(new

PhotoSharingInitializer());

Question: You have created an Entity Framework context class in your


model, added an initialize, and called Database.SetInitializer() from
Global.asax. When you run the application, no database is created and no
model objects displayed on the webpages. What have you forgotten to do?
Using LINQ to Entities

Language Integrated Query (LINQ) es un conjunto de extensiones de Visual C


# y Visual Basic que le permiten escribir expresiones de consulta complejas.

Puede utilizar estas expresiones para extraer datos de bases de datos, objetos
enumerables, documentos XML y otras fuentes de datos. Las expresiones son
similares a las consultas de Transact-SQL, pero utilizan palabras clave C # o
VB para que pueda obtener compatibilidad con IntelliSense y comprobación
de errores en Visual Studio.

What Is LINQ to Entities?


LINQ para Entities es la versión de LINQ que funciona con Entity
Framework. LINQ para Entities le permite escribir consultas complejas y
sofisticadas para localizar datos específicos, unir datos de varios objetos,
actualizar datos y tomar otras acciones en objetos desde un contexto de Entity
Framework. Si utiliza Entity Framework, puede escribir consultas LINQ
donde quiera que necesite una instancia específica de una clase de modelo, un
conjunto de objetos o para necesidades de aplicaciones más complejas. Puede
escribir consultas LINQ en la sintaxis de consulta, que se asemeja a la sintaxis
SQL o sintaxis del método, en el que operaciones como "select" se llaman
como métodos en objetos.

Example LINQ Queries


En las siguientes líneas de código, puede ver cómo obtener una lista de las
fotos más recientes en la base de datos. Se incluyen ejemplos de sintaxis de
consulta y de sintaxis de métodos.

Using LINQ to Get Recent Photos

//This list will store the photos that are returned

List<Photo> photos;

//This is the Entity Framework context

PhotoSharingDB context = new PhotoSharingDB();

if (number == 0)

//If a number of photos is not specified, we’ll get all the photos

in the database

//This example is in method syntax.

photos = context.Photos.ToList();

else

//The number specifies how many of the most recent photos the user

requests

//Use a LINQ query with both query and method syntax to get these

from the database

photos = (from p in context.Photos


orderby p.CreatedDate descending

select p).Take(number).ToList();

Additional Reading: To read many more example LINQ queries, see


http://go.microsoft.com/fwlink/?LinkID=288954&clcid=0x409

Data Access in Models and Repositories

En aplicaciones MVC, puede colocar el código de acceso a datos en el


modelo, junto con la lógica de negocio. Sin embargo, muchos arquitectos de
software prefieren separar estos dos tipos de código porque cumplen
diferentes propósitos:

Lógica de negocios. Este código define los objetos que administran la


o
aplicación web, sus propiedades y sus relaciones entre sí.
Lógica de acceso a datos. Este código define las operaciones necesarias para
persistir datos en una base de datos. Esto incluye operaciones para crear
o
nuevos registros, leer registros, actualizar registros y eliminar registros en
tablas de base de datos. Un único objeto en la capa de lógica de negocios
puede tomar datos de varias tablas de base de datos. Esta abstracción es
manejada por la lógica de acceso a datos.

MVC no requiere que separe la lógica de acceso de datos y negocio, y puede


crear clases de modelo MVC que implementen ambas capas. Esto se hace a
menudo en pequeñas o simples aplicaciones web con pequeños equipos de
desarrollo. En estos escenarios, las clases de Entity Framework se utilizan
directamente en las clases de modelo.

En situaciones más complejas, es necesario colocar la lógica de negocio en las


clases de modelo MVC y colocar la lógica de acceso a datos en clases
dedicadas llamadas repositorios. Cuando adopta este enfoque, las clases de
modelo son independientes de la estructura de la base de datos y no incluyen
el código que depende de nombres de tablas de bases de datos, nombres de
columnas o nombres de vistas. Este enfoque facilita el rediseño de la base de
datos o el traslado a un almacén de datos o tecnología de acceso a datos
diferentes, sin necesidad de volver a codificar toda la aplicación. Utilizando
este enfoque, emplea Entity Framework en sus clases de repositorio, pero no
en sus clases de modelo.

How to Separate Model Classes and Repositories

Si elige separar lógica negocio y lógica de acceso a datos, debe seguir los
siguientes pasos para cada clase de modelo:

Defina una interfaz para la clase de repositorio. Esta interfaz declara los
1. métodos que usa la clase de repositorio para leer y escribir datos desde y
hacia la base de datos.
Cree y escriba código para la clase de repositorio. Esta clase debe
2.
implementar todos los métodos de acceso a datos declarados en la interfaz.
3. Quite todo el código de acceso de datos de la clase de modelo.
Modifique la clase del controlador para usar la clase del repositorio. En su
4. lugar, cree una instancia de la clase de repositorio y llame a sus métodos
para crear el modelo.

A Simple Example Model Class and Repository Class

Para ilustrar cómo separar clases de modelo y clases de repositorio, los


siguientes ejemplos implementan un comentario en una foto.
La clase de modelo de comentarios ayuda a los usuarios a comentar una foto,
como ilustran las siguientes líneas de código.

The Comment Model Class

public class Comment

public int CommentID { get; set; }

public int PhotoID { get; set; }

public string CommentText { get; set; }

public virtual Photo Photo { get; set; }

Esta interfaz para una clase de repositorio de comentarios define sólo un


método para obtener los comentarios de una foto dada, como ilustran las
siguientes líneas de código.

The ICommentRepository Interface

public interface ICommentRepository {

ICollection<Comment> GetComments (int PhotoID);

La clase CommentRepository implementa el método GetComments como


ilustran las siguientes líneas de código.

The CommentRepository Class

public class CommentRepository : ICommentRepository

{
public ICollection<Comment> GetComments(int PhotoID)

//Implement entity framework calls here.

La clase CommentsController utiliza la clase de repositorio, en lugar de


llamar a los métodos de Entity Framework, como ilustran las siguientes líneas
de código.

The CommentsController Class

public class CommentsController : Controller

ICommentRepository commentRepository = new CommentRepository;

public ActionResult DisplayCommentsForPhoto (int PhotoID)

//Use the repository to get the comments

ICollection<Comments> comments =

commentRepository.GetComments(PhotoID);

return View("DisplayComments", comments);

}
Note: By using the ICommentRepository interface, the code makes it easy to
replace CommentRespository with another implementation if you need to.
However, the CommentController code still creates a CommentRespository
object. You have to modify the object to make the replacement.

En una arquitectura aún mejor, puede reemplazar CommentRepository con


una implementación diferente de ICommentRepository sin ningún cambio en
la clase CommentController. Este es un enfoque extremadamente flexible y
adaptable y se llama una arquitectura ligeramente acoplada.

Las arquitecturas ligeramente acopladas también son esenciales para las


pruebas unitarias.

Module 04: Developing ASP.NET MVC 4


Controllers

Module Overview
Lo controladores MVC responden a las peticiones del navegador, crear
objetos de modelo, y los pasan a las vistas para la prestación y mostrar en el
navegador web. Si es necesario, los controladores también pueden realizar
otras acciones, como guardar los cambios de clase modelo a la base de datos.
Los controladores son fundamentales para aplicaciones MVC. Es necesario
comprender el funcionamiento de los controladores que ser capaz de crear los
objetos del modelo de correctos, manipularlos, y pasarlos a los puntos de vista
correctos.

Para maximizar la reutilización de código en los controladores, debe saber


cómo programar filtros de acción. Puede utilizar filtros de acción para ejecutar
código antes o después de cada acción en su aplicación web, en cada acción
en un controlador, o en otras combinaciones de acciones del controlador.

Objectives

Después de completar este módulo, el alumno será capaz de:

Agregar un controlador a una aplicación Web que responde a las acciones de


o
usuario especificadas en el diseño del proyecto.
Escribir código en filtros de acción que se ejecuta antes o después de una
o
acción del controlador.

Lesson 1 : Writing Controllers and Actions


Un controlador es una clase de .NET Framework que hereda de la clase base
System.Web.Mvc.Controller. Los controladores responden a las peticiones
de los usuarios. Dentro de una clase de controlador, crea acciones para
responder a solicitudes de usuario. Las acciones son métodos dentro de un
controlador que devuelven un objeto ActionResult. El objeto ActionResult es
a menudo una vista que muestra una respuesta a la solicitud del usuario; Sin
embargo, también puede producir otros tipos de resultados. Para procesar las
solicitudes de los usuarios entrantes, administrar la entrada y las interacciones
del usuario, e implementar la lógica de la aplicación relevante, necesita saber
cómo crear controladores y acciones. También debe saber cómo crear
parámetros en bloques de código de acción y pasar objetos a acciones.

Lesson Objectives
Después de completar esta lección, usted podrá:

Describir cómo un controlador responde a las acciones del usuario en una


o
aplicación web MVC 4.
Escribir acciones de controlador para responder a solicitudes de navegador
o
web, crear clases de modelo y vistas de llamada.
Explicar cómo utilizar los parámetros pasados en una solicitud de navegador
o a una acción de controlador y utilizarlos para cambiar el resultado de la
acción.
o Explicar cómo pasar información a las vistas que tienen clases de modelo.
o Crear un controlador y acciones.
o Describir las fábricas del controlador.
Respondiendo a solictudes de Usuario

Cuando una aplicación web MVC recibe una solicitud de un navegador web,
los sucesos siguientes ocurren en secuencia:

Un objeto MvcHandler crea una fábrica de controlador. La fábrica del


controlador es el objeto que instancia un controlador para responder a la
solicitud. Por lo general, esta fábrica es un objeto
1. DefaultControllerFactory, pero puede crear una fábrica de controlador
personalizado, si es necesario. El objeto MvcHandler elige la fábrica del
controlador basada en el objeto RequestContext, que tiene información
sobre la solicitud que realizó el usuario.
La fábrica del controlador crea un objeto Controler y el MvcHandler
2.
llama al método Execute en ese controlador.
ControllerActionInvoker examina el objeto RequestContext y determina
3.
la acción a llamar en el objeto Controller.
El ControllerActionInvoker utiliza un model Binder para determinar los
4.
valores que se pasan a la acción como parámetros.
El ControllerActionInvoker ejecuta la acción. A menudo, la acción crea
5.
una nueva instancia de una clase de modelo, tal vez consultando la base de
datos con los parámetros que el invocador le pasó. Este objeto modelo se
pasa a una vista, para mostrar los resultados al usuario. Los métodos de
acción pueden hacer muchas otras cosas, como renderizar vistas y vistas
parciales, redirigir a otros sitios web, mostrar fragmentos de contenido o
mostrar otros archivos.

Note: The routing engine determines which controller and action receives a
request. Routing is not covered in this section.

La Solictud del usuario

Los usuarios de los navegadores web realizan solicitudes escribiendo una


URL en la barra de direcciones del navegador o haciendo clic en un enlace a
alguna dirección de su sitio web. Dichos enlaces pueden estar dentro de su
sitio web, en cuyo caso puede controlar cómo se procesan, o desde un sitio
web externo. Si la solicitud se origina en el sitio web o desde un sitio web
externo, puede incluir información que las acciones del controlador pueden
utilizar como parámetros. Considere los siguientes ejemplos:

http://www.adventureworks.com/: Esta URL es la página principal del sitio


o
web y no especifica más información.
http://www.adventureworks.com/photo: Esta URL especifica un valor
o adicional, Photo. De forma predeterminada, el MvcHandler interpreta esto
como el nombre de un controlador.
http://www.adventureworks.com/photo/index: Esta URL especifica un
o segundo valor, índex. De forma predeterminada, el MvcHandler interpreta
esto como el nombre de una acción dentro del controlador.
http://www.adventureworks.com/photo/display/1: Esta URL especifica un
o tercer valor, 1. De forma predeterminada, ControllerActionInvoker
interpreta esto como un parámetro para pasar al método de acción.
http://www.adventureworks.com/photo/display?id=1: Esta URL incluye una
cadena de consulta, id = 1. El model Binder examina las acciones de
o Visualización en el Photo controller. Si encuentra una acción con un
parámetro llamado id, llama a esa acción y pasa 1 como un parámetro.

Note: You can modify the preceding logic in several ways. For example,
you can create routes that interpret the preceding URLs differently. The
examples are true when only the default route exists.

Consideremos que un usuario solicita un controlador llamado photo,


escribiendo la URL en la barra de direcciones de un navegador web. De forma
predeterminada, MVC DefaultControllerFactory, nombra esta clase de
controlador como PhotoController. Debe cumplir con esta convención al
crear y nombrar controladores. De lo contrario, recibirá errores 404
inesperados y los controladores no funcionarán según lo previsto. Si crea una
fábrica de controlador personalizado, puede definir su propia convención de
nomenclatura para las clases de controlador.

Las plantillas de proyecto de Microsoft Visual Studio incluyen una carpeta


denominada Controladores. Esta es una buena ubicación para crear sus
controladores. Microsoft Visual Studio coloca los controladores en el
namespace projectname.Controllers, de forma predeterminada.

El siguiente ejemplo muestra el código en una clase de controlador MVC


llamada PhotoController. El controlador tiene una sola acción llamada
Índice, que devuelve una lista de elementos Foto del contexto Entity
Framework.

A Simple Controller Class

public class PhotoController : Controller

private ContextDB context = new ContextDB();

public ActionResult Index ()

return View("Index", context.Photos.ToList());

}
Question: What is the convention that you should follow while creating
controllers?

Writing Controller Actions

Los controladores encapsulan la lógica de interacción del usuario para una


aplicación web MVC. Especifica esta lógica escribiendo acciones. Una acción
es un método dentro de la clase del controlador. El código que escribe en un
método de acción determina cómo responde el controlador a la solicitud y la
clase de modelo y la vista que MVC utiliza para mostrar una página web en el
explorador.

Note: When you add a new controller to an MVC application, Visual Studio
presents scaffolding options to help you create action methods and associated
views. For example, if you specify a model class and Entity Framework
context class, Visual Studio can create scaffold index and details, and create,
edit, and delete action methods in your new controller. You can use these as a
starting point for your code. As you become more experienced with action
methods, you may prefer to select the Empty MVC Controller template and
write your own methods without scaffold code.

Las acciones de controlador son métodos públicos que devuelven un objeto


ActionResult. Como alternativa, las acciones pueden devolver objetos de
muchas otras clases que derivan de la clase ActionResult. Por ejemplo, puede
escribir código para un controlador con una acción de Index para obtener
todos los objetos de Photo y pasarlos a la vista de Index.

Cuando desea mostrar un objeto de modelo específico, debe obtener la


instancia correcta de la base de datos. El código siguiente muestra cómo
mostrar el primer objeto Photo.

A Details Action

public ActionResult First ()

Photo firstPhoto = context.Photos.ToList()[0];

if (firstPhoto != null)

return View("Details", firstPhoto);

else

return HttpNotFound();

Algunas acciones de usuario se dividen en dos partes. Por ejemplo, para crear
una nueva Photo, un usuario puede hacer una solicitud HTTP GET a la
siguiente URL: http://www.adventureworks.com/photo/create.
El siguiente código muestra una acción que responde a una solicitud GET,
para mostrar un nuevo formulario photo.

A Create Action for the GET Request

public ActionResult Create ()

Photo newPhoto = new Photo();

return View("Create", newPhoto)

La vista Create muestra un formulario donde los usuarios pueden rellenar


detalles de la foto, como el título, la descripción, etc. Cuando un usuario hace
clic en el botón Enviar, el navegador web realiza una solicitud HTTP POST.

El siguiente método de acción responde a una solicitud POST. Tenga en


cuenta que el nombre del método es el mismo, pero la anotación [HttpPost] se
utiliza para especificar que esta acción responde al verbo HTTP POST.

A Create Action for the POST Request

[HttpPost]

public ActionResult Create (Photo photo)

if (ModelState.IsValid)

context.Photos.Add(photo);

context.SaveChanges();
return RedirectToAction("Index");

else

return View("Create", photo);

Tenga en cuenta que la propiedad ModelState.IsValid se utiliza para


comprobar si el usuario ha enviado datos válidos. Puede especificar la
validación de datos mediante anotaciones de datos de validación en la clase de
modelo. Si los datos son válidos, se agrega y se guarda el objeto del modelo.
De lo contrario, la aplicación mostrará nuevamente la vista Create, para que
el usuario pueda corregir los datos no válidos.

Note: For the preceding code to work, the Create view must contain a form
that uses the POST method.

Possible Return Classes

Los métodos de acción se definen generalmente con la clase ActionResult


como el tipo de retorno. ActionResult es una clase base, y puede utilizar un
rango de clases derivadas para devolver diferentes respuestas al navegador
web.

Las acciones del controlador generalmente devuelven una vista y le pasan una
clase de modelo, para su visualización. Puede crear una acción que llama al
ayudante de View () y crea y devuelve un objeto ViewResult. El ayudante de
View () está disponible cuando se deriva de la clase Controller de base.

Como alternativa, puede devolver un error HTTP. Por ejemplo, puede crear
una acción tal que si no se encuentra un objeto Photo, el código crea un error
no encontrado 404 utilizando el ayudante HttpNotFound ().
A veces, es posible que desee devolver un archivo desde un método de acción.
Por ejemplo, consideremos que en un modelo Photo, el archivo de imagen se
almacena como una matriz de bytes en la base de datos. Para mostrar esta
matriz de bytes como una imagen en una página web, la acción debe
devolverla como un archivo .jpeg, que se puede utilizar para el atributo src de
una etiqueta HTML <img>. Para devolver archivos, puede utilizar el ayudante
File() para devolver un objeto FileContentResult. Puede utilizar esta técnica
en la acción GetImage.

Otros posibles resultados de acción incluyen:

PartialViewResult. You can use this action to generate a section of an


o HTML page, but not a complete HTML page. Partial views can be re-used in
many views throughout a web application.
RedirectToRouteResult. You can use this action result to redirect the web
o
browser to another action method or another route.
RedirectResult. You can use this action result to redirect to a specific URL,
o
either inside your web application or to an external location.
ContentResult. You can use this action result to return text to the web
browser. You can return plain text, XML, a comma-separated table, or other
o
text formats. This text can be rendered in the web browser or parsed with
client-side code.

Child Actions

When an action returns a complete view, MVC sends a new complete


webpage to the web browser for display. Sometimes, you may want to call an
action from within a view, to return a piece of content for display within a
webpage. A child action is an action method that can return a small piece of
content in this manner. The FileContentResult is often a good example of a
child action, because the image returned usually forms part of a webpage.
Partial views also support child actions.

To declare an action method as a child action, you can use the


[ChildActionOnly] annotation. This annotation ensures that the action
method can be called only from within a view by using the Html.Action()
helper. Using this method, you can prevent a user from calling the child action
directly by typing the correct URL into the Address bar.

Question: What are the various ActionResult return types that you can write
as code while creating a controller?

Using Parameters

When users request webpages, they often specify information other than the
name of the webpage itself. For example, when they request a product details
page, they may specify the name or catalog number of the product to display.
Such extra information is referred to as parameters. You must understand how
to determine in code what parameters the user sent in their request.

The ControllerActionInvoker and the DefaultModelBinder classes obtain


parameters from a user request and pass them to action methods. The
DefaultModelBinder can locate

parameters in a posted form, the routing values, the query string, or in the
posted files. If the model binder finds a parameter in the action method that
matches the name and type of a parameter from the request, the action method
is called and the parameter is passed from the request. This arrangement
enables you to obtain and use parameters in your actions. For example, if a
user requests the URL
http://www.adventureworks.com/photo/getphotobytitle/?title=myfirstphoto,
you can easily obtain title values in your action method.

The following example code shows how to determine the value of the title
parameter in a controller action.

Using a Query String Parameter

public ActionResult GetPhotoByTitle (string title)

var query = from p in context.Photos

where p.Title == title

select p;

Photo requestedPhoto = (Photo)query.FirstOrDefault();

if (requestedPhoto != null)

return View("Details", requestedPhoto);

else

return HttpNotFound();

}
}

Note that the action method code uses the parameter title to formulate a LINQ
to Entities query. In this case, the query searches for a Photo with the
specified Title. Parameters in action methods are frequently used in this
manner.

Note: The example works if the DefaultModelBinder passes parameters. If


you create a custom model binder in your application, you must ensure that it
passes parameters in the correct manner. Otherwise, the action method cannot
access the parameters that the user specified in the request.

Question: How does DefaultModelBinder pass parameters?

Passing Information to Views

You can pass a model object, such as a Photo, from the action method to the
view by using the View() helper method. This is a frequently-used method to
pass information from a controller action to a view. This is because this
method adheres closely to the Model-View-Controller pattern, in which each
view renders the properties found in the model class, which the view receives
from the controller. You should use this approach wherever possible.

However, in some cases, you may want to augment the information in the
model class with

some extra values. For example, you may want to send a title, which needs to
be inserted in the page header, to the view. Furthermore, some views do not
use model classes. The home page of a website, for example, often does not
have a specific model class. To help in these situations, you can use two other
methods to provide extra data: ViewBag and ViewData.

Using The ViewBag

The ViewBag is a dynamic object that is part of the base controller class.
Because it is a dynamic object, you can add properties that are of any type to
it, in the action method. In the view, you can use the ViewBag object to obtain
the values added in the action.

You can add properties to the ViewBag object in the action method as
illustrated in the following lines of code.

Adding Properties to the ViewBag Object

ViewBag.Message = "This text is not in the model object";

ViewBag.ServerTime = DateTime.Now;

To obtain and use the same properties in a view, you can use the following
Razor code.

Using ViewBag Properties

<p>

The message of the day is: @ViewBag.Message

</p>
<p>

The time on the server is: @ViewBag.ServerTime.ToString()

</p>

Using The ViewData Dictionary

The ViewBag object was added to MVC in version 3. In the earlier versions,
you could pass extra data to views by using the ViewData dictionary. This
feature is still available in MVC 4 for backward compatibility and for
developers who prefer to use dictionary objects. In fact, ViewBag is a
dynamic wrapper above the ViewData dictionary. This means that you could
save a value in a controller action by using ViewBag and read the same value
back out by using ViewData.

In action methods, you can add data to the ViewData dictionary by using
key/value pairs as the following lines of code illustrate.

Adding Data to the ViewData

ViewData["Message"] = " This text is not in the model object"

ViewData["ServerTime"] = DateTime.Now;

To obtain and use the same values in a view, you can use the following Razor
code.

Using ViewData Values

<p>

The message of the day is: @ViewData["Message"]

</p>

<p>

The time on the server is: @((DateTime)ViewData["ServerTime"])


</p>

In the examples, note that you can cast any ViewData values other than
strings.

Question: Do ViewBag and ViewData serve different purposes?

Demonstration: How to Create a Controller


In this demonstration, you will see how to create a controller and write
common actions in the controller.

Note: At the end of this demonstration, the application will not include views.
Therefore, the application cannot display webpages.

Demonstration Steps
In the Solution Explorer pane of the OperasWebSite - Microsoft Visual
1. Studio window, right-click Controllers, point to Add, and then click
Controller.
In the Controller Name box of the Add Controller dialog box, type
2.
OperaController.
3. In the Template box, click Empty MVC controller, and then click Add.
In the OperaController.cs code window, locate the following code.
4.
using System.Web.MVC;
Place the mouse cursor at the end of the System.Web.MVC namespace,
press Enter, and then type the following code.

5. using System.Data.Entity;

using OperasWebSite.Models;

In the OperaController class code block, press Enter, type the following
6. code, and then press Enter.
private OperasDB contextDB =

new OperasDB();

In the Index action code block, select the following code.


7.
return View();

Replace the selected code with the following code.

return View("Index",
8.

contextDB.Operas.ToList());

Place the mouse cursor at the end of the Index action code block, press
Enter, and then type the following code.

public ActionResult Details (int id)


9.
{

In the Details action code block, type the following code.

Opera opera =

contextDB.Operas.Find(id);

if (opera != null)

10.
{

return View("Details", opera);

else
{

return HttpNotFound();

Place the mouse cursor at the end of the Details action code block, press
Enter twice, and then type the following code.

11. public ActionResult Create ()

}
In the Create action code block, type the following code.

12. Opera newOpera = new Opera();

return View("Create", newOpera);

Place the mouse cursor at the end of the Create action code block, press
Enter twice, and then type the following code.

[HttpPost]
13.
public ActionResult Create

(Opera newOpera)

}
Place the mouse cursor in the Create action code block with the HTTP
verb POST, and then type the following code.

if (ModelState.IsValid)
14.
{

contextDB.Operas.Add(newOpera);
contextDB.SaveChanges();

return

RedirectToAction("Index");

else

return View("Create", newOpera);

On the FILE menu of the OperasWebSite - Microsoft Visual Studio


15.
window, click Save Controllers\OperaControllers.cs.
In the OperasWebSite - Microsoft Visual Studio window, click the
16. Close button.
Note: The message, “Save changes to the following items?” is displayed.
In the Microsoft Visual Studio dialog box, note that the message, “Save
17.
changes to the following items?” is displayed, and then click Yes.

What Are Controller Factories?


A controller factory is an MVC component that instantiates the controller
classes that you create.

For example, when a user requests a list of Photo model objects, a controller
factory should create an instance of the PhotoController class. An action
invoker then calls one of the action methods in that class, and a model binder
passes parameters to it.

The MVC framework includes a built-in DefaultControllerFactory class that


is suitable for most web applications. However, you must understand how
DefaultControllerFactory

determines the controller class that it needs to create. Occasionally, you may
need to create a custom controller factory to implement your own controller
creation logic.

How the DefaultControllerFactory Class Locates a Controller


Class

The DefaultControllerFactory class identifies controller classes by using the


following criteria:
o The class scope must be public.
o The class must not be marked as abstract.
o The class must not take generic parameters.
o The class must have a name that ends with Controller.
o The class must implement the IController interface.

When the MVC web application starts, DefaultControllerFactory creates a


list of all the classes in the application that satisfy these criteria. This list helps
to create the correct controller rapidly. To write a controller, you must ensure
that all the above mentioned criteria are implemented. Usually, you meet the
IController interface criterion by inheriting from the base Controller class.

By default, the DefaultControllerFactory mandates all controller classes to end


with the word Controller. For example, following this convention, for the
Photo model class, you would create a controller called PhotoController.

Creating a Custom Controller Factory

Occasionally, you might want to implement a custom controller factory. There


are two common reasons for doing this:

To modify the criteria for selecting controllers. The criteria described earlier
are suitable for most web applications, but sometimes, you may want to
o
change them. For example, you may not want to name controllers with
Controller at the end, or you may want to add extra criteria of your own.
To support direct injection for testing. Direct injection is a programming
technique that lets you specify classes at run time, instead of specifying
o classes when writing code. This is helpful for unit testing because you can
inject a test class with mock data, instead of real data. The
DefaultControllerFactory class does not support direct injection.

The following code shows how to create a custom controller factory by


implementing the IControllerFactory interface.

A Custom Controller Factory

public class AdWorksControllerFactory : IControllerFactory


{

public IController CreateController (RequestContext requestContext,

string

ControllerName)

Type targetType = null;

if (ControllerName == "Photo")

targetType = typeof(PhotoController);

else

targetType = typeof(GeneralPurposeController);

return targetType == null ? null :

(IController)Activator.CreateInstance(targetType);

public SessionStateBehavior

GetControllerSessionBehavior(RequestContext

requestContext,

string controllerName)
{

return SessionStateBehavior.Default;

public void ReleaseController(IController controller)

IDisposable disposable = controller as IDisposable;

if (disposable != null)

disposable.Dispose();

You must implement the CreateController, GetControllerSessionBehavior,


and ReleaseController methods for any custom controller factory you create.

For example, if the controller name passed to a controller factory is “Photo”,


then the PhotoController is used. Otherwise, the GeneralPurposeController
is used. The logic in a real custom controller should be more sophisticated
than in this example. However the example illustrates the minimal required
code to create a custom controller factory.

Registering a Custom Controller Factory

Even if you create a custom controller factory in your application, MVC will
still use the DefaultControllerFactory class, unless you register your custom
factory.
You register a custom controller factory by using the ControllerBuilder class
in the Global.asax file, as the following lines of code show.

Registering a Custom Controller Factory

protected void Application_Start()

ControllerBuilder.Current.SetControllerFactory(new

AdWorksControllerFactory());

Question: Can you create a controller that does not end with “Controller”?

Lesson 2: Writing Action Filters


In some situations, you may need to run code before or after controller actions
run. Before a user runs any action that modifies data, you might want to run
the code that checks the details of the user account. If you add such code to
the actions themselves, you will have to duplicate the code in all the actions
where you want the code to run. Action filters provide a convenient way to
avoid code duplication. You need to know how to create and use action filters
in your web application, and when to use them.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe action filters.


o Create action filters.
o Determine when to use action filters.

What Are Filters?


The MVC programming model enforces the separation of concerns. For
example, the business logic in model classes is separate from the input logic in
controllers and the user interface logic in views. Each model class is also
clearly distinct from other model classes. However, there are scenarios where
requirements may be relevant to many parts of your application and cut across
logical boundaries. For example, authorization must be done for many
sensitive actions and controllers, regardless of the model and views that they
return. These types of requirements are known as

cross-cutting concerns. Some common examples of cross-cutting concerns


include authorization, logging, and caching.

Filters

Filters are MVC classes that you can use to manage cross-cutting concerns in
your web application. You can apply a filter to a controller action by
annotating the action method with the appropriate attribute. For example, an
action annotated with the [Authorize] attribute, can be run only by
authenticated users. You can also apply a filter to every action in a controller
by annotating the controller class with the attribute.
Filter Types

There are four types of filters that you can use in MVC. These filters run at
slightly different stages in the request process.

Filter Type Interface Default Class Description

Authorization IAuthorizationFilter AuthorizeAttribute Runs before


any other
filter and
before the
code in the
action
method. Used
to check a
user’s access
rights for the
action.

Action IActionFilter ActionFilterAttribute Runs before


and after the
code in the
action
method.

Result IResultFilter ActionFilterAttribute Runs before


and after a
result is
returned from
an action
method.

Exception IExceptionFilter HandleErrorAttribute Runs only if


the action
method or
another filter
Filter Type Interface Default Class Description

throws an
exception.
Used to
handle errors.

Question: Which filter type will you use for the following actions?

1. Intercepting an error
2. Modifying a result
3. Authorizing users
4. Inspecting a returned value

Creating and Using Action Filters

If you have a cross-cutting concern in your web application, you can


implement it by creating a custom action filter or a custom result filter. You
can create custom filters by implementing the IActionFilter interface or the
IResultFilter interface. However, the ActionFilterAttribute base class
implements both the IActionFilter and IResultFilter interfaces for you. By
deriving your filter from the ActionFilterAttribute class, you can create a
single filter that can run code both before and after the action runs, and both
before and after the result is returned.

The following code shows how an action filter is used to write text to the
Visual Studio Output window in the order in which the IActionFilter and
IResultFilter events run. Place this code in a class file within your web
application.

A Simple Custom Action Filter

public class SimpleActionFilter : ActionFilterAttribute

public override void OnActionExecuting(ActionExecutingContext

filterContext)

Debug.WriteLine("This Event Fired: OnActionExecuting");

public override void OnActionExecuted(ActionExecutedContext

filterContext)

Debug.WriteLine("This Event Fired: OnActionExecuted");

public override void OnResultExecuting(ResultExecutingContext

filterContext)

{
Debug.WriteLine("This Event Fired: OnResultExecuting");

public override void OnResultExecuted(ResultExecutedContext

filterContext)

Debug.WriteLine("This Event Fired: OnResultExecuted");

Note: You can also create a custom authorization filter by implementing the
IAuthorizationFilter interface. However, the default AuthorizeAttribute
implementation is highly useful and satisfies almost all authentication
requirements. You should be careful when overriding the default security code
in MVC or any other programming model. If you do so without a full
understanding of the implications, you can introduce security vulnerabilities
that a malicious user can exploit.

Using a Custom Action Filter

After you have created a custom action filter, you can apply it to any action
method or class in your web application by annotating the method or class
with the action filter name.

In the following lines of code, the SimpleActionFilter is applied to the Index


action of the Photo controller.

Using A Custom Action Filter

public class PhotoController : Controller

{
ContextDB contextDB = new ContextDB();

[SimpleActionFilter]

public ActionResult Index()

return View("Index", contextDB.Photos.ToList());

Question: What are the advantages of custom action filters?

Discussion: Action Filter Scenarios

Consider the following scenarios. In each case, discuss with the rest of the
class whether the scenario requires a custom filter, or can be solved with a
built-in filter type, or cannot be solved with filters.
You are writing a photo sharing application and you want to enable each
user to discuss photos, cameras, lenses, and other photography equipment
1. with other users whom they have marked as their friends.

Other users should be prevented from seeing these discussions.


You want to ensure that when MVC calls the GetImage action method, the
2.
ID in the query string is passed as a parameter.
You are writing a photo sharing application and you want to prevent
3.
unauthenticated users from adding comments to a photo.
You want to prevent malicious users from intercepting the credentials
4. entered by users in the logon form for your web application. You want to
ensure that the credentials are encrypted.

Module Review and Takeaways


In this module, you have seen the pivotal role that controllers and actions take
in the construction of an MVC web application. Controllers and actions ensure
that the application responds correctly to each user request, create instances of
model classes, and pass the model class to a view for display. In the next
module, you will see how to create and code views to implement the user
interface for your application.

Best Practice: Unless you have a good reason not to, keep to the convention
that each controller should be named to match the corresponding model class,
with “Controller” appended. For example, for the Photo model class, the
controller should be called PhotoController. By maintaining this convention,
you create a logically named set of model and controller classes, and can use
the default controller factory.

Best Practice: Take great care if you choose to override the built-in
AuthorizeAttribute filter because it implements permissions and security for
the web application. If you carelessly modify the security infrastructure of the
MVC framework, you may introduce vulnerabilities in your application.
Instead, use the built-in filter wherever possible.

Review Question(s)

Question: You want to ensure that the CreatedDate property of a new Photo
object is set to today’s date when the object is created. Should this value be set
in the Photo model class constructor method or in the PhotoController
Create action method?

Module 05: Developing ASP.NET MVC 4


Views
Module Overview
Views are one of the three major components of the MVC programming
model. You can construct the user interface for your web application by
writing views. A view is a mixture of HTML markup and code that runs on
the web server. You need to know how to write the HTML and code found in
a view and use the various helper classes built into MVC. You also need to
know how to write partial views, which render sections of HTML that can be
re-used in many places in your web application. The knowledge of creating
views will help you develop webpages that present dynamic content.

Objectives

After completing this module, you will be able to:

o Create an MVC view and add Razor markup to it to display data to users.
Use HTML helpers in a view to render controls, links, and other HTML
o
elements.
o Re-use Razor markup in multiple locations throughout an application.

Lesson 1 : Creating Views with Razor Syntax


When a user makes a request to an MVC web application, a controller
responds. Often, the controller action instantiates a model object, for example,
a Product. The controller might get the Product by querying the database, by
creating a new Product, or by performing some other step. To display the
Product, the controller creates a view and passes the Product to it. The view
builds a webpage by inserting properties from the Product, and sometimes,
from other sources, into HTML markup. MVC sends the completed webpage
to the browser. To create views, you must understand how MVC interprets the
code you place in views and how a completed HTML page is built. By
default, the Razor view engine performs this interpretation, but you can also
use other view engines. If you take time to understand Razor, you will find it
to be an excellent and versatile view engine that gives a great degree of
control over the rendered HTML. Other view engines have very different
syntaxes, which you may prefer if you have worked with earlier versions of
ASP.NET or other server-side web technologies, such as Ruby on Rails.

Lesson Objectives
After completing this lesson, you will be able to:

o Add views to an MVC 4 web application.


o Use the @ symbol in a Razor view to treat code as content.
o Describe the features of Razor syntax.
o Bind views to model classes to display data.
o Explain how to render HTML that is accessible to visitors with low vision.
o List a few alternative view engines to the Razor view engine.

Adding Views

In an MVC application, there is usually one controller for every model class.
For example, a model class named Product usually has a controller called
ProductController that contains all the actions relevant to products. There
may be some controllers that do not correspond to any model classes, such as
the HomeController.

However, each controller can have multiple views.


For example, you may want to create the following views for Product
objects:

Details. The details view can display a Product, its price, catalog number,
and
o
other details.
Create. The create view can enable users to add a new Product in the
o
catalog.
Edit. The edit view can enable users to modify the properties of an existing
o
Product.
Delete. The delete view can enable users to remove a Product from the
o
catalog.
o Index. The index view can display all the Product objects in the catalog.

By convention, an MVC web application creates all views within the top-level
Views folder. Within this folder, there is a folder for each controller in the
application. In the preceding example, the Views folder would contain a
Product folder. This folder would contain the Details, Create, Edit, Delete,
and Index views.

If you use the Razor view engine and the C# language, views are files with a
.cshtml extension. If you use the Razor view engine and the Visual Basic
language, views are files with a .vbhtml extension. Other view engines use
different extensions.

How to Create a View File

You can add a view file in Visual Studio by performing the following steps:

In the Solution Explorer pane, select the folder where you want to create
1. the view. For example, for a controller named ProductController, MVC
expects view files to be located in the Views/Product folder.
2. Right-click the selected folder, point to Add, and then select View.

Alternatively, you can create a view file for a particular controller action by
opening the controller code file, right-clicking the action, and then clicking
Add View. If you create a view by using the controller code file, some
properties in the Add View dialog box are filled in by default.

The following table describes the properties that you must complete in the
Add View dialog box.

Property Description

View name This is the name of the view. The view file name is this name
with the appropriate extension added. The name you choose
should match the name returned by the corresponding
controller action. If the action controller does not specify the
name of the view to use, MVC assumes the name of the view
matches the name of the controller action.

View engine By default, you can select the Razor or ASPX view engines in
this list. Other engines may be available if you have installed
them.

Create a When you select this check box, you bind the view to a
strongly- specific model class, such as a Product class. When you use
typed view strongly-typed views, you get additional IntelliSense and
error checking help in Visual Studio as you write code in the
view.

Model class If you create a strongly-typed view, you need to specify the
model class to bind to the view. Visual Studio will use this
class when it formulates IntelliSense prompts and checks for
compile-time errors.

Scaffold A scaffold template is a basic view that Visual Studio can use
template to create the view. If you specify a model class for the view,
Visual Studio can create simple templates for Create, Edit,
Details, Delete, and List views. When you become more
experienced in using views, you may prefer to build a view
from the empty scaffold template, rather than use populated
Property Description

scaffold templates.

Reference When you select this check box, links to common client-side
script script files are included in the view. These links include the
libraries jQuery JavaScript library.

Create as a A partial view is a section of Razor code that you can re-use
partial view in multiple views in your application.

Use a layout A layout or master page can be used to impose a standard


or master layout and branding on many pages within the web
page application.

Note: You will see other view engines later in this module.

Question: You are using the Razor view engine and Visual Basic to create
views. You right-click the Delete action in the CustomerController.vb file.
What is the name of the view file that Visual Studio will create by default?

Differentiating Server Side Code from HTML

The Razor view engine interprets view files and runs any server-side code
contained in the view files. To do this, Razor must distinguish server-side
code from HTML content that should be sent to the browser unchanged.

The Razor view engine looks for the @ symbol to identify server-side code.
In the following code example, Razor runs the line with the @ symbol as C#
code on the web server.

This code example displays the value of the Title property of the model class.

Using @ to Declare Server-Side Code

<p>Razor will not interpret any character in this line as code,

because there is no “at”

symbol</p>

<p>

The photo title is:

@Model.Title

</p>

A section of code marked with the @ symbol is referred to as a Razor code


expression. In Razor syntax, you mark the start of a Razor code expression
with the @ symbol, but unlike the ASPX view engine, Razor lacks an
expression ending symbol. Instead, Razor infers the end of a code expression
by using a fairly sophisticated parsing engine.

Modifying the Interpretation of Code and Content

Sometimes, you may need to modify the logic that Razor uses to interpret
code expressions. For example, if you want to display an @ symbol in the
browser, you use @@. Razor interprets this as an escape sequence and
renders a single @ symbol. This technique is useful for rendering email
addresses.

Razor has sophisticated logic to distinguish code from content and often the
@ symbol is all that is required. However, occasionally, you may find that an
error occurs because Razor misinterprets content as code. To fix such errors,
you can use the @: delimiter, which explicitly declares a line as content and
not code.
If you want to declare several lines as content, use the <text> tag instead of
the @: delimiter. Razor removes the <text> and </text> tags before returning
the content to the browser.

In the following code example, Razor interprets the @: delimiter to display


plain text.

Using the @: Delimiter

@(

@: This text is in a code block but the delimiter declares it as

content.

HTML Encoding

For security reasons, when Razor runs any server-side code that returns a
string, it encodes the string as HTML before rendering it to the browser. For
example, you may have a Comment model class with the following
properties:

Subject. This property contains a subject for the comment as a simple string
o
with no formatting information.
HtmlComment. This property contains the comment text itself. More
o important, it includes the formatting information as HTML tags. For
example, it might include <i> tags to italicize a word.

If you have used the normal @Model.HtmlComment syntax to return the


formatted comment text, Razor encodes “<” as “&lt” and “>” as “&gt” in the
HTML source. This results in the user seeing “<i>” on the webpage. This is
not the behavior you intend because you want the users to see italicized text.

To render text without HTML encoding, use the Html.Raw() helper. For
example, use @Html.Raw(Model.HtmlComment).

Note: Razor encodes text as HTML for a specific security reason—to stop
malicious users from injecting malicious code into your web application. If
such attacks are successful, injected code may circumvent security restrictions
in your web application and deny service to users, or it may access sensitive
information. Therefore, you should only use the Html.Raw() helper when it is
absolutely necessary. Also, if you must use the Html.Raw() helper, you must
ensure that it does not operate on unchecked strings entered by users.

Features of Razor Syntax

Razor includes many useful features that you can use to control the manner in
which ASP.NET MVC renders your view as HTML. These features include
the following:

Razor Comments

You may want to include comments in your Razor code to describe it to other
developers in your team. This is an important technique that improves
developer productivity by making it easier to understand code.

You can declare a Razor comment by using the

@* delimiter, as shown in the following code example.

A Razor Comment

@* This text will not be rendered by the Razor view engine, because

this is a comment. *@

Implicit Code Expressions and Parentheses


Razor uses implicit code expressions to determine parts of a line that are
server-side code. Usually, implicit code expressions render the HTML you
want, but occasionally, you might find that Razor interprets an expression as
HTML when it should be run as server-side code.

For example, if the Product.Price property contains the value 2.00, the
following code renders “Price Including Sales Tax: 2.00 * 1.2”.

An Implicit Code Expression

<span>Price Including Sales Tax: @Model.Price * 1.2</span>

You can control and alter this behavior by using parentheses to enclose the
expression for Razor to evaluate.

For example, if the Product.Price property contains the value 2.00, the
following code renders “Price Including Sales Tax: 2.40”.

Using Parentheses to Explicitly Delimit Expressions

<span>Price Including Sales Tax: @(Model.Price * 1.2)</span>

Razor Code Blocks, Loops, and Conditions

If you want to write multiple lines of server-side code, you can do it without
prefacing every line with the @ symbol by using a Razor code block.

A Razor Code Block

@ {

//Razor interprets all text within these curly braces as server-

side code.

Razor also includes code blocks that run conditional statements or loop
through collections.
For example, Razor runs the following code only if the Product.InStock
Boolean property returns true.

A Razor If Code Block

@if (Model.InStock)

Html.ActionLink("Buy This Product", "AddToCart")

Razor loops are useful for creating index views, which display many objects
of a particular model class. A product catalog page, which displays many
products from the database, is a good example of an index view. To
implement an index view, a controller action passes an enumerable collection
of objects to the view.

You can loop through all the objects in an enumerable collection by using the
foreach code block:

A Razor Foreach Code Block

@foreach (var item in Model)

<div>@item.ProductName</div>

Question: You want to describe a code block to developers in your view file.
You do not want your description to be passed to the browser. What syntax
should you use?

Binding Views to Model Classes and Displaying


Properties
Many Razor views are designed to display properties from a specific model
class. If you bind such views to the class they display, you get extra help such
as IntelliSense feedback as you write the Razor code. Other views may
display properties from different model classes in different cases, or may not
use a model class at all. These views cannot be bound to a model class and are
called dynamic views. You must understand how to write Razor code for both
these situations.

Strongly-Typed Views

In many cases, when you create a view, you know that the controller action
will always pass an object of a specific model class. For example, if you are
writing the Display view for the Display action in the Product controller, you
know from the action code that the action will always pass a Product object
to the view.

In such cases, you can create a strongly-typed view. A strongly-typed view is


a view that includes a declaration of the model class. When you declare the
model class in the view, Visual Studio helps you with additional IntelliSense
feedback and error-checking as you write the code. This is possible because
Visual Studio can check the properties that the model class includes.
Troubleshooting run-time errors is also easy. You should create strongly-
typed views whenever you can so that you benefit from this extra IntelliSense
and error-checking. If you follow this as a best practice, you will make fewer
coding errors. A strongly-typed view only works with an object of the model
class in the declaration.
To create a strongly-typed view in Visual Studio, select Create a strongly
typed view in the Add View dialog box, and then choose the model class to
bind to the view.

You can choose the Product model class so that Visual Studio can bind the
view to the class you specify, by adding the following line of code at the top
of the view file.

The Model Declaration

@model MyWebSite.Models.Product

Later in the view file, you can access properties of the model object by using
the Model helper. For example, you might access a product catalog number in
this manner: @Model.CatalogNumber.

Binding to an Enumerable List

Some views display many instances of a model class. For example, a product
catalog page displays many instances of the Product model class. In such
cases, the controller action passes a list of model objects to the view, instead
of a single model object. You can still create a strongly-typed view in this
situation, but you must use a different model declaration. You usually loop
through the items in the list by using a Razor foreach loop.

The following code example shows a multiple-item view with the model
declaration and the loop that enumerates all the Product objects passed by the
action.

A View of a List of Objects

@model IEnumerable<MyWebSite.Models.Product>

<h1>Product Catalog</h1>

@foreach (var Product in Model)

{
<div>Name: @Product.Name</div>

Using Dynamic Views

Sometimes, you might want to create a view that can display more than one
model class. For example, you might want to create a view that can display
your own products and products from a different supplier, together. These
model classes might be named Product and ThirdPartyProduct. Some
properties can be similar while others differ. For example, both Product and
ThirdPartyProduct might include the Price property while only the
ThirdPartyProduct model class includes the Supplier property.

Furthermore, sometimes, the controller action does not pass any model class
to the view. The most common example of such a classless view is the site
home page.

In such cases, you can create a dynamic view. A dynamic view does not
include the @model declaration at the top of the page. You can choose to add
the @model declaration to change the view into a strongly-typed view, later.

When you create dynamic views, you receive less helpful IntelliSense
feedback and error checking because Visual Studio cannot check the model
class properties to verify the code. In such scenarios, you have to ensure that
you access only the properties that exist. To access a property that may or may
not exist, such as the ThirdPartyProduct.Supplier property in the preceding
example, check the property for null before you use it.

Question: You want to write a view that displays ten objects of the Photo
model class. What model declaration should you use?

Rendering Accessible HTML


The Internet is for everyone, regardless of any disabilities an individual user
may have.

Furthermore, if users with disabilities cannot easily browse your website, they
may visit your competitors’ websites and your company may lose business.
You should therefore ensure that people with disabilities—such as those who
have low vision or are hard-of-hearing—can use your web application, and
that their web browsers can parse the HTML content that your site presents.
Because MVC views are responsible for rendering HTML in an MVC web
application, you render accessible

HTML by writing views that follow accessibility guidelines. When you write
views, keep the following challenges and best practices in mind.

Users have different requirements depending on their abilities and disabilities.


For example, consider the following factors:

Users with low vision may use a standard browser, but they may increase
o
text size with a screen magnifier so that they can read the content.
Profoundly blind users may use a browser with text-to-speech software or
o
text-to-Braille hardware.
Color-blind users may have difficulty if a color difference is used to
o
highlight text.
o Deaf users may not be able to access audio content.
o Users with limited dexterity may find it difficult to click small targets.
o User with epilepsy may have seizures if presented with flashing content.
You can ensure that your content is accessible to the broadest range of users
by adhering to the following guidelines:

Do not rely on color differences to highlight text or other content. For


o example, links should be underlined or formatted in bold font to emphasize
them to color-blind users.
Always provide equivalent alternative content for visual and auditory
content. For example, always complete the alt attribute for images. Use this
o
attribute to describe the image so that text-to-speech software or text-to-
Braille hardware can render meaningful words to the user.
Use markup and style sheets to separate content from structure and
presentation code. This helps text interpretation software to render content to
users without being confused by structural and presentation code. For
example, you should apply the following best practices to display content on
your webpage:

Avoid using tables to display the content. You should use tables only to
present tabulated content. Tables can be used to render graphics and

branding on a webpage, but in an accessible site, use positional style sheets
to display content. Text readers do not read style sheets.
Avoid using nested tables. In a nested table, a table cell contains another
o table. These are particularly confusing to text readers because they read
▪ each table cell in a sequential order. The user is likely to become
disoriented and unable to determine which cell is being read and what it
means.
Avoid using images that include important text. Text readers cannot render

text from within an image file. Instead, use markup to render this text.

Additional Reading: The World Wide Web Consortium (W3C) has a


project called the Web Accessibility Initiative (WAI) that promotes
accessible web content. This project has published the Web Content
Accessibility Guidelines (WCAG). These guidelines are accepted by the web
publishing industry as definitive. To read the full guidelines, go to:
http://go.microsoft.com/fwlink/?LinkID=288955&clcid=0x409

Note: In ASP.NET MVC, the developer has complete control over the HTML
that the web server sends to the web browser. However, you must understand
accessibility principles to write accessible MVC views. Ensure that your
entire development team is familiar with the requirements of accessibility and
the related best practices.

Question: You want to present your company logo at the uppermost part of
the page. The logo is a .gif file that includes the name of the company in an
unusual font. How can you ensure that the logo is accessible?

Alternative View Engines

A view engine is a component of the MVC framework that is responsible for


locating view files, running the server-side code they contain, and rendering
HTML that the browser can display to the user. Many views work with the
Razor view engine. Razor is the default view engine in MVC 4 and is a highly
flexible and efficient view engine.

However, some developers may prefer to use a different view engine for the
following reasons:

View Location Logic. Razor assumes that all views are located in the Views
top-

level folder. Within this, Razor assumes

o that each controller has a separate folder. For example, views for the
ProductController are located in the Product folder within Views. Razor
also looks for some views in the Shared subfolder. These views can be used
by more than one controller. If you do not like this view location logic, you
can use an alternate view engine, or create a custom view engine.
View Syntax. Each view engine uses a different syntax in view files. For
example, in Razor, the @ symbol delimits server-side code. By contrast, in
the ASPX view engine, <% %> delimiters are used. This is familiar to
developers who have worked with Web Forms. You may prefer one syntax
over another for the following reasons:

Experience. The technologies that you or your team have previously


o ▪ worked with may make it easier for you to learn the syntax of a specific
view engine.
Readability. Some view engines work with view files that are easily
readable for anyone who knows HTML. Web designers, who do not know

C# or other programming languages, may be able to learn readable
syntaxes.
Succinctness. Some view engines work with view files that are terse and

generate HTML with relatively small amounts of code.

Common View Engines

The following table describes and compares four popular view engines.

View Description Code Example


Engin
e

Razor This is the @model IEnumerable<MyWebSite.Models.Product>


default view
engine for
MVC 4. It is
easy to learn <ul>

for anyone
@foreach (var p in Model)
who has
experience in {
HTML and
C# or Visual <li>Name: @p.Name</li>
Basic. Visual
Studio }
View Description Code Example
Engin
e

provides
good
IntelliSense
feedback for
Razor code
and it is
compatible
with unit
testing.

ASPX This was the <%@ Control Inherits=


default view
engine for "System.Web.Mvc.ViewPage<IEnumerable<Product>>

MVC 1 and "


2. It is easy
to learn for %>

developers
<ul>
with
experience in
<% foreach(var p in model){%>
ASP.NET
Web Forms <li><%=p.Name%></li>
and it is also
known as the <%}%>
Web Forms
View Engine.
It includes
good
IntelliSense
feedback.

</ul>
View Description Code Example
Engin
e

NHaml NHaml is a @type=IEnumerable<Product>


.NET
Framework %ul

version of the
Haml view - foreach (var p in model)

engine used
%li= p.Name
with Ruby on
Rails, a
competitor to
ASP.NET
MVC.
Developers
who have
developed
websites with
Ruby on
Rails may
prefer this
view engine.
Visual Studio
does not
provide
IntelliSense
feedback for
this view
engine.
NHaml
syntax is
terse and
efficient, but
often less
View Description Code Example
Engin
e

intelligible to
inexperience
d developers.

Spark This view <viewdata products="IEnumerable[[Product]]"/>


engine uses
view files <ul if="products.Any()">

that are
easily <li each="var p in

readable and products">${p.Name}</li>

similar to
</ul>
static HTML
files. This
design results
in view files
that are
readable for
anyone who
knows
HTML. You
can obtain
IntelliSense
support for
Spark in
Visual
Studio.

Additional Reading: For more information about alternative view engines,


go to: http://go.microsoft.com/fwlink/?LinkID=288956&clcid=0x409
http://go.microsoft.com/fwlink/?LinkID=288957&clcid=0x409

Creating Custom View Engines


You can also create your own view engine to implement custom logic for
locating views or to implement custom syntax for view files. Custom view
engines are rarely created because the existing view engines are powerful,
flexible, and easy to learn. The default logic for finding view files is also
simple and rarely needs modification. To create a custom view engine, you
must take the following steps:

Create a View Class. This class must implement the IView interface and
have a Render() method. You need to write the custom logic in the
o
Render() method for interpreting custom syntax. This code is likely to
include regular expressions and other sophisticated string-parsing code.
Create a View Engine. This class should inherit the
VirtualPathProviderViewEngine class and include the CreateView() and
CreatePartialView() methods. By inheriting from the
o
ViewPathProviderViewEngine class, you can modify the
ViewLocationFormat property to implement custom logic for locating
views.
Register the Custom View Engine. To register your custom view engine with
MVC, call ViewEngines.Engines.Add() in the Global.asax file.
o
Additional Reading: For more information about creating custom view
engines in ASP.NET MVC page, see:
http://go.microsoft.com/fwlink/?LinkID=288958&clcid=0x409

Question: Is there any HTML markup that the Razor view engine cannot
render?

Lesson 2: Using HTML Helpers


The ASP.NET MVC 4 Framework includes many HTML helper functions
that you can use in views. HTML helpers are C# methods that you can call to
render values, labels, and input controls such as text boxes. Helpers include
common logic that makes it easier for you to render HTML for MVC model
class properties and other tasks. Some HTML helpers examine the definition
of a property in a model class and then render appropriate HTML. Some
HTML helpers call controller actions and others validate user input data. You
can also create custom HTML helpers. You need to know the appropriate
HTML helper to use in any scenario and how to pass the correct parameters to
relevant HTML helpers.

Lesson Objectives
After completing this lesson, you will be able to :

o Use the Html.ActionLink and Url.Action helpers to call a controller action.


Use the Html.DisplayNameFor and HtmlDisplayFor helpers to display the
o
value of a model class property.
Use the Html.LabelFor and HTML.EditorFor helpers to render an editor
o
control for a model class property.
o Use the Html.BeginForm helper to render a form for a controller action.
o Use HTML helpers to validate data typed by users.
o Use various HTML helpers to build a user interface for a web application.

Using Action Helpers

HTML helpers are simple methods that in most cases return a string. This
string is a small section of HTML that the view engine can insert into the view
file to generate the completed webpage. You can write views that render any
type of HTML content without using a single helper if you prefer not to use
HTML helpers. However, HTML helpers make the task of managing HTML
content easier by rendering common HTML strings for often-used scenarios.

The Html.ActionLink() and Url.Action() helpers enable you to render


HTML that calls controller
actions.

The Html.ActionLink() Helper

When the user makes a request to an MVC web application, the ASP.NET
MVC 4 framework forwards the request to the correct controller and action,
thereby passing the correct parameters. It is possible for users to make such
requests by typing a URL into the Address bar of a web browser, but they
rarely know the name of the controller, action, or parameters. Instead, they
usually click a link. The Html.ActionLink() helper can be used to render
links to actions for you. The helper returns an <a> element with the correct
href parameter value when users click a link in a webpage.

In the following code example, the Html.Actionlink() helper renders an <a>


element that calls the Display action in the Photo controller, and passes an
integer for the photo ID.

Using the Html.ActionLink() Helper

@Html.ActionLink("Click here to view photo 1", "Display", new { id = 1

})

By default, the example renders the following HTML:

<a href="/photo/display/1">Click here to view photo 1</a>

Notice that you pass parameters to the helper by using an anonymous object.
In this manner, you can pass multiple parameters.

Note: The Html.ActionLink() helper works with the routing engine to


formulate the correct URL for the link. The helper will render the href value
above, assuming it is called from a PhotoController view. There are several
overloads of the ActionLink helper, however, if you wish to use it to call
actions in other controllers.

The Url.Action Helper

The Url.Action() helper renders a URL by using the routing engine without
rendering the enclosing <a> element.
You can use the Url.Action() helper to populate the src attribute of an <img>
element or <script> element. This helper is useful whenever you want to
formulate a URL to a controller action without rendering a hyperlink.

The following code example shows how to render an image by calling the
Url.Action helper within the src attribute of an img element:

Rendering an Image from an Action

<img alt="This image came from an action" src="@Url.Action("GetImage",

new { id = 1 })"

/>

Additional Reading: For more information about the Html.ActionLink()


and Url.Action() helpers, see:

http://go.microsoft.com/fwlink/?LinkID=288959&clcid=0x409
http://go.microsoft.com/fwlink/?LinkID=288960&clcid=0x409

Question: You want to render an HTML5 <audio> tag to play a sound file
from an action. Would you use the Html.ActionLink() helper or the
Url.Action() helper?

Using Display Helpers

MVC includes several helpers that display properties from model classes. You
can use these helpers to build views that display product details, comment
details, user details, and so on.
Html.DisplayNameFor() renders the name of a model class property.
Html.DisplayFor() renders the value of a model class property. Both these
helpers examine the definition of the property in the model class, including
the data display annotations, to ensure that they render the most appropriate
HTML.

The Html.DisplayNameFor() Helper

You use the Html.DisplayNameFor() helper to render the display name for a
property from the model class. If your view is strongly-typed, Visual Studio
checks whether the model class contains a property with the right name as you
type the code. Otherwise, you must ensure that you use a property that exists
or verify that it is not null before you use it. You specify the property of the
model class to the Html.DisplayNameFor() HTML helper by using a lambda
expression.

The following code example renders the display name of the CreatedDate
property by using the Html.DisplayNameFor() HTML helper .

Using the Html.DisplayNameFor() Helper

@Html.DisplayNameFor(model => model.CreatedDate)

The text rendered by the Html.DisplayNameFor() helper depends on the


model class. If you used a DisplayName annotation to give a more descriptive
name to a property, then Html.DisplayNameFor() will use that DisplayName
annotation value; otherwise, it will render the name of the property.

The Html.DisplayFor() Helper

The Html.DisplayFor() helper considers any display annotations that you


specify in the model class, and then renders the value of the property.

In the following code example, the Html.DisplayFor() helper is used to


render a date string.

Using the Html.DisplayFor() Helper

This was created on: @Html.DisplayFor(model => model.CreatedDate)


If you used the DisplayFormat annotation in the model class with
DataFormatString set to “{0:dd/MM/yy}”, then the Html.DisplayFor() helper
ensures that the date is displayed in short date format.

Question: You want to ensure that a view displays “This product was last
changed on” before the ModifiedDate property. This text is declared in the
class with the DisplayName annotation. What code would you write in the
view?

The Begin Form Helper

To accept user input, you must provide a form on your webpage. A typical
form consists of a set of labels and input controls. The labels indicate to the
user the property for which they must provide a value. The input controls
enable the user to enter a value. Input controls can be text boxes, check boxes,
radio buttons, file selectors, drop-down lists, or other types of control. There is
usually a submit button and cancel button on forms.

Rendering HTML Forms

To build a form in HTML, you must start with a

<form> element in the HTML webpage. All labels and input controls must be
within the <form> element. In an MVC view, you can use the
Html.BeginForm() helper to render this element and set the controller action
to which the form sends data.

You can also specify the HTTP method that the form uses to submit data. If
the form uses the POST method, which is the default, the browser sends form
values to the web server in the body of the form. If the form uses the GET
method, the browser sends form values to the web server in the query string in
the URL.

In the rendered HTML, the <form> element must be closed with a </form>
tag. In Razor views, you can ensure that the form element is closed with an
@using code block. Razor renders the </form> tag at the closing bracket of
the code block.

The following code example shows how to render a form that sends data to
the Register action in the CustomerController. The form uses the POST
HTTP verb.

Using the Html.BeginForm() Helper

@using (Html.BeginForm("Register", "Customer", FormMethod.Post))

@* Place input controls here *@

Using Forms to Post Files

In HTML, if you want to enable website users to upload files, you should use
an HTML form with special properties. Specifically, the <form> element
should include the enctype attribute set to the value multipart/form-data and
the form must use the POST HTTP verb.

You can specify additional attributes for the <form> element by passing them
in an htmlAttributes parameter as new objects. This is a good method to use
to add the enctype attribute. If the form includes any uploaded files, you must
set the enctype attribute to multipart/form-data.

The following code example shows how to render a file upload form that
sends data to the Create action in the ProductController. The form uses the
POST verb and sets the enctype attribute.
Using the Html.BeginForm() Helper

@using (Html.BeginForm("Create", "Photo", FormMethod.Post, new {

enctype =

"multipart/form-data" }))

@* Place input controls here *@

Question: You have created a form with a file selector control that uses the
GET method. You have set the enctype attribute to multipart/form-data, but
when you try to access the file in the action method, an exception is thrown.
What have you possibly done incorrectly?

Using Editor Helpers

Within HTML forms, there are many HTML input controls that you can use to
gather data from users. In Razor views, the Html.LabelFor() and
Html.EditorFor() helpers make it easy to render the most appropriate input
controls for the properties of a model class. To understand how these helpers
render HTML, you must first understand the HTML input controls. Some
common HTML controls are described in the following table.
Contro Example Descriptio n

Text <input A single- line text box in which the user can
box enter a string. The name attribute is used to
type="text" identify the entered value in the query string or
to send form data by using the POST method.
name="Title">

Multi- <textarea A multi- line text box in which the user can
line text enter longer strings.
box name="Description

"

rows="20"

cols="80">

Check box <input A check box submits a


Boolean value.
type="checkbox"

name="ContactMe">

Please send me

new offer details

Additional Reading: For more information about all HTML form elements,
go to: http://go.microsoft.com/fwlink/?LinkID=288961&clcid=0x409
The Html.LabelFor() Helper

The Html.LabelFor() helper is similar to the Html.DisplayNameFor()


helper because it renders the name of the property that you specify, taking into
account the DisplayName annotation if it is specified in the model class.
However, unlike the Html.DisplayNameFor() helper, the Html.LabelFor()
helper renders a <label> element.

The following code example renders a label for the CreatedDate property.

Using the Html.LabelFor() Helper

@Html.LabelFor(model => model.CreatedDate)

The Html.EditorFor() Helper

The Html.EditorFor() helper renders HTML <input> elements and other


form controls for properties from an model class. This helper renders the most
appropriate element for each property data type. For example, the
Html.EditorFor() helper renders <input type="text"> for a string property.
If the string property is annotated with
[DataType(DataType.MultilineText)], the Html.EditorFor() helper renders
a <textarea> element instead. The following table describes the HTML that
Html.EditorFor() renders for different model classes.

Control Model Class Property HTML Rendered by


EditorFor()

Text box public string Title { get; set; } <input type="text"

name="Title">

Multi-line [DataType(DataType.MultilineText)] <textarea


text box name="Description"
public string Description { get;

rows="20"
set;}
cols="80">
Control Model Class Property HTML Rendered by
EditorFor()

Check box [Display(Name = "Please send me <input

type="checkbox"
new offer details")]

name="ContactMe">
public bool ContactMe { get; set;

Please send me new


}
offer

details.

If the action passes an existing model object to the view, the


Html.EditorFor() helper also populates each control with the current values
of each property.

The following code example renders a check box for the ContactMe property.

Using the Html.EditorFor() Helper

@Html.EditorFor(model => model.ContactMe)

Question: You have a property in the Product model class named


ProductID. You want to include this in the HTML page so that client-side
script can use the ProductID value. However, you do not want the value to be
displayed to users. In the model class, you have annotated the ProductID
property with the [HiddenInput(DisplayValue=false)] attribute. How will
the Html.EditorFor() helper render this property?

Using Validation Helpers


When you request information from users, you often want the data they enter
in a certain format for further use in the web application. For example, you
might want to ensure that users enter a value for the LastName property. You
might also want to ensure that users enter a valid email address for the
EmailAddress property. You can set these requirements by using validation
data annotations in the model class. In controller actions, you can check the
ModelState.IsValid property to verify if a user has entered valid data.

When users submit a form, if they have entered

invalid data, most websites display validation messages. These messages are
often highlighted in red, but other colors or formats can be used. Often, there
is a validation summary at the top of the page such as “Please enter valid
information for the following fields: Last Name, Email Address”. The form
may display detailed validation messages next to each control in which the
user entered invalid data, or highlight the problems in user supplied data with
an asterisk.

When your MVC view displays a form, you can easily show validation
messages by using the validation helpers. Validation helpers render HTML
only when users have entered invalid data.

The Html.ValidationSummary() Helper

Use the Html.ValidationSummary() helper to render a summary of all the


invalid data in the form. This helper is usually called at the top of the form.
When the user submits invalid data, the validation messages are displayed for
each invalid field in a bulleted list. You can control the validation messages in
the model class by using this syntax in the annotation:

[Required(ErrorMessage="Please enter your last name")]

The following code example renders a summary of validation messages.

Using the Html.ValidationSummary() Helper

@Html. ValidationSummary()

The Html.ValidationMessageFor() Helper

Use the Html.ValidationMessageFor() helper to render validation messages


next to each input in the form.

The following code example renders a validation message for the LastName
property of the model class.

Using the Html.ValidationMessageFor() Helper

@Html.ValidationMessageFor(model => model.LastName)

Lesson 3: Re-using Code in Views


In a web application, you frequently render similar blocks of HTML content
in different webpages. For example, in an e-commerce web application, you
might want to display the most popular products on the home page, on the
front page of the product catalog, at the top of the product search page, and
perhaps in other locations. To render such HTML content in an MVC
application, you may copy and paste code from one Razor view into others.
However, to change the display of top products later in the project, you would
then have to make identical changes in many locations. A better practice is to
use a partial view. A partial view renders a section of HTML content that can
be inserted into several other views at run time. Because the partial view is a
single file that is re-used in several locations, when you implement a change
in a single location, the changes are updated in other locations in the web
application. Partial views increase the manageability of MVC web
applications and facilitate a consistent presentation of content throughout a
web application.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe how partial views enable you to re-use Razor code.


o Create partial views in an MVC 4 web application.
o Use partial views in an MVC 4 web application.
o Determine when to use partial views.

Creating Partial Views

You can use partial views to render identical HTML or similar HTML in
different locations in your web application. Consider a web application in
which users can comment on articles. In the article view, you want to display
the comments for that specific article at the end of the page. You want a
similar display on the home page, but you want to display the most popular
comments on any article. You can build a single comments partial view for
this scenario as follows:

First, create a partial view that displays a collection of comments in the required
o
format.
Next, create a controller action that retrieves the most popular comments, and
o
then passes them to the partial view.
o Then, create another controller action that uses the article ID to find comments
specific to that article. The controller action then passes this collection of
comments to the partial view.
o Finally, call the appropriate actions from the home page and the article view.

Because the partial view renders a collection of comments, you can re-use it
for various situations by passing different collections to it from controller
actions.

Creating and Naming Partial Views

In Visual Studio, you can create a partial view by using the Add View dialog,
in the same manner as creating any other view. Ensure that you select the
Create as a Partial View check box. Because partial views render a small
section of HTML rather than a complete webpage, Visual Studio does not add
<head>, <body>, and other tags to the partial view. By convention, partial
views are named prefixed with an underscore character, for example,
_CommentsList.cshtml. This convention is optional but is often helpful to
distinguish partial views in Solution Explorer.

Partial views are often created inside the /Views/Shared folder in your site.
Views in the Shared folder are accessible to many controllers, whereas views
in the /Views/Comment folder are accessible only from the
CommentController.

Strongly-typed and dynamic partial views

Similar to other views, you can create strongly-typed partial views if you are
certain that the partial view will always display the same model class. Visual
Studio can provide the most informative IntelliSense feedback and error-
checking for strongly-typed partial views, when compared with other types of
views. A strongly-typed view has the declaration of the @model directive at
the top of the file. Alternatively, you can create a dynamic partial view if you
are not certain that the partial view will always display the same model class.
You can create dynamic partial views by omitting the @model directive
declaration.

In the following example of a partial view, you can see the @model
declaration that makes the partial view strongly-typed. You can also see that
the partial view renders only an unordered list and not a complete HTML
webpage as the following lines of code indicate.

A Strongly-Typed Partial View

@model IEnumerable<Adworks.Models.Comment>

<ul>

@foreach (var item in Model) {

<li>

Subject: @Html.DisplayFor(modelItem => item.Subject)

</li>

</ul>

Question: You want to create a partial view that displays a list of comments.
The comments partial view will be called by actions in the PhotoController
and the HomeController. In which folder should you create the partial view
file?

Using Partial Views


Besides knowing how to create partial views, you need to know how to use
them within multiple other views in your site. You can re-use partial views by
using the Html.Partial() and Html.Action() HTML helpers.

The Html.Partial() Helper

You can use the Html.Partial() helper to render a partial view within another
view file. MVC inserts the HTML that the partial view renders into the parent
view and returns the complete webpage to the browser. The first parameter is
the name of

the partial view file without its file extension. The

second optional parameter is a model object for the partial view to render.
This is the same model object that the parent view uses because other model
objects are not available in this context.

The following lines of code call the _Comments.cshtml partial view without
passing a model object.

Using the Html.Partial() Helper

@Html.Partial("_Comments")

Remember that you can use the ViewBag and ViewData collections to pass
data between the action method and the view. A parent view will share the
same ViewBag or ViewData objects with the partial view. This is a good way
to share data between the controller action, view, and partial view.

The Html.Action() Helper

You can pass a model object from the parent view to a partial view when you
use Html.Partial(). However, the parent view can only pass the same model
object available in the parent view. Sometimes, you may want to use a model
object different from the parent view, often of a different model class, with the
partial view. In such cases, you can use the Html.Action() helper. This calls
an action method that returns the correct partial view. The action method can
create an instance of any model class.
Consider an Article view that displays the text and title of an Article object.
You want to display comments at the end of this view in a partial view. You
can use the Html.Action() helper to call an action in the Comments
controller that returns such a partial view. The partial view can work with a
collection of Comment objects.

In the following example, the Html.Action() helper calls an action in the


CommentController controller and passes the ID of the current article model
object.

Using the Html.Action() Helper

@Html.Action("_CommentsForArticle", "Comment", new { ArticleID =

Model.ID })

Question: You want to display user reviews of a product to each product


page. You have created a _ReviewsForProduct partial view. Would you use
Html.Partial() or Html.Action() to render this view?

Discussion: Partial View Scenarios

Consider the following scenarios when creating a web application:

You want to display the ten latest comments in the web application. When
o users click the Latest Comments link on the home page, they will see a new
webpage with the comments displayed.
You want to display the comments for an article on the Article view. You
o
also want to display the comments for a product on the Product view. There
are separate

ArticleComment and ProductComment

classes in your model, but they have similar properties.


You have a photo sharing web application and you want to display a gallery
of thumbnail images on both the AllPhotos view and the home page Index
o
view. The AllPhotos view should show every Photo object, but the home
page Index view should display only the three most recent photos uploaded.

For each scenario, discuss with the class:

o Whether you need to create a view or a partial view.


o Whether you need to create a strongly-typed view or a dynamic view.
If you decide to create a partial view, whether you need to use the
o
Html.Partial() or the Html.Action() HTML helper in the parent view.

Question: How can you improve the accessibility of the HTML that your
photo views render?

Question: In the lab, how did you ensure that the Create view for Photo
model objects could upload photo files when the user clicked the Create
button?

Module Review and Takeaways


In this module, you saw how to build the user interface for your web
application by creating views with the Razor view engine. Views can display
properties from a model class and enable users to create, read, update, and
delete objects of that model class. Some views display many objects by
looping through a collection of model objects. The HTML Helper methods
that are built into ASP.NET MVC 4 facilitate the rendering of displays,
controls, and forms, and return validation messages to users. Partial views can
be re-used several times in your web application to render similar sections of
HTML on multiple pages.
Best Practice: Use Razor comments, declared with the @**@ delimiters,
throughout your Razor views to help explain the view code to other
developers in your team.

Best Practice: Only use @: and <text> tags when Razor misinterprets
content as code. Razor has sophisticated logic for distinguishing content from
code, so this is rarely necessary.

Best Practice: Use strongly-typed views wherever possible because Visual


Studio helps you to write correct code by displaying IntelliSense feedback.

Common Issues and Troubleshooting Tips

Common Issue Troubleshooting


Tip

When a controller tries to access a partial view, an


exception is thrown.

Review Question(s)

Question: You want to display the name of the Comment.Subject property


in an MVC view that renders an Edit form for comments. You want the label
Edit Subject to appear to the left of a text box so that a user can edit the
Subject value. Which HTML helper should you use to render the field name?

Verify the correctness of the statement by placing a mark in the column to the
right.

Statement Answer

If your Razor generates errors by wrongly interpreting content as


server-side code, this indicates that you have explicitly declared
the content by using the @**@ delimiters.
Module 06: Testing and Debugging ASP.NET
MVC 4 Web Applications

Module Overview
Software systems such as web applications are complex and require multiple
components, often written by different developers, to work together. Incorrect
assumptions, inaccurate understanding, coding errors, and many other sources
can create bugs that result in exceptions or unexpected behavior. To improve
the quality of your web application and create a satisfying user experience,
you must identify bugs from any source and eliminate them. Traditionally,
most testing has been performed at the end of a development project.
However, it has recently become widely accepted that testing throughout the
project life cycle improves quality and ensures that there are no bugs in
production software. You need to understand how to run tests on small
components of your web application to ensure that they function as expected
before you assemble them into a complete web application. You also need to
know how to use the tools available in Microsoft Visual Studio 2012 to debug
and trace exceptions when they arise.

Objectives

After completing this module, you will be able to:

Run unit tests against the Model–View–Controller (MVC) components, such


o
as model classes, and locate potential bugs.
o Build an MVC application that handles exceptions smoothly and robustly.

Lesson 1 : Unit Testing MVC Components


A unit test is a procedure that instantiates a component that you have written,
calls one aspect of the functionalities of the component, and checks that the
component responds correctly according to the design. In object-oriented
programming, unit tests usually instantiate a class and call one of its methods.
In an MVC web application, unit tests can instantiate model classes or
controllers and call their methods and actions. As a web developer, you need
to know how to create a testing project and add tests to the testing project. The
tests check individual aspects of your code without relying on database
servers, network connections, and other infrastructure. This is because unit
tests focus on the code you write.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe the use of unit tests to improve the quality of code you write.
o List the principles of Test Driven Development (TDD).
Describe how loosely-coupled components increase the testability and
o
maintainability of your application.
Write unit tests against model classes, controllers, and views in an MVC
o
web application.
Describe how Inversion of Control (IoC) containers can instantiate
o
controllers and model classes.
o Run unit tests in Visual Studio 2012.
o Use a mocking tool to automate mock creation in unit tests.

Why Perform Unit Tests?

There are three types of tests you can use to identify bugs in your application:

Unit Tests: Unit tests check small aspects of functionality. For example, a
unit test may verify the return type of a single method. By defining many
o
unit tests for your project, you can ensure they cover all functional aspects of
your web application.
Integration Tests: Integration tests check how two or more components work

together. They can be used to check how


o
two or more classes interact with each other. Integration tests can also be
used to check how the entire web application, including the database and
external web services, works to deliver content.
Acceptance Tests: Acceptance tests focus on a functional or technical
requirement that must work for the stakeholders to accept the application.
Similar to integration tests, acceptance tests usually test multiple
o components working together.

Note: Unit tests are important because they can be defined early in
development. Integration and acceptance tests are usually run later, when
several components are approaching completion.

What Is a Unit Test?

A unit test is a procedure that verifies a specific aspect of functionality.


Multiple unit tests can be performed for a single class and even for a single
method in a class. For example, you can write a test that checks that the
Validate method always returns a Boolean value. You might write a second
test that checks that when you send a string to the Validate method, the
method returns a true value. You can assemble many unit tests into a single
class called a test fixture. Often, a test fixture contains all the tests for a
specific class. For example, ProductTestsFixture may include all tests that
check methods in the Product class.

A single unit test usually consists of code that runs in three phases:

Arrange. In this phase, the test creates an instance of the class that it will
test. It also assigns any required properties and creates any required objects
1.
to complete the test. Only properties and objects that are essential to the test
are created.
Act. In this phase, the test runs the functionality that it must check. Usually,
2. in the Act phase, the test calls a single procedure and stores the result in a
variable.
3. Assert. In this phase, the test checks the result against the expected result. If
the result matches what was expected, the test passes. Otherwise, the test
fails.

How Do Unit Test Help Diagnose Bugs?

Because unit tests check a small and specific aspect of code, it is easy to
diagnose the problem when the tests fail. Unit tests usually work with a single
class and isolate the class from other classes wherever possible. If other
classes are essential, the smallest number of classes are created in the Arrange
phase. This approach enables you to fix issues rapidly because the number of
potential sources of a bug is small.

Unit tests should check the code that you write and not any infrastructure that
the production system will rely on. For example, unit tests should run without
connecting to a real database or web service because network problems or
service outages may cause a failure. Using this approach, you can distinguish
bugs that arise from code, which must be fixed by altering code, from the bugs
that arise from infrastructure failures, which must be fixed by changing
hardware, reconfiguring web servers, reconfiguring connection strings, or
making other configuration changes.

Automated Unit Testing

It is important to understand that unit tests, after they are defined, can be rerun
quickly and easily throughout the rest of the project life cycle. In fact,
Microsoft Visual Studio reruns tests automatically whenever you run a project
with debugging. You can also manually initiate tests any time.

This is important because new code can cause bugs at any stage of the
development process. As an example, consider a project that proceeds through
three phases. A unit test defined for phase 1 helps highlight problems in
phases 2 and 3 that might otherwise go unnoticed:

Phase 1. The ProductController class is defined and the


Test_Index_Action unit test is written. The test checks that the Index
1. action works with an integer parameter. When you call the Index action
with an integer, the action returns a collection that includes the same
number of Product objects. The test passes.
Phase 2. A developer modifies the Index action so that it returns a partial
view. The developer renames the action _Index to conform to the team’s
2. partial view naming convention. The test fails because the name has
changed. The developer modifies the test so that it calls the renamed action
and the test passes.
Phase 3. A developer modifies the Index action by writing a different
Language Integrated Query (LINQ) to implement a new functional
3. requirement. However, the developer makes a mistake in the LINQ syntax.
The Index action now returns zero products regardless of the integer that is
passed as a parameter. The test fails.

In Phase 2, the test failure arose because the action name had changed, not
because of a mistake in the action code. The solution was to change the name
of the action called in the test method, but this can remind developers to alter
calls to renamed actions throughout the solution.

In Phase 3, the test failure arose because the developer misunderstood LINQ
or made a typing error in the LINQ syntax. The unit test highlighted the error
as soon as it arose. This helps the developer focus on a solution to resolve the
test failure and ensure that new functionality does not cause failures in code
written earlier in the project.

Question: Board members want you to ensure that your web application
correctly calculates sales tax on every product in the catalog. Is this an
example of a unit test, an integration test, or an acceptance test?

Principles of Test Driven Development


You can use unit tests in any development methodology, including waterfall
projects, iterative projects, and Agile projects to spot potential bugs and
improve the quality of the final application. Any project can benefit from unit
testing, regardless of the development methodology used in the project.
However, a specific development methodology, called Test Driven
Development (TDD), places unit testing at the center of working practices.
TDD is often described as a separate development methodology. Some
authors consider it to be a

core principle of the Extreme Programming methodology.

Write the Test, Pass the Test, Refactor

In TDD, developers repeat the following short cycle to implement a functional


requirement:

Write the Test. The developer starts by creating and coding the unit test.
This step requires a full understanding of the functional requirement, which
1.
can be obtained from use cases or user stories. Because the developer has
not written any code in the application, the test fails.
Pass the Test. The developer writes some quick and simple code in the
application so that it passes the test. During the first iteration, this code is
2.
frequently inelegant and may include false assumptions such as hardcoded
values.
Refactor. The developer cleans up the application code, removes duplicate
code, removes hardcoded values, improves readability, and makes other
3.
technical improvements. The developer reruns the test to ensure that
refactoring has not caused a failure.

The cycle is then repeated. In each iteration, the developer adds a small new
element of the final functionality with a corresponding test.

It is important that the code in your tests is treated as production code. It


should be well thought out and easy to read so that other developers can
understand the test and quickly diagnose any test failures.

Test Driven Development Principles


TDD is different from traditional approaches to application development. To
use TDD effectively, you must understand its fundamental principles:

Write tests before code. In the TDD development cycle, the test is created in
step one before any code in the application. This means the test must fail the
o first time it is run. You can understand the test as a specification for the
functionality you are building. By writing the test first, you ensure that you
begin with a thorough understanding of the problem you are trying to solve.
Move in small steps. By breaking a large application down into small
elements of functionality, you can improve developer productivity. You can
o do this by giving a developer a small problem to solve in each iteration. The
developer can solve the simple problem quickly and understand all the
possible circumstances in which their code runs.
Only write enough code to pass the test. In each iteration, do not be tempted
to add extra code that is not related to the test. For example, if you know that
o users will call an action with other parameters than the ones in the test, do
not write code to handle these parameters. Instead, during the next iteration,
write a second test for those parameters. Then write and refactor that code.

Developers can refer to tests as examples of how to use a class or method.


This can increase developer productivity because developers can view the
code that demonstrates the method or class.

Note: In the lab, you will use some TDD principals as you develop the
solution. However, the lab does not conform to a strict reading of the TDD
methods.

Question: You have written a controller for the Comment model class. You
write a unit test that checks that the Index action returns a collection of
Comment objects. Have you conformed to TDD principles?

Writing Loosely Coupled MVC Components


A loosely coupled application is one in which each component requires few or
no details of the other components of the system. In object-oriented
programming, for example, two classes can be described as loosely-coupled if
one class can call methods on the other class without any code that is specific
to the other class. When system components are loosely-coupled in this
manner, it is easy to replace a class with another implementation of the same
functionality. Loosely coupled components are essential for thorough unit
testing because classes that deal with real

data, such as data from a database, can be easily be replaced with classes that
deal with test data.

Using Loose Coupling in Tests

A loosely-coupled application is easy to test because you can make tests


simpler by replacing a fully functional instance of a class with a simplified
instance that is specifically designed for the test. Replacing classes in tests in
this manner can only be done when components are loosely coupled.
Replacement instances used for unit tests are known as test doubles or fakes.
A test double or fake includes just enough code and properties to pass the
relevant test and prove the functionality.

Other Benefits of Loose Coupling

Loose coupling has other benefits besides testing. Loose coupling makes it
easier to replace simple components with more sophisticated ones—for
example, in version one of an application you might write a class that
calculates a simple arithmetical mean. In version two, you might replace this
class with a new class that calculates a weighted mean based on a more
complex algorithm. If the components are loosely coupled, you can perform
this replacement without modifying any code outside of the averaging classes.

Using Interfaces for Loose Coupling

In object-oriented programming, an interface defines a set of properties and


methods. Any class that implements that interface must implement all the
properties and methods it defines as a minimum. This creates loose coupling
because you need not specify a class in code. Instead, you can specify any
implementation of a particular interface.

Loose Coupling in an MVC Web Application

To show how loose coupling can be used in an MVC web application,


consider the following scenario:

You are writing an MVC web application that displays a product catalog and
enables users to click a product to view the full details. On the product details
page, users can view and add reviews of that product. You want to ensure
during testing that the Product.Reviews property, which is a collection of
Review objects, only includes reviews with the right ProductID value.

Recall that unit tests should not rely on infrastructure such as network
connections or database servers, but only on test code. By contrast, in
production, the application will obtain all product reviews from a database. To
satisfy the needs of testing and production, you can build the following
components:

An IProduct interface. This includes a definition of the Reviews property,


o together with other properties and methods. This interface is known as a
repository.
A Product class. This is the implementation of the IProduct repository that
the application uses in production. When the user calls the Reviews
o
property, all the reviews for the current product are obtained from the
database.
o A TestProduct class. This is the test double or fake implementation of the
IProduct repository that the test uses. The test sets up a TestProduct object
and fake reviews with different ProductID values. The test calls the
TestProduct.Reviews property and checks that only the right reviews are
returned.

Notice that, in the test, the TestProduct double uses in-memory data set up
during the Arrange phase. It does not query the database. Therefore, you can
test your code without relying on the network connection to the database or
the database server itself. This approach also ensures that the test runs quickly,
which is important because slow tests discourage developers from running
tests regularly.

Question: In a test, you create a fake collection of BlogEntry objects. Is this


an example of an interface or a test double?

Writing Unit Tests for MVC Components

The Microsoft ASP.NET MVC 4 programming model is easy to integrate with


the principles of unit testing and TDD because of its separation of concerns
into model, controllers, and views.

Models are simple to test because they are independent classes that you can
instantiate and configure during the Arrange phase of a test.

Controllers are simple classes that you can test, but it is complex to test
controllers with in-memory data, rather than using a database. To test
controllers with in-memory data, you create a test double class, also known as
a fake repository.
Objects of this class can be populated with test data in memory without
querying a database. You need to understand how to write test doubles and
how to write a typical test for MVC classes.

Add and Configure a Test Project

In Microsoft Visual Studio 2012, you can test an MVC web application
project by adding a new project to the solution, based on the Unit Test
Project template. You must add references to the test project so that test code
can access classes in the MVC web application project. You will also need a
reference to System.Web.Mvc and other namespaces from the Microsoft
.NET Framework.

In a Visual Studio test project, test fixtures are classes marked with the
[TestClass] annotation. Unit tests are methods marked with the [TestMethod]
annotation. Unit tests usually return void but call a method of the Assert
class, such as Assert.AreEqual() to check results in the test Assert phase.

Note: There are many other test frameworks available for MVC web
applications and you can choose the one you prefer. Many of these
frameworks can be added by using the NuGet package manager available in
Visual Studio. If you use Visual Studio Express, you cannot use the Visual
Studio Unit Test Project template, but you can add other testing frameworks
by using NuGet.

Test Model Classes and Business Logic

In MVC, model classes do not depend on other components or infrastructure.


You can easily instantiate them in-memory, arrange their property values, act
on them by calling a method, and assert that the result was as expected.
Sometimes, you create business logic in the model classes, in which case the
Act phase involves calling a method on the model class itself. If, by contrast,
you have created a separate business logic layer, code in the Act phase must
call a method on the business object class and pass a model class.

The code in this test creates an instance of the Product model class and sets
its Type property. The test checks that in these circumstances, the
GetAccessories() method returns a collection of BikeAccessory objects.
Testing a Model Class

[TestMethod]

public void Test_Product_Reviews()

//Arrange phase

Product testProduct = new Product();

testProduct.Type = "CompleteBike";

//Act phase

var result = testProduct.GetAccessories();

//Assert phase

Assert.AreEqual(typeof(IEnumerable(BikeAccessory)),

result.GetType());

Create Repository Interfaces

A repository is an interface that defines properties and methods that MVC can
use to store data in a web application. It is common to create a single
repository interface for your entire web application.

In the following code example, the IWebStoreContext interface is a


repository that defines methods such as Add() and Delete(), and properties
such as Products.

A Repository Interface

public interface IWebStoreContext


{

IQueryable<Product> Products { get; }

T Add<T>(T entity) where T : class;

Product FindProductById(int ID);

T Delete<T>(T entity) where T : class;

Implement and Use a Repository in the Application

The repository interface defines methods for interacting with data but does not
fix how that data will be set and stored. You must provide two
implementations of the repository:

An implementation of the repository for use in production and development.


o This implementation will use data from the database or some other storage
mechanism.
An implementation of the repository for use in tests. This implementation
o
will use data from the memory set during the Arrange phase of each test.

The following code example shows how to implement the repository interface
in your MVC project for use in production and development.

Implementing a Repository in the MVC Project

public class WebStoreContext : DbContext, IWebStoreContext

public DbSet<Product> Products { get; set; }

IQueryable<Product> IWebStoreContext.Products { get { return

Photos; } }

T IWebStoreContext.Add<T>(T entity)
{

return Set<T>().Add(entity);

Product IWebStoreContext.FindProductById(int ID)

return Set<Product>().Find(ID);

T IWebStoreContext.Delete<T>(T entity)

return Set<T>().Remove(entity);

Note that the WebStoreContext class still inherits from the Entity Framework
DbContext class but also implements the IWebStoreContext interface that
you just created. In fact, the interface methods such as Add(), Delete(), and
FindProductById() just wrap methods from the DbContext class such as
Remove().

Implement a Repository Test Double

The second implementation of the repository interface is the implementation


that you will use in unit tests. This implementation uses in-memory data and a
keyed collection of objects to function just like an Entity Framework context,
but avoids working with a database.

The following code example shows how to implement a repository class for
tests.
Implementing a Fake Repository

class FakeWebStoreContext : IWebStoreContext

//This object is a keyed collection we use to mock an

//entity framework context in memory

SetMap _map = new SetMap();

public IQueryable<Product> Products

get { return _map.Get<Product>().AsQueryable(); }

set { _map.Use<Product>(value); }

public T Add<T>(T entity) where T : class

_map.Get<T>().Add(entity);

return entity;

public Product FindProductById(int ID)

Product item = (from p in this.Products

where p.ProductID == ID
select p).First();

return item;

public T Delete<T>(T entity) where T : class

_map.Get<T>().Remove(entity);

return entity;

class SetMap : KeyedCollection<Type, object>

public HashSet<T> Use<T>(IEnumerable<T> sourceData)

var set = new HashSet<T>(sourceData);

if (Contains(typeof(T)))

Remove(typeof(T));

Add(set);

return set;

}
public HashSet<T> Get<T>() { return (HashSet<T>)

this[typeof(T)]; }

protected override Type GetKeyForItem(object item)

return item.GetType().GetGenericArguments().Single();

Using the Test Double to Test a Controller

After you have implemented a test double class for the repository, you can use
it to test a controller in a unit test. In the Arrange phase of the test, create a
new object from the test double class and pass it to the controller constructor.
The controller uses this object for its Entity Framework context during the test
Act phase. This enables you to check results.

The following code example shows how to test a controller action by using a
test double for the Entity Framework context.

Using a Test Double to Test a Controller

[TestMethod]

public void Test_Index_Model_Type()

var context = new FakeWebStoreContext();

context.Products = new[] {

new Product(),
new Product (),

new Product ()

}.AsQueryable();

var controller = new ProductController(context);

var result = controller.Index() as ViewResult;

Assert.AreEqual(typeof(List<Product>), result.Model.GetType());

Note that the test creates a new instance of the FakeWebStoreContext class
and adds three Product objects to it. In this case, you can run the test without
setting any properties on the Product objects. This context is passed to the
ProductController constructor and the test proceeds to the Act and Assert
phases.

Question: For what purpose would you use a fake repository when you write
unit tests against an MVC controller?

Specifying the Correct Context

When you use test doubles for unit testing MVC controllers, you must ensure
that the controller uses the correct context in two different scenarios: unit
tests, and at all other times. If you use the test double production code, for
example, no data will be stored in the database. If you use the actual Entity
Framework context for unit testing, all the tests will fail. The following table
gives further details.

Scenario Context

In unit In a unit test, you should test code without relying on underlying
tests infrastructure such as databases. You can use a test double class
that behaves like an Entity Framework context, but uses in-
memory data.

At other When you are not unit testing the code, you use an actual Entity
times Framework context in your controller code, which interacts with
a database.

Using Constructors to Specify a Repository

You can specify the correct repository to use in a test by using controller
constructors. During a unit test, call a controller constructor that takes an
instance of the repository interface as a parameter. At other times, the MVC
controller factory will call the controller constructor without any parameters.

The following code example shows the constructors in an MVC controller that
you can use for production and unit testing.

Using Constructors to Specify Repositories

public class ProductController : Controller

private IWebStoreContext context;

//The parameterless version of the constructor is used by the MVC

controller factory
public ProductController()

//Instantiate an actual Entity Framework context

context = new WebStoreContext();

//This constructor is used by unit tests. They pass a test double

context

public ProductController(IWebStoreContext Context)

//Use the context passed to the constructor

context = Context;

//Add action methods here

Using Inversion of Control Containers

You can also ensure that the correct repository class is used in each context by
using an Inversion of Control (IoC) container. An IoC container is a
framework that you can add to your application that instantiates classes. You
must configure the IoC container so that it can identify the kind of object to
create when the application expects a specific interface. For example, when
code is used to create a new instance of the IWebStoreContext interface, the
IoC container checks its configuration and finds that it should instantiate the
WebStoreContext class, which is an Entity Framework context that
implements the IWebStoreContext interface.
Note: IoC frameworks are also known as Dependency Injection (DI)
frameworks because they inject classes that implement the correct interfaces
into class constructors.

By using an IoC container, you avoid the need to create two constructors for
controller classes. During tests, you can instantiate the test double and pass it
to the controller constructor. At other times, the IoC container instantiates the
actual Entity Framework context and passes it to the controller constructor.

Note: There are many IoC containers designed for use with ASP.NET MVC
web applications. These replace certain components of the MVC framework
to support IoC. For example, they replace the default controller factory with a
factory that instantiates controllers with the right context class. Many IoC
containers are available in the NuGet package library, such as NinJect and
StructureMap.

Question: Which approach is more loosely-coupled: using constructors to


specify the context, or using IoC containers to specify the context?

Using Mocking Frameworks

When you write a unit test, you must, during the Arrange phase, create test
data on which the test will run. By using a test double or mock object to
supply test data, you can test your code in isolation from other classes and
from the infrastructure elements such as databases and network connections
on which the application will rely. You can create test doubles by manually
coding their instantiation, setting their properties, and populating collections.
Such test doubles are known as manual mock objects.

Alternatively, instead of creating mock objects


manually with your own code, you can use a mocking framework to automate
this work. A mocking framework automatically creates mock object by using
the interfaces that you specify. In the case of IoC containers, there are many
mocking frameworks that can be used in testing MVC web applications. You
can find many mocking frameworks by using the NuGet package manager.

Note: Mocking frameworks for ASP.NET MVC 4 include Moq, RhinoMocks,


and NSubstitute. All these frameworks are available in NuGet and there are
alternatives. Choose the framework that best suits your testing needs.

Why Use a Mocking Framework?

There are many situations in which mocking frameworks can significantly


ease unit testing. Even for simple tests, mocking frameworks reduce the
amount of setup code that you have to develop. After you become familiar
with the mocking framework that you choose, and have learned how to write
arrangement code for it, you will begin to save time. In more complex
situations, such as the following, mocking frameworks have great advantages:

Creating multiple mock objects of a single type. You should try to keep each
unit test as simple as possible, but inevitably, some tests require many mock
objects to work with. For example, if you are testing a method that underlies
o
paging functionality in your web application, you must create enough mock
objects to populate multiple pages. Mocking frameworks can automate the
creation of multiple mock objects of the same type.
Mocking objects with multiple interfaces. In some tests, where there are
several dependencies between classes of different types, you must create
o many mock objects of different classes. In such situations, it is tedious to
manually code many mock objects. Mocking frameworks can help by
automatically generating the objects from the interfaces that you specify.

In each unit test, you are interested in a small and specific area of
functionality. Some properties and methods of an interface will be crucial to
your test, while others will be irrelevant. A mocking framework enables you
to specify irrelevant properties and methods in a given test. When the
framework creates a mock object for your test, it creates stubs for the
irrelevant properties and methods. A stub is a simple implementation with
little code. In this way, the mocking framework frees you from having to
implement all the requirements of the interface laboriously.

Question: What is the difference between an IoC container and a mocking


framework?

Lesson 2: Implementing an Exception Handling


Strategy
Unexpected events are likely to occur from time to time in any complex
system, including MVC web applications. Occasionally, such unexpected run-
time events cause an error. When this happens, ASP.NET or the .NET
Framework generates an exception, which is an object that you can use to
diagnose and resolve the error. The exception contains information that you
can use to diagnose the problem. Exceptions that are not handled in your code
will cause the web application to halt and an error message to be displayed to
the user. As a web developer, you need to know how to detect, handle, and
raise exceptions, and identify the cause of the problem. Visual Studio provides
a broad range of tools for debugging exceptions and improving the robustness
of your code. You can also log exceptions to databases and other stores, and
use the .NET Framework code contracts to reduce the frequency of
exceptions.

Lesson Objectives
After completing this lesson, you will be able to:

o Explain how to raise and catch exceptions.


o Explain how to configure exception handling by using Web.config.
o Explain how to trace exceptions by using the IntelliTrace tool.
o Describe how to log exceptions.
o Describe the health monitoring options for an MVC 4 web application.

Raising and Catching Exceptions


An error is an unexpected run-time event that prevents an application from
completing an operation. When a line of code causes an error, ASP.NET or
the common language runtime creates an exception. This exception is an
object of a class that inherits from the System.Exception base class. There are
many exception classes.

Often the object class identifies what went wrong.

For example, if there is an

ArgumentNullException, it indicates that a null value was sent to a method


that does not accept a null value as an argument.

Unhandled Exceptions

When an exception is not explicitly handled by an application, the application


stops and the user sees an error message. In ASP.NET MVC applications, this
error message is in the form of a webpage. You can override ASP.NET
default error pages to display your own error information to users.

If an unhandled exception arises while you are debugging the application in


Visual Studio, execution breaks on the line that generated the exception. You
can use the Visual Studio debugging tools to investigate what went wrong,
isolate the problem, and debug your code.

Sometimes, you may also want to raise your own exceptions as a form of
communication between parts of your application. For example, consider an
application that displays products on a website. In the repository, you
implement a FindProduct method that returns the product with a name that
matches the search string that is passed as an attribute. If the FindProduct
method does not locate a product with the specified name, you may wish to
raise an exception. This approach enables code in the controller, which calls
the FindProduct method, to handle the event that no products are found. You
can use the throw keyword to raise errors in C# code.

Catching Errors with Try/Catch Blocks

The most familiar way to catch an exception, which works in any .NET
Framework code, is to use the try/catch block. Code in the try block is run. If
any of that code generates an exception, the type of exception is checked
against the type declared in the catch block. If the type matches, or is of a
type derived from the type declared in the catch block, the code in the catch
block runs. You can use the code in the catch block to obtain information
about what went wrong and resolve the error condition.

The following code example catches any ArgumentNullException objects.

A Simple Try/Catch Block

try

Product product = FindProductFromComment(comment);

catch (ArgumentNullException ex)

Console.WriteLine("The comment object was null. Error message: " +

ex.Message);

In MVC controllers, there are two methods to catch exceptions—the


OnException method and the [HandleError] annotation.
Catching Controller Exceptions in OnException

The OnException method is defined on the base Controller class, so you can
override it in any MVC controller. When you override the OnException
method in a custom controller, MVC runs the method whenever an exception
arises and is not handled in a try/catch block. Using this approach, you can
handle errors anywhere in your controller without adding many try/catch
blocks throughout the code.

In the OnException method, you can catch specific types of exceptions by


checking the ExceptionContext.Exception property. Your code must set the
context.Result property to display a view to the user. If you do not set this
property, the browser displays a blank webpage to the user.

In the following code example, the OnException method is used to catch


InvalidOperationException objects.

Using OnException to Catch Controller Errors

protected override void OnException(ExceptionContext context)

// Catch invalid operation exception

if (filterContext.Exception is InvalidOperationException)

var model = new HandleErrorInfo(context.Exception,

controllerName, actionName);

var result = new ViewResult

ViewName = "Error",

ViewData = new ViewDataDictionary<HandleErrorInfo>(model),


//Save pass the current Temp Data to the Error view,

because it often

contains

//diagnostic information

TempData = context.Controller.TempData

};

context.Result = result;

Catching Controller Exceptions with HandleError

Using the [HandleError] annotation, you can use an attribute on individual


action methods or on the controller class itself, in which case, the
[HandleError] annotation catches errors in any action. When you use the
[HandleError] annotation without properties, all exceptions are caught and
sent to an MVC view called Error.cshtml. This default error view should be
created in the /View/Shared folder.

You can use two properties to control the behavior of [HandleError]:

ExceptionType. By default, the [HandleError] annotation catches all


o exceptions. If you set a more specific type with the ExceptionType
property, only exceptions of that specific type will be caught.
View. By default, the [HandleError] annotation forwards users to the
Error.cshtml view. You can specify another view file by using the View
o property. By setting both the ExceptionType and View properties, you can
divert exceptions of specific types to views designed specifically to display
them.
In the code example, the first [HandleError] annotation forwards
NotImplementedException errors to the NotImplemented view. All other
errors are forwarded to the default error view.

Using the HandleError Annotation

[HandleError(ExceptionType=typeof(NotImplementedException),

View="NotImplemented")]

[HandleError]

public ActionResult Index()

//Place action code here

Question: You are using the [HandleError] annotation to catch exceptions in


your web application. However, you realize that [HandleError] catches all
exceptions, making it difficult for you to isolate a specific issue. What can you
do to narrow down the exceptions that the [HandleError] annotation is
catching?

Configuring Exception Handling


ASP.NET applications display a default error page to users when an
unhandled exception occurs in your MVC web application. There are two
reasons why you may want to change the default error page:

You want to display a branded and styled error page that has the same layout
o
as other pages in the application and includes the company logo.
You want to avoid drawing attention to the technology that powers the site.
By

o letting malicious users know that your

site runs ASP.NET MVC, you may encourage them to attack it by using
methods that have worked in the past.

To configure a custom error page for your application, use the top-level
Web.config file. The custom error page will be displayed when an exception
in not handled by any try/catch block or [HandleError] attribute.

Custom Error Modes

To configure custom errors, add the <customErrors> element to the


Web.config file. This element must be a child of the <system.web> element.
Use the following attributes:

mode: The mode attribute can be set to one of three values:

▪ Off: Unhandled errors are displayed on the default ASP.NET error page.
On: Unhandled errors are displayed in the page you specify in the

defaultRedirect attribute.
RemoteOnly: In this mode, unhandled errors are displayed differently for
o browsers on remote computers and browsers on the web server. In a
production site, all browsers are remote and errors are displayed on the page
that you specify in the defaultRedirect attribute. In development situations,

the developer often browses to the site on the local computer. When an error
occurs, the developer is directed to the default ASP.NET error page, which
includes debugging information such as the stack trace. Use the RemoteOnly
mode on development computers.
defaultRedirect: This attribute sets the name of the view that will be used to
o display unhandled exceptions. When you create this view, place it in the
Views/Shared folder.

The code in the following example enables custom errors and specifies that
unhandled exceptions are forwarded to the customError view.

Configuring Custom Errors

<system.web>

<customErrors mode="On" defaultRedirect="CustomError" />

</system.web>

HTTP error pages

Some Hypertext Transfer Protocol-level (HTTP) errors cannot be caught by


custom MVC error views as specified in Web.config or the [HandleError]
annotation. For such errors, you can use the <error> element in Web.config,
as a child element of the <customErrors> element.

In the following example, the <error> element is used for specific HTML
files to respond to HTTP 500 errors.

Catching HTTP Error Codes

<customErrors mode="On" defaultRedirect="CustomError" >

<error statusCode="500" redirect="~/Error/Error500.html" />

</customErrors>

Question: You have switched off custom errors in the Web.config file. When
you run your application without debugging, an exception is thrown in a
try/catch block. What page displays the exception to the user?

Using Visual Studio IntelliTrace in MVC


When something goes wrong in your web application, whether it happens
during development or in production, you need information about the state of
the application, to diagnose the problem. Sometimes, a small amount of
information is sufficient. For example, you may be able to see from the URL
query string that a link was formulated wrongly. Often, however, problems
arise in more obscure places and you need as much information as possible to
perform a diagnosis. IntelliTrace is a feature of Visual Studio that assists
debugging by presenting

as much information as possible. IntelliTrace was introduced with Microsoft


Visual Studio 2010 Ultimate.

The Traditional Debugging Workflow

When developers debug malfunctioning code, they run the application in


Visual Studio debugging mode. If an unhandled exception occurs, Visual
Studio breaks execution and displays details such as the exception class and
the exception message. You can use the Locals, Call Stack, and Error List
windows to determine the values of variables and properties that may have
caused the exception. All these pieces of information are presented as they
were when the error occurred.

If a problem originated before the error occurred, you must halt debugging, set
a break point, and then restart debugging. Again, Visual Studio halts
execution, but this time, it is at the break point. You can use the same
windows to gain information and step through code, line by line, to see how
values change, and diagnose the error.
Two problems can occur in this workflow:

If you set the break point too late, you will miss the origin of the error. You
o
must set another break point and restart debugging.
If you are stepping through many lines of code, you can miss the error by
o selecting Debug|StepInto or pressing the F11 shortcut too many times. This
is easy to do when there are hundreds of lines of code to step through.

Debugging With IntelliTrace

IntelliTrace improves this workflow and addresses the two problems that arise
during the traditional debugging workflow by recording a timeline of code
execution. When you run an application in the debug mode, IntelliTrace
records all the events that occur in the background. This can include
exceptions, debugging events such as break points, and other events that you
can configure.

As before, when the debugger encounters an unhandled exception or a break


point, Visual Studio halts execution and displays the details of any exception.
However, the developer can now see all the recorded events in the IntelliTrace
pane. The current event appears at the end of the list and is named Live
Event. You can see all the previous events in the list and can click them for
more details. In this way, you can investigate what happened before the
exception or the break point.

When you click an earlier event in the IntelliTrace pane, the Locals, Call
Stack, and Error List windows display the state of the application at the
moment of the earlier event. The line of code that corresponds to the selected
event is highlighted in orange color. Because of this highlighting, two
problems that arise during the traditional debugging workflow are eased,
namely, missing the origin of error and stepping too far through the code.
Because the relevant code is highlighted, if you miss the origin of the error or
step too far through the code, you can get back to earlier events and
investigate values.

To help you locate the correct event in the IntelliTrace window, you can filter
by event category or execution thread, or use the search option.
IntelliTrace Configuration Options

To configure IntelliTrace, click DEBUG, click IntelliTrace, and then click


Open IntelliTrace Settings. You can enable or disable IntelliTrace event
recording and specify a location and maximum size for the IntelliTrace files.

Most of the configuration options concern the amount of data to record in


IntelliTrace files. The default settings have a mimimal affect on performance,
but if those are insufficient to diagnose a problem, you can choose to log more
information to target the problem. This may compromise performance, but
remember that IntelliTrace information is only recorded during debugging.
Your settings will not degrade performance after the application is deployed
to a web server. Under General, you can set IntelliTrace to record IntelliTrace
events only, or both IntelliTrace events and call information, which includes
all calls to methods and classes. You can configure what is included in
IntelliTrace events by using the IntelliTrace Events list. For example, by
default, ASP.NET events such as error pages, page post backs, and redirects
are included for MVC applications.

Saving and Opening IntelliTrace Files

IntelliTrace automatically saves events in an IntelliTrace file when you enter


debug mode. The file is automatically deleted when you close Visual Studio,
to ensure that IntelliTrace files do not over-use disk space. Note that this
means that the IntelliTrace pane includes events from the current debugging
session and any previous debugging sessions run since you started Visual
Studio. However, these files are temporary.

You can avoid losing an IntelliTrace file when you close Visual Studio by
saving it for later analysis. To do this, click DEBUG, click IntelliTrace, and
then click Save IntelliTrace Session. The file is saved with an .iTrace
extension. If you double-click an .iTrace file, Visual Studio displays the
threads, exceptions, modules, and other information that the file contains.

Additional Reading: For more information about IntelliTrace and how to use
it, see http://go.microsoft.com/fwlink/?LinkID=288962&clcid=0x409
Question: You are looking at IntelliTrace events and suspect that the error
originated in a class written by a colleague who works in another country.
How can you help the colleague to see the events that you can see in
IntelliTrace after you close Visual Studio?

Logging Exceptions

Exceptions that you face during development can be investigated and


debugged by using the Visual Studio debugging tools, including IntelliTrace.
In an ideal situation, no exceptions would arise when your web application is
complete and deployed for users over the Internet. However, in the real world,
unforeseen circumstances arise resulting in exceptions. For example, database
failures, network issues, and configuration errors in any part of the system can
cause exceptions.

You have already seen how to present a branded and informative custom error
page to users when

exceptions occur. It is also appropriate to log the exceptions in a production


web application, so the administrators and developers can assess the extent of
the problem, remove the cause, and improve the robustness of the code.

Writing Error Logging Code

Before you write code to log exceptions in your web application, consider
where exceptions should be recorded. Generally, web applications log
exceptions to an Extensible Markup Language (XML) file. This approach can
be efficient, especially if the text file is kept on a separate drive from the
database of the web application and other critical, commonly accessed files.
However, the file size of the XML files can grow large, making them difficult
to analyze.

A common approach is to log errors to tables in a database. These tables can


be a part of a single web application database, or you can place them in a
dedicated database away from product catalogs, user profiles, and other
information. By logging exceptions to a database, you create a list of
exceptions that can be easily searched and analyzed. You can also build a
webpage to present these logged exceptions to administrators so that they can
access the details from a browser.

You should also consider sending email messages or other types of messages
to administrators and developers when exceptions occur. This approach
ensures that administrators and developers hear of an error very quickly. It
does not require them to review the exceptions logged in the database.
Frequently, error handling code in live applications both logs to a database
and send email messages to administrators and developers.

Where to Write Error Logging Code

When you decide where to write code that logs errors, you should consider
that errors might arise in almost any part of your application. You should
choose an approach that enables you to write error logging code once that will
run for any exception anywhere in your application.

For example, it is not appropriate to write error logging code in individual


try/catch blocks. If you do this, you will have to create a try/catch block for
every procedure in your application, and write duplicate logging code in the
catch block.

A more effective approach is as follows:

Create a custom base controller class for your web application. This class
o
inherits from the System.Web.Mvc.Controller base class.
In your custom base controller class, override the OnException() method.
o
Place you error logging code in this method.
o When you create controllers, inherit from your custom base controller class,
instead of System.Web.Mvc.Controller.

In this way, you can write error logging code only once in the overridden
OnExcpetion() method. This catches exceptions from any of the inheriting
controllers.

Using Third-Party Logging Tools

Because exception logging is a very common functional requirement for web


applications, there are many third-party solutions that you can choose if you
do not want to write your own logging code. Many of these are available
within Visual Studio from the NuGet package manager.

Perhaps, the most commonly used and widely supported error logging
package is Error Logging Modules and Handlers (ELMAH). ELMAH can be
used with any ASP.NET web application and can log exceptions to XML files
or a wide variety of databases, including Microsoft SQL Server, Oracle,
Microsoft SQL Server Compact, MySQL, and others. In addition, ELMAH
includes webpages that you can use to remotely view exception lists and
details, and ELMAH can send alert email messages to the address that you
configure.

Question: You want to ensure that developers can review exception details
that arise during debugging. How should you approach error logging code?

Health Monitoring
Since ASP.NET version 2.0, you can use health monitoring to record what
happens in a web application. Health monitoring can record exceptions
through error logging techniques.

However, health monitoring can also record a wide range of other events such
as application starts and stops, failed logon attempts, membership events, and
user input validation errors. Some pieces of these information are difficult to
access from any other source.

Health Monitoring Features

You can customize the category of events that

health monitoring records. Each event is within one of the five following
categories.

Event Category Description

Application Application lifetime events include application starts and


Lifetime Events stops.

Audit Events Audit events include logons, logoffs, and logon failures.

Error Events Error events incude .NET Framework exceptions and


HTTP errors such as 404 errors.

Request Request processing events include events that occur as


Processing ASP.NET controllers, models, and views receive and
Events respond to webpage requests.

Heartbeats Heartbeats are periodic events that health monitoring can


raise and record to confirm that the application is running.

You can also customize the location where health monitoring stores event
details by configuring health monitoring providers. You can choose from the
following providers.
Health Monitoring Provider Description

EventLogWebEventProvider EventLogWebEventProvider sends events


to the Windows Event Log. These events
appear in the Windows log.

SqlWebEventProvider SqlWebEventProvider sends events to a


SQL Server database.

WmiWebEventProvider WmiWebEventProvider sends events to


Windows Management Infrastructure
client.

SimpleMailWebEventProvider SimpleMailWebEventProvider sends


events in an email message sent to an
address you specify.

TemplatedMailWebEventProvider TemplatedMailWebEventProvider also


sends events in an email message, but you
can use a template email to format the
information.

TraceWebEventProvider TraceWebEventProvider sends events to


the ASP.NET tracing system.

Configuring Health Monitoring

You configure health monitoring by using the <healthMonitoring> element


within the <system.web> element in Web.config. You can use elements
within <healthMonitoring> to add and configure providers and define rules
that govern how events of different types are recorded.

The following code example shows how to configure health monitoring to


record application life cycle events to a SQL Server database.
Configuring Health Monitoring

<system.web>

<connectionStrings>

<add name="HealthDB" connectionString="your connection string

here" />

</connectionStrings>

<healthMonitoring enabled="true">

<providers>

<add name="sqlProvider"

type="System.Web.Management.SqlWebEventProvider"

connectionStringName="HealthDB"

buffer="false"

bufferMode="Notification" />

</providers>

<rules>

<add name="LifeCycle"

provider="sqlProvider"

eventName="Application Lifetime Events" />

</rules>

</healthMonitoring>

<system.web>
Additional Reading:

For full details of all the options that you can configure in Web.config for
health monitoring, see
http://go.microsoft.com/fwlink/?LinkID=293685&clcid=0x409

If you configure health monitoring to use the SqlWebEventProvider,


ASP.NET will, by default, create a database file called, ASPNETDB.MDF, in
the App_Data folder of the web application. You can alter this location by
using the connection string in Web.config. However, health monitoring will
only work if certain data tables are present in the database that you connect to.
You can prepare the database with the correct tables by using the
aspnet_regsql.exe tool. This tool is found in the
%WINDOWS%\Microsoft.NET\Framework\version directory.

The following command prepares a SQL Server database for health


monitoring, authenticating as the current user.

aspnet_regsql.exe –E –S HealthDatabaseServer –d HealthDatabase –A w

Question: After using your recently-developed web application, several users


are facing failed logon attempts. As a result, to track these exceptions, you
have decided to set up a monitoring system that will send an email message to
a specified email address. Which health monitoring provider will you use to
fix this?

Module Review and Takeaways


In this module, you became familiar with various techniques that you can use
to eliminate bugs from your ASP.NET MVC 4 web application. This begins
early in the development phase of the project, when you define unit tests that
ensure that each method and class in your application behaves precisely as
designed. Unit tests are automatically rerun as you build the application so
you can be sure that methods and classes that did work are not broken by later
coding errors. Exceptions arise in even the most well-tested applications
because of unforeseen circumstances. You also saw how to ensure that
exceptions are handled smoothly, and how error logs are optionally stored for
later analysis.
Best Practice: If you are using TDD or Extreme Programming, define each
test before you write the code that implements a requirement. Use the test as a
full specification that your code must satisfy. This requires a full
understanding of the design.

Best Practice: Investigate and choose a mocking framework to help you


create test double objects for use in unit tests. Though it may take time to
select the best framework and to learn how to code mock objects, your time
investment will be worth it over the life of the project.

Best Practice: Do not be tempted to skip unit tests when under time pressure.
Doing so can introduce bugs and errors into your system and result in more
time being spent debugging.

Review Question(s)

Question: You want to ensure that the PhotoController object passes a single
Photo object to the Display view, when a user calls the Search action for an
existing photo title. What unit tests should you create to check this
functionality?

Tools

NinJect, StructureMap. These are Inversion of Control (IoC) containers, also


known as Dependency Injection (DI) frameworks. They create non-test
implementations of interfaces in your web application.

Moq, RhinoMocks, NSubstitute. These are mocking frameworks. They


automate the creation of test doubles for unit tests.

IntelliTrace. This is a part of Visual Studio that displays application state at


the point of an exception or break, and at earlier times.

Health Monitoring. This part of ASP.NET can store health events in a


database, log, or other locations for later analysis.

ELMAH. This exception logging tool can store exceptions in database tables,
XML files, and elsewhere, and enable administrators to view exception details
on a webpage.
Module 07: Structuring ASP.NET MVC 4 Web
Applications

Module Overview
An MVC web application can grow large and complex and the application can
contain many types of information that relate to each other in complicated
ways. A key challenge for such web applications is to ensure that users can
easily locate the information that interests them. Although a search tool is
helpful, you should design your web application in such a way that users can
navigate to the page they need through a short sequence of links. At each
level, users must know what link to click next. The URLs that users see in the
Address bar must be readable and understandable. You need to understand
how to present the model classes you have designed in a way that is logical to
the user. You also need to ensure that Internet search engines can crawl and
analyze your web application structure, so that your application content
appears close to the top of the search engine results. You can achieve these
goals by learning about ASP.NET routing and navigation.

Objectives

After completing this module, you will be able to:

Plan suitable information architecture for a given set of functional


o
requirements.
Add routes to the ASP.NET routing engine and ensure that URLs are user-
o
friendly throughout an MVC web application.
Add navigation controls to an application to enable users to locate data
o
rapidly.

Lesson 1 : Analyzing Information Architecture


When you analyze use cases and user stories to plan a model for your web
application, you must determine the kinds of objects that your web application
will manage. For example, if your web application provides technical
documentation for a product, you can plan model classes such as installation
guides, user guides, frequently asked questions (FAQs), FAQ answers,
categories, comments, and other model classes. The model imposes a logical
structure of objects on the web application. However, you must also consider
how users expect information to be structured. Users may expect a
hierarchical structure, in which FAQs, FAQ answers, and comments are
presented under the product they relate to. When you create a complex MVC
web application, you need to know how to present model classes in a logical
manner, so that your web application is user-friendly.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe information architecture.


o Describe search engine optimization and its importance for web developers.

What Is Information Architecture?

When the information your web application manages is complex and multi-
faceted, it is easy to present objects in a confusing way. Unless you think
carefully about the way users expect information to be structured and how
they expect to navigate to useful content, you may unintentionally create an
unusable web application. During development, when you work with a limited
amount of data, this confusion may not become apparent. Then, when real-
world data is added to your database at production deployment time, it
becomes clear that the web
application is confusing. You can avoid this eventuality by planning the
information architecture.

Information architecture is a logical structure for the objects your web


application manages. You should design such architecture in a way that users
can find content quickly without understanding any technical aspects of your
web application. For example, users should be able to locate a technical
answer about their product without understanding the database structure or the
classes that constitute the model.

Example Scenario: A Technical Documentation Website

To understand the need for information architecture, consider a web


application that presents technical information about a company’s products for
customers and engineers. In this example, the company manufactures
domestic heating furnaces, which are installed in homes by qualified heating
engineers. The web application is intended to enable customers to locate
instructions, hints, and tips. This web application is also intended to enable
engineers to obtain the technical documentation on installing and servicing
furnaces.

The development team has identified the following simple user stories:

Customers have a certain problem with their boilers. They want to find a
specific FAQ answer that solves the problem. They know the boiler product
o name and the fuel, but not the product number. They visit the web
application and navigate to the boiler name. They click the FAQ for their
boiler name and locate the answer that they need.
Engineers need the latest installation manual for a boiler. They know the
boiler product number, product name, and fuel type. They visit the site and
o
navigate to the boiler name. They click the Manuals link and locate the
installation manual.
Engineers have web applications, which they want to link to a specific boiler
o name. You want to ensure that the URL is simple and readable for customers
and engineers.

You have already planned the following model classes:


Furnace. Each furnace object is a product manufactured and sold by the
o
company.
Category. Categories organize the furnaces by type. For example, you can
o
have categories such as oil-fired, gas-fired, and solid fuel.
FAQ. Each FAQ relates to a single furnace. Each furnace can have many
o
questions. The class includes both Question and Answer properties.
Installation Manual. Each furnace has a single installation manual in the
o
form of a PDF document.
User Manual. Each furnace has a single user manual in the form of a PDF
o
document.

Planning a Logical Hierarchy

You can see from the user stories that FAQ and manuals are both accessed by
navigating to the relevant product first. You can also see that the company has
different products, and both customers and engineers know the fuel type for a
particular furnace. Therefore, you can organize furnaces in categories by fuel
type. The following list shows a logical hierarchy of objects, which helps both
the customers and engineers find the information they need by clicking
through each level:

Category

▪ Furnace
o ▪ FAQ
▪ User Manual
▪ Installation Manual

Presenting a Hierarchy in Navigation Controls

The information architecture you design should be presented on webpages in


the form of navigation controls. Common approaches to such controls include:

Site Menus. Most websites have a main menu that presents the main areas of
content. For simple web applications, the main menu may include a small
o
number of static links. For larger web applications, when users click a site
menu link, a submenu appears.
Tree Views. A tree view is a menu that shows several levels of information
hierarchy. Usually, users can expand or collapse objects at each level, to locate
o
the content they require. Tree views are useful for presenting complex
hierarchies in navigable structures.
Breadcrumb Trails. A breadcrumb trail is a navigation control that shows the
user where they are in the web application. Usually a breadcrumb trail shows
o the current pages and all the parent pages in the hierarchy, with the home page
as the top level. Breadcrumb trails enable you to understand how a page fits in
with the information architecture shown in menus and tree views.

The types of navigation controls you build in your web application depend on
how you expect users to find information.

Presenting a Hierarchy in URLs

You can increase the usability of your web application by reflecting the
information architecture in the URLs, which the users see in the Address bar
of the web browser. In many web applications, URLs often include long and
inscrutable information such as Globally Unique Identifiers (GUIDs) and long
query strings with many parameters. Such URLs prevent users from manually
formulating the address to an item, and these URLs are difficult to link to a
page on your web application. Instead, URLs can be plain and
comprehensible, to help users browse through your content.

In MVC web applications, the default configuration is simple, but it is based


on controllers, actions, and parameters. The following are some example
URLs that follow this default pattern:

http://site/Furnace/Details/23: This URL links to the Furnace controller and the


o
Details action, and it displays the furnace with the ID 23.
http://site/FAQQuestion/Details/234: This URL links to the FAQQuestion
o
controller and the Details action, and it displays the FAQ with the ID 234.
http://site/InstallationManual/Details/3654: This URL links to the
o InstallationManual controller and the Details action, and it displays the manual
with the ID 3654.
As you can see, the web application user is required to understand how
controllers, actions, and action parameters work, to formulate URLs
themselves. Instead, users can use URLs that are easier to understand, such as
the following, because they reflect the information hierarchy:

http://site/OilFired/HotBurner2000: This URL links to a Furnace by


o specifying the fuel category and the product name. Customers and engineers
can understand these values.
http://site/OilFired/HotBurner2000/HowToRestartMyFurnace: This URL
o
links to an FAQ by specifying the furnace name the question relates to.
http://site/OilFired/HotBurner2000/: This URL links to the Installation
o
Manual by specifying the furnace name the manual relates to.

As you can see, these URLs are easy for customers and engineers to
understand, because the URLs are based on a logical hierarchy and the
information that the users already have. You can control the URLs that your
ASP.NET web application uses, by configuring the ASP.NET routing engine.

Question: Why may it be difficult for users to understand URLs based on


controllers, actions, and parameters?

What Is Search Engine Optimization?

Most users find web applications by using search engines. Users tend to visit
the links that appear at the top of search engine results more frequently than
those lower down and those on the second page of results. For this reason,
website administrators and developers try to ensure their web application
appears high in search engine results, by using a process known as Search
Engine Optimization (SEO). SEO ensures that more people visit your web
application.

Search engines examine the content of your web application, by crawling it


with a program called a

web bot. If you understand the priorities that web bots and search engine
indexes use to order search results, you can create a web application that
conforms to those priorities and thereby appears high in search engine results.

SEO Best Practices

Various search engines have different web bots with different algorithms to
prioritize results. The complete details of these algorithms are not usually
published. However, if you adopt the following best practices, your site has a
good chance of appearing high in search results:

Ensure that each webpage in your web application has a meaningful <title>
o
element in the <head> section of the HTML.
Ensure that you include a <meta name="keywords"> tag in the <head>
o element of each page. The content attribute of this element should include
keywords that describe the content of the page accurately.
Ensure that you include a <meta name="description"> tag in the <head>
o element of each page. The content attribute of this element should include a
sentence that describes the content of the page accurately.
Ensure that the <title> element and the <meta> elements are different for
o
each page in your web application.
Choose a domain name that includes one or more of your most important
o
keywords.
Ensure that keywords appear in the <h1>, <h2>, or <h3> elements of your
o
webpage.
Ensure that navigation controls enable web bots to crawl your entire web
application. For example, you may have content in your site that users can
o
only find with the search tool, not by clicking through links. As web bots
cannot use search tools, this content will not be indexed.
o Ensure that URLs do not include GUIDs or long query text.
SEO and Web Application Structure

Information architecture is a subject that is closely related to SEO. This is


because both information architecture and SEO are relevant to the structure,
hierarchy, and accessibility of the objects in your web application. Users click
links on menus to navigate to the pages that interest them. Web bots use the
same links to navigate the web application and crawl its content. Users prefer
URLs without GUIDs and long query text because they are meaningful. Web
bots often ignore links with GUIDs and long query text in them. In addition,
when keywords appear in URLs, web bots prioritize a webpage in search
results.

As an ASP.NET MVC developer, you must understand SEO principles and


use them whenever you write code, to ensure that you do not damage the
search engine positioning of your web application. Views are critical to SEO
because they render <meta> tags, and <title> elements. Routes and the
configuration of the routing engine are also critical, because, by using routes,
you can control the URLs that your web application generates.

Question: A developer creates a partial view that contains <meta> tags and
<title> tags. The developer uses this partial view on every page in the web
application. Do these actions conform to SEO best practices?

Lesson 2: Configuring Routes


ASP.NET enables developers to control the URLs that a web application uses,
to link the URLs and the content by configuring routes. A route is an object
that parses a requested URL, and it determines the controller and action to
which the request must be forwarded. Such routes are called incoming routes.
HTML helpers also use routes when they formulate links to controllers and
actions. Such routes are called outgoing routes. You need to know how to
write code that adds a new route to your application. You also need to know
how the routing engine interprets a route so that requests go to the appropriate
controllers, and users see meaningful URLs.

Lesson Objectives
After completing this module, you will be able to:

o Describe the features of the ASP.NET routing engine.


Describe the benefits of adding routes to an ASP.NET MVC web
o
application.
o Explain how to add and configure routes.
o Explain how to use routes to pass parameters.
o Add routes to manage URL formulation.

The ASP.NET Routing Engine

Routing governs the way URLs are formulated and how they correspond to
controllers and actions.

Routing does not operate on the protocol, server, domain, or port number of a
URL, but only on the directories and file name in the relative URL. For
example, in the URL, http://www.advworks.com/photo/display/1, routing
operates on the relative path /photo/display/1.

In ASP.NET, routes are used for two purposes:

To parse the URLs requested by browsers.

This analysis ensures that requests are


o
forwarded to the right controllers and actions. These are called incoming
URLs.
To formulate URLs in webpage links and other elements. When you use
o
helpers such as Html.ActionLink() and Url.Action() in MVC views, the
helpers construct URLs according to the routes in the routing table. These
are called outgoing URLs.

When you create an MVC web application in Visual Studio by using a project
template, the application has a default route. You must understand this default
route before you consider adding extra routes to manipulate URLs in the
application.

Note: You can use routes and the routing engine to govern relative URLs in
any ASP.NET 4.5 application and not just in those that use the MVC
programming model.

The Default Route

The default route is simple but logical and works well in many web
applications. The default route examines the first three segments of the URL.
Each segment is delimited by a forward slash:

The first segment is interpreted as the name of the controller. The routing
o engine forwards the request to this controller. If a first segment is not
specified, the default route forwards the request to a controller called Home.
The second segment is interpreted as the name of the action. The routing
o engine forwards the request to this action. If a second segment is not
specified, the default route forwards the request to a controller called Index.
The third segment is interpreted as an ID value, which is passed to the action
o as a parameter. The parameter is optional, so if a third segment is not
specified, no default value is passed to the action.

You can see that when the user requests the URL,
http://www.advworks.com/photo/display/1, the default route passes the ID
parameter 1 to the Display action of the Photo controller.

The following code shows how the default route is implemented in new
ASP.NET MVC 4 applications.

The Default Route

routes.MapRoute(
name: "Default",

url: "{controller}/{action}/{id}",

defaults: new {

controller = "Home",

action = "Index",

id = UrlParameter.Optional

);

Custom Routes

Developers add their own custom routes to a web application for two main
reasons:

To make URLs easier for site visitors to understand. A URL such as


http://www.advworks.com/photo/display/1 is logical to the visitor, but it
requires some knowledge to formulate such URLs. In this case, to type the
right URL in the Address bar of the web browser, the user must know some
information. This information includes the controller name, Photo, the
action name, Display, and the ID of the photo of interest. If you use
Globally Unique Identifiers (GUIDs) in the database, the ID segment of the
o URL can be long and difficult to remember. Ideally, you should consider
what users know and create routes that accept that information. In this
example, users may know the title of a photo that they had seen earlier in
your application. You should create a route that can interpret a URL such as
http://www.advworks.com/photo/title/My%20Photo%20Title, and forward
the URL to an appropriate action to display the right photo. Although users
usually click links to make requests, friendly URLs like these make a site
easier to use and link to from other sites.
To improve search engine rankings. Search engines do not prioritize
o
webpages that have GUIDs or long query text in the URL. Some web bots
do not even crawl such links. In addition, some search engines boost a
page’s ranking when one or more of its keywords appear in the URL. User-
friendly URLs are therefore a critical tool in SEO.

Controller Factories and Routes

MVC uses controller factories that help create an instance of a controller class
to handle a request. MVC uses action invokers to call the right action and pass
parameters to that action method. Both controller factories and action invokers
refer to the routing table to complete their tasks. The following are steps that
MVC conducts when a request is received from a web browser:

An MvcHandler object creates a controller factory. The controller factory


1.
is the object that instantiates a controller to respond to the request.
The controller factory consults the routing table to determine the right
2.
Controller class to use.
The controller factory creates a Controller object, and the MvcHandler
3.
calls the Execute method in that controller.
The ControllerActionInvoker examines the request URL and consults the
4.
routing table to determine the action in the Controller object to call.
The ControllerActionInvoker uses a model binder to determine the values
that should be passed to the action as parameters. The model binder consults
5. the routing table to determine if any segments of the URL should be passed
as parameters. The model binder can also pass parameters from a posted
form, from the URL query text, or from uploaded files.
The ControllerActionInvoker runs the action. Often, the action creates a
new instance of a model class, perhaps by querying the database with the
6.
parameters that the invoker passed to it. This model object is passed to a
view, to display results to the user.

As you can see, you can use routes to manage the behavior of controller
factories, action invokers, and model binders, because all these objects refer to
the routing table. MVC is highly extensible; therefore, developers can create
custom implementations of controller factories, action invokers, and model
binders. However, by using routes, you can usually implement the URL
functionality that you need with the default implementations of these classes.
You should ensure that routes cannot implement your required functionality
before you plan to customize controller factories, action invokers, or model
binders.

Question: A user wants to edit a comment that the user created in your MVC
application. You have not created any custom routes. What URL do you think
the user must request, to see the edit view with the right comment?

Adding and Configuring Routes

Every MVC web application has a RouteTable object in which routes are
stored, in the Routes properties. You can add routes to the Routes property by
calling the MapRoute() method.

In the Visual Studio project templates for MVC 4, a dedicated


RouteConfig.cs code file exists in the App_Start folder. This file includes
the RouteConfig.RegisterRoutes() static method where the default route is
added to the RouteTable object. You can add custom routes in this method.
The Global.asax.cs file includes a call to RouteConfig.RegisterRoutes() in
the

Application_Start() method, which means that routes are added to the


routing table whenever the MVC application starts.

Properties of a Route

Before you can add a route, you must understand the properties of a route.
This is to ensure that these properties match the URL segments correctly and
pass requests and parameters to the right location. The properties of a route
include the following:

Name. This string property assigns a name to a route. It is not involved in


o
matching or request forwarding.
URL. This string property is a URL pattern that is compared to a request, to
determine if the route should be used. You can use segment variables to
match a part of the URL. You can specify a segment variable by using
o braces. For example, if you specify the URL, “photo/{title}”, the route
matches any request where the relative URL starts with the string, “photo/”,
and includes one more segment. The segment variable is “title” and can be
used elsewhere in the route.
Constraints. Sometimes you must place extra constraints on the route to
ensure that it matches only with the appropriate requests. For example, if
you want relative URLs in the form, “photo/34”, to specify a photo with the
ID “34”, you must use a URL property like “photo/{id}”. However, observe
that this URL pattern also matches the relative URL, “photo/create”, because
o
it has one extra segment. For IDs, you must constrain the URL to match only
segments comprising digits. You can do this by adding a constraint to the
route. The Constraints property enables you to specify a regular expression
for each segment variable. The route will match a request only if all the
segment variables match the regular expressions that you specify.
Defaults. This string property can assign default values to the segment
o variables in the URL pattern. Default values are used for segment variables
when the request does not specify them.

The Default Route Code

The default route specifies the Name, URL, and Defaults properties to obtain
controller and action names, and ID values, from the requested relative URL.
By examining these properties, you can understand how to construct your own
routes.

The following code shows the default route in the Visual Studio MVC project
templates.

The Default Route in RouteConfig.cs


routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id =

UrlParameter.Optional }

);

Observe that the URL pattern specifies three segments: {controller}, {action},
and {id}. This means that a relative URL in the form, “photo/display/23”, will
be sent to the Display action of the PhotoController class. The third segment
will be passed as a parameter to the action method. Therefore, if the Display
action accepts a parameter named id, the value, 23, will be passed by MVC.

In the defaults property, the {id} segment is marked as optional. This means
that the route still matches a relative URL, even if no third segment is
specified. For example, the route matches the relative URL, “photo/create”,
and passes the URL to the Create action of the PhotoController class.

The defaults property specifies a default value of “Index” for the {action}
segment. This means that the route still matches a relative URL, even if no
second segment is specified. For example, the route matches the relative URL,
“photo”, and passes the URL to the Index action of the PhotoController
class.

Finally, the defaults property specifies a default value of “Home” for the
{controller} segment. This means that the route still matches a relative URL,
even if no segments are specified, that is, if there is no relative URL. For
example, the absolute URL, “http://www.advworks.com”, matches this route,
and the URL is passed to the Index action of the HomeController class.

As you can see, with the default route in place, developers build the web
application’s home page by creating a controller named, HomeController,
with an action named, Index. This action usually returns a view called, Index,
from the Views/Home folder.
Creating Custom Routes

You can add custom routes by calling the routes.MapHttpRoute() method,


just like the default route.

In the following code example, a constraint is used to ensure that only digits
match the {id} segment variable.

A Custom Route

routes.MapRoute(

name: "PhotoRoute",

url: "photo/{id}",

defaults: new { controller = "Photo", action = "Details" },

constraints: new { id = "[0-9]+" }

);

Observe that the URL pattern in the route matches any relative URL that starts
with “photo/” and has one or more segments. However, in the constraints
property, the route specifies a regular expression for the {id} segment
variable. This regular expression matches only if the segment is composed of
digits that range from 1 through 9. If the user requests the relative URL,
“photo/234”, then this route matches, and the routing engine forwards the
request to the Details action of the PhotoController class. If the user requests
the relative URL, “photo/create”, then this route does not match and a
subsequent route must be used to forward the request.

Precedence of Routes

Routes are evaluated by the routing engine in the order with which they are
added to the RouteTable.Routes collection. If a route matches, the routing
engine uses it and does not evaluate any later route in the collection. If a route
does not match, the routing engine ignores it and evaluates the next route in
the collection. For this reason, you must add routes to the RouteTable.Routes
collection in the appropriate order. You can add the most specific routes first,
such as routes that have no segment variables and no default values. Routes
with constraints should be added before routes without constraints.

The route named "Default" matches any request, including those with no
relative URL. This default route should be the last that you add to the
RouteTable.Routes collection. If the routing engine evaluates this route, the
route is always used. Any routes added after the “Default” route are never
used.

Question: A developer has removed all code from the Application_Start()


method in Global.asax.cs. When the developer runs the application, he or she
receives 404 errors for any request, regardless of the relative URL. Why does
this occur?

Using Routes to Pass Parameters

The routing engine separates the relative URL in a request into one or more
segments. Each forward slash delimits one segment from the next. If you want
one of the segments to specify the controller name, you can use the
{controller} segment variable. The controller factory always interprets this
variable as the controller to instantiate.

Alternatively, to fix a route to a single controller, you can specify a value for
the controller variable in the defaults property. In a similar manner, if you
want one of the segments to specify the action method, you can use the
{action} segment
variable. The action invoker always interprets this variable as the action to
call. Alternatively, to fix a route to a single action, you can specify a value for
the action variable in the defaults property.

Segment variables or default values with other names have no special


meaning to MVC and are passed to actions. You can access the values of
these variables by using one of two methods: the RouteData.Values
collection or by using model binding to pass values to action parameters.

The RouteData.Values Collection

In the action method, you can access the values of any segment variable by
using the RouteData.Values collection. Consider the following example:

In RouteConfig.cs, you have defined a route with the URL pattern


o
“{controller}/{action}/{title}”.
o The user requests the relative URL, “photo/edit/my%20photo”.

The RouteData.Values collection contains the following values, which you


can use in the action method:

o RouteData.Value["controller"]: This value has the value, “photo”.


o RouteData.Value["action"]: This value has the value, “edit”.
o RouteData.Value["title"]: This value has the value, “my%20photo”.

Using Model Binding to Obtain Parameters

Consider the following action method.

public void ActionMethod Display (int PhotoID)

return View(PhotoID);

The default MVC action invoker is a class named, ControllerActionInvoker.


This invoker uses a class named, DefaultModelBinder, to pass the
appropriate parameters to actions. This model binder uses the following logic
to pass parameters:

The binder examines the definition of the action to which it must pass
1. parameters. In the example, the binder determines that the action requires an
integer parameter called, PhotoID.
The binder searches for values in the request, which can be passed as
parameters by name. In the example, the binder searches for integers
because the action requires integers. The binder searches for values in the
following locations in sequential order:

Form Values. If the user fills out a form and clicks the Submit button, the
a.
binder can find parameters in the Request.Form collection.
Route Values. If the matched route includes the segment variable
2. b. {photoid}, the binder can find the value for the PhotoID parameter in the
RouteData.Values collection. This match is case-insensitive.
Query Strings. If the user request includes named parameters after a
c. question mark, the binder can find these parameters in the
Request.QueryString collection.
Files: If the user request includes uploaded files, these files can be used
d. as parameters in an action. File parameters in actions must use the
HttpPostedFileBase type.

Therefore, you can use the default model binder to pass parameters to action
strings. If the name of an action method parameter matches the name of a
route segment variable, the model binder passes the parameter automatically.

Optional Parameters

Sometimes, you want requests to match a route, regardless of whether


parameter values are supplied. For example, you might want to enable users to
specify a color for a product.

In the following example, the route added includes an optional color


parameter.

A Route with an Optional Parameter


routes.MapRoute(

name: "ProductRoute",

url: "product/{id}/{color}",

defaults: new { color = UrlParameter.Optional }

);

The default values specify that {color} is optional. If the relative URL has
three segments, the route matches, and the third segment is passed to the
RouteData.Values["color"] value. If the relative URL has only two
segments, the route matches, because the {color} is optional. In this case, the
RouteData.Values["color"] value does not exist. If the relative URL has
only one segment, the route does not match.

Question: A developer has replaced the default model binder with a custom
model binder. Now, several action methods are throwing exceptions on lines
that use action parameters. How can you fix this bug?

Demonstration: How to Add Routes


In this demonstration, you will see how to create URLs by adding routes to
the MVC web application. You will also see how to enable visitors to the
Operas web application to browse the operas by title.

Demonstration Steps
On the DEBUG menu of the OperasWebSite - Microsoft Visual Studio
1.
window, click Start Debugging.
2. On the Operas I Have Seen page, click the operas I’ve seen link.
3. On the Index page, click the Details link corresponding to Cosi Fan Tutte.
In the Address bar of the Windows Internet Explorer window, note that the
URL is http://localhost:<portnumber>/Opera/Details/1.
4.
Note: This URL indicates that the controller is Opera, the action is Details,
and the ID is 1.
5. In the Windows Internet Explorer window, click the Close button.
In the Solution Explorer pane, expand OperasWebSite, expand Controllers,
6.
and then click OperaController.cs.
In the OperaController.cs code window, place the mouse cursor at the end of
the Details action code block, press Enter twice, and then type the following
code.

7. public ActionResult DetailsByTitle(string title)

In the DetailsByTitle action code block, type the following code, and then
press Enter.

Opera opera = (Opera)(from o in contextDB.Operas

8.
where o.Title == title

select o).FirstOrDefault();
In the DetailsByTitle action code block, after the code that you just entered,
type the following code.

if (opera == null)

{
9.
return HttpNotFound();

return View("Details", opera);

In the Solution Explorer pane, under OperasWebSite, expand App_Start, and


10.
then click RouteConfig.cs.
In the RouteConfig.cs code window, locate the following code.
11.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

Place the mouse cursor at the end of the call to the IgnoreRoute() method,
press Enter twice, and then type the following code.

routes.MapRoute(

name: "OperaTitleRoute",
12.
url: "opera/title/{title}",

defaults: new { controller = "Opera", action = "DetailsByTitle" }

);

On the FILE menu of the OperasWebSite - Microsoft Visual Studio


13.
window, click Save All.
On the DEBUG menu of OperasWebSite - Microsoft Visual Studio
14.
window, click Start Debugging.
15. On the Operas I Have Seen page, click the operas I’ve seen link.
In the Address bar of the Windows Internet Explorer window, append the
16. existing URL with /title/rigoletto, and then click the Go button.
Note: The details of the Rigoletto opera are displayed.
17. In the Windows Internet Explorer window, click the Close button.
In the OperasWebSite - Microsoft Visual Studio window, click the Close
18.
button.

Unit Tests and Routes


Unit tests are small, isolated methods that check a specific aspect of your
code. As your project grows in complexity, you can rerun all unit tests to
ensure that the verified functionality remains in a working state. If your team
uses Test Driven Development (TDD), you can define tests to specify a
functional requirement and then write code that passes your test. Such
approaches significantly increase the quality of your code, by highlighting
bugs as soon as they arise.

You can use unit tests to ensure that routes in your MVC web application
behave as designed. If

you do such tests, you can prevent many 404 HTTP errors and internal server
errors from reaching web application users. Users generally have a low
tolerance for such errors, and if errors arise too often, they will browse to the
websites of your competitors.

Creating a HTTP Context Test Double

In a webpage request, ASP.NET stores details of the request in an HTTP


Context object. These details include the URL that was requested, details of
the browser, and other information. To write a unit test for routes, you must
simulate the HTTP Context object by creating a test double class.

The following code shows how to create a fake HTTP context object to use as
a test double.

An HTTP Context Test Double

public class FakeHttpContextForRouting : HttpContextBase


{

FakeHttpRequestForRouting _request;

FakeHttpResponseForRouting _response;

//The constructor enables you to specify a request URL and an

Application path in

the test

public FakeHttpContextForRouting(string appPath = "/", string

requestUrl = "~/")

//Create new fake request and response objects

_request = new FakeHttpRequestForRouting(appPath,

requestUrl);

_response = new FakeHttpResponseForRouting();

//This property returns the fake request

public override HttpRequestBase Request

get { return _request; }

//This property returns the fake response

public override HttpResponseBase Response


{

get { return _response; }

//This is the fake request class

public class FakeHttpRequestForRouting : HttpRequestBase

string _appPath;

string _requestUrl;

public FakeHttpRequestForRouting(string appPath, string

requestUrl)

_appPath = appPath;

_requestUrl = requestUrl;

public override string ApplicationPath

get { return _appPath; }

public override string AppRelativeCurrentExecutionFilePath


{

get { return _requestUrl; }

public override string PathInfo

get { return ""; }

public override NameValueCollection ServerVariables

get { return new NameValueCollection(); }

//This is the fake response class

public class FakeHttpResponseForRouting : HttpResponseBase

public override string ApplyAppPathModifier(string virtualPath)

return virtualPath;

}
Writing Routing Tests

After creating an HTTP context test double, you can write unit tests for each
route in the routing table. These unit tests adopt the following general phases:

Arrange. In the Arrange phase of the test, you can create a new HTTP context
from your test double class. You can set the request URL for this object to be
o
the URL you want to test. You can then create a new route collection and call
the RouteConfig.RegisterRoutes() method in your web application.
Act. In the Act phase, you can test the routes by calling the GetRouteData()
o method of the route collection. You can then pass the fake HTTP context to this
method.
Assert. In the Assert phase, you can use the RouteData.Values collection to
o
check that the controller, action and other values are assigned correctly.

In the following example unit test, the default route is checked. The request
URL has only a single segment and the test asserts that this segment is passed
as the controller name.

A Routing Unit Test

[TestMethod]

public void Test_Default_Route_ControllerOnly()

//This test checks the default route when only the controller is

specified

//Arrange

var context = new FakeHttpContextForRouting(requestUrl:

"~/ControllerName");

var routes = new RouteCollection();

MyMVCApplication.RouteConfig.RegisterRoutes(routes);
// Act

RouteData routeData = routes.GetRouteData(context);

// Assert

Assert.AreEqual("ControllerName", routeData.Values["controller"]);

Assert.AreEqual("Index", routeData.Values["action"]);

Assert.AreEqual(UrlParameter.Optional, routeData.Values["id"]);

Question: You are writing a unit test to check your web application’s routing
table. You want to ensure that the request is passed to an action method called,
“Edit”. What line of code would you use in the Assert phase of the test to
check this fact?

Lesson 3: Creating a Navigation Structure


A navigation structure is a logical hierarchy of webpages, which enables users
to browse to the information that interests them. In simple web applications,
the design of the navigation structure is also usually simple. As your web
application grows, it becomes difficult to present menus and navigation
controls that show the users clearly what their next click should be, at every
step. You need to understand how to build menus, which help users
understand where they are in your site and where to go next. You can do this
by building menus and breadcrumb controls.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe the importance of well-designed navigation.


o Build clear menus in a web application.
o Add breadcrumb controls to a web application.
o Build site navigation in a web application.
The Importance of Well-Designed Navigation

The information architecture you design for your web application is a logical
hierarchy of objects.

This hierarchy should be clear and understandable to the audience of your web
application. If your web application is designed for people with specialist
knowledge, you can implement information architecture that requires
specialist knowledge. For example, in an engineering web application, you
could base your information architecture on specialist technologies and
solutions that engineers understand. However, such information architecture
would not be

helpful to the general public.

After designing the information architecture, you must present it in your web
application. You can add routes to ensure that URLs reflect your information
architecture. Similarly, you must add navigation controls to present the
information architecture in the body of each webpage. The navigation controls
you build are the primary means by which users browse your web application
and locate content. You should ensure two things with these navigation
controls:

An obvious next step. You should ensure that users can easily decide what
link to click, on each page. To achieve this aim, you can consider use cases.
o For each use case, you can list what the user knows when they arrive at your
web application. The user should be able to choose the right link without any
specialist or technical knowledge. For example, avoid basing your links on
any kind of technical jargon, unless you know that your audience
understands it.
A clear context. In a simple web application with only one or two levels in
the information architecture, users can easily keep track of where they are. In
larger web applications with many levels, you must provide navigation
controls, which show users where they are and how to navigate back up the
hierarchy. Tree views and breadcrumb controls perform this function well.
o
Best Practice: Base your navigation controls on the information hierarchy,
rather than on the model and model classes, database tables, or other
technical structures in your web application. Users will probably not
understand the model classes, controllers, views, and data storage
mechanisms that underlie your web application.

Common Types of Navigation Controls

Remember that most web application visitors have browsed thousands of


Internet applications before they visit your home page. Visitors are usually
familiar with common types of menus used on many web applications, and
you can make use of this knowledge by using the same types of menus in your
web application. Common menu types include the following:

Top menus. Often placed at the top of the page or immediately beneath the
application branding, top menus link to the main areas of your web
o
application. In some applications, each item in the top menu has a submenu
with links to lower level items and pages.
Tree views. A tree view is a hierarchical menu that can display many items
in multiple levels in your web application. By default, a tree view often
displays only one or two levels of the information architecture. Users can
o
expand lower levels to find the content they need. Tree views enable users to
explore multiple levels on a single page. Tree views can also show clearly
the position of the current page, in the hierarchy.
Breadcrumb trails. Often presented as a horizontal sequence of links across
the top of a webpage, a breadcrumb trail shows the current page and its
o parents in all the higher levels of the hierarchy. Breadcrumb trails show the
current position of the user, in the context of the web application and enable
users to navigate to higher, less specific pages.
Footer menus. The page footer is often not visible when a user arrives on a
page. The user must scroll to the end of the page to see the footer. The footer
o is often used as a location for important, but not business-critical, links. For
example, links to copyright and other legal information, links to parent
companies, and links to site maps are often placed in the footer menu.

The MVC Site Map Provider

In ASP.NET, one way to rapidly build information architecture and navigation


controls to present that architecture is to use a site map provider. A site map
provider is an ASP.NET component that stores the logical hierarchy of your
web application. Navigation controls such as top menus, tree views, and
breadcrumb trails can take their links from this single hierarchy.

The MVC Site Map Provider is a provider designed to work with MVC
controllers and actions. It presents the information architecture that you can
configure in a simple XML file. This hierarchy is completely independent of
the model, controllers, and actions in your applications, although you can
build links to them. The provider also includes HTML helpers, which you can
use in views to render menus, tree views, and breadcrumb trails.

Note: The MVC Site Map Provider is a component by Maarten Balliauw that
is not included in MVC web applications, by default. You can find it in the
NuGet package manager by searching for “MvcSiteMapProvider”.

Question: Analysis of web logs has shown that visitors to your web
application can navigate to low-level pages in your information architecture,
quickly and easily. However, they subsequently find other pages by returning
to the home page and navigating the entire hierarchy again from the top, or
else they use the search tool. How can you enable users to navigate to higher
levels without starting from the home page again?

Configuring the MVC Site Map Provider


After installing the MVC Site Map Provider from the NuGet package
manager, you must configure the provider and set up the logical hierarchy it
should present, before you can render any menus.

Configuring the MVC Site Map Provider in Web.Config

You should configure the MVC Site Map Provider, by adding elements to the
Web.config file in the root folder of your MVC web application. When you
install the site map provider, the NuGet

package adds a <siteMap> element to the <system.web> section of this file.

The following code example shows how to configure the site map provider.

The <siteMap> Element in Web.config

<siteMap defaultProvider="MvcSiteMapProvider" enabled="true">

<providers>

<clear />

<add name="MvcSiteMapProvider"

type="MvcSiteMapProvider.DefaultSiteMapProvider,

MvcSiteMapProvider"

siteMapFile="~/Mvc.Sitemap"

securityTrimmingEnabled="false"
cacheDuration="5"

enableLocalization="false"

scanAssembliesForSiteMapNodes="false"

includeAssembliesForScan=""

excludeAssembliesForScan=""

attributesToIgnore=""

nodeKeyGenerator="MvcSiteMapProvider.DefaultNodeKeyGenerator,

MvcSiteMapProvider"

controllerTypeResolver="MvcSiteMapProvider.DefaultControllerTypeResolv

er,

MvcSiteMapProvider"

actionMethodParameterResolver="MvcSiteMapProvider.DefaultActionMethodP

arameterResolver,

MvcSiteMapProvider"

aclModule="MvcSiteMapProvider.DefaultAclModule,

MvcSiteMapProvider"

siteMapNodeUrlResolver="MvcSiteMapProvider.DefaultSiteMapNodeUrlResolv

er,

MvcSiteMapProvider"
siteMapNodeVisibilityProvider="MvcSiteMapProvider.DefaultSiteMapNodeVi

sibilityProvider,

MvcSiteMapProvider"

siteMapProviderEventHandler="MvcSiteMapProvider.DefaultSiteMapProvider

EventHandler,

MvcSiteMapProvider"

/>

</providers>

</siteMap>

Note that you can configure the name of the XML file where the site map is
stored, enable security trimming, and configure caching.

Additional Reading: For complete details of the configuration values you can
use with the MVC Site Map Provider, together with other documentation, go
to http://go.microsoft.com/fwlink/?LinkID=288963&clcid=0x409

Creating the Site Map File

The MVC Site Map Provider is the only site map provider that enables you to
specify a controller and action for every item in the site map. You do this by
completing a site map file. By default, the site map file is named Mvc.sitemap
and is stored in the highest level of your web application. The hierarchy
consists of nested <mvcSiteMapNode> elements. This is the hierarchy that
the helpers will display in navigation controls.

The following example shows simple information architecture as described in


an MVC site map provider site map file.
An MVC Site Map File

<?xml version="1.0" encoding="utf-8" ?>

<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0"

xsi:schemaLocation=

"http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0

MvcSiteMapSchema.xsd"

enableLocalization="true">

<mvcSiteMapNode title="Home" controller="Home" action="Index">

<mvcSiteMapNode title="Products" controller="Product"

action="Index"

key="AllProducts">

<mvcSiteMapNode title="Bikes" controller="Category"

action="Display">

</mvcSiteMapNode>

</mvcSiteMapNode>

<mvcSiteMapNode title="Latest News" controller="Article"

action="DisplayLatest" >

<mvcSiteMapNode title="About Us" controller="Home"

action="About" />

</mvcSiteMapNode>

</mvcSiteMap>
Question: You use the MVC Site Map Provider. Your boss notices that an
incorrect link appears in the highest menu and the tree view on every page in
your web application. Your boss asks you to fix every page in the web
application. What steps should you take?

Adding Menu Controls

After configuring the site map provider and creating a site map file, you can
add menus, tree views, and other navigation controls to your views.

The MVC site map provider includes some HTML helpers to make this easy.

The following example code shows how to render a main menu in an MVC
view, by using the HTML.MvcSiteMap() helper.

Rendering a Menu Control

@Html.MvcSiteMap().Menu(false, false,

true)

In this example, the first parameter specifies that the menu does not start from
the current node. The menu starts from the top-level node, which is usually
the home page of the web application. The second parameter specifies that the
starting node does not display as a child node at the same level as second-level
nodes. The third parameter specifies that the starting node displays in the
menu.
You can also use the Html.MvcSiteMap() helper to render a breadcrumb
control, as displayed in the following code.

Rendering a Breadcrumb Trail

@Html.MvcSiteMap().SiteMapPath()

The Html.MvcSiteMap() helper also includes functions that you can use to
render node titles and complete site maps.

Additional Reading:

For complete reference documentation that details the Html.MvcSiteMap()


helper and its functions, go to
http://go.microsoft.com/fwlink/?LinkID=288964&clcid=0x409

Question: What are some of the benefits of using the Html.MvcSiteMap()


helper?

Module Review and Takeaways


To create a compelling web application that is easy to navigate, you must
consider carefully the architecture of the information you present. You should
try to ensure that the hierarchy of objects you present in URLs and navigation
controls matches user expectations. You should also ensure that users can
understand this hierarchy of objects without specialist technical knowledge.
By using routes and site map providers, you can present logical information
architecture to application visitors.

Best Practice: The default route is logical. However, it requires knowledge of


controllers and actions for users to understand URLs. You can consider
creating custom routes that can be understood with information that users
already have.

Best Practice: You can use breadcrumb trails and tree view navigation
controls to present the current location of a user, in the context of the logical
hierarchy of the web application.

Best Practice: You can use unit tests to check routes in the routing table,
similar to the manner with which you use tests to check controllers, actions,
and model classes. It is easy for a small mistake to completely change the way
URLs are handled in your web application. This is because new routes, if
poorly coded, can override other routes. Unit tests highlight such bugs as soon
as they arise.

Review Question(s)

Verify the correctness of the statement by placing a mark in the column to the
right.

Statement Answer

You have implemented the MVC Site Map Provider in your web
application and used it to build menus and breadcrumb trails with
which users can navigate the logical hierarchy. MVC automatically
takes routes from the MVC Site Map Provider so the same
hierarchy is used in URLs.

Question: You want to ensure that when the user specifies a relative URL in
the form, “customer/3546”, the request is forwarded to the DisplayByID()
action in the CustomerController. You also want to ensure that when the
user specifies a relative URL in the form, “customer/fullname”, the request is
forwarded to the DisplayByName() action in the CustomerController. What
routes should you add?

Module 08: Applying Styles to ASP.NET MVC


4 Web Applications

Module Overview
While building web applications, you should apply a consistent look and feel
to the application. You should include consistent header and footer sections in
all the views. ASP.NET MVC 4 includes features such as cascading style
sheets (CSS) styles and layouts that enhance the appearance and usability of
your web application. ASP.NET MVC 4 also includes features such as
mobile-specific views that allow you to build applications for different
browsers or mobile devices.

Objectives

After completing this module, you will be able to:

Apply a consistent layout to ASP.NET MVC 4 applications by using CSS


o
and layout.
o Develop device-specific views to support various browsers.
o Build adaptive user interface for mobile devices.

Lesson 1 : Using Layouts


You need to build multiple views to support the operations of the application,
such as creating an order and querying order history. However, several
maintenance issues arise while changing the common part of the application
layout, because of which you need to update each view. To resolve these
maintenance issues, you can build a common module or a shared view. A
shared view that helps to store the application logic is called a layout.
ASP.NET MVC 4 includes features that help simplify the process of creating
and using layouts. You can further simplify the application management
process by using the _ViewStart file, to apply the layout to each view, instead
of individually editing each view.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe layouts.
o Describe how to use layouts.
o Describe the _ViewStart file.

What Are Layouts?


The ASP.NET MVC 4 Razor engine includes a feature called layouts. Layouts
are also called template views. Layouts enable you to define a common style
template, and then apply it to all the views in a web application. The
functionality of layouts is similar to that of the master page in a traditional
ASP.NET web application. You can use layouts to define the content layout or
logic that is shared across views.

You can define multiple layouts in an ASP.NET MVC 4 application, and each
layout can have multiple sections. You can define these sections

anywhere in the layout file, even in the <head> section of the HTML.
Sections enable you to output dynamic content to multiple, non-contiguous,
regions of the final response.

Question: What are some common scenarios when you would use layouts?

Creating a Layout
While creating layouts, you need to store the layout files in the \Views\Shared
folder of the project. The \Views\Shared folder is the default location, where
you can store common view files or templates.

The following example illustrates a layout.

A Layout View

<!DOCTYPE html>

<html>

<head>

<meta name="viewport"

content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<div>

@RenderBody()

</div>

</body>

</html

In the preceding example, the @RenderBody() method indicates to the


rendering engine where the content of the view goes.

ViewBag is an object that the layout and view shares. You can use the
ViewBag object to pass information between a view and a layout. To pass
information, you need to add a property to the ViewBag object, in the
ViewPage of the ViewController or View file, and use the same property in
the layout file. Properties help you control the content in the layout, to
dynamically render webpages from the code in the view file. For example,
consider that the template uses the ViewBag.Title property to render the
<title> content in the view. This property helps define the Title property of
the ViewBag object in the view and retrieve the property in the layout. This
retrieval is possible because the code in the view file runs before the layout
runs.

The following example illustrates a layout that contains a section.

Using Sections in Layouts

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<div id="menu">

@RenderSection("MenuBar",required:false)

</div>

<div>

@RenderBody()

</div>
</body>

</html>

The MenuBar parameter in the RenderSection() helper method specifies the


name of the section that you want to render in the layout. The required
parameter is optional; it allows you to determine if the section you render is
required. Consider that a section is required, and you do not implement the
section in the layout file. In this case, ASP.NET MVC 4.0 displays the
Section not defined exception at runtime.

Implementing sections in a layout file makes it easier to track content errors.


If a section is not required, you can choose to not include it in the layout.

Additional Reading: For more information about layouts and sections, you
can see: http://go.microsoft.com/fwlink/?LinkID=288965&clcid=0x409

Question: Why do you have multiple sections in a layout?

Linking Views and Layouts

After defining the layout, you should link the layout to the view files. You
should first remove the content that is not required anymore in the view. Then,
you need to create the link between the view and the layout, so that the
content removed from the view is not reflected in the layout.

To link a layout to a view, you need to add the Layout directive at the top of
the view file. The following code shows how to add a layout in a view file.

Linking to a View
@{

ViewBag.Title = "Details";

Layout = "~/Views/Shared/SiteLayout.cshtml";

<h2>Details</h2>

You can use the ViewBag.Title property to pass page title information from
the view to the layout. You can define other properties along with the
ViewBag object, such as <meta> elements in the <head> section, and enable
them to pass information to the layout.

If you have multiple sections in the layout file, you define the content of the
sections by using the @section directive. The following code illustrates how
to use the @section directive.

Using the @section Directive

@{

ViewBag.Title = "Details";

Layout = "~/Views/Shared/SiteLayout.cshtml";

<h2>Details</h2>

@section MenuBar {

<p> this is menu</p>

In the preceding example, you set the layout file to display sections at the top
of each view file. Usually, you have the same layout across the entire web
application or section. You can define the layout for an application or section,
by using the _ViewStart file. During runtime, the code in the _ViewStart file
runs before all the other views in the web application. Therefore, you can
place all common application logics in the _ViewStart file.

To use the _ViewStart file, you need to add the _ViewStart.cshtml file in the
\Views folder of your project. The following code illustrates the contents of
the _ViewStart file.

The _ViewStart File

@{

Layout = "~/Views/Shared/SiteLayout.cshtml";

Question: When should you use the _Viewstart file?

Lesson 2: Applying CSS Styles to an MVC


Application
Cascading Style Sheets (CSS) is an industry standard for applying styles to
HTML pages. Different methods of applying CSS to a webpage are available.
These methods include external CSS file, inline CSS, and CSS code block in
HTML. Developers usually use an external CSS file, because this file is
shared across multiple pages and it helps apply a consistent style across the
application. You need to know how to import styles into a web application, to
ensure consistency in the appearance of the application. You also need to
know how to use Expression Blend to create rich and interactive user
interfaces.

Lesson Objectives
After completing this lesson, you will be able to:

Describe the user experience that can be accomplished by using Expression


o
Blend.
o Import styles into an ASP.NET MVC 4 web application.
o Apply a consistent look and feel to an MVC 4 web application.

Overview of User Interface Design with Expression


Blend

Expression Blend is a visual authoring tool that helps developers and


designers to create user interfaces for Windows 8 HTML5 applications and
other web applications. Expression Blend for HTML includes a visual
designer, which serves as a good complement to Visual Studio. Visual Studio
is developer-centric, whereas Expression Blend for HTML is designer-centric.
The functions in Expression Blend facilitate developing HTML styles and
CSS.

Expression Blend for HTML includes the interactive mode that enables
developers to visualize the

result of the design, HTML, CSS, and JavaScript, by displaying results on the
screen while they edit the code. Expression Blend for HTML also includes
CSS tools that enable you to generate and edit CSS styles on the graphical
user interface.

Question: What are the key benefits of using Expression Blend for HTML to
edit CSS?

Importing Styles into an MVC Web Application


After creating CSS styles, you should import these styles into the web
application. After importing the CSS file into the web application, you need to
modify the layout of the web application, so that you can use the CSS styles
that you imported. You can modify the layout of a web application, by using
the <link> element.

The following example shows how to use the <link> element.

Linking to a Style Sheet

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

<link href="~/Views/Shared/StyleSheet1.css" rel="stylesheet"

type="text/css" />

</head>

<body>

<div id="menu">

@RenderSection("MenuBar",required:false)
</div>

<div>

@RenderBody()

</div>

</body>

</html>

CSS selectors help browsers to determine how the CSS styles should be
applied. You can use various selectors, such as class and id selectors, to apply
styles to HTML elements.

CSS class Selector

You can define a CSS class selector to specify a style for a group of elements.
To apply the class selector to an HTML element, you need to add the class
attribute to the HTML element. You can use the .<class> syntax to add the
style in the CSS file.

The following example shows how to add the class selector in a view.

Using a Class

@{

ViewBag.Title = "Details";

Layout = "~/Views/Shared/SiteLayout.cshtml";

<h2>Details</h2>

@section MenuBar {
<p class=”menu”> this is menu</p>

The following CSS snippet shows how to create the class selector.

Applying a Style to a Class

.menu

font-weight:bold;

CSS id Selector

You can use the CSS id selector to specify a style for any unique element in
your HTML code. To apply the id selector to an HTML element, you need to
add the id attribute and a unique name to the HTML element. You can use the
#<id> syntax to add the style in the CSS file.

The following example shows how to use the id attribute in a view.

Using The id Selector

@{

ViewBag.Title = "Details";

Layout = "~/Views/Shared/SiteLayout.cshtml";

<h2>Details</h2>

@section MenuBar {

<p id="leftmenu"> this is menu</p>


}

The following CSS snippet shows how to create the CSS id selector.

Creating an ID Style

#leftmenu

font-size:16px;

Question: What are some common scenarios when you would use the class
selector? What are some common scenarios when you would use the id
selector?

Lesson 3: Creating an Adaptive User Interface


ASP.NET MVC 4 applications facilitate adaptive user interface to render
content on different devices. Adaptive user interface is a type of user interface
that renders content based on the capability of the target web browser or
device. You need to ensure that your application supports mobile devices, so
that it reaches all types of audience. You also need to know how to use media
queries, mobile-specific views, and jQuery Mobile to ensure that your
application is effective on mobile devices.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe the HTML5 viewport attribute.


Explain how CSS media queries apply specific CSS based on the capabilities
o
of the browser.
Explain how you can use MVC 4 templates to render views based on mobile
o
device screen size.
o Describe the use of jQuery Mobile for building user interfaces that work on
a wide variety of mobile devices.
o Use NuGet to add jQuery Mobile to your projects.

The HTML5 Viewport Attribute

Adaptive rendering allows you to customize your web application to display


differently, based on the capabilities of the web browser or device.

Additional Reading: For more information about adaptive rendering


techniques, go to:

http://go.microsoft.com/fwlink/?LinkID=288966&c lcid=0x409

Mobile browsers such as Internet Explorer use the viewport attribute to


render webpages in a

virtual window. This virtual window is usually wider than the application
screen. The viewport attribute helps eliminate the need to reduce the size of
layout of each page. Reducing the size of the layout can break or distort the
display of non-mobile-optimized web applications. Creating the application
interface by using the viewport attribute enables users to zoom into the
different areas of a webpage.

Additional Reading: For more information about the viewport attribute,


visit: http://go.microsoft.com/fwlink/?LinkID=288967&clcid=0x409

The viewport tag is a meta tag that helps to control the width and height of
webpages, while it renders to web browsers.

The following example illustrates how to use the viewport tag.


Using the Viewport Tag

<meta name="viewport" content="width=device-width, initial-scale=1,

maximum-scale=1">

The width and height properties help to specify the width and height of the
virtual viewport window. You can specify the width in pixels. You can use the
keyword device-width to enable the content to fit the native screen size of the
browser.

The initial-scale property controls the initial scale or zoom level of the
webpage. The maximum-scale, minimum-scale, and user-scalable
properties control the other scalability features of the webpage.

Question: How can you control the size of the virtual viewport window?

CSS Media Queries

You may sometimes need to apply different CSS styles in your application, to
support different browsers. HTML5 includes CSS media queries, which are
special selectors that begin with @media. Media queries allow conditional
application of CSS styles, based on the device conditions or browser
capabilities. You can apply media queries in CSS and HTML.

The following example illustrates a media query in CSS.

Using a Media Query

@media only screen and (max-width: 500px) {


header{

float: none;

You can also apply a media query in the <link> element. The following
example illustrates how to include a media query in a <link> element.

Using a Media Query in the Link Element

<link rel="stylesheet" type="text/css" href="smallscreen.css"

media="only screen and

(max-width: 500px)" />

You can use CSS media queries to apply CSS styles when the screen size is
less than 500 pixels. However, you can use CSS media queries only for the
screen layout, but not the print layout.

Additional Reading: For more information about media queries, visit


http://go.microsoft.com/fwlink/?LinkID=288968&clcid=0x409

The following table describes all properties that you can include in a media
query.

Property Description

width The width of the targeted display area, which includes the
browser window in desktop and mobile devices. In desktop
computers, when you resize the browser window, the width of the
browser changes. However, on most mobile browsers, you cannot
resize the browser window. This implies that the width of the
browser remains constant.

height The height of the targeted display area, which includes the
Property Description

browser window in desktop and mobile devices.

device- The width of the entire screen of a device. For a desktop with a
width screen resolution of 1,024x768, the device-width is usually 1,024
pixels.

device- The height of the entire screen of a device. For a desktop with a
height screen resolution of 1,024x768, the device-height is usually 768
pixels.

orientation The orientation of the device. If the device-width is larger than


the device-
height, the orientation value is set to landscape; otherwise, it is
set to portrait.

aspect-ratio The ratio of the width and height


properties.

device-aspect-ratio The ratio of the device-width and


device-height properties. The
following example illustrates the
device-aspect-ratio for a device with
a screen resolution of 1,280x720.

@media screen and (device-aspect-

ratio: 16/9) { }

@media screen and (device-aspect-

ratio: 1280/720) { }

@media screen and (device-aspect-

ratio: 2560/1440) { }

color The number of bits per color


Property Description

component of the device. If the


device is not a color device, the
value is zero.

color-index The number of entries in the color


lookup table, of the output device.

monochrome The number of bits per pixel in a


monochrome frame buffer. For non-
monochrome devices, this value is
zero.

resolution The resolution of the output device,


or the density of the pixels. The
common units for this property
include dpi and dpcm.

scan The scanning process of TV output


devices.

grid The property that detects whether the


output is in the grid or bitmap
format. Grid-based devices return a
value of one; all other devices return
a value of zero.

Question: Why would you choose to use CSS media queries, instead of using
C# code, to define styles for specific browsers?

MVC 4 Templates and Mobile-Specific Views


ASP.NET MVC 4 includes two new features, mobile display mode and
custom display mode, which help you to create webpages for mobile devices
and different browsers.

Additional Reading: For more information about creating webpages for


mobile device browsers, go to

http://go.microsoft.com/fwlink/?LinkID=288966&clcid=0x409

ASP.NET MVC 4 enables you to override views for

mobile devices by using a different set of view files, rather than using a
configuration. When ASP.NET MVC 4 receives a request from a mobile
browser, it analyses the request for views with the naming convention
[view].mobile.cshtml. If ASP.NET MVC 4 detects a view with the mentioned
naming convention, ASP.NET MVC 4 will serve the request by using the
mobile version of the view; otherwise, it returns the request to the standard
view.

Consider that your web application includes a layout that is specific to a


browser. In this case, you can create browser-specific views for that browser
by checking the UserAgent string of that browser. The UserAgent string
helps identify a browser.

Additional Reading: For more information about creating browser-specific


view, visit http://go.microsoft.com/fwlink/?LinkID=288969&clcid=0x409

Question: Why would you choose device-specific display modes over CSS
media queries?
jQuery Mobile

The jQuery Mobile library is a mobile version of the jQuery library, which
helps to develop applications that run on mobile devices. jQuery helps to add
responsive UI elements to a web application. jQuery also enables developers
to add interactive content to the mobile version of a web application. The
library also helps to ensure that older mobile devices see usable controls.
Similar to jQuery, jQuery Mobile library includes a set of JavaScript and CSS
files that enable you to build mobile-specific applications, without adjusting
the HTML elements.

jQuery mobile includes the following JavaScript and CSS files:

o jquery.mobile.structure-<version>.css
o jquery.mobile.structure-<version>.min.css
o jquery.mobile.theme-<version>.css
o jquery.mobile.theme-<version>.min.css
o jquery.mobile-<version>.css
o jquery.mobile-<version>.js
o jquery.mobile-<version>.min.css
o jquery.mobile-<version>.min.js
o images/ajax-loader.gif
o images/ajax-loader.png
o images/icons-18-black.png
o images/icons-18-white.png
o images/icons-36-black.png
o images/icons-36-white.png
The jQuery.Mobile.MVC NuGet package simplifies the process of adding the
jQuery Mobile library to a web application by eliminating the need to
manually install the library files. NuGet is a Visual Studio extension that
enables users to download packaged content from the Internet and directly
install the content into the project. The NuGet package contains the following
items:

The App_Start\BundleMobileConfig.cs file. This file helps to reference the


o
jQuery JavaScript and CSS files.
o jQuery Mobile CSS files
o A ViewSwitcher controller widget
o jQuery Mobile JavaScript files
o A jQuery Mobile-styled layout file
A view-switcher partial view. This provides a link at the upper-end of each
o page; this link helps switch from desktop view to mobile view, and vice
versa.
o .png and .gif image files

Additional Reading: For more information about the NuGet package, visit
http://go.microsoft.com/fwlink/?LinkID=288970&clcid=0x409

Note: You can use the Microsoft Ajax Content Delivery Network (CDN) to
attend to users, by using the servers that are located geographically closer to
them. CDN helps to improve the performance of the application. After adding
the NuGet package to your ASP.NET MVC application, you can change the
code in HTML or the view, to reference the jQuery Mobile library that is
hosted on Microsoft Ajax CDN.

Additional Reading: For more information about jQuery mobile that is


hosted on Microsoft CDN, visit
http://go.microsoft.com/fwlink/?LinkID=288971&clcid=0x409

Question: What are the benefits of using Microsoft Ajax CDN?

Module Review and Takeaways


In this module, you learned how to apply a consistent look and feel to a web
application, and share other common components, such as headers and
footers, between all views. You also learned how to use the CSS and display
modes to adapt the web application for smaller screens and mobile devices.
You also familiarized yourself with HTML5 elements that allow you to
develop web applications that work on various browsers and devices.

Real-world Issues and Scenarios

When you develop web applications, you need to create applications that work
on different devices and browsers, such as iPhone, iPad, Windows Phone,
Google Chrome, and Internet Explorer 10. In such cases, you can use the
HTML5 elements and features in MVC 4, such as mobile-specific views,
media queries, and jQuery Mobile library, to create applications that work
well in various browsers and devices.

Review Question(s)

Question: You are building an application, which needs to work in different


mobile devices, Windows Phone, Windows, and Mac. You want to reduce the
effort for maintaining the code which is required for different devices and you
want to ensure that it would work with new browsers. What should you do?

Module 09: Building Responsive Pages in


ASP.NET MVC 4 Web Applications

Module Overview
Many web applications need to display large amount of information and
graphics. Large volumes of data make web applications take longer to load.
Instead of having all the elements on the page load multiple times, you can
implement caching in your web applications to reduce the need to repeatedly
load the same elements. You can also use partial page updates to reduce the
need to load the entire webpage, by enabling the application to refresh only
specific sections of the webpage.

Objectives
After completing this module, you will be able to:

Implement partial page updates that help reduce the need to reload entire
o
pages.
Implement caching to reduce the loading time of the different elements of a
o
webpage.

Lesson 1 : Using AJAX and Partial Page Updates


While developing web applications, to update individual sections in the page,
you may need to reload the entire webpage. Asynchronous JavaScript and
XML (AJAX) in ASP.NET MVC 4 enables partial page updates, to help
update sections of a webpage, without reloading the entire page. The
Ajax.ActionLink helper helps implement partial page updates in your web
application.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe the benefits of using partial page updates.


o Use AJAX in an ASP.NET MVC 4 web application.
o Use the Ajax.ActionLink helper.

Why Use Partial Page Updates?

ASP.NET and MVC facilitate server-side processing. Server-side processing


enables HTML rendering to occur at the server side and the server usually
generates the HTML. When you update a webpage, any updates or actions
performed on the page require a round-trip request to the server. Such
constant server requests affect the performance of the application.

The AJAX development model helps reduce the need for refreshing an entire
webpage, each time an update of page content is required. AJAX uses

JavaScript and XML to obtain information from the client system. AJAX
creates webpages based on the XML information downloaded from the server.
However, developing web applications by using AJAX is not easy, because it
requires using complex technologies, such as JavaScript and XML. Microsoft
includes a feature in ASP.NET called partial page updates that functions along
with AJAX to reduce the need for refreshing an entire webpage, each time an
update occurs.

Partial page updates use AJAX technologies to help update individual sections
of a webpage, during postback. Partial page updates:

o Require fewer lines of code.


o Help reduce the data sent to users, each time a webpage update occurs.
o Increase the responsiveness of the web application.

Question: How do partial page updates help in improving the responsiveness


of a web application?

Using AJAX in an MVC 4 Web Application

To implement AJAX in your MVC 4 application, you need to create views


that render only the updated content, and not the entire webpage.
You can initially develop your web application without using AJAX, and then
check the application for any functionality errors. This practice helps reduce
the time required to troubleshoot the application. This practice also helps
separate any application functionality errors from errors that occur while
implementing AJAX.

To implement partial page updates, you need to create a view, called a partial
view, which includes

only the section that you need to update.

For example, consider a view as shown in the following code.

An Example View

@{

Layout = null;

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Index</title>

</head>

<body>

<div>

<div id="divMessage">@ViewBag.Message</div>
@Html.ActionLink("Refresh","HelloWorld")

</div>

</body>

</html>

In the preceding code example, ActionLink helps direct users to another view
called HelloWorld.

The following code shows the HelloWorld view.

The Hello World View

@{

Layout = null;

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>HelloWorld</title>

</head>

<body>

<div>

@ViewBag.Message

</div>
</body>

</html>

To implement AJAX in the preceding code example, you need to update the
HelloWorld view to render only the content that is updated.

Consider another example wherein you want to render only an updated


message, on a webpage. The following code shows a view that is updated to
render only the changed message.

A ViewBag Example

@ViewBag.Message

With AJAX, the Javascript retrieves only a specific portion of a webpage,


which you want to update, from the server. In the ViewController class, you
need to update the View function to return the PartialView class, instead of
the entire View class.

The following code shows how to update the View function to return the
PartialView class.

Returning a Partial View in a Controller Action

public class Default1Controller : Controller

//

// GET: /Default1/

public ActionResult Index()

ViewBag.Message = "Hello";
return View();

[HttpGet]

public PartialViewResult HelloWorld()

ViewBag.Message = "Hello World";

return PartialView();

Optionally, you can add the HttpGet or HttpPost attributes before the View
function. These attributes help indicate if the partial page update should be
performed over the HTTP POST or HTTP GET method.

Question: What is the mandatory action that you should perform to


implement partial page updates in your web application?

The Ajax.ActionLink Helper

You can use the Ajax.ActionLink helper to trigger partial page updates. The
Ajax.ActionLink helper helps initiate the Javascript, to obtain the updated
HTML information from the view and replace or insert the updated HTML
information at a specific location.

The following code shows how to use the Ajax.ActionLink helper.

Using the Ajax.ActionLink Helper

@{

Layout = null;

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Index</title>

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-

1.8.3.js"

type="text/javascript"></script>

<script

src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-

ajax.min.js"

type="text/javascript"></script>

</head>

<body>

<div>

<div id="divMessage">@ViewBag.Message</div>
@Ajax.ActionLink("Refresh","HelloWorld", new AjaxOptions{

HttpMethod = "POST",

UpdateTargetId = "divMessage", InsertionMode = InsertionMode.Replace

})

</div>

</body>

</html>

In the preceding example, parameters such as HttpMethod and


UpdateTargetId are included along with the Ajax.ActionLink helper, to:

Obtain the HTML information from the HelloWorld view, by using the
o
HTTP POST method.
o Replace the content in the divMessage HTML element.

While using the Ajax.ActionLink helper, you need to include the jQuery and
jQuery unobtrusive libraries in the same webpage, because the
Ajax.ActionLink helper uses scripts from these two libraries.

Question: What is the primary function of the Ajax.ActionLink helper?

Lesson 2: Implementing a Caching Strategy


Web applications display information on a webpage by retrieving the
information from a database. If the information that should be retrieved from
the database is large, the application may take longer to display the
information on a webpage. ASP.NET MVC 4 supports some caching
techniques to help reduce the time required to process a user request.

Before implementing caching, you should first analyze if caching is relevant


to your application, because caching is irrelevant to webpages whose content
change frequently. To successfully implement caching in your web
application, you need to familiarize yourself with the various types of caches,
such as output cache, data cache, and HTTP cache.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe the benefits of using caching.


o Describe the output cache.
o Describe the data cache.
o Describe the HTTP cache.
Describe how to prevent caching for webpage content that changes
o
frequently.
o Configure caching.

Why Use Caching?

Caching involves storing the information that is obtained from a database in


the memory of a web server. If the content rendered by a webpage is static in
nature, the content can be stored in caches or proxy servers. When a user
requests content from a web application, caching ensures that the user receives
content from the cache, thereby eliminating the need for repeated real-time
processing.

Caching:

Reduces the need to repeatedly retrieve


o
the same information from the database.
o Reduces the need to reprocess data, if a user places a request multiple times.
Helps improve the performance of a web application, by reducing the load
o
on servers.
o Helps increase the number of users who can access the server farm.
However, caching does not help web applications that include frequent
content changes. This is because, the content rendered from a cache may be
outdated, when compared to the current information. Therefore, you should
evaluate the content of your web application and analyze the impact of
rendering outdated content, before implementing caching.

Question: How does caching help increase the scalability of a web


application?

The Output Cache

Output cache allows ASP.NET engines to store the rendered content of a


webpage in the memory of the web server. Therefore, when a user requests a
specific page multiple times, the content is retrieved from the cache, thereby
avoiding the execution of programming code in the server.

Output cache is a good complement to AJAX partial page updates. Output


cache and partial page updates reduce the workload on the server and increase
the number of user requests that a server can handle.

In ASP.NET MVC 4, you can implement output

caching, by adding the OutputCache attribute to the controller.

The following code shows how to implement output caching.

Configuring the Output Cache

[OutputCache(Duration = 60)]
public PartialViewResult HelloWorld()

ViewBag.Message = "Hello World";

return PartialView();

The OutputCache attribute helps direct the rendering engine to the cache that
contains results from the previous rendering process. The Duration parameter
of the OutputCache attribute helps control the period of time in seconds for
which data should be stored in the cache.

By default, the output cache stores only one copy of the rendered content, for
each view. Consider a view with the QueryString input parameter that
enables content to change based on the variable gathered from the database or
a prior request. In this case, you can add the VaryByParam property to the
OutputCache attribute, to store a copy of each unique combination of
parameters in the cache.

The following code shows how to add the VaryByParam property to the
OutputCache attribute.

Caching by Parameter Value

[OutputCache(Duration = 60, VaryByParam="ID")]

public PartialViewResult HelloWorld()

ViewBag.Message = "Hello World";

return PartialView();

}
In the preceding example, observe that the VaryByParam property refers to
QueryString, instead of other MVC parameters. You can also use the
VaryByCustom property.

The following code shows how to add the VaryByCustom property to the
OutputCache attribute.

Using VaryByCustom

[OutputCache(Duration = 60, VaryByCustom="browser")]

public PartialViewResult HelloWorld()

ViewBag.Message = "Hello World";

return PartialView();

You can add browser as the input parameter to the VaryByCustom property.
The browser parameter helps store a copy of the rendered content
corresponding to each browser that the application is run on. If you want to
control and implement your own logic to determine when a new copy should
be stored, you need to override the GetVaryByCustomString function in the
Global.asax file of your project.

Question: How does the functioning of a web application that implements the
output cache differ from an application that does not implement output cache?

The Data Cache


Web applications usually depend on the content in a database, to render
content on a webpage.

Databases sometimes encounter performance issues caused by poorly written


queries, which can slow down the performance of database requests resulting
in poor webpage performance. You can implement the data cache in your web
application to avoid loading data from a database every time a user places a
request. The MemoryCache class allows you to implement data cache in your
web application. Implementing the data cache involves the following actions:

1. Loading information from the database


2. Storing content in the MemoryCache object
3. Retrieving data from the MemoryCache object
Ensuring that content is available in the MemoryCache object; otherwise,
4.
reloading the content

The following code shows how to add the MemoryCache object.

Using the Memory Cache

System.Data.DataTable dtCustomer =

System.Runtime.Caching.MemoryCache.Default.

AddOrGetExisting("CustomerData", this.GetCustomerData(),

System.DateTime.Now.AddHours(1));

In the preceding example, the following parameters are specified:


Key. The unique identifier of the object that should be stored in the memory
o
cache.
o Value. The object that should be stored in the memory cache.
o AbsoluteExpiration. The time when the cache should expire.

You can use the AddOrGetExisting function, instead of the Add function, to
enable the application to refresh and retrieve data in one line of code. If the
cache contains the relevant data, the AddOrGetExisting function retrieves
the data from the cache. If the cache does not contain the relevant data, the
AddOrGetExisting function allows adding the data to the cache, and then
rendering the same data on the webpage.

Question: What are the benefits of implementing data caching in MVC


applications?

The HTTP Cache

You can implement HTTP caching in the Browser Cache and the Proxy
Cache.

The Browser Cache

Most web browsers store the content downloaded from web servers in their
local cache. Storing data in the local cache helps remove the need to
repeatedly download content from the server.

Web browsers frequently check content for updates. If the content is updated
in the server, web browsers download the content from the server, to attend to
user requests. Otherwise, web
browsers render content from the local cache.

The Proxy Cache

The functionality of the proxy cache is similar to the functionality of the


browser cache. However, the cache is stored on a centralized server. Users can
connect to the Internet or web servers by using this proxy server. Proxy
servers store a copy of a web application in a manner similar to a web browser
storing a copy of an application in the local drives. Many users can access the
cache in a proxy server, while only one user can access the browser cache at a
time.

Question: What is the difference between HTTP cache and output cache?

Preventing Caching

Caching can sometimes create issues in web applications, because if an


application involves frequent content updates, caching prevents users from
viewing these content updates. To resolve caching issues, you can implement
an HTTP header called Cache-Control. The Cache-Control header indicates to
the web browser how to handle the local cache. All HTTP clients, such as
browsers and proxy servers, respond to the instructions provided in the Cache-
Control header to determine how to handle the local cache of a web
application.

Additional Reading: For more information about setting this header, go to:
http://go.microsoft.com/fwlink/?LinkID=288972&clcid=0x409
You can use the HttpCachePolicy.SetCacheability method to specify the
value of the Cache-Control header. The HttpCachePolicy.SetCacheability
method helps control caching performance.

The following code shows how to use the HttpCachePolicy.SetCacheability


method.

Using SetCacheability

Response.Cache.SetCacheability(HttpCacheability.Private);

In the preceding example, the HttpCachePolicy.SetCacheability method


takes the Private enumeration value.

To prevent caching in your web application, you should set the Cache-Control
header value to NoCache.

The code shows how to exclude the HTTP cache in your web application.

Preventing Caching

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Question: What scenarios would require you to prevent caching for a web
application?

Module Review and Takeaways


In this module, you used AJAX and partial page updates in MVC applications.
AJAX and partial page updates help reduce the need for reloading the entire
page, when a user places a request. Partial page updates also reduce the need
for writing multiple lines of code, to update specific portions of a webpage.
You also used caching to increase the performance of a web application.

Real-world Issues and Scenarios

Web applications usually run multiple queries to retrieve information from a


database and render content on the webpages. Users sometimes complain that
webpages take longer to load. Therefore, developers implement caching in the
web application, to reduce the need to load data from a database, every time a
user places a request. Caching helps webpages load faster, thereby increasing
the performance of the application.

Review Question(s)

Question: An application is refreshing the content every 10 seconds for the


updated information from database. User complaints that this is impacting
their work and has caused data loss. How would you propose to help resolve
this issue?

Module 10: Using JavaScript and jQuery for


Responsive MVC 4 Web Applications

Module Overview
Responsive web design is a web designing approach that helps create visually
rich and interactive web applications. JavaScript plays an important role in the
development of responsive web applications. You need to know how to use
JavaScript to implement application logic and resize interface elements,
without triggering a full-page refresh. To simplify adding JavaScript to your
web application, you need to know how to use libraries such as jQuery,
jQuery UI, and jQuery Mobile.

Objectives

After completing this module, you will be able to:

o Add JavaScript code to your web application.


o Use the jQuery and jQuery UI libraries, in your web application.

Lesson 1 : Rendering and Executing JavaScript


Code
You can create interactive HTML elements in your web application by using
JavaScript. ASP.NET renders these interactive elements on your webpages.
You can add packaged JavaScript libraries to your project by using the NuGet
tool. You should know how to use AJAX to update the contents of webpages.
By using AJAX, you can optimize the performance of your web application.
In addition, you should know how the content delivery network (CDN) helps
take content geographically closer to users.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe how to add JavaScript files to an MVC application.


o Describe how to call JavaScript functions in JavaScript libraries.
o Describe how to use JavaScript Libraries in MVC 4 web applications.
List the benefits of using CDN to improve the performance of JavaScript
o
libraries.
o Describe how to use the NuGet tool to add packages.
o Use the NuGet tool to add a JavaScript Library.

Adding JavaScript Files

You can add JavaScript code to web applications by:

o Adding the JavaScript code to HTML.


o Defining the JavaScript code in dedicated JavaScript files.
JavaScript code helps add interactive functionalities to the webpages of your
application. The following example shows how to add JavaScript to HTML.

Inserting a JavaScript Function

<body>

<script type="text/javascript">

function HelloWorld() {

alert('Hello World');

</script>

<div>

...

</div>

</body>

If you have multiple HTML pages in a web application, you need to add
JavaScript code for each HTML page. You cannot simultaneously add
JavaScript code for multiple HTML pages. Therefore, you can define the
JavaScript code in a JavaScript file (.js file). Then, you can reference the
JavaScript file in multiple HTML pages. This enables you to maintain a single
JavaScript file, to edit the JavaScript code for multiple HTML pages. You can
also have multiple JavaScript code files for a single HTML page.

The following image displays the Add New Item dialog box that helps to add
a JavaScript file.
FIGURE 10.1:ADDING A JAVASCRIPT FILE

The following example shows how to reference the new JavaScript file in
HTML pages.

Referencing JavaScript Files

<script src="~/Scripts/JavaScript1.js"

type="text/javascript"></script>

You can create the Scripts folder in the root folder of your MVC project, and
then save all JavaScript files in the Scripts folder.

Question: What are the advantages of using a JavaScript file?

Calling JavaScript Procedures


You can call functions defined in JavaScript files by using script blocks or
event handlers.

The following code shows how to call the HelloWorld function from a script
block.

Using a Script Block

<body>

<script type="text/javascript">

HelloWorld();

</script>

<div>

Hello

</div>

</body>

Before calling a JavaScript function, you need to define the function by using
a script block. Then, you must reference the JavaScript file from the HTML
pages.

If you want to avoid calling the JavaScript function directly, you can use the
onclick JavaScript event to trigger JavaScript functions. The onclick event
initiates the JavaScript function assigned to an HTML file, when you click the
corresponding HTML element. JavaScript functions that are attached to
document object model (DOM) events are called event handlers.

The following code shows how to add the HelloWorld event handler to the
button’s onclick event.

Using an Event Handler


<body>

<div>

Hello

<input type="button" value="Hello" onclick="HelloWorld();" />

</div>

</body>

Additional Reading: For more information about events that are available for
HTML elements, go to
http://go.microsoft.com/fwlink/?LinkID=288973&clcid=0x409

Question: What is the advantage of initiating JavaScript functions by using


JavaScript events?

JavaScript Libraries

You can reduce the time taken to develop applications by using JavaScript
libraries.

JavaScript libraries help to:

o Reduce the amount of code you need to write to add functions.


o Reduce the time the system takes to debug the application.

Some commonly used JavaScript libraries include the following:


jQuery
o
(http://go.microsoft.com/fwlink/?LinkID=288974&clcid=0x409)
o jQuery UI (http://go.microsoft.com/fwlink/?LinkID=288975&clcid=0x410)
jQuery Mobile
o
(http://go.microsoft.com/fwlink/?LinkID=288976&clcid=0x411)
jQuery Validation
o
(http://go.microsoft.com/fwlink/?LinkID=288977&clcid=0x412)
jQuery Cycle
o
(http://go.microsoft.com/fwlink/?LinkID=288978&clcid=0x413)
jQuery DataTables
o
(http://go.microsoft.com/fwlink/?LinkID=288979&clcid=0x409)
o Prototype (http://go.microsoft.com/fwlink/?LinkID=299651&clcid=0x409)
o MooTools (http://go.microsoft.com/fwlink/?LinkID=299652&clcid=0x409)

You can use JavaScript libraries to make your application more interactive.
The functioning of JavaScript codes depends on the version of the library you
use. Not all code may work with all versions of a library.

The jQuery library (and its related libraries) has the additional advantage of
dealing with the differences in the DOM across different browsers and
different browser versions.

Question: What is the advantage of using JavaScript libraries?

Using Content Delivery Networks for JavaScript


Libraries
A content delivery network (CDN) is a group of geographically distributed
servers used for hosting contents for web applications. In many cases, you can
bring web content geographically closer to your applications users by using a
CDN to host libraries. This will also improve the scalability and robustness of
the delivery of that content.

The amount of content stored in a CDN varies among different web


applications. Some applications store all their content on a CDN, while other
applications store only some of their

content.

Microsoft has a dedicated CDN called Microsoft Ajax CDN that hosts some
popular JavaScript libraries, such as:

o jQuery
o jQuery UI
o jQuery Mobile
o jQuery Validation
o jQuery Cycle
o jQuery DataTables
o Ajax Control Toolkit
o ASP.NET Ajax
o ASP.NET MVC JavaScript Files

Note that Microsoft does not own the license of the JavaScript libraries
mentioned in the preceding list. Microsoft only hosts the libraries for
developers.

You can often reduce the loading time of your web application, by using the
JavaScript libraries hosted on Microsoft Ajax CDN. Web browsers can cache
these JavaScript libraries on a local system.

The following code shows how to use JavaScript libraries.

Linking to JavaScript Libraries


<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"

type="text/javascript"></script>

Additional Reading: For more information about Microsoft AJAX CDN, go


to http://go.microsoft.com/fwlink/?LinkID=293689&clcid=0x409

Question: How can CDN help improve the performance of a web application?

Using the NuGet Tool to Add Packages

You can use the NuGet package manager to manage JavaScript libraries. You
can avoid adding JavaScript libraries manually to your web application by
installing the NuGet package manager in your application. This practice helps
reduce the need for configuration tasks, while adding JavaScript libraries to an
application.

Microsoft Visual Studio 2012 supports installing and using NuGet packages.
You can search for NuGet packages in the NuGet store of Microsoft Visual
Studio 2012. Then, you can directly install them into your MVC application.

The following image shows the application page that you can use to manage
NuGet packages.
FIGURE 10.2:MANAGING NUGET PACKAGES

After you select the NuGet package that you wish to install, click Install, to
download and install the package into your project.

Additional Reading: To search for NuGet packages and analyze the details
of each package, go to
http://go.microsoft.com/fwlink/?LinkID=288981&clcid=0x410

Question: Why should you use NuGet packages to add JavaScript libraries to
your web application?

Lesson 2: Using jQuery and jQueryUI


jQuery is a JavaScript library that simplifies the adding of JavaScript to
HTML pages. jQuery is an open-source software that you can use for free. It
helps reduce the amount of code that you need to write, to perform tasks such
as accessing and modifying HTML elements on a webpage. You can use the
ajax function in jQuery to call a web service in your application. You can also
use jQuery UI to add interactions, animations, effects, and widgets to your
web applications.

Lesson Objectives
After completing this lesson, you will be able to:
o Describe jQuery.
Describe how to link web applications to jQuery Libraries for client-side
o
scripting.
o Describe how jQuery helps access the HTML elements of a webpage.
o Describe how to modify elements by using jQuery.
o Describe how to call a web service by using jQuery.
o Describe jQuery UI.
o Add a jQuery UI widget to an MVC 4 web application.

Introduction to jQuery

jQuery is a JavaScript library that you can use with different browsers. jQuery
was first released in 2006. jQuery helps query the HTML Document Object
Model (DOM) and obtain a set of HTML DOM elements. This feature of
jQuery helps:

o Reduce the amount of code that you need to write, to perform a task.
o Reduce the development time of HTML applications.

jQuery includes the following features:

o DOM element selections


o DOM traversal and modification
o DOM manipulation, based on CSS selectors
o Events
o Effects and animations
o AJAX
o Extensibility through plug-ins
o Utilities
o Compatibility methods
o Multi-browser support

Additional Reading: For more information about jQuery, go to:


http://go.microsoft.com/fwlink/?LinkID=288982&clcid=0x411

The jQuery family includes the following two companion modules:

jQuery UI. This library adds functions and other supporting elements that
o
help implement a rich interface to HTML-based applications.
jQuery mobile. This library adds functions that optimize the application
o
interface for mobile devices.

Question: Why should you use jQuery while developing web applications?

Linking to jQuery Libraries

jQuery Original Version and jQuery Minified Version provide similar


functionalities; however, they optimize web applications for different
purposes:

jQuery Original Version (jQuery-<version>.js). This is the uncompressed


o
version of the jQuery library, with files sizes larger than 200 kilobytes (KB).
jQuery Minified Version (jQuery-<version>.min.js). This includes the
compressed and gZip versions of jQuery,
o
with file sizes of about 30 KB.
When you develop the production environment, you can use jQuery Minified
Version to reduce the loading time of the web application. If you use the
minified version while working on the development environment, you cannot
access the source code of the JavaScript libraries during the debug operation.
Therefore, you can use the original version of jQuery, while creating the
development environment.

The following code shows how to reference the jQuery library in your web
application. You can add the line of code in the <head> element of your
HTML.

Referencing jQuery

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-

1.8.0.min.js"

type="text/javascript"></script>

Bundling and Minification

Bundling is a new feature in ASP.NET 4.5 that you can use in MVC 4 web
applications. Bundling helps combine multiple JavaScript libraries into a
single HTTP request.

Minification compresses code files before incorporating them in the client


application. Bundling and minification help reduce the loading time of web
applications by reducing both the number and size of HTTP requests.

To use bundling and minification in your web application, you should perform
the following steps:

Reference the Microsoft.AspNet.Web.Optimization library in your


1.
application by using NuGet packages.
2. In the App_Start folder of your project, add the BundleConfig.cs file.
In the BundleConfig.cs file, add the following code.
3.
public static void
RegisterBundles(System.Web.Optimization.BundleCollection bundles)

bundles.Add(new

System.Web.Optimization.ScriptBundle("~/bundles/jquery").Include(

"~/Scripts/jquery-

{version}.js","~/Scripts/JavaScript1.js"));

4. In the Global.asax Application_Start event, add the following code.


BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundl

es);

The ScriptBundle class enables you to define the bundle that helps combine
multiple JavaScript libraries into a single file. You can use a special
placeholder, such as {version} in the JavaScript path, to help update the
version of jQuery libraries. ASP.NET replaces {version} with the latest
version number of the JavaScript libraries present in the Scripts folder. If the
minified version of jQuery is available in the Scripts folder, the MVC 4
engine selects the minified version for bundling. Then, in your View file, you
can include the following lines of code to render the bundled JavaScript file.

<head>

@Scripts.Render("~/bundles/jquery")

</head>

You should add the following line of code in a page or namespace of the
Web.config file in the View folder. This code helps trigger the functioning of
@Scripts.Render.

<add namespace="System.Web.Optimization"/>
Based on the compilation setting in the Web.config file, the jQuery library
renders minified versions of Javascript. For example, the following code sets
the debug attribute of the compilation element to false, which allows jQuery
to use the non-minified version of the libraries, making debugging of the
libraries easier.

<compilation debug="false" />

Question: What are the benefits of using the minified version of jQuery in the
production environment?

Accessing HTML Elements by Using jQuery

jQuery helps access HTML elements, to create interactive web applications.


You use the following selector to select elements by element name, id, or CSS
class, while adding jQuery code to access HTML elements.

$(element name|#id|.class)

The following jQuery selector accesses the HTML element with the
HelloButton ID.

$(“#HelloButton”)

You can use jQuery to access or modify all instances of a specific HTML
element, in an HTML page. The following jQuery selector identifies all
instances of the A element in an HTML page.

$(“a”)
After accessing the HTML elements, you can perform actions on the
elements, such as:

o Modifying the attributes on the HTML elements.


Defining event handlers to respond to events associated with the selected
o
HTML elements.

The following example adds an event handler to the click event of the
HelloButton HTML element.

Using a jQuery Event Handler

$("#HelloButton").click(function (event) {

alert("Hello World");

});

If the jQuery scripts load before the webpage loads, you may encounter errors
such as object not defined. You can place the jQuery code in the
document.ready event, to prevent the code from loading until all HTML
elements in the page load.

The following code shows how to use the document.ready function

Using the Document Ready Function

$(document).ready(function () {

//Code placed here will not execute before the page is fully

loaded.

});

The following complete example shows how to access HTML elements by


using jQuery.

A Complete Example
<body>

<div>

Hello

<input type="button" value="Hello" id="HelloButton" />

</div>

<script type="text/javascript">

$(document).ready(function () {

$("#HelloButton").click(function (event) {

alert("Hello World");

});

});

</script>

</body>

Question: Why should you include the jQuery code in the document.ready
event?

Modifying HTML Elements by Using jQuery


You can use jQuery to query HTML DOM and obtain HTML elements. You
can use jQuery functions to modify the attributes associated with the HTML
elements. The following are some commonly used jQuery functions, which
enable you to modify HTML elements:

You can use the val function to get or set the value of an HTML element. The
following example shows how to use the val function to set the value of the
HelloButton element to “Hello World”.

The val Function

$('#HelloButton').val('Hello World');

You can use the css function to get or set the inline CSS style associated with
an HTML element. The following example shows how to use the css function
to set the background color of an HTML element to blue.

The css Function

$('#HelloButton').css('background-color','blue);

You can use the addclass function to assign a CSS class to an HTML
element. The following example shows how to use the addclass function to
add the input_css_class to an HTML element.

The addclass Function

$('#HelloButton').addClass('input_css_class');

Additional Reading: For more information about jQuery functions, go to


http://go.microsoft.com/fwlink/?LinkID=288983&clcid=0x412

Question: If querying HTML DOM returns multiple HTML elements, how


will jQuery functions handle these elements?

Calling a Web Service by Using jQuery


jQuery includes the ajax function that helps:

1. Perform asynchronous calls to web services.


2. Retrieve the data returned from web services.

The following example illustrates how to use the ajax function.

Using the ajax Function

var req= $.ajax({

type: "POST",

dataType: "json",

url: "Customer.asmx/GetCustomerInfo",

data: "{'ID': '123'}",

contentType: "application/json; charset=utf-8",

success: function (msg) {

alert("Data Saved: " + msg);

},

failure: function (msg) {

alert(msg);

});
The ajax function uses the parameters type, datatype, url, data,
contentType, success, and failure to control how to call the web services.
These parameters are described as follows:

type. This parameter controls the request type that you should use while
o
querying the web services.
o dataype. This parameter defines the data type to be sent for AJAX services.
o url. This parameter provides the URL of the web services.
data. This parameter defines the data that you should provide as a parameter
o
to the web services.
contentType. This parameter defines the HTTP content type that you should
o
use, when you submit HTTP requests to web services.
success. This parameter defines the name of the function, which will be
o
triggered when the call completes successfully.
failure. This parameter defines the name of the function, which will be
o
triggered when the call completes with errors.

When calls to the web services complete, jQuery triggers one of two callback
functions based on the success of the call.

Additional Reading: For more information about the AJAX function, go to


http://go.microsoft.com/fwlink/?LinkID=288984&clcid=0x413

Question: Why should you call web services by using jQuery?

Introduction to jQueryUI
jQuery simplifies interacting with JavaScript elements, by providing a simple
query-based syntax. jQuery UI is a library that includes widgets, animations,
and themes that help you to build a rich user interface.

jQuery Widgets

You can add different types of widgets to your pages by using the following
jQuery functions:

o Accordion. This function adds accordion containers to your webpage.


Autocomplete. This function adds auto-
o
complete boxes that are based on user input.
o Button. This function adds buttons to your webpage.
o Datepicker. This function adds date-pickers to your webpage.
o Dialog. This function adds dialog boxes to your webpage.
o Menu. This function adds a menu to your webpage.
Progressbar. This function adds animated and static progress bars to your
o
webpage.
o Slider. This function adds sliders to your webpage.
o Spinner. This function adds a number spinner to a data entry box.
o Tabs. This function adds tabs to your webpage.
o Tooltip. This function displays a tooltip for interface elements.

jQuery Effects

You can add various effects by using the following jQuery functions:

o Color Animation. This function animates colors.


Toggle Class, Add Class, Remove Class, and Switch Class. This function
o
adds or removes CSS classes.
Effect. This function adds a variety of effects, such as appear, slide-down,
o
explode, and fade-in.
o Toggle. This function toggles any jQuery effect on and off.
o Hide and Show. This function displays or hides any jQuery effect.

jQuery Utility
You can align your webpage content by using the Position jQuery utility. This
utility helps align an element in relation to the position of another element.

To use jQuery UI:

Download the script and supporting files from


1.
http://go.microsoft.com/fwlink/?LinkID=288985&clcid=0x414
2. Reference the JavaScript libraries in the HTML files.

The following line of code shows how to use jQuery UI.

Linking to jQuery UI

<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-

ui.min.js"

type="text/javascript"></script>

Question: What is the key difference between jQuery and jQuery UI?

Module 11: Controlling Access to ASP.NET


MVC 4 Web Applications

Module Overview
Authentication is a vital requirement in most web-based applications.
Developers usually display only restricted information to all users. Web
applications require users to authenticate themselves to view exclusive
information. Web applications also display specific information that is
relevant to specific user roles. Microsoft ASP.NET 4.5 includes various
authentication models, including local authentication providers, claim-based
authentication systems, and federated authentication systems. You need to
know how to use these authentication models to implement authentication
functionality in your web application. You should also know how to authorize
users and roles in your application to restrict information access according to
user and role membership.
Objectives

After completing this module, you will be able to:

o Implement authentication and authorization systems in your web application.


o Manage users and roles in your web application.
o Authorize users and roles in your web application.

Lesson 1 : Implementing Authentication and


Authorization
Membership providers, which were introduced in ASP.NET 2.0, help you to
create secure authentication and authorizations systems for web applications.
You need to know how to use the membership provider model in ASP.NET
4.5, to change authentication methods with minimum changes to the code.
You can use claim-based authentication and federated authentication to allow
external users to authenticate themselves, and access and use the web
application. You should know how to configure restrictions in the web
application to ensure that users access only specific information that is
permitted and relevant to them.

Lesson Objectives
After completing this lesson, you will be able to:

List the local authentication options available for an ASP.NET 4 web


o
application.
o Describe how client-based authentication works.
o Describe how federated authentication works.
o Describe how to restrict access to resources.
Authorize access to specific users to MVC 4 web application controller
o
actions.

Local Authentication Providers


Authentication providers include code that runs when ASP.NET needs to
authorize a user. The code authenticates users by using the information stored
in back-end databases, such as Active Directory or Microsoft SQL Server.
The membership system in ASP.NET 4.5 includes the following
authentication providers:

ActiveDirectoryMembershipProvider, SqlMembershipProvider,
SimpleMembershipProvider, and UniversalProviders. The
SimpleMembershipProvider and

UniversalProviders are new authentication providers that support the OAuth


authentication mechanism.

The ASP.NET 4.5 membership system allows application developers to


switch amongst authentication providers, without modifying the code.

The following is a description of the authentication providers—


ActiveDirectoryMembershipProvider and SqlMembershipProvider:

ActiveDirectoryMembershipProvider. This provider class is defined in the


System.Web.Security namespace, and the provider enables you to use
o
Active Directory as the membership and role repository of your web
application.
SqlMembershipProvider. This provider class is defined in the
o System.Web.Security namespace. The provider works with a specific table
schema that you can generate by using the aspnet_regdb.exe command.
ActiveDirectoryMembershipProvider and SqlMembershipProvider are
configured to work only with a specific table schema or directory. To
overcome this restriction, Microsoft developed SimpleMembershipProvider
and UniversalProviders to replace ActiveDirectoryMembershipProvider
and SqlMembershipProvider.

SimpleMembershipProvider. This is a new generation of membership


providers that works with the SQL Server, SQL Server Compact Edition,
Windows Azure SQL Database, and other versions of SQL Server.
o
SimpleMembershipProvider requires only three key parameters—table
name, user ID, and user name. You use this provider to implement
authentication that works with any SQL Server database table schema.
UniversalProviders. This is a set of membership providers that works with
any database that Entity Framework supports. However, these providers
o work only with the database schema designed by Microsoft. While
initializing a universal provider, if the schema does not exist in the database,
the provider generates the schema.

Question: What is the benefit of using SimpleMembershipProvider?

Claims-Based Authentication

Claims-based authentication is a model that facilitates single sign-on. Single


sign-on is a feature that allows you to receive a claim when you log on to a
centralized authentication system.
The claim is a ticket that authentication systems use to authenticate user
logons. The claim contains user identity information that helps authentication
systems identify users. With claims-based authentication systems, you can
focus efforts on developing business functions, rather than worrying about
authenticating users.

Claims-based authentication facilitates:

o Authenticating users to access applications.


o Storing user account information and passwords.
o Checking enterprise directories for user information.
Integrating the application with the identity systems of other platforms or
o
companies.

To implement claims-based authentication in your web application, you need


to use Windows Identity Foundation (WIF) 4.5. WIF 4.5.is a set of .NET
Framework classes that helps read information from the claims in a web
application.

The following steps describe the functioning of claims-based authentication


systems:

When an unauthenticated user requests a webpage, the request is redirected


1.
to the Identity Provider (IP) pages.
The IP requires you to enter credentials such as the user name and
2.
password.
After you enter the credentials, the IP issues a token. Then, the token is
3.
returned to the web browser.
The web browser is redirected to the webpage that you originally requested.
WIF determines if the token satisfies the requirements to access the
webpage. If the token satisfies all requirements, a cookie is issued to
4.
establish a session. This cookie ensures that the authentication process
occurs only once. Then, the authentication control is passed on to the
application.

Question: What are the benefits of using claims-based authentication?


Federated Authentication

Federations rely on claims-based authentication to allow external parties such


as trusted companies to access their applications.

Federations use the WS-Federations claim standard to enable the exchange of


claims between two parties in a standardized manner.

WIF provides support for federations by using the


WSFederationAuthenticationModule HTTP module.
WSFederationAuthenticationModule enables you to implement support for
federations in your ASP.NET 4.5 application, without implementing
individual logic.

Federated authentication enables Security Token Service (STS) to:

o Process the claims from business partners.


o Extract user information from the claims.

STS enables you to focus more on writing the business logic. It eliminates the
need to manage the authentication information of business partners, in your
web application.

Configuring the WSFederationAuthenticationModule helps specify the STS


to which non-authenticated requests should be redirected. WIF provides two
methods of federated authentication—FederatedPassiveSignIn and Passive
Redirect.

FederatedPassiveSignIn Control
Consider cases when unauthenticated users try to access protected resources
and you want to redirect these users to a logon page. For such cases, you can
embed the FederatedPassiveSignIn control in the logon page of your web
application, to redirect unauthenticated users to the logon page. The
FederatedPassiveSignIn control is configured with issuer (STS) information.

You can use the FederatedPassiveSignIn control to:

o Exclude application-wide protection.


o Include a logon page with clickable controls.

Passive Redirect

Consider cases when unauthenticated users try to access a protected resource,


and you want to redirect these users to an STS without using an application
logon page. For such cases, you can use passive redirect.

Passive redirect enables STS to:

o Verify the identity of the unauthenticated users.


o Issue security tokens that contain the appropriate claims for users.

Passive redirect requires you to add WSFederationAuthenticationModule in


the pipeline of the Hypertext Transfer Protocol (HTTP) modules, to identify
unauthenticated user requests and redirect users to the STS you specify.
Adding WSFederationAuthenticationModule in the HTTP pipeline
processes the claim information before passing the claim to the ASP.NET 4.5
engine.

You can instantiate WSFederationAuthenticationModule and use it to


trigger the sign-on process. This functionality is similar to that of the
FederatedPassiveSignIn control; however, passive redirect implements this
sign-on functionality with minimum coding effort.

Question: What are the benefits of using federated authentication?

Restricting Access to Resources


You can restrict user access by implementing the Authorize attribute in a
controller, instead of using the Web.config file as you would use in an
ASP.NET WebForms application. The Web.config file requires physical files
to exist, for access control to work. You cannot use the Web.config file to
restrict user access because MVC applications route requests to actions, not
pages.

The following code shows how to add the Authorize attribute to your
controller class.

Authorizing Action Methods

[Authorize()]

public ActionResult GetEmployee()

return View();

Observe the Authorize attribute in the code sample. If you specify this
attribute, ASP.NET 4.5 mandates that users should be authorized to access the
view returned by the code sample.

If you add the Authorize attribute at the class level, the attribute requires
users to log on before they can access anything in the controller class. To
allow anonymous users to access a specific portion of your class, you can use
the AllowAnonymous attribute.

The following code shows how to use the AllowAnonymous attribute.

Using the AllowAnonymous Attribute

[AllowAnonymous()]

public ActionResult Register()

return View();

Question: Why should you use the Authorize attribute, instead of the
Web.config file to control authorization of pages in your ASP.NET MVC
application?

Lesson 2: Assigning Roles and Membership


Roles and memberships complement authentication features, to help you
control all modes of access in web applications. To define access levels for
different types of users, you need to know how to implement roles and users.
ASP.NET 4.5 provides role providers and membership providers to help you
assign roles and users. ASP.NET 4.5 also enables you to create custom role
providers and custom membership providers. These custom providers allow
you to store role and user information in data sources not supported by
ASP.NET 4.5, such as a FoxPro or Oracle database.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe role providers in ASP.NET 4.5.


o Describe how to add user accounts to roles.
o Describe how to build custom role providers.
o Describe membership services.
o Describe how to build custom membership providers.
o Add code to an MVC 4 web application to help users reset their password.

Role Providers in ASP.NET 4.5

Role providers help develop applications by using a role-based security


model. Similar to membership providers, two types of role providers are
available in ASP.NET 4.5—ActiveDirectoryRoleProvider and
SqlRoleProvider:

ActiveDirectoryRoleProvider. This provider class is defined in the


o System.Web.Security namespace, and the provider enables you to use
Active Directory as the management model for roles.
SqlRoleProvider. This provider class is defined in the System.Web.Security
namespace. The provider works with only a specific table schema in
o
Microsoft SQL Server. You can generate this schema by using the
aspnet_regdb.exe command.
WindowsTokenRoleProvider. This provider uses the Windows authentication
token to determine the role of users. Then, the provider checks if users
o belong to any group stored in the Windows authentication token that was
generated when they first logged on. The format of the group name is
Domain\Group.

ActiveDirectoryRoleProvider and SqlRoleProvider have restrictions such


as lack of support for non-SQL databases or developer-defined schema.
Therefore, Microsoft developed SimpleRoleProvider and
UniversalProviders to replace ActiveDirectoryRoleProvider and
SqlRoleProvider. The following list describes the SimpleRoleProvider and
UniversalProviders:

SimpleRoleProvider. This is a new generation of role provider that works with


SQL Server, SQL Compact Editions, and others versions of SQL Server.
o
SimpleRoleProvider enables you to implement authorization based on the
table defined by application developers.
UniversalProviders. This is a database agnostic version that works with any
database that Entity Framework supports. However, the database schema is
o
determined by Microsoft. The provider usually generates tables during
initialization.

You can choose a role provider based on the membership provider that you
select. You can also mix role providers; for example, you can combine
SimpleMembershipProvider and UniversalRoleProvider. However, you
should avoid mixing role providers because the manner in which each
provider identifies users is different.

Question: What is the difference between SimpleRoleProvider and


SqlRoleProvider?

Adding User Accounts to Roles

When you use a database-based role provider, such as SimpleRoleProvider


or UniversalRoleProvider, you can load the initial data onto the database by
directly editing the table. You can also edit the table by using the
AddUsersToRoles function. To use the AddUsersToRoles function, you
need to implement the custom management tool in your application. The
custom management tool helps call the AddUsersToRoles function, to add
roles to a database.

The following code shows how to use the

AddUsersToRoles function.

Using the AddUsersToRoles Function

AddUserToRoles("Peter", new string[] {"Admin","Staff"})

You can also use the AddUsersToRoles function in business applications to


add users to a role. However, you must ensure that the role to which you want
to add users exists, before using the AddUsersToRoles function. ASP.NET
4.0 and all previous versions of ASP.NET include the Website Administration
Tool (WSAT). Unfortunately, WSAT does not work with the
SimpleRoleProvider.

Question: Why should we not use WSAT while using SimpleRoleProvider?

Building a Custom Roles Provider

ASP.NET 4.5 allows you to build custom role providers. Custom role
providers enable you to implement role management that uses your own
database schema and logic. To build a custom role provider, you need to
create a class that inherits the RoleProvider class.
The following code shows how to build a custom role provider.

Creating a Custom Role Provider

public class CustomRoleProvider :

RoleProvider

In the RoleProvider class, you need to implement the GetRolesForUser


function. The GetRolesForUser function takes the user name as the input and
returns a list of roles to which the user belongs. You can write your own code
to obtain role information from the database or other back-end stores.

The following code shows how to use the GetRolesForUser method.

Implementing the GetRolesForUser Function

public override string[] GetRolesForUser(string username)

//code to return a list of roles for users

After implementing the GetRolesForUser function, you need to apply the


custom role provider to the application by modifying the Web.config file.

The following code shows how to apply the custom role provider to the
application.

Configuring a Site to Use a Custom Role Provider

<roleManager defaultProvider="CustomRoleProvider" enabled="true"

cacheRolesInCookie="false">
<providers>

<clear />

<add name="CustomRoleProvider" type="CustomRoleProvider” />

</providers>

</roleManager>

Question: Why should you create a custom role provider?

Providing Membership Services

You need to add the

SimpleMembershipProvider to the membership section of the Web.config


file to use it for membership services.

The following code shows how to add SimpleMembershipProvider to the


Web.config file.

Configuring the Simple Membership Provider

<membership

defaultProvider="SimpleMembershipProvider"

>
<providers>

<clear/>

<add name="SimpleMembershipProvider"

type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"

/>

</providers>

</membership>

Next, you need to create a User table. If you do not have a User table created
already, you can modify the AccountModel.cs file, to generate the table. To
view the AccountModel.cs file, you should select the Internet Application
template, when you create the project.

In the following code sample, the UserProfile class from AccountModel.cs


has been modified to add an additional property, Country.

Creating a User Table

[Table("UserProfile")]

public class UserProfile

[Key]

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

public int UserId { get; set; }

public string UserName { get; set; }

public string Country { get; set; }


}

After modifying the AccountModel.cs file, you need to call the


WebSecurity.InitializeDatabaseConnection function in the App.Start.cs
file. The WebSecurity.InitializeDatabaseConnection function ensures that
SimpleMembershipProvider is configured with connection strings to the
database.

The following code shows how the membership provider connects to the User
table, by using the DBConn connection string.

Connecting to the User Table

WebSecurity.InitializeDatabaseConnection(“DBConn”,”User”,”id”,”Usernam

e”,false)

If a specific table does not exist in a database, the autoCreateTables


parameter helps indicate to the membership provider that it may create the
table. To initialize SimpleMembershipProvider, you need to add the
InitializeSimpleMembership attribute to the AccountController class.

The following code shows how to add the InitializeSimpleMembership


attribute to the AccountController class.

Adding the InitializeSimpleMembership Attribute

[Authorize]

[InitializeSimpleMembership]

public class AccountController : Controller

Question: Why should we use the InitializeDatabaseConnection method?

Building a Custom Membership Provider


If you need to add functionality to a membership provider, such as custom
logic for authentication, you need to implement a custom membership
provider.

The following code shows how to implement a custom membership provider.

A Custom Membership Provider

public class CustomMembershipProvider :

SimpleMembershipProvider

After implementing the custom membership provider, you override the


ValidateUser method defined in SimpleMembershipProvider. The
following code shows how to override the ValidateUser method defined in
SimpleMembershipProvider.

Overriding the ValidateUser Method

public override bool ValidateUser(string username, string password)

}
In the preceding code sample, the ValidateUser method validates the user
name and password against the membership store.

Perhaps, you want to add logic to get the decryption key for passwords. To
add this logic, you can override the Provider constructor, when the custom
membership provider is initializing. Overriding the Provider constructor
initializes the encryption engine.

Overriding the Provider Constructor

public CustomAdminMembershipProvider(SimpleSecurityContext

simpleSecurityContext)

After adding logic to the custom membership provider, you need to modify
the Web.config file to apply the custom provider class to the application.

Adding a Custom Provider to Web.config

<membership defaultProvider="CustomMemberProvider">

<providers>

<clear/>

<add name="CustomMemberProvider" type="

CustomAdminMembershipProvider " />

</providers>

</membership>
Question: Why should you implement a custom membership provider?
Module 12: Building a Resilient ASP.NET
MVC 4 Web Application

Module Overview
Security is always the top priority for web applications, because publicly
accessible web applications are usually the targets of different types of web
attacks. Hackers use web attacks to access sensitive information. To help
prevent these attacks, you need to know how to use AntiXSS and request
validation for your web application. Using various security mechanisms, you
can build a secure web application. Another problem that developers usually
face is the need to retain information amongst multiple postbacks. You need
to know how to use state management techniques to retain information for
multiple HTTP requests. Using state management, you can help reduce the
need for users to re-enter information every time they need to place a request.

Objectives

After completing this module, you will be able to:

o Develop secure sites.


o Implement state management.

Lesson 1 : Developing Secure Sites


Web applications are often subject to security attacks. These attacks prevent
the applications from functioning properly, and the attackers try to access
sensitive information stored in the underlying data store. ASP.NET provides
built-in protection mechanisms that help prevent such attacks. However, such
mechanisms also tend to affect the operation of your applications. You should
know when to enable or disable the protection mechanisms to avoid any
impact on the functionalities of your application. You also need to know how
to use Secure Sockets Layer (SSL) to prevent unauthorized access to
information during information transmission.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe how to avoid malicious attacks that use cross-site scripting.


o Describe the common attack techniques used by malicious users.
o Describe how to disable attack protection in your MVC application.
o Decide whether to disable attack protection in various scenarios.
Describe the role of Secure Sockets Layer in helping secure web
o
applications.

Cross-Site Scripting

Cross-site scripting involves the malicious insertion of scripts in a user


session. Cross-site scripting poses information to other websites, by using the
authentication information of users, without their knowledge. For example,
consider the code inserted into a web application to maliciously post messages
on social networking websites, without the knowledge of the users.

When a script is inserted into a web application, the script has full access to
the Document Object Model (DOM) of the HTML. This access allows the
attacker to create fake input boxes in the

application, create fake users, and post fake information on the web
application.

The cross-site scripting attack usually takes input from improperly escaped
output. These scripting attacks usually impact query strings. For example,
consider the following URL:
http://localhost/Default1/?msg=Hello

The following code shows how to access the msg querystring parameter from
a controller action.

Accessing a Query String Parameter

public ActionResult Index(string msg)

ViewBag.Msg = msg;

return View();

The following code shows how to display the value of the querystring
parameter in a view.

Displaying the Query String Parameter

<div class="messages">@ViewBag.Msg<div>

After running the preceding code samples, the application should display the
resultant word, Hello. Now, consider a scenario where the query string
parameter msg is changed to a less benign value resulting in the following
URL:

http://localhost/Default1/?msg=<script>alert('pwnd')</script>

As a result, the script block included in the query string is displayed to users.
In such cases, attackers can inject malicious code into your app by using the
value of a query string parameter.

ASP.NET includes request validation, to help protect the input values that are
subject to cross-site scripting attacks. However, attackers can bypass this
mechanism by using encoding to subvert common cross-site scripting filters.
For example, here is the same query string, this time encoded:
http://localhost/Default1/?msg=Jon\x3cscript\x3e%20alert(\x27pwnd\x27)%2
0\x3c/script\x3e

You can modify the view class to use the @Ajax.JavaScriptStringEncode


function to help prevent cross-site scripting attacks, instead of directly using
the input from query strings. The following line of code shows how to use the
@Ajax.JavaScriptStringEncode function.

Using the JavaScriptStringEncode Function

<div class="messages">@Ajax.JavaScriptStringEncode(ViewBag.Msg)<div>

You can also import the AntiXSS library to check the query string content for
possible attacks. The AntiXSS library is part of the Web Protection Library,
which was developed by Microsoft to detect more complex web attacks than
those that the request validation of ASP.NET can detect.

Additional Reading: To view more information on the AntiXSS library, go


to http://go.microsoft.com/fwlink/?LinkID=293690&clcid=0x409

After importing the AntiXSS library in your MVC application, you can use
the library to encode any output content in HTML.

The following code shows how to use the AntiXSS library.

Using the AntiXSS Library

@using Microsoft.Security.Application

<div class="messages">@Encoder.JavaScriptEncode(ViewBag.Msg)<div>

The code in the preceding sample illustrates how to encode input values by
using the JavaScriptEncode method of the AntiXSS library, when displaying
output in HTML. This practice ensures that the input values are safe for
display.

Question: What causes cross-site scripting attacks?

Other Attack Techniques


In addition to cross-site scripting attacks, hackers can use other types of
attacks, including cross-site request forgery and SQL injection attacks to
subvert web applications.

Cross-Site Request Forgery

Cross-site request forgery (CSRF) is an attack that occurs when you open a
URL in a web browser, by using your user context, without knowing that you
are allowing attackers to make changes to your system. For example, consider
that your application uses query strings to pass information

to other applications. You receive an email message with a link such as the
following:

<a href="http://localhost/Default1/?id=100">Click Me</a>

When you click the link, the action associated with the view runs on your web
browser. Because, you are an authenticated user in the application, the
attacker can now access your system.

You can prevent CSRF by using the following rules:

Ensure that a GET request does not replay by clicking a link. The HTTP
1. specifications for GET requests imply that GET requests should be used
only for retrieval and not for state modifications.
Ensure that a request does not replay if an attacker uses JavaScript to
2.
simulate a form POST request.
Prevent any data modifications that use the GET request. These
3.
modifications should require some user interaction. This practice of
introducing user interaction does not help prevent form-based attacks.
However, user interaction limits several types of easier attacks, such as
malicious links embedded in XSS-compromised sites.

The @Html.AntiForgeryToken() function helps protect your system from


CSRF by using unique tokens that are passed to the application along with
requests. The @Html.AntiForgeryToken() function uses not only a hidden
form field but also a cookie value, making it more difficult to forge a request.

The following code shows how to use the @Html.AntiForgeryToken()


function in a view.

Using an Anti-Forgery Token

@using (Html.BeginForm())

@Html.AntiForgeryToken();

@Html.EditorForModel();

<input type="submit" value="Submit" />

The following code shows how to force Anti-Forgery token checking in a


controller by using the ValidateAntiForgeryToken attribute.

Forcing Anti-Forgery Token Checking

[HttpPost]

[ValidateAntiForgeryToken()]

public ActionResult Index(User user)

{
Return View();

Note the ValidateAntiForgeryToken() attribute in the preceding code


sample. This attribute enables the controller to check if the user input from the
HTML form includes the token generated by the
@Html.AntiForgeryToken(), before accepting a request.

SQL Injection Attack

SQL injection attacks are similar to cross-site scripting attacks. However, the
difference is that the user input is used to create dynamic SQL, instead of
HTML. Observe the following line of code.

cmd.CommandText = "select userID from Users where userID = '" +

Request.QueryString["user"] + "'";

Consider a scenario where an attacker modifies the query string as displayed


in the following line of code.

user=1' AND 1=1 GO SELECT * from Users WHERE NOT 0='

The following line of code denotes the resultant SQL.

select userID from Users where userID = '1' AND 1=1 GO SELECT * from

Users WHERE NOT

0=''

In this case, SQL returns everything from the Users table.

To prevent SQL injection attacks, you should:

1. Validate user input.


2. Avoid using string concatenations to create dynamic SQL.
3. Use parameterized commands with dynamic SQL.
4. Store all sensitive and confidential information in encrypted formats.
Ensure that the application does not use or access the database with
5.
administrator privileges.

Question: What is the best way to prevent SQL injection attacks if you cannot
avoid dynamic SQL?

Disabling Attack Protection

Request validation is an ASP.NET feature that examines an HTTP request and


determines if it contains potentially dangerous content.

Potentially dangerous content can include any HTML markup or JavaScript


code in the body, header, query string, or cookies of the request.

However, request validation can also cause the application to function


improperly by preventing some input from entering the application page for
processing. Consider a situation in which your application uses an HTML
editor to generate HTML code for user input, before saving the input

on the database. In this case, you may want to disable the request validation to
allow the HTML editor to function properly.

You can choose to disable request validation at different levels, such as, in the
Web.config file, on a webpage, or in a specific HTML element.

The following code shows how to disable request validation for your
application in the Web.config file.

Disabling Request Validation


<system.web>

<httpRuntime requestValidationMode="2.0" />

</system.web>

The following code shows how to add the ValidateInput(false) attribute to


the controller, to disable request validation for an action in a controller.

Using the ValidateInput Attribute

[HttpPost]

[ValidateInput(false)]

public ActionResult Edit(string comment)

return View(comment);

The following code shows how to add the AllowHtml attribute to the Prop1
property of the model, to disable request validation for this property

Using the AllowHtml Attribute

[AllowHtml]

public string Prop1 { get; set; }

You should consider using attack protection techniques that:

o Have a minimum impact on the application.


Involve minimum fields to accept HTML elements in the request
o
validations.
Question: Describe a scenario when you would want to disable request
validation?

Secure Sockets Layer

Secure Sockets Layer (SSL) is an application layer protocol that helps:

o Encrypt content by using the public key infrastructure (PKI) keys.


o Protect the content that is transmitted between the server and client.
o Prevent unauthorized access of content during transmission.
o Reassure users that a site is genuine and certified.

You can use SSL on views that accept user input if the input includes sensitive
information, such as credit card information and passwords. Using SSL on
such crucial views ensures the confidentiality of the content and the
authenticity of the sender. However, you may not be able to analyze your code
and easily detect if a user accesses the web application by using SSL.

ASP.NET MVC 4 includes the RequireHttps attribute that enables you to use
SSL on the views that involve sensitive information. The RequireHttps
attribute redirects users to the SSL link, if they request a view by using normal
HTTP.

The following code shows how to add the RequireHttps attribute in your
controller class and action methods to require a user to use the SSL protocol.

Using the RequireHttps Attribute

[RequireHttps]
public class Controller1

[RequireHttps]

public ActionResult Edit()

You can use the RequireHttps attribute at the controller level or action level.
This flexibility allows you to choose SSL when required in your web
application.

Note that web servers require you to configure the PKI certificate so that the
server accepts SSL connections. SSL certificates need to be purchased from a
certificate authority (CA). During application development, you can use the
self-sign certificate to simplify the configuration process.

Question: What action is required to be performed on the web server, before


implementing SSL?

Lesson 2: State Management


While developing applications, you may want to create functions that require
information to be retained across requests. For example, consider an
application in which you need to first select a customer and then work on the
order relevant to the customer. HTTP is a stateless protocol. Therefore,
ASP.NET includes different state management techniques to help store
information for multiple HTTP requests. You need to know how to configure
and scale state storage mechanisms to support web server farms.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe the benefits of storing state information.


o List the options for storing state information.
o Configure state storage.
o Describe the scalability of state storage mechanisms.
o Store and retrieve state information in an MVC 4 web application.

Why Store State Information?

HTTP is a stateless protocol that does not relate submitted requests to each
other. HTTP treats each request as a new request. However, this independence
among the requests affects business applications that have information
dependencies amongst functions. For example, consider that you can access
the Update Address function only after you provide the user logon
information. The page that handles the User Logon function is different from
the page that handles the Update Address function. Therefore, these functions
require two separate HTTP

requests. With the default HTTP implementation, the server may lose the
result of the logon request, when a user accesses the Update Address page.
ASP.NET implements the session management technology to retain
dependent information for multiple HTTP requests.

Session management enables web applications to store values for multiple


HTTP requests, regardless of whether the request is directed to the same page
or multiple pages. The session management process involves two
techniques—server-side techniques and client-side techniques, to retain user
information pertinent to multiple HTTP requests.

Client-Side Session Management

Client-side session management technologies include:

o Hidden fields
o Cookies
o Query strings

Client-side session management technologies help retain dependent


information when a user triggers the HTTP POST action by clicking a button
on a webpage. Then, when a page is rendered, the server generates the
dependent information.

Note: If you are familiar with ASP.NET Web Forms, you may have used
View State and Control State as client-side state storage. These techniques are
not available in MVC because they rely on Web Forms server controls.

Server-Side Session Management

Server-side options provide higher security for storing page information than
the client-side options because information retained by using client-side
options is not visible to the client system. However, server-side options
require more web server resources such as memory for storing data. This
additional usage of resources can lead to scalability issues if the size of the
information to be stored is large.

ASP.NET provides the following server-side session management options:

o Application state
o Session state
o TempData
o Profile properties
o Database support
Additional Reading: For more information about ASP.NET state
management recommendations, go to
http://go.microsoft.com/fwlink/?LinkID=288986&clcid=0x415

Question: Why do you need to implement session management?

State Storage Options

You can store values for requests, and the subsequent requests related to the
previous requests, by using the TempData object. By default, the TempData
object uses the Session variable to store information relevant to requests.

You can use the TempData object to access session information, instead of
using the Session variable. The TempData object includes logic to handle
redirection of information to different views.

You can use the sessionState element in the Web.config file, to define the
repository that

should retain the session state information. You can also use the sessionState
element to turn off session-state support. The following list describes some of
the commonly used session state storage options:

o The InProc mode. Stores the session in the ASP.NET process.


The StateServer mode. Stores session information in dedicated services
o running on the web server or on a dedicated server. It does not store
information on Internet Information Services (IIS).
The SQLServer mode. Stores the session information in a SQL Server
o
database.
o The Off mode. Deactivates the session state support in your application.

Question: Consider that you have a web server that contains multiple web
servers. You want to allow users to access the same state information for all
the web servers they access. In this case, which state storage mode should you
used?

Configuring State Storage

You can configure state storage to use the StateServer and SQLServer modes.

The StateServer Mode

You need to run the ASP.NET state service on the server used for storing
session information, before using the StateServer mode. The ASP.NET state
service is installed as a service when ASP.NET and the .NET Framework are
installed as part of Microsoft .NET Framework. The ASP.NET service is
installed at the following location:

systemroot \Microsoft.NET\Framework\ versionNum

ber \aspnet_state.exe

To configure an ASP.NET application for using the StateServer mode, you


should perform the following steps:

In the Web.config file of the application, set the mode attribute of the
o
sessionState element to StateServer.
o In the Web.config file of the application, set the stateConnectionString
attribute to tcpip=<serverName>:42424.

To configure StateServer support in your application, you should perform the


following steps:

1. Run the services.msc file.


Set the ASP.NET state service Startup Type attribute to automatic, and
2.
right-click the service.
Open the Web.config file, identify the sessionState element, and then
3.
update the code.

Consider that a session state is stored on the SampleStateServer remote


computer. The following code shows how to configure the StateServer mode.

Configuring the State Server Mode

<configuration>

<system.web>

<sessionState mode="StateServer"

stateConnectionString="tcpip=SampleStateServer:42424"

cookieless="false"

timeout="20"/>

</system.web>

</configuration>

Note: The objects stored in session state must be serializable, if the mode is
set to StateServer or SQLServer.

The SQLServer Mode

Before using the SQLServer mode, you need to install the ASP.NET session
state database on the SQL Server.. You can install the ASP.NET session state
database by using the aspnet_regsql.exe tool. To configure an ASP.NET
application for using the SQLServer mode, you should perform the following
steps:

In the Web.config file of the application, set the mode attribute of the
o
sessionState element to SQLServer.
In the Web.config file of the application, set the sqlConnectionString
o
attribute to a connection string for your SQL Server database.

To create the session state database on SQL Server, you should perform the
following steps:

1. Open the command prompt with administrative privileges.


From the <systemroot\Microsoft.NET\Framework\versionNumber> folder
2.
on your web server, run the Aspnet_regsql.exe tool.
Open the Web.config file, identify the sessionState element, and then
3.
update the code.

Consider that a session state is stored on the SampleSqlServer SQL Server.


The following code shows how to configure the SQLServer mode.

Configuring SQL Server Session State Storage

<configuration>

<system.web>

<sessionState mode="SQLServer"

sqlConnectionString="Integrated Security=SSPI;data

source=SampleSqlServer;" />

</system.web>

</configuration>
You can customize the behavior of the aspnet_regsql.exe tool by using
switches such as -E, -S, and -d. You can use these switches to change the
name of the default ASPState database.

Additional Reading: For more information about the aspnet_regsql.exe tool,


go to: http://go.microsoft.com/fwlink/?LinkID=293693&clcid=0x409

Question: Which tool should you install before using the SQLServer mode?

Scaling State Storage Mechanisms

The StateServer and SQLServer modes help access the state storage on a web
server. These modes allow multiple servers to access state storage
information. This process distributes the web workload among multiple web
servers.

You can implement partitioning of session state to allow multiple state servers
or multiple SQL Server databases to handle session state information. You can
apply the logic for partitioning, by implementing the IPartitionResolver
interface in your application. You need to configure the Web.config file to
control the session

management engine. Configuring the session management engine helps you


use the logic to identify the appropriate web server on which you can store
information.

The following code shows how to configure the Web.config file, to enable the
IPartitionResolver interface.
Using the IPartitionResolver Interface

<configuration>

<system.web>

<sessionState

mode="SQLServer"

partitionResolverType=

"PartitionResolverClass" />

</system.web>

</configuration>

You can use the IPartitionResolver interface only when the session state uses
the SQLServer or StateServer modes. In the preceding code sample, note that
no connection string is specified by using the sqlConnectionString or
stateConnectionString attributes.

Additional Reading: For more details about implementing state partitioning,


go to: http://go.microsoft.com/fwlink/?LinkID=288988&clcid=0x417

Question: When should you implement the IPartitionResolver interface?

Module Review and Takeaways


Web applications are usually subject to different kinds of attacks. These
attacks enable attackers to access sensitive information stored in the database
and to perform malicious actions. You can use AntiXSS and request
validation, to protect the applications from web attacks. You can also use state
management techniques to store information for multiple HTTP requests to
help avoid users from typing the same information more than once.

Review Question(s)
Question: Recently, an error occurred in one of applications that you had
developed for your company. After performing few tests, you realize that the
issue was due to an HTML code that was passed from the user to the server.
You want to prevent such issues in the future. What would you consider to
do?

Real-world Issues and Scenarios

While implementing web applications, you may want to use a rich format
input editor, to enable users to format the input within text boxes. Therefore,
you may need to disable request validation, to enable ASP.NET to capture and
process user input.

Complex business functions usually involve multiple views. Such functions


can pose problems because information must be shared across multiple views.
Session state management helps resolve these problems, because it enables
retaining information pertinent to multiple views.

Module 13: Using Windows Azure Web


Services in ASP.NET MVC 4 Web
Applications
Module Overview
Developers often place all application logic in the application code. While this
practice works for small-scale applications, it may not work for applications
with a large number of users. An alternate approach is to make the code
modular, by modifying the applications to use web services.

Windows Azure is a cloud-based platform that enables you to host web


applications and services. You can use Windows Azure to make your web
application more scalable and manageable. To effectively use Windows
Azure, you need to know how to write a web service. You also need to know
how to call a web service from a web application or from other applications,
such as a mobile device application.

Objectives
After completing this module, you will be able to:

o Describe Windows Azure.


o Design Windows Azure services.
o Call Windows Azure services from a web application.

Lesson 1 : Introducing Windows Azure


Windows Azure is a Microsoft platform that helps meet specific needs of
hosting web applications, such as creating scalable and highly available web
applications. Windows Azure enables you to host services, applications, and
databases. Windows Azure also helps you create cost-effective and secure
web offerings that suit businesses of various types and sizes. You need to
know how to host applications, services, and databases on Windows Azure to
increase the scalability, flexibility, and availability of your web offerings.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe Windows Azure.


o Describe the hosting services available in Windows Azure.
o Explain how to host web applications in Windows Azure.
Describe the data storage options offered by Azure Storage and Windows
o
Azure SQL Database.
o Determine when to use Windows Azure.

What Is Windows Azure?


The Windows Azure application platform provides comprehensive services to
host applications, files, media, and databases. Windows Azure is a flexible
platform that supports businesses of various sizes, helps reduce the effort to
develop scalable web applications, and decreases development costs.

Microsoft hosts Windows Azure in multiple data centers, across the United
States, Europe, and Asia.

Windows Azure provides the following categories of services:

Execution Models. Provides three different

o execution models—virtual machines

(VMs), web applications, and cloud services, for running applications


Windows Azure Identity Management. Includes Windows Azure Active
o Directory and Access Control services to help manage identities,
authentication, and authorization in a web application.
Data Management. Includes services to host and manage relational database
o
and Blob content
Business Analytics Solutions. Includes services that helps perform business
information analysis by using SQL Server Reporting Services and Apache
o
Hadoop. Business analytics solutions support all the data stores distributed
across multiple Windows Azure data centers.
Networking Services. Includes services that provide networking capabilities
o
to securely connect multiple services in Microsoft data centers.
Messaging with Service Bus. Includes services that enable applications to
o
communicate on Windows Azure.
Media Management. Includes services that bring content geographically
closer to users and help store large volumes of content outside the web
o
application. Storing content outside the application helps improve the
performance of the application.

Question: What are the benefits of hosting applications on Windows Azure?

Benefits of Hosting Services in Windows Azure


Windows Azure enables you to configure application logic to run as services.
Services denote a portion of the application code, which performs specific
business logic based on user inputs, such as retrieving product pricing
information. These services usually do not require:

o Administrator access to Windows.


o Complete access to the user interface of Windows.
Access to other functionalities that allow interacting with users, which VMs
o
facilitate.

Windows Azure cloud services do not use a dedicated VM. However,


Windows Azure cloud services use a role-based model that relies on the VM
to host applications. The role-based model includes a web role and a worker
role. Each role is a VM that is preconfigured to support automated
deployment and monitoring of applications.

While deploying these cloud services, you need not create the VM. You only
need to upload a configuration file to direct Windows Azure how to configure
the application. You need not upload this configuration file on the VM; you
can upload the file on to the staging environment. Then, the Windows Azure
management agent copies this configuration information to the production
servers.

Windows Azure cloud services do not retain state data in a role, because the
VM has no permanent storage. You can either use other services to retain state
data or design the application in a stateless manner.
Question: What are the benefits of using Windows Azure cloud services?

Benefits of Hosting Web Applications in Windows


Azure

Hosting web applications on Windows Azure is similar to hosting services,


because both cases use virtual machines. However, unlike services, web
applications provide full access to the IIS instance assigned to your
application. You can use a web application to host ASP.NET websites, static
content, open source applications, and other file-based web applications.

Hosting web applications in Windows Azure provides the following benefits:

It automates the process of deploying


o
applications to different hosting servers.
It simplifies the process of scaling up and down as your application usage
o
grows or contracts.

Question: What are the key benefits of using Windows Azure web
applications?

Windows Azure Storage Services


Windows Azure includes the following storage services:

Azure Storage. This is also known as BLOB (Binary Large Object) service.
You can use Azure storage to store objects or file content relevant to your
o
web applications. Each Blob includes a unique URL that allows applications
to directly access content in the Azure Storage.
SQL Database. This is a relational database service on the Windows Azure

platform. You can use SQL Database as

the database engine for storing application data in a web application hosted
in Azure or on any other Internet server. Other applications, such as desktop
o packages and mobile apps can connect to the same database over the
Internet. When you use SQL Database in Windows Azure, you:

Increase the availability and scalability of the data store and any

applications built on that data store.
▪ Reduce investments in hardware.

Question: What are the benefits of using Windows Azure SQL Database?

Discussion: Windows Azure Scenarios


Consider the following scenarios. In each case, discuss which Azure service
will best suit the scenario.

You are creating a photo sharing application, and you want to enable each user
to discuss the photos with their friends. You need to ensure that the photos in
1. your application do not occupy large disk storage in your web farm. Therefore,
you do not want to store the photos, which the users upload, in your application
database or server.
You are creating a Windows-based business
2.
application. This application requires a centralized database that users can
access by using the Internet.
You are writing business logic for your company, and both public and internal
3.
applications want to use this business logic.
You are creating an application that uses a third-party component. The third-
4.
party component requires full access to the Windows console.

Lesson 2: Designing and Writing Windows Azure


Services
Windows Azure cloud services provide a scalable hosting platform for web
applications. You can use Windows Azure cloud services to host Windows
Communication Foundation (WCF) services. Hosting such services helps
transfer key business logic from a web application onto a cloud platform. You
need to know about the life cycle of the Windows Azure services to add and
modify code during the different stages of application development. You also
need to know how to use diagnostic tools in Windows Azure, to identify the
problems that occur in your application

Lesson Objectives
After completing this lesson, you will be able to:

o Describe Windows Azure Visual Studio project templates.


o Write code to create a web service.
o Describe the life cycle of a web service.
o Deploy a web service.
o Debug a Windows Azure web service.

Windows Azure Visual Studio Project Templates

Microsoft Visual Studio provides project templates such as Windows Azure


project, web role project, and worker role project, which help create
applications and host them on Windows Azure.

Windows Azure Project

The Windows Azure project template facilitates role-based projects. This


template includes service definition and service configuration files.

Web Role Project

The web role project provides templates for the

following web roles:


o ASP.NET Web Forms
o ASP.NET MVC4
o ASP.NET MVC3
o ASP.NET MVC2
o WCF Service
o Silverlight Business Application

Worker Role Project

A worker role performs background processing by communicating with


storage services and other Internet-based services, without interacting with
end users. Worker role projects are ideal for long running services and other
modular business logic.

Question: Which project template should you use to create Windows


Communication Foundation (WCF) services?

Coding a Web Service

Modular programming plays an important role in developing applications,


because it enables you to re-use application code. Re-using services enables
cross-application sharing of business logic.

To create code for a web service, you need to perform the following steps:

Open Microsoft Visual Studio and create a Windows Azure WCF Service web
1.
role project.
2. Rename the IService1 interface that the template creates by default. You can
use the Visual Studio Refactor menu to rename the

interface and update references to it throughout the solution.


Modify the interface code to define the interface-level properties and methods.
The following code shows a simple service interface that defines a single
method. Note the [ServiceContract] and [OperationContract] annotations.

[ServiceContract]

public interface IMyServiceInterface

3.
{

[OperationContract]

string GetHelloWorld();

Rename the Service1 class that the template creates by default. Again, you can
4.
use the Refactor menu to help with this task.
Modify the service code to implement the methods required in the service
interface. The following code shows a simple service class that implements the
previous simple interface.

public class MyService : IMyServiceInterface

5. public string GetHelloWorld()

return "Hello Azure

}
Press F5 to test the services locally by using the Windows Azure emulator.
6. This practice ensures that the services function appropriately, before deploying
the services on Windows Azure.

Question: Why should you test the service code before deploying the service
on Windows Azure?

The Life Cycle of a Service

The RoleEntryPoint class defines the method that Windows Azure hosts call,
based on the development stage of the application. The RoleEntryPoint class
also helps define the functions that add logic to services. WCF services may
sometimes inherit the RoleEntryPoint class; however, worker roles services
mandatorily inherit the RoleEntryPoint class.

The RoleEntryPoint class helps define the following three life-cycle


methods:

OnStart. Windows Azure triggers this


o
method when the application starts.
o OnStop. Windows Azure triggers this method when the application stops.
o Run. Windows Azure triggers this method to start long running processes.

The OnStart and OnStop methods return a Boolean value to the Windows
Azure host, when a function completes running. If the OnStart and OnStop
methods returns false, Windows Azure stops the application from running.
You should ensure that the OnStart and OnStop methods always return true,
to ensure that your application continues running.
Windows Azure does not trigger the OnStop method if a process terminates
because of exceptions. Windows Azure treats all uncaught exceptions as
unhandled exceptions that cause processes to terminate.

While defining the RoleEntryPoint class, you must:

Call the Application_Start method after the RoleEntryPoint.OnStart


o
method finishes.
Call the Application_End method before calling the
o
RoleEntryPoint.OnStop method.

Question: When should you use the RoleEntryPoint class?

Deploying a Web Service

When you create an application project, the system creates two files—
ServiceDefinition.csdef and ServiceConfiguration.cscfg. These files control
the Windows Azure instance that helps run the application.

The following list describes the ServiceDefinition.csdef and


ServiceConfiguration.cscfg files:

o ServiceDefinition.csdef. It helps define roles for your application.


ServiceConfiguration.cscfg. It is a hosted

o file that helps configure the instance assigned for your application. For
example, you can use ServiceConfiguration.cscfg to configure the number of
instances for your application.
Two copies of ServiceConfiguration.cscfg are available, a cloud version and a
local version, which you can use to locally test the services before deploying
on Windows Azure. You can manually update the details in the
ServiceConfiguration.cscfg file by using the Windows Azure property
window.

Additional Reading: For more information about configuring a Windows


Azure project, go to:
http://go.microsoft.com/fwlink/?LinkID=288989&clcid=0x418

You can use the Package tool in Microsoft Visual Studio to generate the
service package:

In the Solution Explorer pane, right-click the web service project, and then
1.
click Package.
In the Service Configuration box of the Package Windows Azure
2. Application dialog box, ensure that Cloud is selected, and then, in the
Build Configuration box, click Release.
Click Package. Visual Studio creates the .cspkg file and the .cscfg file for
3.
the service and displays them in the File Explorer window

Then, you need to upload the services package to the staging environment of
the Windows Azure platform by using the management portal. Package files
have the .cspkg extension. When you upload the package, you also need to
upload the ServiceConfiguration.cscfg file. The ServiceConfiguration.cscfg
file directs Windows Azure on how to configure the hosting environment.

After uploading and deploying the package on the Windows Azure platform,
you can access the service by using a URL, for example:

http:// <guid>.cloudapp.net/<service file name>

Question: When should you use the ServiceConfiguration.cscfg file?

Debugging a Windows Azure Web Service


You can debug a Windows Azure application by using the following tools:

o Diagnostic log
o IntelliTrace
o Remote Desktop

Diagnostic Logs

To debug Windows Azure web services, you need to include the Diagnostic
module in the ServiceDefinition.csdef file. The Diagnostics module helps
access the Application

Programming Interface (API), to perform diagnosis.

The following code shows how to include the Diagnostic module in the
ServiceDefinition.csdef file.

Configuring the Diagnostic Modulec

<?xml version="1.0" encoding="utf-8"?>

<ServiceDefinition name="MyHostedService"

xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefi

nition">

<WebRole name="WebRole1">

<Imports>
<Import moduleName="Diagnostics" />

</Imports>

</WebRole>

</ServiceDefinition>

Running the code in the preceding sample displays diagnostic data.

Additional Reading: For more information about the data types that you can
configure your application to collect, go to:
http://go.microsoft.com/fwlink/?LinkID=288990&clcid=0x419

To enable your application to monitor additional information, you need to add


the following lines of code in the OnStart method of your application file.

Add Data Sources

var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

config.WindowsEventLog.DataSources.Add("System!*");

DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.Co

nnectionString",

config);

The lines of code in the preceding sample help:

Configure the Windows Azure service to capture the Windows Event log.
o
The Windows Azure engine generates this log when the service runs.
Save the Windows Event log to the log files that are stored in LocalStorage.
o You can access the log files by using the Windows Azure storage explorer
and download the files.
IntelliTrace

IntelliTrace is a feature in Windows Azure that enables you to:

o Access event log information.


Debug the application.

Note: The virtual machines in Windows Azure always run 64-bit operating
o
systems. If you have Visual Studio 2010 Ultimate installed on a machine
that runs a 32-bit operating system, you must install this Intellitrace hotfix.
This Intellitrace hotfix helps install the 64-bit IntelliTrace components.

Additional Reading: To install the Intellitrace hotfix, go to:


http://go.microsoft.com/fwlink/?LinkID=288991&clcid=0x420

You can enable IntelliTrace, while you deploy or package services. You can
also configure services to enable IntelliTrace for specific events. This
configuration helps capture detailed information such as Windows log and
system configurations.

The following image displays the IntelliTrace Settings dialog box.

FIGURE 13.1:THE INTELLITRACE SETTINGS DIALOG BOX

IntelliTrace also helps in problem diagnosis. You can simulate some problems
that you may encounter while running web services. Then, you can download
the IntelliTrace logs from Windows Azure by using the Server Explorer.
These logs can help you to access and understand the problems.
The following image displays the IntelliTrace tool in the Server Explorer.

FIGURE 13.2:INTELLITRACE LOGS

Remote Desktop

If you use Windows Azure Cloud Services, you can configure the application
to provide remote desktop access to an instance. This configuration provides
full access to Windows event logs.

You can enable remote desktop access when you publish your cloud service.
To do this, in the Visual Studio Publish wizard, on the Settings page, select
Enable Remote Desktop for all roles. Then, you specify the credentials that
a user should use to access the remote desktop console. All instances of your
application that run on Windows Azure will use these credentials.

After publishing the application on Windows Azure, you can access the
remote desktop by using the management portal.

Question: What is the difference between using diagnostic logs and


IntelliTrace?

Lesson 3: Consuming Windows Azure Services in


a Web Application
After completing the setup and deployment of the Windows Azure Services,
you need to add logic to your application to use the services from ASP.NET
MVC application and HTML code. You can call a Windows Azure web
service using server-side code or by using client-side code.
Lesson Objectives
After completing this lesson, you will be able to:

o Call a Windows Azure web service by using server-side code.


Explain how to call a Windows Azure web service by using jQuery and
o
JSON.
o Call a Windows Azure web service by using jQuery.

Calling a Windows Azure Service by Using Server-Side


Code

You can call web services hosted on Windows Azure in the same manner with
which you call standard web services or WCF services. To call a web service,
you need to:

1. Add the service reference in your application.


2. Use the generated proxy class.

To add a service reference in an application, you need to use the URL of the
service. You can deploy a service in the production environment, by using the
following URL format:

http://<urlname>.cloudapp.net/<servicename>.sv

You can deploy a service in the staging environment, by using the following
URL format:
http://<guid>.cloudapp.net/<servicename>.svc

To use the WCF service hosted on Windows Azure, from your MVC
application, you need perform the following steps:

In the Solution Explorer pane, right-click your project name, and then click
1.
Add Service Reference.
2. Enter the URL of the WCF service, and then click Go.
Define the local namespace of the service, and then click Add Service
3.
Reference.
Add the following code to an MVC controller class to use the generated
4.
proxy class and call the web service created earlier in this module.
public ActionResult Index()

Service1Client client = new Service1Client();

GetHelloWorldRequest request = new GetHelloWorldRequest();

GetHelloWorldResponse response = client.GetHello(request);

ViewBag.Response = response.GetHelloWorldResult;

return View();

Question: What is the key difference between deploying a service in the


production environment and deploying a service in the staging environment?

Calling a Windows Azure Service by Using jQuery


You can enable the jQuery ajax function to call WCF services, by configuring
the services to accept POST requests in the JavaScript Object Notation
(JSON) data format. JSON is a data format that facilitates requests and
responses between client and server systems.

The following code shows how to configure services to accept POST requests
in the JSON data format.

Accepting POST Requests

[ServiceContract]

public interface IService

[OperationContract]

[WebInvoke(Method = "POST",

BodyStyle = WebMessageBodyStyle.Wrapped,

ResponseFormat = WebMessageFormat.Json)]

string GetHelloWorld();

You can use the ajax function in jQuery to submit requests to WCF services.
While adding the ajax function, you need to specify parameters such as type,
url, contentType, and dataType. The following code shows how to use the
ajax function in jQuery, to call an Azure-hosted WCF service.

Sending Requests to a WCF Service

// Function to call WCF Service

function CallService() {

$.ajax({

type: 'POST',

url: 'http://<guid>.cloudapp.net/service1.svc/GetHelloWorld',

data: '{}',

contentType: 'application/json; charset=utf-8',

dataType: “json”,

processdata: true,

success: function(msg) {

ServiceSucceeded(msg);

},

error: ServiceFailed// When Service call fails

});

function ServiceFailed(result) {

function ServiceSucceeded(result) {
result=result.GetHelloWorldResult;

After successfully calling the WCF service, the code in the preceding sample
triggers the ServiceSucceeded callback function.

Module Review and Takeaways


You can upload applications and services on Windows Azure to enable better
scalability and re-usability of the application logic. Windows Azure includes
different roles that support application needs such as hosting and storage. You
can also use cloud services to host WCF services, and use the hosting services
available in MVC and HTML applications.

Review Question(s)

Question: Your teammate enquired whether you would be using Windows


Azure or self host the server for the application. What should you recommend
to your teammate based on the fact that the application loading would be
seasonal?

Module 14: Implementing Web APIs in


ASP.NET MVC 4 Web Applications
Module Overview
Most web applications require integration with external systems such as
mobile applications. You need to know how to use Web APIs to promote
application interaction with external systems. You can use the Web API to
implement Representational State Transfer (REST) services in your
application. REST services help reduce application overhead and limit the
data that is transmitted between client and server systems. You need to know
how to call Web API services by using server-side code, jQuery code, and
JSON.NET library to effectively implement REST-style Web APIs in your
application.
Objectives

After completing this module, you will be able to:

o Develop a Web API.


o Call a Web API from mobile and web applications.

Lesson 1 : Developing a Web API


You need to know how to develop Web API for applications, because Web
API facilitates creating APIs for mobile applications, desktop applications,
web services, web applications, and other applications. By creating a Web
API, you make the information in your web application available for other
developers to use in their systems. Each web application has a different
functional methodology; this difference can cause interoperability issues in
applications. REST services have a lightweight design, and Web API helps
implement REST services to solve the interoperability issues. You need to
know how to use the different routing methods that ASP.NET provides to
implement REST services.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe Web APIs.


o Create a Web API for an MVC 4 web application.
o Describe REST services.
o Describe data return formats.
o Explain how to use routes and controllers to implement REST in Web APIs.
o Explore a Web API by using Internet Explorer as a client.

What Is a Web API?


Web API is a framework that is part of ASP.NET MVC 4 that enables you to
build Representational State Transfer (REST)-enabled APIs. REST-enabled
APIs help external systems use the business logic implemented in your
application to increase the reusability of the application logic. Web API
facilitates two-way communication between the client system and the server
through tasks such as:

o Instructing an application to perform a specific task


o Reading data values
o Updating data values

Web API enables developers to obtain business information by using REST,


without creating complicated XML requests such as Simple Object Access
Protocol (SOAP). Web APIs use URLs in requests, thereby eliminating the
need for complicated requests. For example, the following URL obtains
information for a customer entity with the ID 1:

http://api.contoso.com/api/customers/1

Web API uses such URLs in requests and obtains results in the JSON format.
The following code shows a Web API request response in the JSON format.

A Web API JSON Response

[{"Id":1,"Name":"Tomato

soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":
"Yo-

yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category"

"Hardware","Price":16.99}]

REST and Web API enable all kinds of different applications, including
mobile device applications, to interact with services. In particular, REST and
Web API provide the following benefits for mobile applications:

They reduce the processing power needed to create complex request


o
messages for data retrieval.
They enhance the performance of the application by reducing the amount of
o
data exchange between client and server.

Question: What is the key benefit of using REST with Web APIs?

Routing in Web API

When you create a new project by using the Web API template in ASP.NET
MVC 4, it includes a default routing rule. This routing rule helps map HTTP
requests to the Web API controllers and actions by using HTTP verbs and the
request URL.
You can make use of a naming convention to map requests to actions, or you
can control the behavior of the mapping by using annotations on action
methods.

The Default API Route

Like standard MVC web applications, MVC Web

API uses routes to map requests to the right API

controller and action. In the Visual Studio project templates, the default API
route is defined in the WebApiConfig.cs file in the App_Start folder.

The following code shows the default route.

The Default API Route

routes.MapHttpRoute(

name: "API Default",

routeTemplate: "api/{controller}/{id}",

defaults: new { id = RouteParameter.Optional }

);

In the preceding code sample, observe that the default route includes the
literal path segment api. This segment ensures that Web API requests are
clearly separate from MVC controller routes, because Web API requests must
start with api.

The first placeholder variable, {controller} helps identify the API controller to
forward the request to. As for MVC controllers, Web API appends the word,
Controller, to this value to locate the right API controller class. For example,
Web API routes a request to the URI, api/products, to the controller called,
ProductsController. As for MVC controllers, the optional placeholder
variable, {id}, is sent to the action as a parameter.
You can also define your own API routes in the same manner as you do for
MVC routes. Observe, however, that Web API routes can handle requests
from many types of client systems, including mobile device applications,
desktop applications, web applications, and web services. MVC routes only
handle web browser requests.

Using the Action Naming Convention

The default Web API route does not include a placeholder variable for the
action name. This is because Web API uses the HTTP verb and a naming
convention to route requests to the right action within a given controller.

Clients can make HTTP requests with one of four standard verbs: GET,
POST, PUT, and DELETE. Other verbs are possible. Web API looks for an
action whose name begins with the requested HTTP verb. For example, if the
client sends a DELETE request to the URI api/products/23, Web API looks
for a controller called ProductsController. Within this controller, it locates
an action whose name begins with Delete. According to the default route, the
segment 23 is the {id} parameter. If there is more than one action whose name
begins with Delete, Web API chooses the action that accepts a parameter
called id.

The HttpGet, HttpPut, HttpPost, and HttpDelete Attributes

You can use the HttpGet, HttpPut, HttpPost, or HttpDelete attributes in


your controller action to override the action naming convention. You can also
use these verbs to specify that a function is mapped to a specific HTTP verb.
The following table describes how the HTTP attributes map to the HTTP
verbs.

Attribute HTTP Verb

HttpGet GET

HttpPut PUT

HttpPost POST
Attribute HTTP Verb

HttpDelete DELETE

The following code illustrates the use of the HttpGet attribute on the
FindProduct action.

Specifying the HTTP Verb

public class ProductsController : ApiController

[HttpGet]

public Product FindProduct(id) {}

In the preceding code sample, observe that the HTTP attributes only allow
mapping of one HTTP verb to an action in the controller.

The AcceptVerbs Attribute

The use of the AcceptVerbs attribute allows you to specify custom HTTP
Verbs or multiple HTTP verbs to the same actions in the controller.

The following code shows the use of the AcceptVerbs attribute to map
specific HTTP verbs to the action.

The AcceptVerbs Attribute

public class ProductsController : ApiController

[AcceptVerbs("GET", "HEAD")]

public Product FindProduct(id) { }


[AcceptVerbs("MKCOL")]

public void MakeCollection() { }

The ActionName attribute

By default, the action name is the name of the action you specify in the
controller. You can use the ActionName attribute to specify the action name
to be used in the routing.

The following code shows how to map an action to an HTTP request by using
a custom action name.

Mapping an Action

public class ProductsController : ApiController

[HttpGet]

[ActionName("Thumbnail")]

public HttpResponseMessage GetThumbnailImage(int id);

[HttpPost]

[ActionName("Thumbnail")]

public void AddThumbnailImage(int id);

Question: What is the purpose of using the HTTP attributes?

Creating a Web API for an MVC 4 Web Application


MVC4 provides a Web API project template that helps implement Web API
in a project.

The following image shows the list of project templates available in Microsoft
Visual Studio.

FIGURE 14.1:THE NEW PROJECT DIALOG BOX

To implement a Web API template in your project, you need to perform the
following steps:

1. In the New Project dialog box, click ASP.NET MVC 4 Web Application.
In the Select a Template box of the New ASP.NET MVC 4 Project dialog
2.
box, click Web API.

The following image shows the New ASP.NET MVC 4 Project dialog box.
FIGURE 14.2:THE NEW ASP.NET MVC 4 PROJECT DIALOG BOX

After selecting the Web API template, you need to add a new MVC controller
class that derives from ApiController. The API controller class hosts
application code for handling Web API requests. ASP.NET MVC4 engine
maps the URL together with the HTTP verb and the controller or the action
function of a controller, in the following format.

<http verb> http://<hostname>/api/<entity name>/<parameters>

The HTTP verb communicates to the Web API about the operations that it
should perform; whereas, the rest is to communicate which entity and
operations to perform on. Therefore, HTTP plays an important role. For
example, consider the following API controller class.

public class ProductsController : ApiController

{
public IEnumerable<Product> GetAllProducts()

public Product GetProductById(int id)

In the preceding code sample, note the controller classes GetAllProducts and
GetProductById. The GetAllProducts controller class helps obtain a full list
of products from the database. You can map the following URL and HTTP
verb with the GetAllProducts controller class.

GET /api/products

The GetProductById controller class helps obtain a specific product by using


the ID detail. You can map the following URL with the GetProductById
controller class.

GET /api/products/id

Question: What is the syntax that the ASP.NET MVC engine uses for
mapping controllers and action functions?

RESTful Services
REST uses URLs and HTTP verbs to uniquely identify the entity that it
operates on and the action that it performs. REST helps retrieve business
information from the server. However, in addition to data retrieval, business
applications perform more tasks such as creating, updating, and deleting
information on the database. Web API and REST facilitate handling such
additional tasks. They use the HTTP method to identify the operation that the
application needs to perform.

The following table provides information on some HTTP methods that Web
API and REST use.

HTTP Description
Verb

GET Use this method with the following URL to obtain a list of all
customers.

/api/customers

GET Use this method with the following URL to obtain a customer
by using the ID detail.

/api/customers/id
HTTP Description
Verb

GET Use this method with the following URL to obtain customers
by using the category detail.

/api/customers?country=country

POST Use this method with the following URL to create a customer
record.

/api/customers

PUT Use this method with the following URL to update a customer
record.

/api/customers/id

DELETE Use this method with the following URL to delete a customer
record.

/api/customers/id

Web API allows developers to use a strong typed model for developers to
manipulate HTTP request. The following code shows how to use the POST,
PUT, and DELETE methods for the create, update, and delete requests to
handle the creation, retrieval, updation, and deletion (CRUD) of the customer
records.

CRUD Operations

public HttpResponseMessage PostCustomer(Customer item)

public void PutCustomer(int id, Customer item)

public void DeleteProduct(int id)

Question: What is the mandatory requirement of create and update requests?

Data Return Formats

When a client makes a request to a Web API controller, the controller action
often returns some data. For GET requests, for example, this data might be all
the properties of a specific product or all the properties of all the products.
Web API can return this data in one of two formats: JavaScript Object
Notation (JSON) or XML.

JSON and XML Data Formats

Both JSON and XML are text formats that represent information as strings.
You can also use

JSON outside the JavaScript code.

The following code is a simple example of JSON.

A JSON Response

{"Name":"Albert","Age":29,"Height":145,"Skills":["Programming",

"Technical Writing"]}

You can represent the same data in the previous code sample, by using XML
as shown in the following code.

An XML Response

<Employee Name="Albert" Age="29" Height="145">

<Skills>

<Skill Name="Programming" />

<Skill Name="Technical Writing" />

</Skills>

</Employee>

When a client makes a request, the client can specify the data format for the
response. If the data format is not specified, Web API formats data as JSON
by default.

Media Formatters
Web API uses a media formatter to format or serialize the information that a
Web API REST service returns. Web applications usually use the JSON
format to format the data that functions return. However, you can alternatively
use the XML media formatter or add a custom media formatter to control the
data returned. Media formatters format the content that the server renders to
the client systems.

For example, consider that you want Web API to return CSV files. In this
case, you need to create a custom media formatter, to create as output data
files in the CSV format, instead of XML files in the JSON format.

The following code shows to add a new class in your project, to create a
custom media formatter.

A Custom Media Formatter

public class CsvFormatter : BufferedMediaTypeFormatter

Media formatter classes inherit from the following classes:

o MediaTypeFormatter. This is the fundamental class for all formatter classes.


BufferedMediaTypeFormatter. This is an extended class of formatter classes,
o
which provides support for buffering and asynchronous operations.

Additional Reading: For more information on creating media formatters, go


to: http://go.microsoft.com/fwlink/?LinkID=288992&clcid=0x421

Question: Why should you use a media formatter for Web API REST
services?

Using Routes and Controllers in Web APIs


ASP.NET MVC4 uses a route table to map a URL and a controller. When you
create a project, ASP.NET adds a default route by using the Web API
template. This default route helps support the operations of the REST-style
Web APIs.

The following code shows the default route.

The Default API Route

routes.MapHttpRoute(

name: "API Default",

routeTemplate:

"api/{controller}/{id}",

defaults: new { id =

RouteParameter.Optional }

);

Consider that you want to include multiple actions, such as creating customers
with XML and JSON, in the same HTTP method. In this case, you cannot use
the default route because it requires a new request for each HTTP method and
URL combination. Therefore, you need to update the routing by modifying
the Route Map in the WebApiConfig class.
The following code shows how to update the routing, to support multiple
operations in the same HTTP method.

Supporting Multiple Operations

routes.MapHttpRoute(

name: "ActionApi",

routeTemplate: "api/{controller}/{action}/{id}",

defaults: new { id = RouteParameter.Optional }

);

You can use the WebApiConfig class to enable multiple versions of API to
coexist in the same project. For example, you can include /api/v1/{controller}
as Version One of your API and include /api/v2/{controller} as a new version
or Version Two of the API.

You may want to include supporting functions in the controller class, and hide
the supporting functions from the REST functions. You can eliminate the
exposure of the function to the REST interface by adding the NoAction
attribute to the action function.

The following code shows how to add the NoAction attribute to the action
function.

Using NoAction

[NonAction]

public string GetPrivateData()

}
By default, Web API exposes all public methods as REST services. You can
prevent this by making the function private, but this action prevents
application code in the same project from accessing the function. Therefore,
you can use the NonAction attribute for functions that need to be in public,
but do not need to be exposed in REST.

Question: What is the key benefit of using the routing map?

Lesson 2: Calling a Web API from Mobile and


Web Applications
After you complete the development of the Web API services, you need to
create the client applications to call these services. Calling Web API services
is different from calling WCF services. However, the methods that you need
to use to call these services are similar, regardless of the platform. You need
to know how to call Web API services by using server-side code, jQuery code
and JSON.NET library, to effectively implement Web API services in most
application platforms.

Lesson Objectives
After completing this lesson, you will be able to:

o Call Web APIs by using server-side code.


o Call Web APIs by using jQuery.
o Call Web APIs by using Windows Phone applications.

Calling Web APIs by Using Server-Side Code


You can call REST-style services by using ASP.NET server-side code. You
can use the HttpWebRequest class to create a manual HTTP request to the
REST services. ASP.NET provides a .NET library that you can use in web
applications to call REST-enabled Web API services from the .NET server.
To use the .NET library, you need to install the
Microsoft.AspNet.WebApi.Client NuGet package. This NuGet package
provides access to the HttpClient class. The HttpClient class simplifies
interacting with Web APIs, because it reduces coding efforts.

After installing the NuGet package, you need to initialize the HttpClient
class. The following code illustrates how to initialize the HttpClient class.

Initializing the HttpClient Class

HttpClient client = new HttpClient();

client.BaseAddress = new Uri("http://localhost/");

client.DefaultRequestHeaders.Accept.Add(new

MediaTypeWithQualityHeaderValue("application/json"));

The last line of code in the preceding code sample informs the client system
about the media type that the client system should use. The default media type
that applications use is application/json. However, applications can use any
other media type, based on the media type that the REST-style services
support.

The following code shows how to call Web API REST services by using
server-side code.

Calling the API from Server-Side Code

HttpResponseMessage response =

client.GetAsync("api/customers").Result;

if (response.IsSuccessStatusCode)
{

var products =

response.Content.ReadAsAsync<IEnumerable<Customer>>().Result;

else

Console.WriteLine("{0} ({1})", (int)response.StatusCode,

response.ReasonPhrase);

After running the code in the preceding code sample, you need to define a
data model that aligns itself with the one used by the Web API service to
enable the .NET library to:

o Process the results of the server-side code.


o Return results as .NET objects for the application to use.

Then, you can use the GetAsync and ReadAsAsync methods to:

o Create requests to Web API REST services.


o Parse the content into .NET objects.

The PostAsJsonAsync function uses the HTTP POST method to call Web
API services that support the POST method.

Question: What is the benefit of using the Microsoft.AspNet.WebApi.Client


NuGet package?

Calling Web APIs by Using jQuery Code


You can call Web API services in the same manner as you call other services
that use technologies such as WCF. You can also call Web API services by
using the jQuery ajax function.

The following code shows how to call a Web API service by using the jQuery
ajax function.

Using the jQuery ajax Function

$.ajax({

url:

'http://localhost/api/customers/,

type: 'GET',

dataType: 'json',

success: function (data) {

},

error: function (e) {

});
In the preceding code sample, observe the dataType parameter of the ajax
function. You should set this parameter to json or another data type that the
Web API service supports. Most applications use JSON because it is light
weight. The ajax function has built-in functionalities that parse JSON results
for the ease of developers.

You can use JSON.stringify() in the data parameter of the ajax function to
serialize the JavaScript objects into JSON objects for sending to the Web API
method. The following code shows how to use JSON.stringify() in the data
parameter of the ajax function.

Using the stringify function

var customer = {

ID:'1',

CustName: 'customer 1'

};

$.ajax({

url: 'http://localhost/api/customer',

type: 'POST',

data:JSON.stringify(customer),

contentType: "application/json;charset=utf-8",

success: function (data) {

},

error: function (x) {

});

Question: What is the benefit of using JSON.stringify() in the ajax function?

Calling Web APIs Using Windows Phone Applications


You can use NuGet packages to call Web API REST services in .NET
applications. However, in Windows Phone web applications, you need to use
the JSON.NET library to call Web API REST services. The JSON.NET
library is more light weight and it enhances the performance of Windows
Phone applications. You can download the library from

http://go.microsoft.com/fwlink/?LinkID=288993&clcid=0x422

The JSON.NET library contains a set of .NET classes that help create JSON
requests to any REST-style

APIs. To use the JSON.NET library, you need to download it and place the
JSON.NET assembly in the /WindowsPhone folder of the /bin folder.

The following code shows how to call an HTTP request by using the
WebClient class.

Using the WebClient Class

WebClient webClient = new WebClient();

Uri uri = new Uri("http://localhost/api/customer/");

webClient.DownloadStringCompleted += new

DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted)

;
webClient.DownloadStringAsync(uri);

When you make a request by using the WebClient class, the JSON.NET
library processes the request and produces results from the WebClient class to
return .NET objects. When you call Web APIs by using the library, you need
to add the DownloadStringCompleted event handler. This event handler
helps place logic to handle the data that Web APIs return.

In the DownloadStringCompleted event handler, you should add the code


similar to the following.

Coding the Event Handler

using Newtonsoft.Json;

/// Lines skipped

List<Customer> customers =

JsonConvert.DeserializeObject<List<Customer>>(e.Result);

foreach (Customer em in customers)

The code in the preceding sample helps enable the JSON.NET library to
deserialize the results into .NET objects.

Question: What is the key benefit of using the JSON.NET library?

controller in Exercise 1 differ from other actions in MVC controllers?

Module Review and Takeaways


You can use the Web API framework to facilitate creating REST-style Web
API calls in applications. REST-style Web API is recommended for mobile
applications because of the light weight design of REST services.
REST services use HTTP methods such as GET, POST, and PUT to notify
the API of the action that it needs to perform. Web APIs use the media
formatter and the JSON.NET library to serialize and deserialize information,
respectively. You can call Web API services by using server-side code,
jQuery code, and the JSON.NET library.

Real-world Issues and Scenarios

Consider that you develop a mobile application by using Web APIs and the
application needs to use currency rate services. For this application, you
cannot use WCF, because WCF can impede the performance of the
application by using XML for data exchanges. Therefore, you should use
REST and JSON in the application to reduce the data that is transmitted
between the client system and the server.

Review Question(s)

Question: We are developing a mobile application, which requires to access


business data via internet. You are proposing to use Web API but your
colleague is proposing to use WCF. What would be the key point for using
Web API in this scenario?

Module 15: Handling Requests in ASP.NET


MVC 4 Web Applications
Module Overview
ASP.NET MVC provides functionalities that help develop web applications.
However, ASP.NET MVC does not include functionalities that help change
the encoding of the output. In such cases, you need to know how to use an
HTTP module or HTTP handler, to facilitate such specific requests. Most web
applications require two-way communication between the client and server
systems. The web sockets protocol facilitates two-way communications in a
robust manner.

Objectives
After completing this module, you will be able to:

o Use HTTP modules and HTTP handlers.


o Use web sockets.

Lesson 1 : Using HTTP Modules and HTTP


Handlers
Applications perform actions on a request in the HTTP pipeline, before
rendering a webpage. You need to know how to use an HTTP module to
implement custom authentication mechanism for a webpage, before rendering
the webpage. You can also use an HTTP module to create code that renders
content in a non-default encoding format that fits application needs.
Sometimes, you may need the application to handle requests by using
application logic that differs from the built-in ASP.NET page rendering logic.
In such cases, you should know how to use the HTTP handler to process such
specific requests.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe how HTTP modules intercept web requests.


o Create HTTP modules.
o Describe how HTTP handlers intercept web requests.
o Create HTTP handlers.
o Determine when to use HTTP modules and HTTP handlers.

What Is an HTTP Module?


An HTTP module is a program that runs application logic on a webpage,
before ASP.NET renders the webpage. To understand the relevance of an
HTTP module, you need to know about the HTTP request pipeline. The IIS
HTTP request pipeline is a sequence of programs that run on requests, to help
the application perform tasks. When the application receives a request, it
passes the request to the isapi_aspnet.dll ISAPI library and starts the
ASP.NET execution pipeline, to process the request.

Then, the request passes through the

HttpApplication instance of the application and the HttpModule library.

HTTP modules provide the following features to an application:

Security. Provide support for the custom authentication and authorization


o
logic of your application
Logging and statistics. Gather low-level information about the web
o
application execution cycle, for monitoring and logging purposes
Custom headers and footers. Allow insertion of custom header information
o
in the response of each request

The following is a list of HTTP modules in ASP.NET:

o OutputCache
o Session
o WindowsAuthentication
o FormsAuthentication
o PassportAuthentication
o UrlAuthorization
o FileAuthorization
o DefaultAuthentication

If you configure HTTP modules in an application, HTTP modules apply to all


the HTTP requests that the application receives. You cannot configure an
HTTP module for a specific page.

Question: What are the benefits of using HTTP modules in web applications?

Creating HTTP Modules

You can create an HTTP module by adding the CustomModule class to your
project; this class implements the IHttpModule interface in your application.

The following code shows how to create the CustomModule class in a


project.

Coding a Custom Module

public class CustomModule : IHttpModule

public CustomModule ()

}
public String ModuleName

get { return "CustomModule"; }

public void Init(HttpApplication application)

context.Response.Write("<h1>Demo<h1>");

In the CustomModule class, you need to implement the following two


methods:

ModuleName property. Provides a display name that enables other


o
application code to identify the HTTP module.
Init function. Provides the location to implement all logic for an HTTP
o module. The HttpApplication class triggers this function when the
application receives a request.

After you complete the development of an HTTP module, you need to register
the HTTP module in the Web.config file. The following code shows how to
register an HTTP module for an application running in IIS 6.0 or later
versions, configured in the Classic mode.

Registering an HTTP Module for IIS 6.0

<configuration>

<system.web>

<httpModules>
<add name="CustomModule" type="CustomModule "/>

</httpModules>

</system.web>

</configuration>

The following code shows how to register an HTTP module for an application
running in IIS 7.0 or later versions, configured in the Integrated mode.

Registering an HTTP Module for IIS 7.0 or Later

<configuration>

<system.webServer>

<modules>

<add name="CustomModule" type="CustomModule"/>

</modules>

</system.webServer>

</configuration>

Question: You have developed a custom HttpModule. What must you do to


ensure that your ASP.NET application uses the custom module developed?

What Is an HTTP Handler?


HTTP modules help apply logic to all HTTP requests that an application
receives. The HttpHandler function is a processing engine that processes
specific HTTP requests. For example, you can configure an HttpHandler
function to handle *.ashx files. You can map an HttpHandler function to a
URL based on the file extension of the requested server-side page, such as
*.aspx.

The following list describes some common HttpHandler functions:

ASP.NET page handler (*.aspx). This is the default HTTP handler for
o
ASP.NET pages.
Web service handler (*.asmx). This is the default HTTP handler for web
o
service pages.
Generic web handler (*.ashx). This is the default HTTP handler for all web
o handlers that do not have a user interface and include the @WebHandler
directive.
Trace handler (trace.axd). This is a handler that helps display page trace
o
information.

You can use the *.ashx file extension with the Http handler because:

o The extension does not include any page-rendering logic.


The extension allows developers to write logic to send responses to the client
o
systems.

You can use a custom HTTP handler with the *.rss extension, to generate
Real Simple Syndication (RSS) feed content for user requests. You can also
use a custom handler to request images from the database and send the images
to the client systems.

Question: What is the primary use of the HTTP generic handler (*.ashx)?

Discussion: Scenarios for HTTP Modules and


Handlers

Consider the following scenarios. In each case, discuss with the rest of the
class to determine whether an HttpModule or HttpHandler best suits the case.

You are creating a photo sharing application, and you want to enable each
user to discuss photos and cycling trips with their friends. You need to
o
ensure that the application renders photos to users, from the database table,
without requiring users to first save the file on their system.
You are creating a Representational State Transfer (REST)-based business
o application programming interface (API) that requires a custom HTTP
header, before accepting a request.
o You are creating a business API to provide content in custom XML format.
You developing an application that requires saving diagnostic information
o
about the header of an HTTP request.

Lesson 2: Using Web Sockets


AJAX technologies are constantly evolving. The HTTP protocol does not
cater to crucial requirements such as real-time information updates from the
server. You need to know how to use web sockets to create two-way
communication between the client and server systems. You also need to know
when to use the traditional HTTP model and the web sockets protocol, based
on the needs of your application.

Lesson Objectives
After completing this lesson, you will be able to:

o Describe the WebSocket protocol.


o Describe how to create web sockets connections.
o Determine when to use web sockets.
Add a web sockets-based application to an ASP.NET MVC 4 web
o
application.

What Is the WebSocket Protocol?

The WebSocket protocol is a standard from the World Wide Web Consortium
(W3C). The HTML 5 specification includes support for web sockets.

Additional Reading: For more information about the WebSocket protocol,


go to:

http://go.microsoft.com/fwlink/?LinkID=288994&clcid=0x423

The protocol facilitates two-way communication between web browsers and


web servers. The

protocol helps overcome the issue of HTTP not providing two-way


communication.
Developers often build two-way communication applications by using
inefficient techniques such as long running loops and polling. These
techniques consume large amounts of memory and other resources of both the
server and client systems. The WebSocket protocol resolves the problems that
arise with using such techniques by creating a constant socket connection
between the client and server. All communication between the client and
server systems then occurs through the socket. This socket eliminates the need
to re-create a request multiple times, during real-time communications
between the client and server systems. Remember that all browsers may not
support web sockets. Microsoft Internet Explorer 10 and Windows 8
applications, which use JScript and HTML5, do support web sockets. Latest
versions of Chrome, Safari, and Firefox also support web sockets.

The web sockets work in a similar manner as traditional network sockets. The
only difference is that during the initial handshake, web sockets use the
Upgrade HTTP request that includes the Upgrade HTTP header. If the server
accepts web sockets, the server returns a response with the status code, 101.
Then, the client and server systems send the payload by using the socket.
When the client system no longer requires communication with the server, the
application sends a close connection payload, to notify the server to close the
web socket.

Question: What is the key difference between traditional HTTP and web
sockets?

Coding Web Sockets Connections


To use web sockets, you need to implement server-side services that can
handle the two-way communication between the server and the client systems.
To simplify the programming work, Microsoft provides the
Microsoft.WebSockets NuGet package. This package includes a library that
helps handle web socket operations on the server. While coding web sockets,
you can:

Use the Web API framework to create a REST service that handles the
o
initial handshake.
Use the WebSocket library to promote
o
communication between the client and server systems.

The following code shows how to create a REST service and use the
WebSocket library, to handle the operations of web sockets on the server.

Using the Web Sockets Library

public class ChatController : ApiController

public HttpResponseMessage Get(string username)

HttpContext.Current.AcceptWebSocketRequest(new

ChatWebSocketHandler());

return

Request.CreateResponse(HttpStatusCode.SwitchingProtocols);

class ChatWebSocketHandler : WebSocketHandler

{
public ChatWebSocketHandler()

public override void OnOpen()

public override void OnMessage(string message)

Observe the Get function in the preceding code sample. The ASP.NET engine
maps this function to a URL and the controller with a GET request. After the
initial handshake:

The WebSocket library establishes the web socket at the client and server
o
end.
The application passes the handling of communications to the
o ChatWebSocketHandler class inherited from the WebSocketHandler
class.

Whenever the client system sends a message to the service application hosted
on the web server, the message triggers the OnMessage function. The
OnMessage function enables you to respond to the message.

To ensure that a message triggers the OnMessage function, you need to add
the following code to the Web.config file.
Configuring Web Sockets

<configuration>

<appSettings>

<add key="aspnet:UseTaskFriendlySynchronizationContext"

value="true" />

</appSettings>

</configuration>

On the client side, you can use the WebSocket object to establish two-way
communication between the client and server systems. The following code
shows how to use the WebSocket object in JavaScript.

Calling Web Sockets from the Browser

$(document).ready(function () {

websocket = new WebSocket('ws://localhost/api/service1');

websocket.onopen = function () {

};

websocket.onerror = function (event) {

};

websocket.onmessage = function (event) {

};

websocket.send('Hello');

websocket.close();
});

The preceding code sample shows how to add JavaScript functions to respond
to events. The following list describes some common JavaScript functions.

onmessage. You can use this function when the client system receives a
o
message from the server.
onopen. You can use this function when the WebSocket library establishes
o
the web socket.
o onerror. You can use this function when an error occurs.

To send a message in JavaScript, you can use the WebSocket.send() function.


After all communications between the client and server systems end and you
no longer need the web socket connection, you can use the
WebSocket.close() function. This function helps close the web socket
communication channel between the client and server systems.

Question: What is the purpose of using Web APIs to create a service for
handling web sockets?

What Is SignalR?

SignalR is a set of components that simplifies the development of


bidirectional real-time web applications, such as chat rooms in websites.

SignalR uses WebSockets wherever possible to connect. This means that it


supports all HTML5 compatible browsers. A key advantage of using SignalR
is that it supports remote procedure calls (RPCs) with HTML or even .NET
applications and can automatically switch to periodic polling for older
browsers.

To install the package to your application, you can use NuGet to find the
package,

Microsoft.AspNet.SignalR.

After installation, you can implement the server-side code for the server logic.

To use SignalR, you need to implement a class that inherits from SignalR
library. The following example broadcasts a message to all clients when a
message is received from one client.

Coding SignalR Connections

using System.Threading.Tasks;

using Microsoft.AspNet.SignalR;

public class DemoConnection : PersistentConnection

protected override Task OnReceived(IRequest request, string

connectionId, string

data)

return Connection.Broadcast(data);

After the server code is implemented, you need to add ASP.NET routing to
map the URL back to the SignalR library. The following code maps the /demo
URL to the DemoConnection library for handling the message communication
by using SignalR.

Mapping SignalR URLs

public class Global : System.Web.HttpApplication

protected void Application_Start(object sender, EventArgs e)

RouteTable.Routes.MapConnection<DemoConnection>("demo",

"/demo");

SignalR also includes a JavaScript library that can be used by clients to help
perform communications between client and server. The SignalR library
depends on the jQuery library.

The following JavaScript code sends a message to the server, receives a


message back, and displays the received message.

Client-Side SignalR Code

<script src="http://code.jquery.com/jquery-1.7.min.js"

type="text/javascript"></script>

<script src="Scripts/jquery.signalR-1.0.1.min.js"

type="text/javascript"></script>

<script type="text/javascript">

$(function () {
var connection = $.connection('/demo);

connection.received(function (data) {

alert(data);

});

connection.start().done(function() {

$("#broadcast").click(function () {

connection.send('Hello');

});

});

});

</script>

Question: What is the key benefit of using SignalR, instead of WebSockets


directly?

Module 16: Deploying ASP.NET MVC 4 Web


Applications

Module Overview
After developing an application, you need to deploy the application to the
production environment to make the application available to users. The
configuration or deployment method of each application varies based on the
setup of the production environment. ASP.NET MVC applications have some
special considerations such as the configuration needed for IIS.
Objectives

After completing this module, you will be able to:

o Configure and deploy an ASP.NET web application.


o Deploy an ASP.NET MVC 4 web application.

Lesson 1 : Deploying a Web Application


The considerations for deploying a web application to a web farm are different
for single and multi-server configurations. For example, in multi-server web
farms, you need to ensure that the state information is available on all web
servers. You also need to ensure that the dependencies needed for hosting
ASP.NET MVC 4 web applications are present in the web farm. If any of the
application dependencies are missing on the production web servers, some or
all of your applications may not function and users may encounter errors. You
need to apply special considerations while deploying web applications on
Windows Azure. Deploying a web application on Windows Azure provides
advantages such as high availability and flexibility.

Lesson Objectives
After completing this lesson, you will be able to:

Ensure that dependencies are present for hosting ASP.NET MVC4


o
applications.
o Deploy an ASP.NET MVC4 web application to a single-server web farm.
o Deploy an ASP.NET MVC4 web application to a multi-server web farm.
o Deploy an ASP.NET MVC 4 web application on Windows Azure.

ASP.NET MVC 4 Dependencies


ASP.NET MVC 4 is built on the ASP.NET Framework 4.0. Each web
application requires a range of different components to be present on the web
server, to function appropriately.

Examples of common requirements include:

The ASP.NET Framework 4.0 Common Language Runtime (CLR). The CLR
runs any managed code such as C# classes. All ASP.NET web applications
o
require the CLR, and you can install the CLR with Internet Information
Services (IIS).
The ASP.NET MVC 4 runtime. The

ASP.NET MVC 4 runtime locates controllers and actions to handle each


o request that the web application receives, and it returns the compiled
webpages to users. You can install the MVC runtime in your web
application by installing the MVC 4 NuGet package. All MVC web
applications require the MVC runtime.
A Database server. Most web applications use a database to store
information such as product details, customer details, images, and other
entities. You need to ensure that the production environment supports the
o database that you used during development. For example, if you use SQL
Compact during development, you need to ensure that Microsoft SQL
Compact is installed on the production server. Alternatively, you can migrate
the database to Microsoft SQL Server.
Entity Framework. If you use Entity Framework to model data in your web
o application, you need to ensure that you deploy the framework with your
application.
Membership Providers. If your application uses membership providers to
store user accounts and roles, you need to ensure that these providers are
available on the server. The .NET Framework includes the SQL Server
o
Membership Provider. If you use the Universal Membership Providers by
installing the NuGet package, you need to ensure that you include the NuGet
package with your deployed application.

Question: Which of the common requirements in the above list is required to


support forms authentication?

Deploying Web Applications to Web Servers

Before you deploy a web application to a production IIS web server, you must
create and configure the IIS application and the folder that hosts the
application.

Creating an IIS Web Application

You need to host ASP.NET MVC 4 web applications in an IIS web folder that
is marked as a web application starting point. You can use the Internet Service
Manager tool to configure this setting on the top-level folder of the web
application. When you mark a web folder as a web

application, you enable IIS to recognize that the

content of the folder is ASP.NET and requires the ASP.NET runtime engine
to process each request.
After creating an application, you need to configure the application to use
.NET 4.0 or above. This practice enables ASP.NET MVC 4 to run, because
the MVC runtime components are part of the .NET framework.

IIS Application Pools

In IIS, web applications are run within a context known as an application


pool. You can run many applications in the same application pool or install an
application in its own isolated pool. Applications that run in the same
application pool share the following resources:

Worker Process. The worker process uses a single execution process to run all
o
the applications in a pool.
Memory. The applications share a single memory range, because the
o
applications in a pool share a single worker process.
o Identity. The applications within a single pool share a user account.

You can place two or more applications in an application pool, and thereby
reduce the total memory usage, because the applications share memory.
However, this arrangement can reduce the reliability of each application,
because a malfunctioning application can affect all the applications in the
pool. To maximize the reliability of an application, you should install the
application in an isolated pool that runs only one specific application.

The shared identity within an application pool affects the way the applications
authenticate resources such as database servers when using integrated
authentication. Each application within a pool shares a single user account. If
each application has a separate database, you need to set permissions, to
enable the user accounts to access all the databases. If you separate
applications into isolated pools, you can use a different user account for each
application. This practice can enhance the security of the application, because
each account can access only one database.

Deploying the Application

When the IIS web application is ready, you need to copy the web application
files to IIS. These files include all the model classes, controllers, views, script
files, style sheets, images, and any other content in the Microsoft Visual
Studio ASP.NET MVC 4 project. You can use the deployment tools available
in Microsoft Visual Studio, or other technologies such as FTP, to copy these
files. When the copy operation is complete, the web application is ready for
deployment.

Question: What is the purpose of configuring additional application pools?

Deploying Web Applications to Multi-Server Farms

You can deploy a web application to a multi-server web farm to increase


performance, resilience, and reliability. In a multi-server web farm, a group of
two or more web servers host a single web application. All the servers in the
farm share a single server name, such as www.contoso.com. Windows
Network Load Balancing or dedicated hardware load balancers distribute
browser requests to the servers.

A multi-server farm usually has greater capacity than a single web server,
because the multi-server farm almost equally shares the load amongst

several servers. Multi-server farms also increase reliability. When a server


fails for any reason, the load balancing mechanism automatically directs
requests to another server that remains online.

If you decide to deploy your web application to a multi-server farm, you need
to perform the following steps. To complete these steps, you may need to
work with the web server administrator who is responsible for the server farm:

1. Create IIS applications and application pools on each server. This step is the
same as configuring the applications and application pools in a single-server
scenario. However, you need to perform this step on every server in the farm.
You also need to ensure that applications and application pools have the same
configuration, throughout the farm.
Create a matching IIS configuration on each server. IIS configuration options,
2. such as any encryption certificates, file extensions, and optional components,
should be identical on every server in the farm.
Use external hosted session state or session affinity. You can configure
ASP.NET web applications to store session state in the Windows State Service
or a database. You should use this technique in a multi-server farm, because
each request from a single user session might be directed to a different web
server. Alternatively, by configuring session affinity, you can ensure that all
3. requests from a user session are always sent to the same web server. If you do
not use external hosted session state or session affinity, the user preference on
one web server may get lost when a request is sent to another web server.
Session affinity is supported by some but not all load balancing solutions.
Work with your web server administrator to determine if affinity is available
on your farm.
Configure the machineKey element in the Web.config file. If you are using
external hosted session state, you can encrypt the connection between the web
servers and the State Service server or database server. This technique
improves security by protecting session state during network transmissions.
4. You can configure this encryption by setting up the machineKey element in
the Windows registry.

Additional Reading: For more information about configuring the


machineKey element, go to:
http://go.microsoft.com/fwlink/?LinkID=288995&clcid=0x424

Question: What is the purpose of configuring the machineKey element in the


Web.config file?

Deploying Web Applications on Windows Azure


You can deploy any ASP.NET web application, including ASP.NET MVC 4
web applications, on Windows Azure. By choosing Windows Azure as a
platform, you can use a highly-available and flexible infrastructure that you
can optimize to cope with intense load. You have a choice of subscriptions,
which can help you to pay only for the traffic that your web application uses.

Deploying a web application on Windows Azure is different from deploying


the application on on-premise versions of IIS. To deploy an application on
Windows Azure, you perform the following

steps:

1. Create a new web application in the Windows Azure management portal.


2. Download and save a publishing profile for the new web application.
In Microsoft Visual Studio, open your web application solution. Then, start
3.
the Publish wizard and import the publishing profile.
Ensure that you select the correct connection strings for Entity Framework
4. connections, service database connections, and any other database
connections.
5. Complete the Publish wizard.
Observe that Microsoft Visual Studio publishes the web application to
6.
Windows Azure.

When the process is complete, you can access the Windows Azure-hosted web
application from any Internet-connected browser.

Note: At the time of writing, Windows Azure web applications are still in
preview, within the Windows Azure platform.
Windows Azure Web Applications and Windows Azure
Cloud Services

Instead of publishing an ASP.NET MVC web application as a web application


in Windows Azure, you can choose to build and publish a Windows Azure
cloud service. A cloud service is a Windows Azure component that you can
use to build a flexible multi-tiered application, with a discrete architecture. A
cloud service consists of one or more web roles and worker roles, each with
its own application files and configuration.

In a Windows Azure web application, all components of your web application


run in a single process. You can administer the web application as a single
object.

Windows Azure cloud services help separate user interface logic that you
build in a web-role project, from business logic that you build in a worker
process project. This separation provides greater flexibility, and it enables
calling the business logic from other processes, such as mobile applications.
You can separately administer web roles and worker processes, and run them
in separate processes. However, to publish a web application as a cloud
service with separate web roles and worker roles, you need to download and
install the Windows Azure SDK. You can download and install the Windows
Azure SDK by using the Web Platform Installer. You can use the Windows
Azure cloud service templates as the starting point for your application.

Question: How does Windows Azure cloud services help enhance the
flexibility of the application?

Lesson 2: Deploying an ASP.NET MVC 4 Web


Application
Deploying ASP.NET MVC applications is similar to deploying other
ASP.NET applications. This process is simple and straightforward. However,
you need to update the configuration of the application for use in the
production environment. Microsoft Visual Studio includes features that
simplify updating the configuration of the application. You can also automate
the deployment process by using deployment tools available in Microsoft
Visual Studio.

Lesson Objectives
After completing this lesson, you will be able to:

Reconfigure an ASP.NET MVC application to deploy it on a production web


o
server.
Use the Bin Deploy method to deploy the .NET Framework libraries along
o
with your web application.
o Use the deployment tools in Visual Studio.

Reviewing Configuration for Production

Each ASP.NET MVC web application includes a Web.config file. In addition


to this file, Microsoft Visual Studio creates two variance files to specify
deployment transformations to the Web.config file. You can use these
variance files for different build configurations. The variance files include:

The Web.release.config file. This file stores the changes that Microsoft
o Visual Studio applies to the Web.config file, when you compile the
application in the Release mode.
The Web.debug.config file. This file stores
o
the changes that Microsoft Visual Studio applies to the Web.config file,
when you compile the application in the Debug mode.
Microsoft Visual Studio can automatically transform the Web.config file for
use in different environments. Before you publish the application, you can
remove the debug attribute from the Web.config file.

The following code shows how to remove the debug attribute from the
Web.config file by using a deployment transformation.

Removing the Debug Attribute for Deployment

<system.web>

<compilation xdt:Transform="RemoveAttributes(debug)" />

</system.web>

The following code shows how to remove the debug attribute from the
Web.config file by using a deployment transformation.

Removing the Debug Attribute by Using a Deployment Transformation

<system.web>

<compilation xdt:Transform="RemoveAttributes(debug)" />

</system.web>

The preceding code sample uses the xdt:Transform attribute to modify the
existing Web.config file and produce the published Web.config file. You can
also use the Insert value to add additional elements to the resultant
Web.config file.

For example, the following code shows how to insert a new connection string
setting in the resultant Web.config file.

Inserting a Connection String

<connectionStrings>
<add name="DemoConnStr" connectionString="Data

Source=|DataDirectory|demo.sdf"

providerName="System.Data.SqlServerCe.4.0"

xdt:Transform="Insert"/>

</connectionStrings>

Question: How can you configure the Web.config file for publishing to a
production environment without using the Web.release.config configuration
file?

Using Bin Deploy

ASP.NET MVC applications depend on a range of .NET assemblies; these


assemblies ensure that the application functions as required. These assemblies
are dynamic-link library (DLL) files available in your project references. The
assembly files are usually already present on the web server because they are
included as part of the MVC library installation. However, sometimes the web
server administrators do not install all .NET Framework assemblies. Microsoft
Visual Studio provides the Bin Deploy feature to copy all depending assembly
files into a folder within the

deployed web application. This feature helps deploy dependencies on the


server.
You can use the Add Deployable Dependencies feature to generate the
_bin_deployableAssemblies folder. This folder includes the following
libraries:

o Microsoft.Web.Infrastructure
o System.Web.Helpers
o System.Web.Mvc
o System.Web.Razor
o System.Web.WebPages
o System.Web.WebPages.Deployment
o System.Web.WebPages.Razor

You can choose a specific set of libraries to include in Microsoft Visual


Studio. This practice enables you to ensure that Microsoft Visual Studio
deploys the:

o Right assemblies.
o Right versions of the assemblies.

You can then copy the library to the bin folder of the production server, after
adding it to the library of your project.

Question: Why should you use the deployable assembly as part of the
deployment plan?

Using Visual Studio 2012 Deployment Tools


The Publish feature helps generate a copy of the web application when the
application is ready for deployment in the production environment. The
feature includes three methods to deploy the application:

o File Share
o FTP
o Web Deploy

On the Publish web application page, you can publish the application by using
File Share or FTP.

You can use File Share for servers to which you

have direct network access. Alternatively, you can use File Share to publish a
web application first to a local folder. Then, you can manually copy the files
to the web server. File Share also allows you to specify a profile to store all
deployment options. This practice eliminates the need to specify the
deployment options every time you publish the application.

If you select Web Deploy, you can specify database settings, such as
connection strings, in the publishing wizard. These settings will override the
settings in the Web.config file in the target environment. Web Deploy also
includes tools to automatically update the schema of the database. These tools
eliminate the need to manually update the schema. The publishing tool detects
all schema changes and generates scripts to apply those changes to the
published database. If your development and production web servers are
isolated from each other, you can run these generated scripts on the
production environment. This practice replicates schema changes on a server
where Microsoft Visual Studio is not installed.

The following image shows the Publish web application page.


FIGURE 16.1:THE PUBLISH WEB APPLICATION PAGE

Question: What is the benefit of using the Web Deploy publish tool?

Module Review and Takeaways


Deployment is usually the last task that developers perform; however, this is
the task that developers do not spend much time on. The target environment
usually impacts the deployment procedure. In the case of Windows Azure,
service packages allow the management portal to deploy the package to the
virtual machine that hosts the workload.

To simplify the deployment process, Microsoft Visual Studio consists of a


number of tools that help developers generate files for deployment. These
tools also help handle the database during deployment. You can also generate
the Web.config file based on the environment that it deploys to.

Review Question(s)

Question: You need to create two packages for deployment-for testing and
for production environment. This is because of the difference in server name
and other environment settings. What should you do?
Course Evaluation
Keep this evaluation topic page if this is the final module in this course. Insert
the Product_Evaluation.ppt on this page.

If this is not the final module in the course, delete this page

Your evaluation of this course will help Microsoft understand the quality of
your learning experience.

Please work with your training provider to access the course evaluation form.

Microsoft will keep your answers to this survey private and confidential and
will use your responses to improve your future learning experience. Your
open and honest feedback is valuable and appreciated.

Das könnte Ihnen auch gefallen