Posts Tagged ‘ASP.NET’

February 3rd, 2009

A potentially dangerous Request.Form value was detected in ASP.NET MVC

If you are getting something like the following error message in ASP.NET MVC:

A potentially dangerous Request.Form value was detected from the client (Description=”<p>some HTML text</p>”)

This is because of something called Request Validation, that is a feature put in place to protect your application cross site scripting attacks, as described in a White Paper on ASP.NET:

Many sites are not aware that they are open to simple script injection attacks. Whether the purpose of these attacks is to deface the site by displaying HTML, or to potentially execute client script to redirect the user to a hacker’s site, script injection attacks are a problem that Web developers must contend with.

Script injection attacks are a concern of all web developers, whether they are using ASP.NET, ASP, or other web development technologies.

The ASP.NET request validation feature proactively prevents these attacks by not allowing unencoded HTML content to be processed by the server unless the developer decides to allow that content.

You need to add the following to your action method:

[ValidateInput(false)]
public ActionResult MyAction (int id, string content) {
    // ...
}

This is a new feature that was added to ASP.NET MVC RC1 and it will turn off request validation for this action and this action only. However you need to take special precautions to double check your content for script tags, which may indicate a cross site scripting attack. And if you find one make sure to do a simple replace that will render it harmless, such as:

content = content.Replace("<script", "[script").Replace("</script>","[/script]");

The above is not the most bullet proof code, but if you are using the ValidateInputAttribute on your action make sure to do a quick search on XSS or Cross Site Scripting and become familiar with the basics of this kind of attack.

Tags: ,

Posted in ASP.NET | kick it on DotNetKicks.com | Bookmark | View blog reactions | 9 Comments »

February 1st, 2009

Introducing the ASP.NET MVC (Part 7) - The Controller

This is a continuation of my Introduction to ASP.NET MVC series. As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2. I am doing this so I can receive feedback on this chapter as early as possible. Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

The Controller

In ASP.NET MVC, the controller contains the application logic for manipulating the model, handling user interactions, and choosing the view to display to the browser.  It can be thought of as the glue that holds the model and views together.

The controller, in actuality, is just a class object that inherits from the System.Web.Mvc.IController interface.  However, the typical implementation that you will encounter will be abstracted away from the IController interface, using an already implemented Controller class.  A properly implemented controller will contain one or more action methods, which we will cover in a later section of this chapter.

URL Routes

Another important part of the controller is the routes that define the URL.  The routes tell the controller factory which controller to instantiate and which action in the controller should be executed.  Let’s take the default route, which we learned about earlier in the chapter, as an example:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

In the above route definition, the URL can be constructed in the following manner:

{controller}/{action}/{id}

How the controller and routes work is one of those instances where it is easier to demonstrate the capabilities than to try to explain, so here is a table to demonstrate how the above route breaks up the following URL’s.

URL Controller Action ID
/ Home Index
/Home Home Index
/Home/About Home About
/Account Account Index
/Account/User/1 Account User 1

You may have noticed in the above table that some of the parts of the URL are not defined, and in the first case none of the parts are defined.  This is because there are a set of defaults defined for each part of the URL, and if the part of the URL is missing, then the default is used.  The default is defined with the following line in the above example code:

new { controller = "Home", action = "Index", id = "" }

In ASP.NET MVC there are two parts that need to be present in every route and they are controller and action.  This is because these two parts are required by the controller factory to find the correct controller object and then the correct action method in that controller.  All the other parts can optionally map to the action methods parameters.

When we talk about the controller factory from here on forward, we will be specifically referring to the ASP.NET MVC implementation, called DefaultControllerFactory, which is based on the controller objects using the following format: {controller_name}Controller (i.e. HomeController, AccountController).  There are many other types of controller factories, such as those based on the Inversion of Control principle, Castle Windsor, Sprint.NET, Structure Map, and Unity that are available from the MVC Contrib project located at www.codeplex.com/mvccontrib, if you are interested in learning more.

Controller Factory

The default controller factory in the ASP.NET MVC Framework, the DefaultControllerFactory, uses the following criteria, by default, when searching for available controllers for use:

  • The namespace of the web assembly with Controllers added on the end (that is, TheBeerHouse.Web.Controllers).
  • The objects in the namespace must be in the following format {controller_name}Controller (that is,  HomeController, AccountController).
  • The objects must also inherit from the IController interface.

These criteria can best be seen in the default solution that we saw earlier in this chapter. Let’s take another look at the controllers, as seen in Figure 2-25.

Figure 2-25

Figure 2-25

All of those criteria may have made the process of adding a new controller sound complex, but really all that you need to do to accomplish this is add a new code file to the Controllers directory and make sure the object in the code file inherits the Controller object from the System.Web.Mvc namespace.

Actions

The actions, like we talked about earlier in this chapter, are what binds the URL to the view being displayed.  They are not that difficult to understand, but to help separate out the different parts that make up an action I have divided them into a couple of logical sections below.  We are going to use the following code example to help bring all of the different sections together.

[AcceptVerbs(HttpVerbs.Post)]
[OutputCache(Duration = 600)]
public ActionResult GetCustomer (string name, string email)
{
    // code for executing the GetCustomer action
    return View(customer);
}

