ASP.NET MVC 3 New Features in Preview 1

Resources:
ASP.NET MVC 3 Preview 1 – MVC-3-Preview-1-Release-Notes.doc
ASP.NET MVC Preview 3 Release – ScottGu
ASP.NET MVC 3 Preview 1 Released : Channel 9 Video and Hanselminutes Podcast 224, Oh My!
ASP.NET MVC 3 Preview 1 Released – Phil Haack

Razor View Engine
The Razor view engine is a new view engine option for ASP.NET MVC that supports the Razor templating syntax. The Razor syntax is a streamlined approach to HTML templating designed with the goal of being a code driven minimalist templating approach that builds on existing C#, VB.NET and HTML knowledge. The result of this approach is that Razor views are very lean and do not contain unnecessary constructs that get in the way of you and your code.

ASP.NET MVC 3 Preview 1 only supports C# Razor views which use the .cshtml file extension. VB.NET support will be enabled in later releases of ASP.NET MVC 3. For more information and examples, see Introducing “Razor” – a new view engine for ASP.NET on Scott Guthrie’s blog.

Dynamic View and ViewModel Properties

A new dynamic View property is available in views, which provides access to the ViewData object using a simpler syntax. For example, imagine two items are added to the ViewData dictionary in the Index controller action using code like the following:

public ActionResult Index() {
     ViewData["Title"] = "The Title";
     ViewData["Message"] = "Hello World!";
}

Those properties can be accessed in the Index view using code like this:

 <h2>View.Title</h2>
 <p>View.Message</p>

There is also a new dynamic ViewModel property in the Controller class that lets you add items to the ViewData dictionary using a simpler syntax. Using the previous controller example, the two values added to the ViewData dictionary can be rewritten using the following code:

public ActionResult Index() {
    ViewModel.Title = "The Title";
    ViewModel.Message = "Hello World!";
}

“Add View” Dialog Box Supports Multiple View Engines
The Add View dialog box in Visual Studio includes extensibility hooks that allow it to support multiple view engines, as shown in the following figure:

Service Location and Dependency Injection Support
ASP.NET MVC 3 introduces improved support for applying Dependency Injection (DI) via Inversion of Control (IoC) containers. ASP.NET MVC 3 Preview 1 provides the following hooks for locating services and injecting dependencies:
• Creating controller factories.
• Creating controllers and setting dependencies.
• Setting dependencies on view pages for both the Web Form view engine and the Razor view engine (for types that derive from ViewPage, ViewUserControl, ViewMasterPage, WebViewPage).
• Setting dependencies on action filters.
Using a Dependency Injection container is not required in order for ASP.NET MVC 3 to function properly.

Global Filters
ASP.NET MVC 3 allows you to register filters that apply globally to all controller action methods. Adding a filter to the global filters collection ensures that the filter runs for all controller requests. To register an action filter globally, you can make the following call in the Application_Start method in the Global.asax file:

     GlobalFilters.Filters.Add(new MyActionFilter());

The source of global action filters is abstracted by the new IFilterProvider interface, which can be registered manually or by using Dependency Injection. This allows you to provide your own source of action filters and choose at run time whether to apply a filter to an action in a particular request.

New JsonValueProviderFactory Class
The new JsonValueProviderFactory class allows action methods to receive JSON-encoded data and model-bind it to an action-method parameter. This is useful in scenarios such as client templating. Client templates enable you to format and display a single data item or set of data items by using a fragment of HTML. ASP.NET MVC 3 lets you connect client templates easily with an action method that both returns and receives JSON data.
For an example of how JsonValueProviderFactory is used, read Sending JSON to an ASP.NET MVC Action Method Argument on Phil Haack’s blog.

Support for .NET Framework 4 Validation Attributes and IValidatableObject
The ValidationAttribute class was improved in the .NET Framework 4 to enable richer support for validation. When you write a custom validation attribute, you can use a new IsValid overload that provides a ValidationContext instance. This instance provides information about the current validation context, such as what object is being validated.
This change enables scenarios such as validating the current value based on another property of the model. The following example shows a sample custom attribute that ensures that the value of PropertyOne is always larger than the value of PropertyTwo:

public class CompareValidationAttribute : ValidationAttribute {
    protected override ValidationResult IsValid(object value,
             ValidationContext validationContext) {
        var model = validationContext.ObjectInstance as SomeModel;
        if (model.PropertyOne > model.PropertyTwo) {
            return ValidationResult.Success;
        }
        return new ValidationResult("PropertyOne must be larger than PropertyTwo");
    }
}

Validation in ASP.NET MVC also supports the .NET Framework 4 IValidatableObject interface. This interface allows your model to perform model-level validation, as in the following example:

