BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

Browse by Tags

All Tags » .NET » ASP.NET » Visual Studio   (RSS)

  • ASP.NET MVC Design Gallery and Upcoming View Improvements with the ASP.NET MVC Release Candidate

    Today we launched a new ASP.NET MVC Design Gallery on the www.asp.net site.  The design gallery hosts free HTML design templates that you can download and easily use with your ASP.NET MVC applications.  Included with each design template is a Site.master file, a CSS stylesheet, and optionally a set of images, partials, and helper methods that support them. 

    The gallery allows you to preview each of the designs online, as well as download a .zip version of them that you can extract and integrate into your site.  The gallery allows anyone to create and submit new designs under the creative commons license.  Visitors to the gallery can vote to provide feedback on them (thumbs up/thumbs down).  The most popular designs show up at the top of the gallery. 

    We think this will provide a useful way for developers to more easily create attractive, standards compliant, sites.  It will also hopefully encourage folks to create and share designs that can be easily re-used by others.

    Upcoming View Improvements with the Release Candidate

    While on the topic of UI, I thought I'd also share a few details about some of the View-related improvements that are coming with the new ASP.NET MVC Release Candidate build that will be shipping shortly.  In addition to bug fixes, the RC incorporates a number of view-specific feature additions and community suggestions.

    Views without Code-Behind Files

    Based on feedback from a lot of people, we've decided to make a change so that MVC view files by default do not have code-behind files. This change helps to reinforce the purpose of views in a MVC world (which are intended to be purely about rendering and to not contain any non-rendering related code), and for most people eliminates unused files in the project:

    With the ASP.NET MVC Beta, developers could eliminate the code-behind file by using the CLR syntax for generic types in a view's inherits attribute, but that CLR syntax is (to put it mildly) pretty undiscoverable and hard to use.  The ASP.NET MVC team was able to combine a few extensibility features already in ASP.NET to now enable the standard VB/C# language syntax within the inherits attribute with the ASP.NET RC build:

    One other nice benefit of not using a code-behind file is that you'll now get immediate intellisense when you first add them to the project.  With the beta you had to do a build/compile immediately after creating a view in order to get code intellisense within it.  The RC makes the workflow of adding and immediately editing a view compile-free and much more seamless.

    Top-Level Model Property on Views

    With previous builds of ASP.NET MVC, you accessed the strongly typed model object passed to the view using the ViewData.Model property:

    The above syntax still works, although now there is also a top-level "Model" property on ViewPage that you can use:

    This property does the same thing as the previous code sample - its main benefit is that it allows you to write the code a little more concisely.

    HTML/AJAX Helpers Now Enable Expression Syntax

    One of the requests a few people have asked for is the ability to use strongly-typed expression syntax (instead of using strings) when referring to the Model when using a View's HTML and AJAX helper objects.

    With the beta build of ASP.NET MVC this wasn't possible, since the HtmlHelper and AjaxHelper helper classes didn't expose the model type in their signature, and so people had to build helper methods directly off of the ViewPage<TModel> base class in order to achieve this.  The ASP.NET MVC RC build introduces new HtmlHelper<TModel> and AjaxHelper<TModel> types that are exposed on the ViewPage<TModel> base class.  These types now allow anyone to build strongly-typed HTML and AJAX helper extensions that use expression syntax to refer to the View's model.

    For example, I could build a (very simple) strongly-typed "TextBox" helper method using the code below:

    And then use it within any of my views to bind against a Product model object like so:

    Visual Studio will provide full intellisense for the strongly-typed expression syntax when working against the View's model in the source editor in this way:

     

    Note: the HTML helper extensions in the core ASP.NET MVC V1 assembly will still use the existing (non-expression based) syntax.  We are then planning to add expression-based versions to the MVCFutures assembly. You can of course also add your own helper methods (using either strings or strongly-typed BLOCKED EXPRESSION.  All of the built-in helper methods can also optionally be removed (because they are extension methods) if you want to replace or override them with your own.

    Scaffolding Support

    The ASP.NET MVC RC build includes automatic "UI scaffolding" support when creating views using the new ASP.NET MVC "Add View" command inside Visual Studio.  The scaffolding support enables the automatic generation of views against any .NET type or object - meaning it can work against POCO classes, LINQ to SQL, LINQ to Entities, NHibernate, SubSonic, LLBLGen Pro, or any other object model. The scaffolding engine uses reflection to retrieve the public shape of a View's model type, and then passes it to a scaffolding template to populate appropriate markup based on it within the view being created.

    For example, assume we have a ProductsController class and want to create an "Edit" action on it to display an edit view of a particular Product.  Using the RC build we can right-click within our "Edit" action method and choose the "Add View" context menu command like so:

    Within the "Add View" dialog we can then indicate that we are passing a "Product" type to our View:

    We can indicate that we want an "Empty" view template created (like above), or indicate that we want VS to automatically scaffold a form "Edit" view for the Product object we are supplying:

    If we choose the "Edit" template VS will automatically generate a file for us that has the appropriate HTML and validation helpers to create an editable form view:

    We can then run the application and immediately get edit UI:

    We can then go in and change the generated edit.aspx file however we want to tweak/customize it. 

    One of the really nice things about the scaffolding system we are shipping is that it is implemented using Visual Studio's built-in T4 code generation system (Scott Hanselman has a nice post about this here).  The "List", "Edit", "Create" and "Details" templates we ship with ASP.NET MVC can all be completely customized or replaced with T4 templates of your own (or downloaded from the ASP.NET MVC Design Gallery). So if you have your own particular way of creating HTML, or want to use custom HTML helpers (for example: strongly-typed expression based ones) you can update the default templates and the scaffolding system will use them going forward. 

    We are planning to enable the templates to be overriden both on a machine-wide level, as well as on a per-project level (so that you can check-in application-specific scaffolding templates under source control and share them across a team).

    MSBuild Task for Compiling Views

    By default when you do a build on an ASP.NET MVC project it compiles all code within the project, except for the code within view files.  With the ASP.NET MVC Beta you had to roll your own MSBuild task if you wanted to compile the views.  The ASP.NET MVC RC build now includes a built-in MSBuild task that you can use to include views as part of the project compilation process.  This will verify the syntax and code included inline within all views and master pages for the application, and give you build errors if it encounters any problems.

    For performance reasons we don't recommend running this for quick compiles during development, but it is convenient to add to particular build configuration profiles (for example: staging and deployment) and/or for use with Build or CI (continuous integration) servers.

    Other ASP.NET MVC Release Candidate features coming

    Above is a short list of some of the view-specific functionality coming with the release candidate build. 

    There are many other features and requests coming with the RC as well including: IDataErrorInfo support to enable models to surface validation error messages, as well as richer error validation extensibility to enable you to use your own approach to surface model validation errors to ModelBinders (the IDataErrorInfo support is built on top of this); new FileResult and JavaScriptResult ActionResult types (allowing you to more easily download files as well as executable JavaScript to browsers); built-in jQuery -vsdoc intellisense support; refactored AccontController support to enable easier unit testing and extensibility with form login scenarios; a variety of project template improvements, more extensibility everywhere; lots of bug fixes; and a few other cool features I'll blog about later once the RC is out.

    We'll be releasing the ASP.NET MVC Release Candidate in January.  Our plan is to have that build be ASP.NET MVC V1 API and feature-complete and have zero known bugs.  We'll give people a short period to upgrade to it, give it a good tire-kicking, and report any last minute issues they find.  We'll then ship the official V1 release shortly after that (so not far off now).

    Hope this helps,

    Scott

  • Dec 2nd Links: ASP.NET, ASP.NET Dynamic Data, ASP.NET AJAX, ASP.NET MVC, Visual Studio, Silverlight/WPF

    I'm flying out later today on a pretty intense business trip (22,000 miles, 5 countries, 3 continents, 1 week, no sleep... :-), so my blog activity over the next week and a half will be pretty light.  To keep you busy till I return, here is the latest in my link-listing series.  Also check out my ASP.NET Tips, Tricks and Tutorials page and Silverlight Tutorials page for links to popular articles I've done myself in the past.

    ASP.NET

    • Geolocation/Geotargeting Reverse IP Lookup Code: Scott Hanselman has a cool sample that demonstrates how to perform IP address lookups on users visiting your site to determine where they are located on the globe (down to the latitude and longitude).  Pretty cool stuff.

    • Tracking User Activity: Scott Mitchell has a nice article that discusses how to track end-user activity when visiting an ASP.NET web site.

    • iTunes Data Grid Skin: Matt Berseth continues his cool series showing off cool new skins you can apply to ASP.NET controls (especially the GridView and DetailsView controls).  This post shows off a pretty sweet iTunes like skin.

    ASP.NET Dynamic Data

    • ASP.NET Dynamic Data Videos: Joe Stagner has 6 nice ASP.NET Dynamic Data "How Do I?" videos posted on www.asp.net that you can check out to learn about the new ASP.NET Dynamic Data feature in .NET 3.5 SP1.

    • ASP.NET Dynamic Data Routing: Rachel Appel has a nice post that talks about how to use the new ASP.NET routing features with ASP.NET Dynamic Data to enable customized URLs.

    ASP.NET AJAX

    ASP.NET MVC

    • How to Setup ASP.NET MVC on IIS6: Phil Haack has a great post that walks-through how to enable ASP.NET MVC on IIS6 servers (including how to enable it on a hosting server that you can't install anything on).

    • Fluent Route Testing in ASP.NET MVC: Ben Scheirman has a nice post where he blogs about new helper methods he is creating that make it easier to unit test ASP.NET MVC routes using a fluent API.

    Visual Studio

    WPF / Silverlight

    • XAML Power Toys - Instant Form Creation: Karl Shifflett has a great video that shows off his XAML Power Toys tool that integrates into Visual Studio and enables rapid forms creation for WPF and Silverlight.

    Hope this helps,

    Scott

  • jQuery Intellisense in VS 2008

    Last month I blogged about how Microsoft is extending support for jQuery.  Over the last few weeks we've been working with the jQuery team to add great jQuery intellisense support within Visual Studio 2008 and Visual Web Developer 2008 Express (which is free).  This is now available to download and use.

    Steps to Enable jQuery Intellisense in VS 2008

    To enable intellisense completion for jQuery within VS you'll want to follow three steps:

    Step 1: Install VS 2008 SP1

    VS 2008 SP1 adds richer JavaScript intellisense support to Visual Studio, and adds code completion support for a broad range of JavaScript libraries.

    You can download VS 2008 SP1 and Visual Web Developer 2008 Express SP1 here.

    Step 2: Install VS 2008 Patch KB958502 to Support "-vsdoc.js" Intellisense Files

    Two weeks ago we shipped a patch that you can apply to VS 2008 SP1 and VWD 2008 Express SP1 that causes Visual Studio to check for the presence of an optional "-vsdoc.js" file when a JavaScript library is referenced, and if present to use this to drive the JavaScript intellisense engine.

    These annotated "-vsdoc.js" files can include XML comments that provide help documentation for JavaScript methods, as well as additional code intellisense hints for dynamic JavaScript signatures that cannot automatically be inferred.  You can learn more about this patch here.  You can download it for free here.

    Step 3: Download the jQuery-vsdoc.js file

    We've worked with the jQuery team to put together a jQuery-vsdoc.js file that provides help comments and support for JavaScript intellisense on chained jQuery selector methods.  You can download both jQuery and the jQuery-vsdoc file from the official download page on the jQuery.com site:

    Save the jquery-vsdoc.js file next to your jquery.js file in your project (and make sure its naming prefix matches the jquery file name):

    You can then reference the standard jquery file with an html <script/> element like so:

    Or alternatively reference it using the <asp:scriptmanager/> control, or by adding a /// <reference/> comment at the top of a standalone .js file. 

    When you do this VS will now look for a -vsdoc.js file in the same directory as the script file you are referencing, and if found will use it for help and intellisense.  The annotated

    For example, we could use jQuery to make a JSON based get request, and get intellisense for the method (hanging off of $.):

    As well as help/intellisense for the $.getJSON() method's parameters:

     

    The intellisense will continue to work if you nest a callback function within the method call.  For example, we might want to iterate over each JSON object returned from the server:

    And for each of the items we could execute another nested callback function:

    We could use the each callback function to dynamically append a new image to a list (the image src attribute will point to the URL of the returned JSON media image):

    And on each dynamically created image we could wire-up a click event handler so that when it is pressed it will disappear via an animation:

    Notice how the jQuery intellisense works cleanly at each level of our code. 

    JavaScript Intellisense Tips and Tricks

    Jeff King from the Web Tools team wrote up a great post earlier this week that answers a number of common questions about how JavaScript intellisense works with VS 2008.  I highly recommend reading it.

    One trick he talks about which I'll show here is a technique you can use when you want to have JavaScript intellisense work within user-controls/partials (.ascx files).  Often you don't want to include a JavaScript library <script src=""/> reference  within these files, and instead have this live on the master page or content page the user control is used within.  The problem of course when you do this is that by default VS has no way of knowing that this script is available within the user control - and so won't provide intellisense of it for you.

    One way you can enable this is by adding the <script src=""/> element to your user control, but then surround it with a server-side <% if %> block that always evaluates to false at runtime:

    At runtime ASP.NET will never render this script tag (since it is wrapped in an if block that is always false).  However, VS will evaluate the <script/> tag and provide intellisense for it within the user-control.  A useful technique to use for scenarios like the user control one.  Jeff has even more details in his FAQ post as well as his original jQuery intellisense post.  Rick Strahl also has a good post about using jQuery intellisense here.

    More Information

    To learn more about jQuery, I recommend watching Stephen Walther's ASP.NET and jQuery PDC talk. Click here to download his code samples and powerpoint presentation.

    Rick Strahl also has a really nice Introduction to jQuery article that talks about using jQuery with ASP.NET.  Karl Seguin has two nice jQuery primer posts here and here that provide shorter overviews of some of the basics of how to use jQuery. 

    I also highly recommend the jQuery in Action book.

    Hope this helps,

    Scott

  • October 22nd Links: ASP.NET, Visual Studio, WPF and Silverlight

    Here is the latest in my link-listing series.  Also check out my ASP.NET Tips, Tricks and Tutorials page and Silverlight Tutorials page for links to popular articles I've done myself in the past.

    ASP.NET

    • Building a Great ASP.NET AJAX Application from Scratch: Brad Abrams has a nice end to end application tutorial that shows off building an ASP.NET AJAX application from scratch. It covers ASP.NET, LINQ, Server and Client-side AJAX, the ASP.NET AJAX Control Toolkit, jQuery and more.  A great end to end read.

    • ASP.NET MVC and the new IIS7 URL Rewriting Module: Scott Hanselman has a great post that shows off using the new IIS7 Rewriitng Module (which is free and very, very cool) to deliver great SEO (search engine optimization) for sites built with ASP.NET and specifically ASP.NET MVC. 

    Visual Studio

    • VS 2008 Snippet Designer: A cool utility that enables you to quickly create re-usable Visual Studio snippets.  Very handy for automating common tasks.

    Silverlight and WPF

    • XAML Power Toys Released for WPF and Silverlight: Karl Shifflett has released an awesome update to his XAML Power Toys download.  This is a must-have download if you are doing WPF or Silverlight development, and provides a bunch of great wizards and tools that help automating application development.  Very, very cool stuff.

    • WPF Pixel Shader Effects Library on CodePlex: .NET 3.5 SP1 added Pixel Shader support to WPF - which enables you to add cool DirectX optimized visual effects to any WPF control or surface.  This article from Jamie points to a nice new CodePlex project that is available that delivers a bunch of pre-built effects you can use.

    • Silverlight 2 UI Templates: Tim Heuer writes about some cool new UI templates available for the recently released Silverlight 2.

    Hope this helps,

    Scott

  • ASP.NET MVC Beta Released

    Today we released a beta of the new ASP.NET MVC framework.  Click here to download it.  You can also visit www.asp.net/mvc to explore tutorials, quickstarts, and videos to learn more.

    The ASP.NET MVC Beta works with both .NET 3.5 and .NET 3.5 SP1, and supports both VS 2008 and Visual Web Developer 2008 Express SP1 (which is free - and now supports class libraries and web application project types).

    Today's ASP.NET MVC Beta release comes with an explicit "go-live" license that allows you to deploy it in production environments.  The previous preview releases also allowed go-live deployments, but did so by not denying permission to deploy as opposed to explicitly granting it (which was a common source of confusion).  Today's release is clearer about this in the license.

    The beta release is getting close to V1 feature complete, although there are still a few more features that will be added before the final "V1" release (including several VS tooling enhancements).  The team decided to call this release a "beta", though, because the quality and testing of it is higher than the previous previews (a lot of bug fixes and performance tuning work went into it), and they feel that the core features that are in it are now "baked enough" that there won't be major changes from this release to the final product.

    This post contains a quick summary of some of the new features and changes in this build compared to the previous "Preview 5" release: 

    I am also planning to publish a few end to end tutorials in the weeks ahead that explain ASP.NET MVC concepts in more depth for folks who have not looked at it before, and who want a "from the beginning" set of tutorials on how to get started.

    New "Add View" Menu in Visual Studio

    With previous ASP.NET MVC preview releases you had to manually add views through the Project->Add New Item dialog in VS, and creating and wiring up everything required several manual steps (making sure the directory/file structure is right, going into the code-behind file to specify the strongly typed ViewData model type, etc).

    Today's beta makes the steps much easier.  You can now just move your source editor cursor to be within a Controller action method in the source editor, and then right-click and select a new "Add View" context menu item (alternatively you can type the Ctrl-M Ctrl-V keyboard shortcut to invoke this without having to take your hands off the keyboard):

    This will bring up a new "Add View" dialog that allows you to specify the name of the view you want to create, its master page, and optionally its strongly typed ViewData "Model" type:

     

    Visual Studio will automatically pre-populate the view name based on the action method your cursor is within (you can then override this if you want).  For example, if our cursor had been within an "Edit" action method when we selected "add view" it would have pre-populated the view name textbox with "Edit" instead of "Browse".

    The strongly typed ViewData "model" for a view can be selected from an editable ComboBox that lists all classes in (or referenced) from the MVC project:

    You can either select a type from the list, or manually type one in the ComboBox.  You can also optionally pick an initial type from the list and then tweak it.  For example, we could select the "Product" class from the list and then use the ComboBox editing support to wrap it as an IEnumerable<Product> - meaning a sequence of products:

    When we click the "Add" button, Visual Studio will automatically create the appropriate view directory structure, and add a strongly typed view with the right name and base class to our project.  For example, if I followed the steps above it would create a new \Views\Products directory for me (since my controller class name is "ProductsController") and add the strongly-typed "Browse.aspx" view to it (which derives from ViewPage<IEnumerable<Product>> - since that was the model type we indicated in the dialog above):

    The newly created view will automatically be opened for us in the IDE.  We can then implement our view with full intellisense (tip: make sure to do a build immediately after creating the view to ensure that intellisense shows up for your strongly typed model):

    And at runtime we will now have an SEO optimized product browsing page built with ASP.NET MVC:

    Note: The view file created by Add-View with this beta release is empty.  For the final release we are hoping to add some "scaffolding" features to the Add-View dialog that will allow you to optionally specify that you want to automatically create an HTML list/details view or edit/insert form based on the strongly-typed model specified in the add-view dialog (you can then start with this initial html view and tweak it however you want).  In the future we will also integrate ASP.NET Dynamic Data with MVC to support even richer scaffolding options.

    New \Scripts directory and jQuery Support

    The project template that ships with today's release now adds a new \Scripts directory underneath the project root.  This is now the recommended place to store JavaScript files in your application.

    The ASP.NET MVC Beta now adds both ASP.NET AJAX and jQuery libraries to this folder:

    The jQuery files are the standard jQuery libraries, and are licensed under the MIT source license (read my previous jQuery and Microsoft post for details).

    With the SP1 updates of VS 2008 or Visual Web Developer 2008 Express, you will get basic JavaScript intellisense when using the above jQuery files.  We will be shipping a jQuery intellisense-annotation file in a few more weeks that provides much better and more complete jQuery intellisense support (including the ability to get intellisense when using multiple chained selectors/commands).  This will be included built-in with the next ASP.NET MVC update.

    Form Post and Model Binder Improvements

    One of the biggest areas of feature investment with the ASP.NET MVC "Preview 5" release was the work around form post scenarios.  I did an in-depth blog post about these form post scenario features last month.

    Today's beta includes a number of additional tweaks, enhancements, and refinements in this area.  These include:

    Built-in Model Binder support for Complex Types

    Preview 5 introduced the concept of "model binders" - which allow you to map incoming form post values to complex .NET types passed as Controller action method parameters.  Model binders in preview 5 were extensible, and you could create custom binders and register them at multiple levels of the system.  Preview 5 didn't ship with any "pre-built" binders, though, that you could use out of the box (you instead had to build your own).  Today's beta now includes a built-in, pre-registered, binder that can be used to automatically handle standard .NET types - without requiring any additional code or registration. 

    For example, we can now create a "Person" class like below with standard properties:

    And then have a Controller action method take it as an parameter argument simply by writing the code below:

    Because the argument parameter above is named "person", the model binder will by default look for form-post values whose key names are in the format "person.Name", "person.Age", "person.Email".  It will then use these values to create and populate a new "Person" object that is passed into our action method.

    Developers can optionally override the default name mapping logic using a new [Bind] attribute introduced with today's beta - and by setting its "Prefix" property.  For example, if we set the prefix property to "PersonToSave", the binder would instead look for the following form values: "PersonToSave.Name", "PersonToSave.Age", and "PersonToSave.Email" when creating the person instance.  You can set the prefix to an empty string to have the binder map "Name", "Age" and "Email" with no prefix:

    The [Bind] attribute allows you to optionally specify an "Included" or "Excluded" property - which can be used to either "whitelist" or "blacklist" properties from being mapped on the objects.  For example, the code below indicates that we want to map only the "Name" and "Age" properties on our person object:

    Important safety tip: In general you want to be very careful to make sure you don't allow properties to be mapped that you don't want mapped.  Always use include/exclude anytime you have properties that you don't want to be mapped on an object.  For example: assuming there was a "Salary" property on our Person object - we would not want to map it unless we explicitly wanted an end-user to be able to set it.  You want to be explicit about not mapping unwanted properties like this to prevent a hacker from trying to fake out a form request and attempting to submit additional property information not editable in the UI.

    Refactored Model Binder Infrastructure

    The model binder system has been refactored significantly for the beta.  You can now re-use and plug-in functionality in a much more granular fashion when building your own custom model binders.

    Model binders are also now used by the UpdateModel and TryUpdateModel methods - allowing you to write one binder and re-use it everywhere any form value is handled inside ASP.NET MVC.

    Improved UpdateModel and TryUpdateModel methods

    The UpdateModel and TryUpdateModel methods now support several new options and overloads (including richer whitelist and blacklist options). 

    It also now optionally supports the ability to just call "UpdateModel" to populate an instance with the default binding rules (with preview 5 you always had to supply a whitelist - and several people asked for an option to just map all):

    Another new feature in today's beta is the ability to define a strongly-typed whitelist filter that you use with UpdateModel/TryUpdateModel.  You can do this by defining an interface with the subset of bindable properties that you want to map.  For example, below I'm defining a "IPersonFormBindable" interface that only has three properties (and does not have the salary property):

    We could then indicate that we want to use this contract to limit which properties are mapped using code like below:

    This will ensure that only those properties defined on the IPersonFormBindable interface are mapped - and that the Salary one is not mapped.

    Improved Unit Testing of UpdateModel and TryUpdateModel Scenarios

    With Preview 5 you had to use mocking in order to unit test form post scenarios that used the UpdateModel or TryUpdateModel methods.  Today's beta now allows you to unit test all form post scenarios without ever requiring mocking (which enables better friction-free unit testing).

    There is a new IValueProvider interface introduced with today's beta that the model binding infrastructure uses to retrieve values to bind (as opposed to always going against the request object).  The FormCollection class (which is built-into the beta) implements this interface - and you can now explicitly pass an instance of this to UpdateModel/TryUpdateModel to bind its values from. 

    For example: below in the "Save" action method we are binding all incoming form values to a FormCollection (which will be passed in as an argument to the action method).  I can then pass this form collection to the UpdateModel call and have it map the values onto the person model object using this parameter: 

    We could then unit test a successful form post scenario for the above action method using the code below (notice how we don't need to mock anything - instead we can just create a formcollection, populate it, and pass it as a parameter):

    We could then unit test an unsuccessful form post (which fails because of invalid input for the age value) using the code below.  Notice how we are verifying that the edit form is redisplayed (so that users can correct their problem) in a form-post failure scenario:

    We did not have to mock anything to unit test both of the above form submission scenarios.

    Strongly Typed [AcceptVerbs] attribute

    ASP.NET MVC Preview 5 introduced a new [AcceptVerbs] attribute that you could use to indicate which HTTP verbs an action method supported. 

    In preview 5 you always specified verbs using strings.  We still support this with the beta, but have also added support for common verbs to be specified using a strongly-typed enum mask.  For example:

    Today's beta release also no longer requires that you specify [AcceptVerbs] on both actions in scenarios like above.  By default ASP.NET MVC now looks for an action method that explicitly supports the incoming http verb - and if one is not found will use the action method that doesn't have an explicit verb specified.  This saves some typing for common GET/POST scenarios (you no longer need to decorate the GET method).

    Validation Error Messages

    One of the features that unfortunately did not make it into the beta (but which we will add for the next update) is support so that you can expose custom error validation messages from your model classes (as opposed to customizing them in the Controller like you can do today).  We are currently investigating a few ways to enable this - including adding support for the IDataErrorInfo interface, as well as support for the new Dynamic Data attributes in the System.ComponentModel.DataAnnotations namespace.

    One improvement that did make it into today's beta, though, is that the default validation error messages are now more end-user friendly (which hopefully eliminates the need to define custom validation messages in a lot of cases):

    HTML Helper Cleanup

    Today's beta has some miscellaneous cleanup improvements to the HTML helpers (in general this is a tricky area - since there are so many overload combinations to get right). 

    Html.Form -> Html.BeginForm

    One of the usability changes made with today's beta was to rename Html.Form() to Html.BeginForm() and to support two modes of using it - one leveraging a using statement, and the other leveraging an explicit Html.EndForm() helper method.  The reason we've moved to support both of these approaches is that we've seen a lot of questions/confusion in the forums around how the using statement works for this scenario (the pattern is unfamiliar to a lot of developers). 

    Below are two examples that demonstrate how we can implement the above create screen scenario (complete with validation error message UI) using the two different form approaches:

    Approach 1: Using Statement with Html.BeginForm():

    The below approach uses the IDisposable pattern with the using keyword in VB and C# to auto-terminate the </form>:

    Approach 2: Explicit Html.BeginForm() and Html.EndForm():

    The below approach uses an explicit EndForm() call to close the </form>:

    Developers can use whichever they feel most comfortable with - both approaches logically do the exact same thing.

    Many HTML Helper Methods Moved to be Extension Methods

    One change we made with today's beta was to move many of the Html helper methods to be extension methods that live under the System.Web.Mvc.Html namespace (previously they were just instance methods on the HtmlHelper class).  We did a similar thing with the AJAX helper methods in "Preview 5" (they now live in the System.Web.Mvc.Ajax namespace). 

    These changes don't impact intellisense in the view markup (we by default automatically reference the namespace in the web.config file so it works just like before - although if you are migrating an app from preview 5 you'll need to add the namespace yourself to web.config, read the release notes for steps on how to-do this).  If you have standalone classes/tests that use the helper methods make sure to add the appropriate "using" statement to import them.

    The reason we moved the helper methods to be extension methods instead of instance methods was to provide developers with more flexibility to add/remove/replace our built-in implementations (as well as to give ourselves more flexibility in the future). If you want to override the HTML rendering of a method you can now easily do so - and still keep the same method code/signature in your markup.

    Silverlight / ASP.NET MVC Project Integration

    When you create a new Silverlight 2 project within Visual Studio or Visual Web Developer 2008 Express (using the recently released Silverlight 2 and VS 2008 Tools for Silverlight download), you now have the ability to select a ASP.NET Web Site, ASP.NET Web Application Project and now an ASP.NET MVC Project to host it within:

    When you choose this option, Visual Studio will automatically copy and deploy/update the Silverlight application into the ASP.NET MVC application when you make a change and do a build within the IDE.  This makes it easier to start integrating a .NET based Silverlight front-end (running inside the browser) with an ASP.NET MVC web backend - and opens up some interesting new possibilities.

    ASP.NET MVC Futures Assembly

    For the last several preview releases, ASP.NET MVC features have been split across two assemblies - System.Web.Mvc.dll and Microsoft.Web.Mvc.dll.  The later assembly + namespace contains "futures" features that hadn't yet been committed to ship in the core V1 product.  As features become "committed" we move them from the futures assembly into the core assembly - and also change the namespace (from Microsoft.Web.Mvc to System.Web.Mvc). 

    The previous preview releases automatically shipped and added the "futures" assembly when you did a File->New ASP.NET MVC project.  Starting with today's beta we are no longer automatically adding this assembly - instead you need to explicitly add it from your project if you want to use it.  The reason for this is so that developers can clearly distinguish those features that will be in the fully supported V1 product (which implies product support and a higher commitment around backwards compatibility), and those that might still evolve in the future (and not be added to the supported product until vnext).

    Important: the futures assembly (along with all the source code in it) will continue to ship and will work with ASP.NET MVC V1.  So if there is a feature in it you really like, you do not have to worry about it disappearing on you (it is still there and you can still use it).  You just now need to explicitly reference the assembly and use it in your project. 

    We plan to ship a version of the ASP.NET MVC Futures assembly that works with the Beta later today.  You will be able to download it here.

    \Bin and GAC Deployment

    The ASP.NET MVC beta now supports both GAC based deployment (where you install the assembly once for the machine) as well as local \bin based deployment (where you store a copy of the assembly in the application directory). 

    We will use the GAC to enable automatic-servicing updates via Windows Update (where an administrator can automatically patch a machine - like they do with the rest of the .NET Framework today, and not have to update each individual application).  One downside with GAC based deployment, though, is that it can make deploying applications that require a GAC component harder for hosted scenarios - since you typically do not have admin access on the server machine (and you need admin rights to install components in the GAC).

    To make sure hosted scenarios work well (and to ensure that you don't need your hoster to install anything other that ASP.NET 3.5 in order for ASP.NET MVC to work), we will also support the ability to deploy the ASP.NET MVC framework assemblies in the \bin directory of your application.  This will allow you to just xcopy/ftp the application onto the server and have it work (no admin access or setup needs to be run on it).  The one caveat with this is that you'll be responsible for updating the assembly anytime a servicing update comes out - Windows Update can't automatically find all the application directories on a machine to-do this for you.

    Summary

    Today's beta release is a step closer to the final ASP.NET MVC 1.0 product.  While not 100% feature complete, we think the major subsystems are all getting really close to being done, and that the quality level is now pretty good.

    I am going to try and post some more end-to-end tutorials in the coming weeks that show off how to use ASP.NET MVC from the beginning, and then logically progress to richer and richer scenarios.  Included in the list of tutorials will be my infamous AJAX with MVC post that I keep promising to write - but so far haven't (my excuse: the Silverlight 2, ASP.NET MVC, .NET 4.0, VS10, and Windows 7 ship cycles are all happening in parallel on my team - and I've unfortunately been really busy which is the reason for the delay).

    As I always like to make sure I point out: If you don't like the MVC model or don't find it natural to your style of development, you definitely don't have to use it.  It is a totally optional offering - and does not replace the existing WebForms model.  Both WebForms and MVC will be fully supported and enhanced going forward (ASP.NET WebForms in .NET 4.0 will add richer URL routing features, better HTML css markup support, complete control over the ClientId property, more AJAX features, and more that I'll be blogging about soon).  So if you don't like the MVC option, don't worry, and don't feel like you should or need to use it (you don't). 

    Hope this helps,

    Scott

  • jQuery and Microsoft

    jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web.

    A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code.  jQuery supports this via a nice "selector" API that allows developers to query for HTML elements, and then apply "commands" to them.  One of the characteristics of jQuery commands is that they can be "chained" together - so that the result of one command can feed into another.  jQuery also includes a built-in set of animation APIs that can be used as commands.  The combination allows you to do some really cool things with only a few keystrokes.

    For example, the below JavaScript uses jQuery to find all <div> elements within a page that have a CSS class of "product", and then animate them to slowly disappear:

    As another example, the JavaScript below uses jQuery to find a specific <table> on the page with an id of "datagrid1", then retrieves every other <tr> row within the datagrid, and sets those <tr> elements to have a CSS class of "even" - which could be used to alternate the background color of each row:

    [Note: both of these samples were adapted from code snippets in the excellent jQuery in Action book]

    Providing the ability to perform selection and animation operations like above is something that a lot of developers have asked us to add to ASP.NET AJAX, and this support was something we listed as a proposed feature in the ASP.NET AJAX Roadmap we published a few months ago.  As the team started to investigate building it, though, they quickly realized that the jQuery support for these scenarios is already excellent, and that there is a huge ecosystem and community built up around it already.  The jQuery library also works well on the same page with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.

    Rather than duplicate functionality, we thought, wouldn't it be great to just use jQuery as-is, and add it as a standard, supported, library in VS/ASP.NET, and then focus our energy building new features that took advantage of it?  We sent mail the jQuery team to gauge their interest in this, and quickly heard back that they thought that it sounded like an interesting idea too.

    Supporting jQuery

    I'm excited today to announce that Microsoft will be shipping jQuery with Visual Studio going forward.  We will distribute the jQuery JavaScript library as-is, and will not be forking or changing the source from the main jQuery branch.  The files will continue to use and ship under the existing jQuery MIT license.

    We will also distribute intellisense-annotated versions that provide great Visual Studio intellisense and help-integration at design-time.  For example:

    and with a chained command:

    The jQuery intellisense annotation support will be available as a free web-download in a few weeks (and will work great with VS 2008 SP1 and the free Visual Web Developer 2008 Express SP1).  The new ASP.NET MVC download will also distribute it, and add the jQuery library by default to all new projects.

    We will also extend Microsoft product support to jQuery beginning later this year, which will enable developers and enterprises to call and open jQuery support cases 24x7 with Microsoft PSS.

    Going forward we'll use jQuery as one of the libraries used to implement higher-level controls in the ASP.NET AJAX Control Toolkit, as well as to implement new Ajax server-side helper methods for ASP.NET MVC.  New features we add to ASP.NET AJAX (like the new client template support) will be designed to integrate nicely with jQuery as well. 

    We also plan to contribute tests, bug fixes, and patches back to the jQuery open source project.  These will all go through the standard jQuery patch review process.

    Summary

    We are really excited to be able to partner with the jQuery team on this.  jQuery is a fantastic library, and something we think can really benefit ASP.NET and ASP.NET AJAX developers.  We are looking forward to having it work great with Visual Studio and ASP.NET, and to help bring it to an even larger set of developers.

    For more details on today's announcement, please check out John Resig's post on the jQuery team blog.  Scott Hanselman is also about to post a nice tutorial that shows off integrating jQuery with ASP.NET AJAX (including the new client templating engine) as well as ADO.NET Data Services (which shipped in .NET 3.5 SP1 and was previously code-named "Astoria").

    Hope this helps,

    Scott

  • ASP.NET MVC Preview 4 Release (Part 1)

    The ASP.NET MVC team is in the final stages of finishing up a new "Preview 4" release that they hope to ship later this week.  The Preview 3 release focused on finishing up a lot of the underlying core APIs and extensibility points in ASP.NET MVC.  Starting with Preview 4 this week you'll start to see more and more higher level features begin to appear that build on top of the core foundation and add nice productivity.

    There are a bunch of new features and capabilities in this new build - so much in fact that I decided I needed two posts to cover them all.  This first post will cover the new Caching, Error Handling and Security features in Preview 4, as well as some testing improvements it brings.  My next post will cover the new AJAX features being added with this release as well.

    Understanding Filter Interceptors

    Action Filter Attributes are a useful extensibility capability in ASP.NET MVC that was first added with the "Preview 2" release.  These enable you to inject code interceptors into the request of a MVC controller that can execute before and after a Controller or its Action methods execute.  This enables some nice encapsulation scenarios where you can easily package-up and re-use functionality in a clean declarative way.

    Below is an example of a super simple "ScottGuLog" filter that I could use to log details about exceptions raised during the execution of a request.  Implementing a custom filter class is easy - just subclass the "ActionFilterAttribute" type and override the appropriate methods to run code before or after an Action method on the Controller is invoked, and/or before or after an ActionResult is processed into a response.

    Using a filter within a ASP.NET MVC Controller is easy - just declare it as an attribute on an Action method, or alternatively on the Controller class itself (in which case it will apply to all Action methods within the Controller):

    Above you can see an example of two filters being applied.  I've indicated that I want my "ScottGuLog" to be applied to the "About" action method, and that I want the "HandleError" filter to be applied to all Action methods on the HomeController.

    Previous preview releases of ASP.NET MVC enabled this filter extensibility, but didn't ship with pre-built filters.  ASP.NET Preview 4 now includes several useful filters for handling output caching, error handling and security scenarios.

    OutputCache Filter

    The [OutputCache] filter provides an easy way to integrate ASP.NET MVC with the output caching features of ASP.NET (with ASP.NET MVC Preview 3 you had to write code to achieve this). 

    To try this out, modify the "Message" value set within the "Index" action method of the HomeController (created by the VS ASP.NET MVC project template) to display the current time:

    When you run your application you'll see that a timestamp updates each time you refresh the page:

    We can enable output caching for this URL by adding the [OutputCache] attribute to the our Action method.  We'll configure it to cache the response for a 10 second duration using the declaration below:

    Now when you hit refresh on the page you'll see that the timestamp only updates every 10 seconds.  This is because the action method is only being called once every 10 seconds - all requests between those time intervals are served out of the ASP.NET output cache (meaning no code needs to run - which makes it super fast).

    In addition to supporting time duration, the OutputCache attribute also supports the standard ASP.NET output cache vary options (vary by params, headers, content encoding, and custom logic).  For example, the sample below would save different cached versions of the page depending on the value of an optional "PageIndex" QueryString parameter, and automatically render the correct version depending on the incoming URL's querystring value:

    You can also integrate with the ASP.NET Database Cache Invalidation feature - which allows you to automatically invalidate the cache when a database the URL depends on is modified (tip: the best way to-do this is to setup a CacheProfile section in your web.config and then point to it in the OutputCache attribute). 

    HandleError Filter

    The [HandleError] filter provides a way to declaratively indicate on a Controller or Action method that a friendly error response should be displayed if an error occurs during the processing of a ASP.NET MVC request. 

    To try this out, add a new "TestController" to a project and implement an action method that raise an exception like below:

    By default when you point your browser at this URL, it will display a default ASP.NET error page to remote users (unless you've gone in and configured a <customErrors> section in your web.config file):

    We can change the HTML error displayed to be a more friendly end-user message by adding a [HandleError] attribute to either our Controller or to an Action method on our Controller:

    The HandleError filter will catch all exceptions (including errors raised when processing View templates), and display a custom Error view response when they occur.  By default it attempts to resolve a View template in your project called "Error" to generate the response.  You can place the "Error" view either in the same directory as your other Controller specific views (for example: \Views\Test for the TestController above), or within the \Views\Shared folder (it will look first for a controller specific error view, and then if it doesn't find one it will look in the shared folder - which contains views that are shared across all controllers).

    Visual Studio now automatically adds a default "Error" view template for you inside the \Views\Shared folder when you create new ASP.NET MVC Projects starting with Preview 4:

    When we add a [HandleError] attribute to our TestController, this will by default show remote users an html error page like below (note that it picks up the master page template from the project so that the error message is integrated into the site).  You can obviously go in and customize the Error view template to display whatever HTML and/or friendlier customer error message you want - below is simply what you get out of the box:

    To help developers, the default Error view template provided by the new project template in Visual Studio is written to display additional error stack trace information when you are browsing the application locally:

    You can turn this off either by deleting the code from the Error view template, or by setting <customErrors> to "off" inside your web.config file.

    By default the [HandleError] filter will catch and handle all exceptions that get raised during the request.  You can alternatively specify specific exception types you are interested in catching, and specify custom error views for them by specifying the "ExceptionType" and "View" properties on [HandleError] attributes:

    In the code above I'm choosing to display custom error views for SqlExceptions and NullReferenceExceptions.  All other exceptions will then use the default "Error" view template.

    Authorize Filter

    The [Authorize] filter provides a way to declaratively control security access on a Controller or Action method.  It allows you to indicate that a user must be logged in, and optionally require that they are a specific user or in a specific security role in order to gain access.  The filter works with all types of authentication (including Windows as well as Forms based authentication), and provides support for automatically redirecting anonymous users to a login form as needed.

    To try this out, add an [Authorize] filter to the "About" action in the HomeController created by default with Visual Studio:

    Declaring an [Authorize] attribute like above indicates that a user must be logged into the site in order for them to request the "About" action.  When non-logged-in users attempt to hit the /Home/About URL, they will be blocked from gaining access.  If the web application is configured to use Windows based authentication, ASP.NET will automatically authenticate the user using their Windows login identity, and if successful allow them to proceed.  If the web application is configured to use Forms based authentication, the [Authorize] attribute will automatically redirect the user to a login page in order to authenticate (after which they'll have access):

    The [Authorize] attribute optionally allows you to grant access only to specific users and/or roles.  For example, if I wanted to limit access to the "About" action to just myself and Bill Gates I could write:

    Typically for all but trivial applications you don't want to hard-code user names within your code.  Instead you usually want to use a higher-level concept like "roles" to define permissions, and then map users into roles separately (for example: using active directory or a database to store the mappings).  The [Authorize] attribute makes it easy to control access to Controllers and Actions using a "Roles" property:

    The [Authorize] attribute does not have a dependency on any specific user identity or role management mechanism.  Instead it works against the ASP.NET "User" object - which is extensible and allows any identity system to be used.

    AccountController Class

    I mentioned above that the [Authorize] attribute can be used with any authentication or user identity management system.  You can write or use any custom login UI and/or username/password management system you want with it.

    To help you get started, though, the ASP.NET MVC Project Template in Visual Studio now includes a pre-built "AccountController" and associated login views that implement a forms-authentication membership system with support for logging in, logging out, registering new users, and changing passwords.  All of the views templates and UI can be easily customized independent of the AccountController class or implementation:

    The Site.master template also now includes UI at the top-right that provides login/logout functionality.  When using forms-based authentication it will prompt you to login if you are not currently authenticated:

    And it displays a welcome message along with a logout link if you are authenticated on the site:

    Clicking the Login link above takes users to a Login screen like below that they can use to authenticate:

    New users can click the register link to create new accounts:

    Error handing and error display is also built-in:

    The AccountController class that is added to new projects uses the built-in ASP.NET Membership API to store and manage user credentials (the Membership system uses a provider API allowing any back-end storage to be plugged-in, and ASP.NET includes built-in providers for Active Directory and SQL Server).  If you don't want to use the built-in Membership system you can keep the same AccountController action method signatures, View templates, and Forms Authentication ticket logic, and just replace the user account logic within the AccountController class.  For the next ASP.NET MVC preview release we are planning to encapsulate the interaction logic between the AccountController and the user identity system behind an interface - which will make it easier to plug-in your own user storage system (without having to implement a full membership provider) as well as to easily unit test both it and the AccountController.

    Our hope is that this provides a nice way for people to quickly get started, and enable them to have a working end to end security system as soon as they create a new project.

    Testing TempData

    One last improvement to touch on in this first preview 4 post is some improvements being made on the Controller class that allow you to more easily unit test the TempData collection.  The TempData property allows you to store data that you want to persist for a future request from a user.  It has the semantic of only lasting one future request (after which it is removed).  It is typically used for MVC scenarios where you want to perform a client-side redirect to change the URL in the browser, and want a simple way to store scratch data.

    With previous ASP.NET MVC Previews you had to mock objects in order to test the TempData collection.  With Preview 4 you no longer need to mock or setup anything.  You can now add and verify objects within the Controller's TempData collection directly within your unit tests (for example: populate a controller's TempData property before calling its action method, or verify that the action updated the TempData after the action returned).  The actual storage semantics of the TempData collection is now encapsulated within a separate TempDataProvider property. 

    Conclusion

    Hopefully the above post provides a quick look at a number of the new features and changes coming with ASP.NET MVC Preview 4.  My next post on ASP.NET MVC Preview 4 will cover the new AJAX functionality that has been added, and demonstrate how to take advantage of it.

    Hope this helps,

    Scott

  • Silverlight 2 Beta2 Released

    Silverlight 2 Beta2 was released today.  You can download both Silverlight 2 Beta2 and the Visual Studio and Expression Blend tools support to target it here.

    Beta2 adds a lot of new features (more details below), but is still a 4.6 MB download that takes less than 10 seconds to install on a machine.  It does not require the .NET Framework or any other software to be installed for it to work, and all features work cross-browser on both Mac and Windows machines.  These features will also be supported on Linux via the Moonlight 2 release.

    Silverlight 2 Beta2 supports a go-live license that allows you to start using and deploying Silverlight 2 for commercial applications. There will be some API changes between Beta2 and the final release, so you should expect that applications you write with Beta2 will need to make some updates when the final release comes out.  But we think that these changes will be straight-forward and relatively easy, and that you can begin planning and starting commercial projects now.

    You can build Silverlight Beta2 applications using the VS 2008 Tools for Silverlight and Expression Blend 2.5 June Preview downloads.  You can download both of them here.  The VS 2008 Tools for Silverlight download works with both VS 2008 and the recent VS 2008 SP1 beta release. 

    UI and Control Improvements

    Silverlight 2 Beta2 includes a bunch of work in the UI and Control space:

    More Built-in Controls

    In Beta 1 only a few controls were included with the core Silverlight setup.  Most common controls (including Button, ListBox, Slider, etc) were shipped within separate assemblies that you had to bundle with your applications (which increased the app download size).  Beta 2 now installs 30+ of the most common controls as part of the core Silverlight 2 download.  This means that you can now build Silverlight 2 applications that use core controls that are as small as 3kb in size - making Silverlight application downloads small and startup time fast.

    In addition to the core controls included with the base Silverlight 2 setup, we are also this week shipping additional higher-level controls that are implemented in separate assemblies that you can then reference and include with your applications.  This includes controls like DataGrid (more details on its new Beta2 features below), Calendar (now with multi-day selection and blackout date support in Beta2), and a TabPanel control (new in Beta2).

    We ultimately expect to ship over a 100 controls for Silverlight.

    Control Template Editing Support

    One of the most powerful features of the WPF and Silverlight programming model is the ability to completely customize the look and feel of controls.  This allows developers and designers to sculpt the UI of controls in both subtle and dramatic ways, and enables a tremendous amount of flexibility.  I covered these concepts a little in my previous Silverlight Control Templating blog post here.

    This week's Expression Blend 2.5 June Preview now adds designer support for editing control templates - which makes it easy for you to quickly change the look of any control without having to drop-down to XAML source to-do it. 

    To see control template editing in action, just drag/drop two Slider controls onto the Expression Blend design surface:

    We might decide that the slider head in the default Slider control template is too large and wide for our application.  To use control template editing to change it, we can right-click on one of the sliders in the designer and select the "Edit Control Parts" context menu item.  We can choose to create a new empty control template for our slider (and start from scratch), or alternatively edit a copy of the built-in control template (and start from that and tweak it):

    After we choose to edit a copy of the existing control template, Blend will prompt us to create and name a re-usable style resource that we'll define our control template within.  We can name it and then choose to store the style at either the application level (within App.xaml) or within our current page/user-control:

    When we click "ok" we'll find ourselves in template editing mode for our Slider control.  We can change, tweak, or add/remove any of the underlying elements within the Slider control's template.  Notice below how in template editing mode we can see and select any of the underlying elements that make up the slider's control template (these are circled in red below in the "Objects" window). 

    To make our slider head narrower, we can select the "HorizontalThumb" element within the control template and adjust its width (either graphically or via the property grid): 

    We can then use the breadcrumb navigation bar at the top of the designer to navigate back to our page and see the control template changes applied:

    Notice that right now only one of our slider controls is using the new Style resource with the control template we defined. 

    To apply the same style resource to the other slider control as well, we can select it, right-click, and then use the "Apply Resource" context menu to apply our "ScottSlider" style to it as well:

    Once we do this both our sliders reference the same style:

    Changes we make to the "ScottSlider" style going forward will automatically apply to both controls.

    Note that all controls shipped with Silverlight 2 support control templates and will support the above editing experience in Expression Blend.

    Visual State Manager (VSM) Support

    Control templates in Silverlight and WPF support customizing both the "look" of a control, as well as the "feel" of a control.  By "feel" I mean changing its interactive responsiveness.  For example: how it reacts when pushed, when it gets focus, loses focus, is in a pushed state, is in a disabled state, has something inside it selected, etc.  Often you want animations to execute when the user interacts with a control like this.

    One of the new things we are introducing with Silverlight 2 Beta2 is a "Visual State Manager" (VSM) feature that makes it much easier to build interactive control templates.  VSM introduces two basic concepts that you can take advantage of within control templates: "Visual States" and "State Transitions".  For example, a control like Button defines multiple visual states for itself - "Normal", "MouseOver", "Pressed", "Disabled", "Focused", "Unfocused".   When in template editing mode in Blend, designers now have the ability to easily edit what the button looks like in each particular state, as well as setup transition rules to control how long it should take to animate when moving from one state to another.  At runtime Silverlight will then dynamically run the appropriate animation Storyboards to smoothly move the control from one state to another.

    What is nice about this model is that designers do not need to write code, do not need to manually create animation storyboards, and do not need to understand the object model of controls in order to be productive.  This makes the learning curve for creating interactive control templates really easy, and means that existing graphic designers can very easily work on Silverlight projects.  Later this year we will also be adding Visual State Manager (VSM) support to WPF as well, which will let you use the same approach with Windows applications as well as share control templates between WPF and Silverlight projects.

    To see an example of this in action, let's add a Button control onto our design surface:

    We can then right click on the button and edit its control template. Instead of starting with the existing default control template (like we did with the slider example above), let's create an empty control template and start from scratch:

    Blend will prompt us for the name of the Style resource we want to create.  We'll name it "ScottButton" and click ok.  This will then put the designer in control editing mode for the Button, and start with an empty control template:

    One of the things to notice above is the new "States" window inside Blend.  This will show us all of the available "Visual States" that the Button control exposes.  Above the "Base" state is currently selected - which allows us to define the common visual tree of our Button control template. 

    We can then add some vector elements into our base state that defines the look of a custom button like below.  We could use the built-in vector drawing tool support provided by Blend to author these graphics, or alternatively use Expression Design or Adobe Illustrator to build the vector art and then import it into Blend.  Below we are adding 4 "Path" elements into our control template - one a rounded background (named "background"), one a drop shadow (named "shadow"), one a 40% opacity "shine" that adds a glow near the top, and one that defines the default inner content (in this case a picture of a house):

    Note: we could have alternatively imported an image, but using vector elements will give us the flexibility to scale/stretch/transform the button later and retain a crisp look and feel at any resolution or scale (particularly useful with Silverlight mobile scenarios - where screen resolutions might be different or smaller).  It will also allow us to easily animate/change any vector element within the artwork.

    Once we've finished designing our base state above, we can press F5 to run our application in the browser:

    As you can see above - our Button control now has a nicer look.  Despite its new look, the button still raises the same focus, click and hover events just like before - so a developer using the button does not need to change any code when working with a button that uses our new control template.

    One downside with our new button control template, though, is that it isn't interactive.  This means that I don't get any visual feedback if the button gains/looses focus, or if a mouse hovers over it.  I also don't get a nice depress/bounce-back animation when I click it.

    To add interactivity to our button, we'll return back to Blend and work with our Button's control template again.  Previously we added vector graphic elements to the "Base" state of our Button control.  This allowed us to define the default visual look of all visual states of our Button.  We can now go back and customize individual Button visual states further.

    For example, to implement a mouse-over behavior for our Button, we can select the "MouseOver" state in the "States" window, and then tweak the look of the button when it is in that state.  Below I've selected the "shine" vector element inside our control template and adjusted its Opacity property in the property grid to have it be more visible when in the MouseOver state.  Notice how Blend automatically highlighted the "Shine" element with a red dot and then listed the Opacity property below it in our objects window.  This makes it easy to quickly track all changes that we've made between the "Base" state and the "MouseOver" state in our control template:

    We can then select the "Pressed" state in the "States" window, and customize what a button looks like when it is pressed.  We'll change two things from the "base" state.  The first change is to make the "shine" element visible (like the MouseOver state). The second change will be to slightly offset the contents of the button control - while keeping the shadow element stationary.  This will give the button a nice "depressed" look and contrast nicely with its base visual:

    We can implement the offset change to the background, content and shine elements by selecting them in the designer, and then apply an offset render transform to them in the property browser:

    And now when we run our application again in the browser, we'll find that our Button now has interactive visual feedback when it is being used.  Below is the "normal" look of our Button:

    <