Methods

When we refer to an action, we are actually talking about a standard .NET method with parameters, return values, and attributes just like any other in your code.  The only thing that makes it an action is the fact that the method is inside of a controller class.

In the above example code the whole thing can be considered our method, and is probably pretty similar to every other method that you have ever seen or developed.

Results

A result is just another name for the return value of the method.  The only criterion for the return value is that it must be, or inherit from, the type ActionResult.

In the example code above, the result type is ActionResult, but it actually returns an object that inherits from ActionResult called ViewResult.  The ViewResult is created from a protected method available on the controller called View() which does all the necessary instantiating of the ViewResult to be returned.

Filters

The filters are implemented as attributes on the action methods.  There are two types of filters, one for actions and another for results.  The action filter refers to the action method and has two events. One is for custom processing before the action method has been executed and the other is for after the action method has been executed.  The results filter refers to the HTTP response and has the same two events that the action has, one for before the response is sent and one for after the response is sent to the browser.  We are not going to go into great detail about filters in this book, however we will be using them for such things as authorization, caching, and RESTful service results.

In the sample code above, the filter is the attribute called OutputCache.

Selectors

The selectors are implemented as attributes on the action methods.  Since both filters and selectors are implemented using attributes it is often difficult to determine the difference between them, but there is a huge difference.  The selectors are used when the controller factory is trying to determine which action method is the correct one to process the request, so they really have nothing to do with the action method execution, just the selection of the action method by the controller factory.

In the sample code above, the selector is the attribute called AcceptVerbs.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 5 Comments »

January 12th, 2009

Introducing the ASP.NET MVC (Part 6) - The View

This is a continuation of my Introduction to ASP.NET MVC series. As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2. I am doing this so I can receive feedback on this chapter as early as possible. Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

The View

In ASP.NET MVC, the view is the presentation of your applications’ business layer or model.  Typically with ASP.NET MVC this is HTML, but your view can be rendered in any form that can be transmitted over the internet, including JSON, XML, binary, RSS, ATOM, and your own customized protocol if you have one.

These dynamic ranges of views that, allow it to be capable of such a wide range of delivery types in the ASP.NET MVC Framework are because of a provider engine appropriately called the view engine.  The view engine is responsible for taking the controller and action names and then delivering the right view based on these names.

When I talk about the view engine from here on forward, I will be specifically referring to the ASP.NET MVC implementation, called WebFormViewEngine, which is based on the aspx, ascx, and master files.  There are many other types of view engines, such as Brail, NHaml, NVelocity, and XSLT that are available from the MVC Contrib project located at www.codeplex.com/mvccontrib, if you are interested in learning more.

ViewEngine

The default ViewEngine in the ASP.NET MVC Framework, the WebFormViewEngine, uses a hierarchy of folders and aspx and ascx files when rendering HTML pages to the browser.  The WebFormViewEngine, uses the standard ASP.NET Web Forms rendering engine that has been present in the framework since version 1.0, however the emphasis has been moved from control based rendering to an inline code based rendering that is reminiscent of its predecessor, plain old ASP.

Let’s take another look at the hierarchy that the default view engine uses, as seen in Figure 2-24.

Figure 2-24

Figure 2-24

The view engine treats aspx and ascx files almost equally, so that it is possible to render your HTML from an ascx or user control file, in the same way that an aspx or page file works.  As you can probably imagine there needs to be a hierarchy or order to which an aspx or ascx file is picked from the controller or Shared directory in Figure 2-24.  The default ASP.NET MVC view engine uses the following lookup order, from top to bottom, when trying to determine which view to render.

  1. ~/Views/{controller}/{action}.aspx
  2. ~/Views/{controller}/{action}.ascx
  3. ~/Views/Shared/{action}.aspx
  4. ~/Views/Shared/{action}.ascx

What this above lookup order means is that:

  • Controller directories are always checked before the Shared directory.
  • aspx or page files are always checked before the ascx or user control files.

The above lookup order even applies to master files, which allows you to select the master page template that you want to render with your view.  The lookup order that the master pages follows is slightly different than the page and user controls:

  1. ~/Views/{controller}/{master_name}.master
  2. ~/Views/Shared/{master_name}.master

Now that we have learned how view pages, controls, and master page are selected let’s take a little closer look at the files themselves.

ViewMasterPage, ViewPage, and ViewUserControl

In ASP.NET MVC there are three new takes on objects that you are probably familiar with from ASP.NET Web Forms.  These types probably come as no surprise, given what we just covered in the ViewEngine section and the title of this section, but they are as follows listed with their Web Form equivalent.

MVC Web Forms Description
ViewMasterPage MasterPage Responsible for providing a template to the page object.
ViewPage Page Responsible for the main content of the web page being viewed.
ViewUserControl UserControl This is used to sub-divide content and provide a modular

These object types in MVC are actually inherited from their Web Form counterparts, because they rely on their built in execution, in the ASP.NET Core, as a way of delivering the content through the servers such as IIS.  So all the interfaces you have become acustumed to (i.e. User, Context, Request, Response, IsPostBack, etc.) are still available in the MVC version of the page, user control, and master page.