public class SomeModel : IValidatableObject {
    public int PropertyOne { get; set; }
    public int PropertyTwo { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (PropertyOne <= PropertyTwo) {

            yield return new ValidationResult(
                "PropertyOne must be larger than PropertyTwo");
        }
    }
}

New IClientValidatable Interface
The new IClientValidatable interface allows the validation framework to discover at run time whether a validator has support for client validation. This interface is designed to be independent of the underlying implementation; therefore, where you implement the interface depends on the validation framework in use. For example, for the default data annotations-based validator, the interface would be applied on the validation attribute.
Support for .NET Framework 4 Metadata Attributes
ASP.NET MVC 3 now supports .NET Framework 4 metadata attributes such as DisplayAttribute.
New IMetadataAware Interface
The new IMetadataAware interface allows you to write attributes that simplify how you can contribute to the ModelMetadata creation process. Before this interface was available, you needed to write a custom metadata provider in order to have an attribute provide extra metadata.
This interface is consumed by the AssociatedMetadataProvider class, so support for the IMetadataAware interface is automatically inherited by all classes that derive from that class (notably, the DataAnnotationsModelMetadataProvider class).

New Action Result Types
In ASP.NET MVC 3, the Controller class includes two new action result types and corresponding helper methods.

HttpNotFoundResult Action
The new HttpNotFoundResult action result is used to indicate that a resource requested by the current URL was not found. The status code is 404. This class derives from HttpStatusCodeResult. The Controller class includes an HttpNotFound method that returns an instance of this action result type, as shown in the following example:

public ActionResult List(int id) {
    if (id < 0) {
        return HttpNotFound();
    }
    return View();
}

HttpStatusCodeResult Action
The new HttpStatusCodeResult action result is used to set the response status code and description.

Permanent Redirect
The HttpRedirectResult class has a new Boolean Permanent property that is used to indicate whether a permanent redirect should occur. A permanent redirect uses the HTTP 301 status code. Corresponding to this change, the Controller class now has several methods for performing permanent redirects:
• RedirectPermanent
• RedirectToRoutePermanent
• RedirectToActionPermanent
These methods return an instance of HttpRedirectResult with the Permanent property set to true.

Breaking Changes
The order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller with the same Order as those on an action method were executed before the exception filters on the action method. This would typically be the case when exception filters were applied without a specified order Order value. In MVC 3, this order has been reversed in order to allow the most specific exception handler to execute first. As in earlier versions, if the Order property is explicitly specified, the filters are run in the specified order.

Known Issues
When you are editing a Razor view (CSHTML file), the Go To Controller menu item in Visual Studio will not be available, and there are no code snippets.

Posted in ASP.NET, C#, MVC. Tags: , . No Comments »

Upgrading an ASP.NET MVC 2 Project to ASP.NET MVC 3

Resources:
ASP.NET MVC 3 Preview 1 – MVC-3-Preview-1-Release-Notes.doc
ASP.NET MVC Preview 3 Release – ScottGu
ASP.NET MVC 3 Preview 1 Released : Channel 9 Video and Hanselminutes Podcast 224, Oh My!
ASP.NET MVC 3 Preview 1 Released – Phil Haack

ASP.NET MVC 3 can be installed side by side with ASP.NET MVC 2 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 2 application to ASP.NET MVC 3.

The simplest way to upgrade is to create a new ASP.NET MVC 3 project and copy all the views, controllers, code, and content files from the existing MVC 2 project to the new project and then to update the assembly references in the new project to match the old project. If you have made changes to the Web.config file in the MVC 2 project, you must also merge those changes with the Web.config file in the MVC 3 project.

To manually upgrade an existing ASP.NET MVC 2 application to version 3, do the following:

  1. In both Web.config files in the MVC 3 project, globally search and replace the MVC version. Find the following:
  2. System.Web.Mvc, Version=2.0.0.0
    

    Replace it with the following

    System.Web.Mvc, Version=3.0.0.0
    

    There are three changes in the root Web.config and four in the Views\Web.config file.

  3. In Solution Explorer, delete the reference to System.Web.Mvc (which points to the version 2 DLL). Then add a reference to System.Web.Mvc (v3.0.0.0).
  4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click again and select Edit ProjectName.csproj.
  5. Locate the ProjectTypeGuids element and replace {F85E285D-A4E0-4152-9332-AB1D724D3325} with {E53F8FEA-EAE0-44A6-8774-FFD645390401}.
  6. Save the changes and then right-click the project and select Reload Project.
  7. If the project references any third-party libraries that are compiled using ASP.NET MVC 2, add the following highlighted bindingRedirect element to the Web.config file in the application root under the configuration section:
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc"
          publicKeyToken="31bf3856ad364e35"/>
      <bindingRedirect oldVersion="2.0.0.0" newVersion="3.0.0.0"/>
    </dependentAssembly>
  </assemblyBinding>
