Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘asp.net mvc’

ASP.NET MVC 2 RC2 (Release Candidate 2) Released

ASP.NET MVC 2 is a framework for developing highly testable and maintainable Web applications by leveraging the Model-View-Controller (MVC) pattern. The framework encourages developers to maintain a clear separation of concerns among the responsibilities of the application – the UI logic using the view, user-input handling using the controller, and the domain logic using the model. ASP.NET MVC applications are easily testable using techniques such as test-driven development (TDD).
The installation package includes templates and tools for Visual Studio 2008 SP 1 to increase productivity when writing ASP.NET MVC applications. For example, the Add View dialog box takes advantage of customizable code generation (T4) templates to generate a view based on a model object. The default project template allows the developer to automatically hook up a unit-test project that is associated with the ASP.NET MVC application.
Because the ASP.NET MVC framework is built on ASP.NET 3.5 SP 1, developers can take advantage of existing ASP.NET features like authentication and authorization, profile settings, localization, and so on. Download it at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7aba081a-19b9-44c4-a247-3882c8f749e3&displaylang=en

What is new:

  • The new ASP.NET MVC 2 validation feature now performs model-validation instead of input-validation (this means that when you use model binding all model properties are validated instead of just validations on changed values of a model).  This behavior change was based on extensive feedback from the community.
  • The new strongly-typed HTML input helpers now support lambda expressions which reference array or collection indexes.  This means you can now write code like Html.EditorFor(m=>m.Orders[i]) and have it correctly output an HTML <input> element whose “name” attribute contains the index (e.g. Orders[0] for the first element), and whose “value” contains the appropriate value.
  • The new templated Html.EditorFor() and Html.DisplayFor() helper methods now auto-scaffold simple properties (and do not render complex sub-properties by default).  This makes it easier to generate automatic scaffolded forms.  I’ll be covering this support in a future blog post.
  • The “id” attribute of client-script validation message elements is now cleaner.  With RC1 they had a form0_ prefix.  Now the id value is simply the input form element name postfixed with a validationMessage string (e.g. unitPrice_validationMessage).
  • The Html.ValidationSummary() helper method now takes an optional boolean parameter which enables you to control whether only model-level validation messages are rendered by it, or whether property level validation messages are rendered as well.  This provides you with more UI customization options for how validation messages are displayed within your UI.
  • The AccountController class created with the default ASP.NET MVC Web Application project template is cleaner.
  • Visual Studio now includes scaffolding support for Delete action methods within Controllers, as well as Delete views (I always found it odd that the default T4 templates didn’t support this before).
  • jQuery 1.4.1 is now included by default with new ASP.NET MVC 2 projects, along with a –vsdoc file that provides Visual Studio documentation intellisense for it.
  • The RC2 release has some significant performance tuning improvements (for example: the lambda based strongly-typed HTML helpers are now much faster).

Server Side Validation With ASP.NET MVC

aspnet_mvc When you’re using ASP.NET MVC, there’s no validation controls for you compared to ASP.NET WebForms. It is always important to validate data on the server as well as the client. Back when Dynamic Data was being developed, a set of attributes was created to help tell the Dynamic Data folks about validation and other metadata so they could create smart scaffolds. What this allows you to do is decorate your classes or properties with validation attributes. A project that is available on CodePlex gives you the power to inject this validation into your MVC project. The CodePlex project can be found here. The end results are you can decorate your classes with some of the following attributes to perform server side validation:

  • Required – a required field
  • StringLength – allows you to set the minimum and maximum length of a string
  • RegularExpression – performs regular expression validation

When you use this your validation classes will look like the following example:

Via C#

   1: public class EmployeeMetaData

   2: {

   3: [Required]

   4:       [StringLength(10, ErrorMessage="Given name cannot be more than 10 characters")]

   5:       public string GivenName { get; set; }

   6:  

   7:       [Required]

   8:       public string Surname { get; set; }

   9: }

Via VB

   1: Public Class EmployeeMetaData

   2: Private privateGivenName As String

   3: <Required, StringLength(10, ErrorMessage:="Given name cannot be more than 10 characters")> _

   4: Public Property GivenName() As String

   5:       Get

   6:             Return privateGivenName

   7:       End Get

   8:       Set(ByVal value As String)

   9:             privateGivenName = value

  10:       End Set

  11: End Property

  12:  

  13:        Private privateSurname As String

  14:        <Required> _

  15:        Public Property Surname() As String

  16:              Get

  17:                    Return privateSurname

  18:              End Get

  19:              Set(ByVal value As String)

  20:                    privateSurname = value

  21:              End Set

  22:        End Property

  23: End Class

ASP.NET MVC 2 and Visual Studio 2010

Unfortunately, because Visual Studio 2010 Beta 2 and ASP.NET MVC 2 Beta share components which are currently not in sync, running ASP.NET MVC 2 Beta on VS10 Beta 2 is not supported. Regarding Visual Studio 2010 and .NET 4 support, that is unfortunately not a feasible option. The most recent public release of VS2010 and .NET 4 is Beta 2. However, our internal builds of MVC 2 for VS2010 and .NET 4 depend on features that were available only after Beta 2. In other words, if we released what we have right now for VS2010 and .NET 4 then it wouldn’t even run.

The good news is that the Visual Studio 2010 Release Candidate will include a newer version of ASP.NET MVC 2. 

Highlights

As you might expect from a release candidate, most of the work focused on bug fixes and improvements to existing features. We also spent a lot of time on performance profiling and optimization.

Much of the focus on this release was in the client validation scripts. For example, the validation script was moved into its own file and can be included at the top or bottom of the page. Client validation also now supports globalization.