However when developing for MVC there is a primary difference in the way in which an MVC view is constructed in the code-behind compared to its Web Form counterpart.  The best way to illustrate this difference is by showing you all that this required to have a fully functional view in MVC:

public partial class MyViewPage : ViewPage
{
}

Yup, that is all that is required, pretty cool huh?  This is possible because all the application logic that used to be in button clicks, post backs, and other event actions, has been moved to the controller actions.

It is actually considered bad practice in ASP.NET MVC to put any code in the code-behind file.

We have covered the basics of how views are rendered and found and the differences between MVC views compared to their Web Form counterparts.  We will be going in to a great depth of detail on programming views in later chapters of this book.  However we are not quite done, there are a couple more basics things I want to cover before moving on to The Controller section.  These include special properties designed to allow easy communication between the model, controller and view.

I have broken up the properties in to logical sections, so that we can discuss the purpose and intended use of each of them as envisioned by the ASP.NET MVC team.

ViewData, and Model

The ViewData property is used to store and transmit data from the model and controller to the view for rendering.  It can either be used as a Dictionary object, such as:

<%= ViewData["text"] %>

Or as a typed model object, such as:

<%= ViewData.Model.CustomerID %>

That is defined using generics in the inheriting object, such as a Customer type in the ViewPage:

public partial class EditCustomer : ViewPage<Customer>

It is a very versatile collection that is available to both the views and the controllers, and is passed via the ViewContext, which inherits from the ControllerContext.

TempData

The TempData property is a session-backed temporary storage dictionary, much like ViewData, which is available for the current request, plus one.  What this means is that any data you store in the TempData is kept in the session storage for one additional request, beyond the one you’re currently processing.

You may be scratching your head like I was when I first learned about TempData, and wondering why this would be important enough to include in the framework.  There is actually a very simple answer to this question, it allows you to pass data across requests, much like you have been accustomed to with the ViewState that is used in Web Forms.  It is also great for passing data between redirects, say you have the following scenario:

A user comes in to your site unauthenticated and you have to redirect them to the login page, but you what to display a message saying they need to login before viewing the content, but that message should display only when they don’t visit the login page directly.

Previously to accomplish this type of process you had to jump through hoops to determine if the user came from another page on your site, by checking the referrer or some other custom process that you had to come up with.  Additionally even after you got this done it was hard to customize that message to give the user some indication of where they came from or are going after they login.  TempData really comes to the rescue in this case, because you can the following is the only code that you need to display that message:

<% if (TempData["Message"] != null) { %>
<div class="message"><%= TempData["Message"] %></div>
<% } %>

You can even put this code in your master page so that you can display a message to your user on any page in your site, and all that you need is these three lines of code in the view.

HTML and AJAX Extension Methods

The HTML and AJAX extension methods provide a way to generate snippets of code for such things as form inputs and links.  For example if you wanted to generate a text box with the name attribute set to CustomerName, you just need to put the following in your view:

<%= Html.TextBox("CustomerName") %>

And it will generate the following HTML:

<input type="text" name="CustomerName" id="CustomerName" value="" />

As one added feature if you actually wanted to render the page with CustomerName already filled in, you would just need to set ViewData["CustomerName"], in the controller, equal to whatever you want to be rendered in the HTML.

An extension method for all of the form inputs available through HTML, have been provided with the ASP.NET MVC Framework, plus some other extensions such as AJAX implementations of the form inputs, and anchor link generation for controller actions.  Ninety-nine percent of all the HTML and AJAX extension methods that you will need to generate a web page have been provided in the framework, and if there is something that you must have, you can extend your own method from the HTML helper by doing the following:

public static string MyCustomControl (this HtmlHelper html, string name)

The this keyword is what is used to add these custom methods on to the HtmlHelper, which is represented as Html in the view pages, we will cover extension methods in greater detail later on in Chapter 6.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 11 Comments »

January 11th, 2009

Introducing the ASP.NET MVC (Part 5) - The Model

This is a continuation of my Introduction to ASP.NET MVC series. As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2. I am doing this so I can receive feedback on this chapter as early as possible. Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

The Model

In ASP.NET MVC, the model referrers to your applications’ business layer or domain objects.  These objects are responsible for persisting the state of your application, which is often, but note necessarily, stored in a database.

There really isn’t much to explain about the model as it relates to the ASP.NET MVC Framework, because it is based on your implementation and design of your business layer.  You can use any design pattern, methodology, and or custom process to accomplish the creation of the model:

  • DDD (Domain Driven Design)
  • TDD (Test Driven Design)
  • ALT.NET
  • Repository Pattern
  • Service Pattern
  • Specification Pattern
  • POCO (Plain Old CLR Object)
  • LINQ To SQL
  • ADO.NET Entity Framework
  • NHiberante
  • Data Tables
  • Your custom own business layer
  • Any combination of the above.

The point behind all of this is to try to demonstrate that it is up to you to define the model.  It is up to you to make the best decisions related to your requirements.  It is up to you to make it as simple or as complex as needed.  Everything is up to you, when we are talking about the M in MVC.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 6 Comments »

January 6th, 2009