</runtime>
Posted in ASP.NET, C#, MVC. Tags: , . No Comments »

The NoSql movement…

What is NoSql?

Wikipedia defines it as:

NoSql is a movement promoting a loosely defined class of non-relational data stores that break with a long history of relational databases. These data stores may not require fixed table schemas, usually avoid join operations and typically scale horizontally. Academics and papers typically refer to these databases as structured storage.

The NoSQL movement isn’t brand new as it has produced many different flavors over the years such as Document Stores(CouchDB,MongoDB,RavenDB), Graph(Neo4j), Key/Value stores on disk(Memcachedb,Redis,BigTable), Key/Value stores in RAM(Memcached), Eventually-consistent key-value store(Cassandra), Ordered Key-Value stores(MemcacheDB), Multivalue databases(OpenQM), Object databases(Db4o), Tabular(BigTable) and Tuple stores(Jini). There are probably many more.

The most popular type lately and of most interest to myself, has been the document stores that use the JSON format.  I believe that the advancement in JavaScript frameworks such as jQuery and ExtJS have really opened the door for them.

RavenDB

Raven is an Open Source (with a commercial option) document database for the .NET/Windows platform. Raven offers a flexible data model design to fit the needs of real world systems. Raven stores schema-less JSON documents, allow you to define indexes using Linq queries and focus on low latency and high performance.

  • Scalable infrastructure: Raven builds on top of existing, proven and scalable infrastructure
  • Simple Windows configuration: Raven is simple to setup and run on windows as either a service or IIS7 website
  • Transactional: Raven support System.Transaction with ACID transactions. If you put data in it, that data is going to stay there
  • Map/Reduce: Easily define map/reduce indexes with Linq queries
  • .NET Client API: Raven comes with a fully functional .NET client API which implements Unit of Work and much more
  • RESTful: Raven is built around a RESTful API

CouchDB

Apache CouchDB is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. CouchDB also offers incremental replication with bi-directional conflict detection and resolution.

CouchDB provides a RESTful JSON API than can be accessed from any environment that allows HTTP requests. There are myriad third-party client libraries that make this even easier from your programming language of choice. CouchDB’s built in Web administration console speaks directly to the database using HTTP requests issued from your browser.

CouchDB is written in Erlang, a robust functional programming language ideal for building concurrent distributed systems. Erlang allows for a flexible design that is easily scalable and readily extensible.

MongoDB

MongoDB bridges the gap between key-value stores (which are fast and highly scalable) and traditional RDBMS systems (which provide rich queries and deep functionality).

MongoDB (from “humongous”) is a scalable, high-performance, open source, document-oriented database. Written in C++, MongoDB features:

Posted in NoSql. Tags: , . No Comments »

T4 (Text Template Transformation Toolkit) Resources

Posted in Tools. Tags: . No Comments »

Quick intro into the Google Web Toolkit

So, what is the Google Web Toolkit(GWT)?

Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. Its goal is to enable productive development of high-performance web applications without the developer having to be an expert in browser quirks, XMLHttpRequest, and JavaScript. GWT is used by many products at Google, including Google Wave and the new version of AdWords. It’s open source, completely free, and used by thousands of developers around the world.

Features:

  • The GWT SDK provides a set of core Java APIs and Widgets. These allow you to write AJAX applications in Java and then compile the source to highly optimized JavaScript that runs across all browsers, including mobile browsers for Android and the iPhone.
  • You can debug AJAX applications in your favorite IDE just like you would a desktop application, and in your favorite browser just like you would if you were coding JavaScript. The GWT developer plugin spans the gap between Java bytecode in the debugger and the browser’s JavaScript.
  • Google Web Toolkit contains two powerful tools for creating optimized web applications. The GWT compiler and Speed Tracer.
  • GWT compiles your Java source code into optimized, stand-alone JavaScript files that automatically run on all major browsers, as well as mobile browsers for Android and the iPhone.
  • Plugin for Eclipse


Posted in AJAX, CSS, HTML, JavaScript, Tools. Tags: , , , , . No Comments »

Pick a color any color

Need help picking colors, try these sites out:
http://kuler.adobe.com

Discover Adobe® Kuler™ — the web-hosted application for generating color themes that can inspire any project. No matter what you’re creating, with Kuler you can experiment quickly with color variations and browse thousands of themes from the Kuler community.

http://0to255.com/

0to255 is a simple tool that helps web designers find variations of any color.

Posted in CSS, Tools. Tags: . No Comments »

jQuery 1.4 Released