The other change related to validation is that the ValidationSummary now supports overloads where only model-level errors are displayed. This is useful if you are displaying validation messages inline next to each form field. Previously, these messages would be duplicated in the validation summary. With these new changes, you can have the summary display an overall validation message (ex. “There were errors in your form submission”) as well as a list of validation messages which don’t apply to a specific field.

What’s Next?

RTM of course! The RTM release of ASP.NET MVC will be included in the RTM release of Visual Studio 2010, which is slated for some time in March. The VS2008 version of ASP.NET MVC 2 might release earlier than that. We’re still working out those details.

asp.net mvc best practices

The ASP.NET  MVC  is becoming more and more popular each day.  As the application grows in size so does the maintenance nightmare.  Following are some of the better practices, that if followed, may help maintain our application and also provides a means of scalability as the demand increases.  Feel free to add/update practices as required.

  1. Isolate Controllers
    Isolate the controllers from dependences on HttpContext, data access classes, configuration, logging etc.  Isolation could be achieved by creating wrapper classes and using an IOC container for passing in these dependencies
  2. IoC Container
    Use an IoC container to manage all external dependencies  The following are some of the wellknown containers/framework.
    1. Ninject
    2. Autofac
    3. StructureMap
    4. Unity Block

  3. No "magic strings"m
    Never use magic string in your code.   More to come on this.
  4. Create a ViewModel for each view
    Create a specialized ViewModel for each view.  The role of ViewModel should only be databinding.  It should not contain any presentation logic.
  5. HtmlHelper
    For generating view html use HtmlHelper.  If  the current HtmlHelper is not sufficient extend it using extension methods.  This will keep the design in check.
  6. Action Methods
    Decorate your action methods with appropriate verbs like Get or Post as applicable.
  7. Caching
    Decorate your most used action methods with OutputCache attribute.

  8. Controller and Domain logic
    Try to keep away domain logic from controller.  Controller should only be responsible for
    1. Input validation and sanitization.
    2. Get view related data from the model.
    3. Return the appropriate view or redirect to another appropriate action method.
  9. Use PRG pattern for data modification
    PRG stands for Post-Redirect-Get to avoid the classic browser warning when refreshing a page after post.  Whenever you make a POST request, once the request complets do a redirect so that a GET request is fired.  In this way when the user refresh the page, the last GET request will be executed rather than the POST thereby avoiding unnecessary usability issue.

  10. Routing
    Design your routes carefully.  The classic route debugger comes to rescue http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

Build your own FaceBook applications with ASP.NET, ASP.NET MVC, WinForms or Silverlight !

Another great project in codeplex: http://facebooktoolkit.codeplex.com/

This toolkit is provided as a Facebook Client Library similar to Facebook’s PHP Client Library or Facebook’s JavaScript library. The goal is to enable .NET developers to quickly and easily leverage the various features of the Facebook Platform. This toolkit has evolved over time with input from the community and from Microsoft. The latest release (v3.0) includes new architectural improvements and provides an asynchronous interface for using the toolkit from Silverlight and from WPF.

The main entry point is the API (Facebook.Rest.Api) class in the Facebook.dll assembly. This class wraps the Facebook REST API and provides an easy to use interface for calling the different methods currently available in the Facebook API. We’ve also provided samples and tools for helping develop Facebook applications in the various .NET platforms including: ASP.NET, Silverlight, WPF and WinForms. Additionally, we’ve provided all the source code for the API, components, controls, and samples for you to explore.

The toolkit is comprised of the following core assemblies:

  • Facebook.dll: This is the main assembly that will be used by all applications. This has all the logic to handle communication with the Facebook application. This assembly also has specific support of XAML applications (Silverlight and WPF) to enhance the Facebook platform to make databinding and data caching easier.
  • Facebook.Silverlight.dll: This is the Silverlight version of the main assembly that will be used by all Silverlight applications. This has all the logic to handle communication with the Facebook application. This assembly also has specific support of XAML applications to enhance the Facebook platform to make databinding and data caching easier. The REST API in this assembly is Asynchronous only.
  • Facebook.Web.dll: This assembly should be used by Canvas applications. The main functionality supported in this assembly is to encapsulate the handshake between the Facebook application and a canvas application (both FBML and IFrame)
  • Facebook.Web.Mvc.dll: Provide a support building canvas applications using ASP.NET MVC. Separated from Facebook.Web.dll to avoid all developers from needing to install the MVC bits.
  • Facebook.Winforms.dll: This assembly provides support for writing Facebook applications using Winform technology. This provides a Component that wraps the API to make it easier to use from Winforms. This also contains some user controls to help display Facebook data easily.

Changes in asp.net MVC Preview 2

Helpers now return an MvcHtmlString object

In order to take advantage of the new HTML-encoding expression syntax in ASP.NET 4, the return type of the HTML helpers is now MvcHtmlString instead of a string. Note that if you use ASP.NET MVC 2 and the new helpers with ASP.NET 3.5, you will not be able to take advantage of the HTML-encoding syntax; the new syntax is available only when you run ASP.NET MVC 2 on ASP.NET 4.

JsonResult now responds only to HTTP POST requests

In order to mitigate JSON hijacking attacks that have the potential for information disclosure, by default, the JsonResult class now responds only to HTTP POST requests. AJAX GET calls to action methods that return a JsonResult object should be changed to use POST instead. If necessary, you can override this behavior by setting the new JsonRequestBehavior property of JsonResult. For more information about the potential exploit, see the blog post JSON Hijacking on Phil Haack’s blog.

Model and ModelType property setters on ModelBindingContext are obsolete

A new settable ModelMetadata property has been added to the ModelBindingContext class. The new property encapsulates both the Model and the ModelType properties. Although the Model and ModelType properties are obsolete, for backward compatibility the property getters still work; they delegate to the ModelMetadata property to retrieve the value.