Introducing the ASP.NET MVC (Part 4) - Your First ASP.NET MVC Project

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

Your First ASP.NET MVC Project

To create your first ASP.NET MVC Project, you only need the prerequisites listed in the previous section.  To start, you first need to open Visual Web Developer 2008 or any version of Visual Studio 2008.

For the purpose of this section I will be using Visual Studio 2008 Team Development Edition.  I have, however, verified that this process works on Visual Web Developer 2008 SP1, Visual Studio 2008 Professional, and Visual Studio 2008 Team Development Edition.

After Visual Studio is open we need to create a new project (File > New > Project), see Figure 2-16 for an example.

Figure 2-16

Figure 2-16

Doing this will put you in the New Project screen, which you will then select your preferred language (in our case Visual C#).  From there we need to select Web @@> ASP.NET MVC Web Application, as depicted in Figure 2-17.

Figure 2-17

Figure 2-17

I am going to leave all the project configuration fields set to their default values as shown in Figure 2-17, you may configure them however you desire.  When you are done click OK, and you will see the screen shown in Figure 2-18.

Figure 2-18

Figure 2-18

You have probably not seen a screen like this before, even if you have done ASP.NET Web Forms development.  It is totally new to the ASP.NET MVC project creation process, and it automatically creates a unit testing project based on the default MVC project.

As an added feature it also allows you to select the testing framework that you would like to use, even non-Microsoft ones, such as NUnit, MbUnit, XUnit, Visual Studio Unit Test, and any others that decide to provide an interface to this Visual Studio process.

You can choose to create a unit project, or wait till a later time if desired.  For the purpose of this demonstration I am going to create a unit test project using MbUnit v3 from the drop down.  When you are done click OK, and you will see a Solution Explorer that looks like Figure 2-19.

Figure 2-19

Figure 2-19

This is what the default folder and file structure looks like for the ASP.NET MVC project, it has a separate folder for Models, Views (as seen in Figure 2-21), and Controllers (as seen in Figure 2-20).  As well as a set of default folders for storing JavaScript, CSS, or anything else you would want to deliver from your web application (as seen in Figure 2-22).

Figure 2-20

Figure 2-20

There are two controllers created by default.  The HomeController is used to render the home page and the about page.  The AccountController is used to authenticate a user with the standard ASP.NET membership provider.  These two controllers provide you everything you need to create a very basic web application.

Figure 2-21

Figure 2-21

For the views there is a mirroring of the controllers created.  One for Account and another for Home, in these folders there are aspx files that are call views.  Each of these views mirror an action method from the controller, by default.  As you will see later in this book there is a many to many relationship between the views and action methods.  In that an action method can map to multiple views and a view can have multiple action methods that use it.  Let’s not get to in-depth about the mapping of views and action methods at this point, because we will cover this in great detail later in this chapter and future chapters when implementing our application.

There is also a shared folder called Shared, which is, for lack of a better word, shared between all of the controllers and can be called by any of the controllers in the project.

The last thing I want to talk about before we move on to the rest of the files in the solution, is what appears to be a rouge Web.config file located under the Views directory.  This is a deliberate and strategic Web.config that is used, in addition to the one in the root, to block access to all the aspx files from getting accessed directly.  This Web.config file contains the following configuration information:

<?xml version="1.0"?>
<configuration>
	<system.web>
		<httpHandlers>
			<remove verb="*" path="*.aspx"/>
			<add path="*.aspx" verb="*" type="System.Web.HttpNotFoundHandler"/>
		</httpHandlers>
	</system.web>

	<system.webServer>
		<validation validateIntegratedModeConfiguration="false"/>
		<handlers>
			<remove name="PageHandlerFactory-ISAPI-2.0"/>
			<remove name="PageHandlerFactory-ISAPI-1.1"/>
			<remove name="PageHandlerFactory-Integrated"/>
			<add name="BlockViewHandler" path="*.aspx" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
		</handlers>
	</system.webServer>
</configuration>

It contains both configuration information for IIS 7, <system.webServer />, and IIS 6 and lower, <system.web />.  So you will be covered on which ever server you decide to deploy your MVC application to.

Figure 2-22

Figure 2-22

The rest of the solution files, includes JavaScript, Style Sheets, and other ASP.NET files that you should be familiar with.  The JavaScript files that are included by default are Microsoft AJAX and jQuery, as well as debug version of the files.

In the Fall of 2008, Microsoft announced a partnership with jQuery (www.jquery.com) to provide support and deliver jQuery with Visual Studio 2010 and some key projects.  One of the key projects that jQuery will be delivered with, is ASP.NET MVC.

If you are going to be using jQuery heavily in your application, as we are in this book, I highly recommend that you download the latest version of jQuery and the Visual Studio Intellisense Documentation for jQuery.  jQuery is constantly being developed and new features are getting added all the time, so it really pays to be running the latest version, so be sure to get the latest production and development files:

http://www.jquery.com

There are some standard ASP.NET files that we have all seen before, but I would like to take this opportunity to give you a quick overview of the purpose of the Global.asax and Default.aspx files.  These two files have a special purpose in an MVC application that you should be made aware of.

Global.asax

This is a standard ASP.NET file.  MVC takes advantage of the file to initialize all the URL routes, for mapping actions and controllers to URL’s, when the application is first started, using the Application_Start event handler.

public static void RegisterRoutes(RouteCollection routes)
{
	routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

	routes.MapRoute(
		"Default",
		"{controller}/{action}/{id}",
		new { controller = "Home", action = "Index", id = "" }
	);
}

protected void Application_Start()
{
	RegisterRoutes(RouteTable.Routes);
}

Default.aspx

This is a standard ASP.NET file.  It is not necessary on IIS 7, because of IIS 7’s integrated pipeline.  However you should not worry about it being present on and IIS 7 MVC application because, it will not interfere with the execution of the code.  The sole purpose, of this file, is to handle root requests on IIS 6 and lower, it does this using the Page_Load event handler of the page and forcing the request through the MvcHttpHandler, instead of rendering the page, which is empty.  The Page_Load event handler is shown in the code below.

public void Page_Load(object sender, System.EventArgs e)
{
	HttpContext.Current.RewritePath(Request.ApplicationPath);
	IHttpHandler httpHandler = new MvcHttpHandler();
	httpHandler.ProcessRequest(HttpContext.Current);
}

The final thing I want to cover is what the default ASP.NET MVC application design looks like when running in a browser, you can see an example of this in Figure 2-23.

Figure 2-23

Figure 2-23

It is a pretty basic layout, but it is a good example of the Home and Account controllers and can be used to render to and interact with the browser.

In the rest of this chapter, we are going to cover the basics of the ASP.NET MVC Framework, with a specific focus on the Model, View, and Controller.  So let’s get started.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 6 Comments »

January 5th, 2009

Introducing the ASP.NET MVC (Part 3) - Installing the Prerequisites

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

Installing the Prerequisites

To start developing ASP.NET MVC and to run the code in this book, you will need the following prerequisites installed on your system:

  1. Visual Web Developer 2008 Express Edition SP1
    http://www.microsoft.com/express/download/
  2. SQL Server 2005 Express Edition
    http://www.microsoft.com/express/sql/download/
  3. Micorosft.NET Framework 3.5 SP1
    http://msdn.microsoft.com/en-us/netframework/
  4. Microsoft ASP.NET MVC
    http://www.asp.net/mvc/

You can cover prerequisites 1-3 by downloading just the Visual Web Developer 2008 Express Edition installation file, which includes .NET 3.5 SP1 by default and SQL Server 2008 Express Edition as an optional add-on during the install process.

If you have already installed all of the software above, or have an edition of the software that is better you may skip to the Your First ASP.NET MVC Project section.

Read the rest of this entry »

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 6 Comments »

December 29th, 2008

Introducing the ASP.NET MVC (Part 2) - ASP.NET MVC vs. ASP.NET Web Forms

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

ASP.NET MVC vs. ASP.NET Web Forms

As you have seen, in the previous section, and can probably imagine MVC is going to be an architectural pattern that is going to be around for the foreseeable future, especially on the web.  So it is very important to internalize and understand the major differences between ASP.NET MVC and the older ASP.NET Web Forms.

ASP.NET Web Forms

Starting with the .NET Framework Version 1.0, in January 2002, Web Forms was Microsoft’s first real attempt to provide a first class web application layer that was both robust and flexible enough to meet the demands of the web at that time.  ASP.NET Web Forms has proven to be a mature technology that runs small and large scale websites alike.  Web Forms, was built around the Windows Form construction, where you had a declarative syntax with an event driven model.  This allowed visual designers to take full advantage of the drag and drop, WYSIWYG, interface that they had become accustom to under Windows Forms development in Visual Studio 6.0.  In that they only needed to drop controls onto the ASP.NET page and then wire up the events, as was common in Visual Basic 6.0 development at the time. This made Web Forms a natural choice for Windows Forms developers, because the learning curve was low and the need to understand HTML and many of the web centric technologies almost zero.  Web Forms have many strengths and weaknesses:

Strengths
  • Mature technology
  • Provides very good RAD development capabilities
  • Great WYSIWYG designer support in Visual Studio
  • Easy state management
  • Rich control libraries from Microsoft and third party vendors
  • Abstracts the need to understand HTTP, HTML, CSS, and in some cases JavaScript
  • ViewState and PostBack model
  • A familiar feel to Windows Forms development

Web Forms has grown so much since 2002 because it has the ability to do great things that are often much harder to accomplish in other frameworks.

Weaknesses
  • Display logic coupled with code, through code-behind files
  • Harder to unit test application logic, because of the coupled code-behind files
  • ViewState and PostBack model
  • State management of controls leads to very large and often unnecessary page sizes

Web Forms is not all roses and buttercups, there are some serious setbacks that usually show up when you are trying to optimize your code for scalability, the biggest problems are the ViewState and PostBack model.  ViewState is a way to store the state of the controls, such as data, selections, etc, which is needed to preserve the Windows Form like development habits of the developers.  ViewState was necessary, because the web is a stateless environment meaning that when a request comes in to the server it has no recollection of the previous request.  So in order to give state to a stateless environment you need to communicate the previous state back to the server, in Web Forms this was accomplished using hidden <input /> fields that can become ridiculously large. This increased size becomes apparent when server controls such as GridView are added to the page.  PostBack was another creation to facilitate the Windows Form development feel, it renders JavaScript for every subscribed event, which leaves web developer less control over how the browser communicates with the server.

ASP.NET MVC

ASP.NET was often overlooked as a viable platform for modern highly interactive websites that required a very granular control over the output of the HTML, because of the lack of control over the rendered HTML.  This granularity of control was sacrificed in Web Forms to make if more like Windows Forms development, in other words easier for the drag and drop developers.  This lack of control over the HTML rendering forced developers to move the platforms such as PHP and Ruby on Rails, which offered the level of control they required and the MVC programming model that provided a necessary separation of concerns for their highly complex web applications.

This led Microsoft to announce in the Fall of 2007 that they were going to create a platform based off of the core of ASP.NET that would compete against these other popular MVC web centric platforms.  Microsoft implemented ASP.NET MVC to be a modern web development platform that gives a ‘closer to the metal’ experience to the developers that program with it, by providing full control and testability over the output that is returned to the browser.  This is the main and most important different between Web Forms and MVC, in my opinion.  MVC has many strengths and weaknesses

Strengths
  • Provides fine control over rendered HTML
  • Cleaner generation of HTML (well as clean as you keep it)
  • Clear separation of concerns
  • Provides application layer unit testing
  • Can support multiple view engines, such as Brail, NHaml, NVelocity, XSLT, etc.
  • Easy integration with JavaScript frameworks like jQuery or Yahoo UI frameworks
  • Ability to map URLs logically and dynamically, depending on your use
  • RESTful interfaces are used by default (this helps out with SEO)
  • No ViewState and PostBack model
  • Supports all the core ASP.NET features, such as authentication, caching, membership, etc.
  • Size of the pages generated typically much smaller because of the lack of the ViewState
Weaknesses
  • Not event driven by the framework, so it maybe more difficult for ASP.NET Web Form developers to understand
  • Requires the need to understand, at least at the basic level, HTTP, HTML, CSS, and JavaScript
  • Third party library support is not as strong
  • No direct upgrade path from Web Forms
  • No ViewState and PostBack model (makes it more difficult to preserve state)

As you can see the pros and cons of MVC have to be weighed just as much as Web Forms, and MVC is not always the logical choice.

How do I choose?

It’s up to you to decide and you choice needs to be weighted with a number of other factors, such as team and application requirements, when deciding which ASP.NET technology to implement.  I have developed the following worksheet that will hopefully help you decide, when you need to make this decision.

The Worksheet

This worksheet is meant to be a guide for when you are trying to choose between Web Forms and MVC.  The values in the Value column are representations of how easy it would be to accomplish the requirement in either MVC or Web Forms.

The values range from 0 to 30, zero being no effort to implement and 30 requiring a great amount of effort to implement.  If the value is positive then it is an advantage to MVC, if the value is negative then it is an advantage to Web Forms.  For example if the value is, +4, then the requirement is more suited for MVC, and it would take a little work to get it to work as easily in Web Forms.  Alternatively, if the value is, -25, then the requirement is definitely suited for Web Forms, and it would take a lot of work to get the requirement to work with MVC.

Requirement Value Selection
Clean HTML Rendering

+4

Use RAD Designers

-5

Use TDD (Test Driven Design)

+8

Testability

+7

Data-heavy application

-10

Upgrade from Web Forms

-25

Need event-driven model compared to Windows Forms programming model

-7

Work on an Agile Team

+4

Need separation of concerns

+10

Creating a proof of concept or prototype

-6

SEO

+3

RESTful interface

+3

Need to preserve state of request

-2

Building an Internet Application

+3

Building an Intranet Application

-3

Need to support multiple views of the same application through mobile, web, and REST API

+7

Need to use existing third party controls for ASP.NET Web Forms

-10

Need control over the URL that is generated

+5

So after you make your selection and add up all the values, you should end up with a number representing your project.  Check that number against the table below, and you should have your answer as to which technology, MVC or Web Forms, is best for your project and team.

Value Reasoning

< -50

No Brainer, go with Web Forms

-25

Very Strongly Web Forms

-10

Strongly Web Forms

-3

Slightly Web Forms

0

It is a tossup between Web Forms and MVC

+3

Slightly MVC

+10

Strongly MVC

+25

Very Strongly MVC

> +50

No brainer, go with MVC

I want to mention one last thing if you have want to do new development in MVC, but you have to maintain some legacy Web Form pages, you can mix MVC and Web Forms in the same application. You just need to be aware of the differences between the two, and that you probably will not be able to share any of the Web Form front end code with MVC, such as Themes, Master Pages, and User Controls.

As you probably can guess by the name of this book, The Beer House application landed well in to the MVC side of the worksheet.  Which probably doesn’t surprise you if you are reading this book!

Feel free to use the above decision table and modify it for your own teams’ decision process.  The information provided above however should arm you with most of the important information that you need to know when deciding which way your project should go technology wise.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 11 Comments »

December 14th, 2008

Introducing the ASP.NET MVC (Part 1) - The Model-View-Controller Pattern

About a month and a half ago I announced that I am writing a book, I was really overwhelmed by the amount of support that I received from this announcement.  Both myself and Al are really looking forward to the day when this book ships, and we start receiving real feedback on all our hard work.  However, both of us would like to start receiving feedback as soon as possible, so…

In an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

The Model-View-Controller Pattern

The Model-View-Controller architectural pattern has been around since 1978 and was first described by Trygve Reenskaug while working on a programming language called Smalltalk at Xerox PARC.  The implementation was first described in his now famous paper on the subject, titled Applications Programming in Smalltalk-80: How to use Model-View-Controller, published on December 1979, and has been popping its head up in many different ways and forms since the original paper was published.  Reenskaug maintains a page that explains MVC in his own words (http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html), and contains his publications on the subject; it is well worth the read and is only two pages long.

The MVC pattern has been implemented in most every programming language that is in use today, including ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby, Smalltalk, XML, and of course .NET.  In fact in November, 2002 the W3C, the main international standards body for the World Wide Web, voted to make the MVC pattern part of their XForms specification, which will be integrated directly into the XHTML 2.0 standard.

Reenskaug explains on this site that “The essential purpose of MVC is to bridge the gap between the human user’s mental model and the digital model that exists in the computer.”  As illustrated in Figure 2-1.

Figure 2-1

Figure 2-1

He goes on to explain that “The ideal MVC solution supports the user illusion of seeing and manipulating the domain information directly.  The structure is useful if the user needs to see the same model element simultaneously in different contexts and/or from different viewpoints.”  This is important because it puts the emphasis not on the application, but how the user perceives the data, the controller and view is only a means to the end of allowing the user to visualize the model in other words.

Reenskaug defines the Model-View-Controller in the following way.

  • Model: Represents knowledge.  A model can be in the simplest case a single object in your application, or in a complex case combination of objects.  It should represent the world as seen by the developer for the application that is being developed, in other words your database or domain.
  • View: Visual representation of the Model.  It should highlight the certain aspects of the model while minimizing the others where possible.  According to Reenskaug it should act as a presentation filter.  What he describes as a presentation filter is the notation of a contract created between the Model and the View that will provide the parts of the model requested for the presentation by the View.
  • Controller: A controller provides a link between the user and the system.  It provides the user with actions that can be taken against the Model, which in other words creates a set of inputs that can be acted upon and represented to the user in one or more ways through a View.

Bringing MVC Down To Earth

The concepts and ideas behind MVC were honestly a little abstract for me when I was first getting started, it took me a while to understand how the Model, View, and Controller where suppose to work together to create an application.  Unfortunately at the time I didn’t have a great example that clearly defined the lines between the different parts of the Model, View, and Controller, so I had to learn the hard way.  Lucky for us Jeff Atwood, of codinghorror.com fame, provided an example that really struck a chord with me.  Figure 2-2 is a visual representation of his example.

Figure 2-2

Figure 2-2

This example almost perfectly represents MVC in a way that any web developer with only basic knowledge of HTML and CSS can understand.

  • Model: The HTML is the “skeleton” or definition of the data to be displayed to the user.
  • View: The CSS is the “skin” that gives the HTML a visual presentation.  The CSS can be swapped out to view the original content in a different manor, without altering the underlying Model.  They are relatively, but not completely, independent of each other.
  • Controller: The browser is responsible for combining the CSS and HTML, into a final representation that is rendered out to the screen in the form of pixels.  It gathers input from users, but it is restricted to the input defined by the HTML in the form of input, select, textarea, and button DOM objects.

I find this to be an awesome acknowledgement to the success of the Model-View-Controller, because the browser is a natural interface for a computer user that wants to visualize the World Wide Web.  It successfully maps the Mental Model, from Figure 2-1, that a designer envisioned as an interface for the user to the Computer Model, which a developer coded for use on the World Wide Web.  So I hope this helped you visualize MVC in a way that helps you break out and understand the concepts behind the Model, View, and Controller.  If you would like to read Jeff’s full article it is available at http://www.codinghorror.com/blog/archives/001112.html.

For the purpose of this book we are going to define MVC as the following:

  • Model: The classes which are used to store and manipulate the state of the database, through our domain objects, combined with some business logic.
  • View: The user interface parts, coded in HTML, necessary for rendering the Model to the user.  It may also render the Model as XML or JSON if needed programmatically by JavaScript.
  • Controller: The application layer that will accept the input and save that information to the database through our Model.  It will also contain a small amount of business logic necessary for controlling and validating the inputs.  The controller will also decide which view to render, the HTML, XML, or JSON depending on the form that was requested by the browser.

The above definition of MVC for our application, The Beer House, is an almost exact representation of MVC as defined by the ASP.NET MVC team.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, News, Personal, Review, SEO | kick it on DotNetKicks.com | Bookmark | View blog reactions | 7 Comments »

October 28th, 2008

ASP.NET MVC Has Changed My Life

Lately I have been neglecting my blog and not posting as often as I would have liked.  I have had some very exciting things start up, at the begining of the summer, in my life that 6 months ago I would have said “no way is that going to happen.”  These new adventures are the growing popularity of my blog, public speaking engagements, and a new book I was asked to write on ASP.NET MVC. Many of you picked up on the fact that I was writing a book based on my profile on the Philly.NET website, but I had officially announced it until this post.  Many of my friends and family don’t even known I am writing a book so feel lucky in knowning you guys are some of the first people to know.

As you can imagine writing a book is about the same as writing a detailed blog post only 10,000% harder, because a two page post now needs to be extended out in to a 600 page book that needs to flow just as easily as the 2 page post did.  Luckily for me my best friend, Al Katawazi who I have known since 9th grade, is also a pretty decent programmer from the Rochester, NY area and he agreed to help me get this book out the door by the end of the year to align with the ASP.NET MVC release.

The book is titled ASP.NET MVC Website Programming: Problem - Design - Solution, and can currently be found at the following places for pre-order:

Sorry about the lack of a book picture, I haven’t had the time to go out and get a professional photo taken of me for the cover.  That will be coming pretty soon.

The current description of the book according to the Wiley site is, which also pretty well sums up the book as a whole in my opinion:

The utility of this book will be a nuts and bolts how-to guide on creating a website using MVC.  It will solve some of the most common problems that programmers run into when creating their first application or when trying to upgrade a current application to this new technology.

The book, much like the first one, will break each section down into 3 parts: the Problem, the Design, and the Solution.  For the most part, the chapter outline will be mostly the same, because the majority of the chapters are still just as important now to web developers as they were when the book was originally written. However, this edition includes MVC updates within these chapters.

Some of the site features covered in the book and provided in the TheBeerHouse example/framework code are:

  • registration and membership system and user-selectable themes
  • content management system for articles and photos
  • polls, mailing lists, and forums
  • e-commerce store, shopping cart, order management with real-time credit-card processing
  • localization

In building and working with these features the site developer will learn:

  • Master pages, themes, membership, and profiles
  • Server-side UI controls
  • Compilation, deployment, instrumentation, error handling and logging
  • Data access
  • The MVC (model view controller) approach to separation of the site UI and presentation layer from the pluggable data access layer and business logic layer

The code for the book will be published to CodePlex probably this weekend, that is if you want a sneak peak at what has taken me away from posting on my blog for the past couple of months.

http://www.codeplex.com/TheBeerHouse

If you want to wait for the book I totally understand, because who wants to spoil Christmas by peaking at the presents.  I am just kidding, I don’t think my code can be compared to Christmas morning, but maybe the 3rd Tuesday morning of October.

All kidding aside I really have to thank Scott Guthrie, Phil Haack and the whole ASP.NET MVC, because with out the great support for this product and the fore sight of Microsoft to actually create a product that ALT.NET developers like my self have been crying out for. I wouldn’t be in this place in my life.  I never thought that an interest in a small alpha release of a product back in December 2007 would lead me to writing a book, but it has been a great ride and I only hope it continues.

I am going to continue to try and post content that is useful to other developers like myself as much as I can, but please bear with me until the end of the year when all my chapters will be written and the book will be getting ready for the presses.

Tags: , , , ,

Posted in News, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 7 Comments »

October 16th, 2008

ASP.NET MVC Goes Beta (Part 2)

From what I can tell ASP.NET MVC Beta is just ASP.NET MVC PR5 with a couple bug fixes.  So the good news is that the interface has finally solidified and we shouldn’t see anymore breaking changes before the final release.

New features:

  • MvcFutures.dll is not included in the beta (as it wouldn’t be included in the final release)
  • The Beta installer installs the ASP.NET MVC assemblies (System.Web.Mvc.dll, System.Web.Routing.dll, and System.Web.Abstractions.dll) into the GAC.
  • New Simple Membership Features in the Default Project Template
  • New Filter Types for Authorization and Exception Handling
  • New Output Cache Filter
  • Changes for ASP.NET AJAX
  • Namespaces in Routes
  • New Interface for Enhanced Testability of TempData
  • ActionInvoker Extensibility Improvements
  • ViewDataDictionary (minor change)
  • ViewEngine Improvements
  • Helper Improvements
  • Controller and Filter Improvements

Bug fixes:

  • Fixed a bug in which the ignore-routes setting (created by using the IgnoreRoute extension method) affected URL generation.
  • Fixed a view engine caching bug when the application is not in debug mode (that is, when debug=”false” is set in the Web.config file). This bug occurred if different action methods in different controllers had the same name. In that case, an action method could render the view for the wrong controller.
  • Fixed a bug in OutputCacheAttribute in which cached authenticated content did not require authentication. Even though the content is cached, if it requires authentication, the user should be required to authenticate first before seeing the cached content.
  • Fixed a bug in which RenderPartial does not work when tracing is turned on.
  • Fixed a bug in the Html.TextArea helper method in which an overload was not looking in ViewData for its value when the provided value is null.
  • Fixed the OutputCacheAttribute.CacheProfile property so that it works in Medium Trust.

Update: Derik at Dimecast.net has found some things I overlooked.  Nothing life changing, just some house cleaning on the teams part.

Tags: ,

Posted in ASP.NET | kick it on DotNetKicks.com | Bookmark | View blog reactions | 3 Comments »