In celebration of jQuery’s 4th birthday, the jQuery team is pleased to release the latest major release of the jQuery JavaScript library! A lot of coding, testing, and documenting has gone into this release, and we’re really quite proud of it.

Its here, head over to 14 Days of jQuery Day 1 for downloads links, performance stats and much much more.

Here is a link to all of the API changes/additions: Version 1.4

Posted in AJAX, CSS, JavaScript. No Comments »

14 Days of jQuery – Marketing Campaign

14 Days of jQuery and the New API Browser

Beginning on January 14th, we’ll start a fourteen-day event. Each day we’ll have fresh videos and announcements — there’ll be code releases, project-related updates, and jQuery UI goodness, among other things. In addition to the announcements, we’ll also be releasing a set of videos over the 14 days with talks and tutorials relating the jQuery 1.4 release and other general jQuery topics. You’ll want to check back at jQuery14.com every day during the two weeks to see what’s new, or sign up to be notified via email. Think of it like an online conference, only longer, freer, and with a bit of mystery and suspense!

Want a free jQuery book:

The jQuery project is a non-profit, open-source effort, and we rely heavily on donations and contributions to help fund everything we do. We’ll be running a fundraising drive starting now and throughout the 14 Days of jQuery. If you’re a jQuery user, show your support by making a tax-deductible donation of $20 USD or more to the project during the event, and you’ll receive a free jQuery book with your donation.

Posted in AJAX, JavaScript, Tools. Tags: . No Comments »

Hierarchical Table Manipulation with jQuery

I recently had to propagate change down a table that represented hierarchical data as well as show and hide columns.  The most important requirement was that the changes should not propagate up any levels, only down.  I have put up a sample on JSBin here that simulates generated HTML from ASP.NET(ie: dynamic control ids).  Most of the manipulation is done with class names.  The show and hide columns could probably have been done better, but you will get the gist.

jQuery functions:

       $(document).ready(function () {
            $('.HideTableDemoTab').click(function () {
                HideTableColumn(this);
            });

            $('.ShowTableDemoTab').click(function () {
                ShowTableColumn(this);
            });

            $('.TableDemoTabShowAll').click(function () {
                ShowAllColumns();
            });

        });

        function PropagateChanges(rowId, inputChanged, inputTarget, level) {
            if ($('.chkPropagate input').attr('checked')) {
                var tableRows = $('.TableDemo &gt; tbody &gt; tr:gt(' + rowId + ')');
                tableRows.each(function () {
                    var tableCells = $(this);
                    var currentLevel = tableCells.find('.Level').val();

                    if (currentLevel &lt; level) {
                        tableCells.find('.' + inputTarget).val($('#' + inputChanged).val());

                    }
                    else {
                        return false; //break out of loop can't change parents

                    }

                });
            }
        }

        function HideTableColumn(column) {
            if (column.id == &quot;tabHideCol1&quot;) {
                $(&quot;#TableDemo td:nth-child(1)&quot;).hide();
            }
            else if (column.id == &quot;tabHideCol2&quot;) {
                $(&quot;#TableDemo td:nth-child(2)&quot;).hide();
            }
            else if (column.id == &quot;tabHideCol3&quot;) {
                $(&quot;#TableDemo td:nth-child(3)&quot;).hide();

            }
        }

        function ShowTableColumn(column) {
            if (column.id == &quot;tabShowCol1&quot;) {
                $(&quot;#TableDemo td:nth-child(1)&quot;).show();
            }
            else if (column.id == &quot;tabShowCol2&quot;) {
                $(&quot;#TableDemo td:nth-child(2)&quot;).show();
            }
            else if (column.id == &quot;tabShowCol3&quot;) {
                $(&quot;#TableDemo td:nth-child(3)&quot;).show();

            }
        }

        function ShowAllColumns() {
            $(&quot;#TableDemo td:nth-child(1)&quot;).show();
            $(&quot;#TableDemo td:nth-child(2)&quot;).show();
            $(&quot;#TableDemo td:nth-child(3)&quot;).show();
        }
Posted in ASP.NET, HTML, JavaScript. Tags: , , . No Comments »

Free .NET IDE's

#develop

#develop (short for SharpDevelop) is a free IDE for C#, VB.NET and Boo projects on Microsoft’s .NET platform.

MonoDevelop

MonoDevelop is an IDE primarily designed for C# and other .NET languages. MonoDevelop enables developers to quickly write desktop and ASP.NET Web applications on Linux, Windows and Mac OSX. MonoDevelop makes it easy for developers to port .NET applications created with Visual Studio to Linux and to maintain a single code base for all platforms.

Posted in ASP.NET, C#, Tools. Tags: . No Comments »