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   (RSS)

  • Introducing ASP.NET MVC 3 (Preview 1)

    This morning we posted the “Preview 1” release of ASP.NET MVC 3.  You can download it here.

    We’ve used an iterative development approach from the very beginning of the ASP.NET MVC project, and deliver regular preview drops throughout the development cycle.  Our goal with early preview releases like the one today is to get feedback – both on what you like/dislike, and what you find missing/incomplete.  This feedback is super valuable – and ultimately makes the final product much, much better.

    ASP.NET MVC 3

    As you probably already surmised, ASP.NET MVC 3 is the next major release of ASP.NET MVC. 

    ASP.NET MVC 3 is compatible with ASP.NET MVC 2 – which means it will be easy to update projects you are writing with MVC 2 to MVC 3 when it finally releases.  The new features in MVC 3 build on top of the foundational work we’ve already done with the MVC 1 and MVC 2 releases – which means that the skills, knowledge, libraries, and books you’ve acquired are all directly applicable with the MVC 3 release.  MVC 3 adds new features and capabilities – it doesn’t obsolete existing ones.

    ASP.NET MVC 3 can be installed side-by-side with ASP.NET MVC 2, and you can install today’s “Preview 1” release on your machine without it impacting existing MVC 2 projects you are working on (they will continue to use MVC 2 unless you explicitly modify the projects to retarget them to MVC 3).  When you install “Preview 1” you will have a new set of ASP.NET MVC 3 project templates show up within Visual Studio 2010’s “New Project” dialog – choosing one of those when you create a new project will cause it to use MVC 3.

    Below are details about some of the new features and capabilities in today’s “Preview 1” release.  Unless otherwise noted, all of the features I describe are enabled with the preview build you can download and use today.  More ASP.NET MVC 3 features will come in future preview refreshes as we flesh out the product more and iterate on your feedback.

    View Improvements

    ASP.NET MVC 3 “Preview 1” includes a bunch of view-specific improvements.

    Add->View Dialog

    “Preview 1” includes a new “Add->View” dialog that makes it easy for you to choose the syntax you want to use when you create new view template files.  It allows you to select any of of the available view engines you have installed on your machine – giving you the ability to use whichever view templating approach feels most natural to you:

    AddView9

    There are a bunch of great open source view template engines out there (including Spark, NHaml, NDjango and more) – it is now much easier for them to integrate into Visual Studio.

    Today’s “Preview 1” build of ASP.NET MVC 3 comes with two view-engine already pre-enabled within the dialog: ASPX and Razor. 

    New “Razor” View Engine

    Earlier this month I blogged about the new “Razor” view engine we’ve been working on.  Based on the comments in the post, a lot of people are eagerly waiting to use it.  The good news is that you can start using it with today’s “Preview 1” release.

    Simple Razor Example

    Let’s build a super-simple store site that lists product categories, and allows visitors to click the categories to see a listing of products within them.  You can download a completed version of this sample here.

    image

    Below is a StoreController class that implements the two action methods (“Index” and “Browse”) needed to build the above scenario:

    image

    We’ll use the new “Razor” view engine to implement the view templates for our StoreController.

    Below is the “Layout.cshtml” layout-page that will define the common layout UI we want across our site.  The “RenderBody()” method indicates where view templates that are based on this master layout file should “fill in” the body content:

    image

    Below is the view template for the Index action.  It is based on the above layout page, and outputs a <ul> list of category names: 

    image

    The template above is using the standard Html.ActionLink() helper method in ASP.NET MVC to render a hyperlink that links to the “Browse” action method of our StoreController.  All of existing HTML helper methods in ASP.NET MVC work in “Razor” views – this is true both for the HTML helper methods built-into ASP.NET MVC, as well as those built by others (including vendors and the MvcContrib project).

    Below is the view template for the Browse action.  It lists the products within a specific category:

    image

    Notice above how we are using the “Model” property within our foreach statement to access the strongly-typed List of products we passed from our Controller.  We are doing this just like we would within .aspx view templates.  Razor also supports a “View” property which allows us to access un-typed “ViewData” passed to the view template.  “View” is a dynamic property (a new feature of .NET 4) – which gives us a slightly cleaner syntax when accessing ViewData.  Instead of writing ViewData[“Cateogry”] we can now just write View.Category.

    Clean and Concise

    The code in the screen-shots above contains everything we need to write to implement our Controller + Views.  “Razor” helps make view templates clean and concise, and I think you’ll find it enables a very fluid coding workflow. Read my “Razor” blog post from earlier in the month to learn more about the syntax and understand how it works.  You can download a running version of the above sample here.

    Code Intellisense and Colorization

    One of the things you might have noticed from the screen-shots above is that “Razor” file colorization and code intellisense is not yet supported in Visual Studio with today’s “Preview 1” release.  We will be enabling full code intellisense and colorization with a future preview refresh.  The VS 2010 editor will support Razor file intellisense for C#/VB code, as well as for HTML/CSS/JavaScript. 

    Other Improvements in the Future

    Three other enhancements we are working to enable in a future preview refresh are:

    • The ability to use a @model statement at the top of a “Razor” file instead of having to explicitly inherit from a base class.  This reduces the code and simplifies it.  
    • The ability to specify a default LayoutPage for the site to avoid having to explicitly set it within each view template.  This further reduces the code within the view template, and makes your code more DRY.
    • The ability to unit-test individual “Razor” template files without having to run the application or launch a web-server.

    With these first two changes the above Browse template will be able to be written as simply:

    image

    The above template syntax will be supported in a future preview refresh.  Full colorization and code-intellisense will be provided within the editor.

    Controller Improvements

    ASP.NET MVC 3 “Preview 1” includes several nice controller-specific enhancements.

    Global Filters

    ASP.NET MVC supports the ability to declaratively apply “cross-cutting” logic using a mechanism called “filters”.  You can specify filters on Controllers and Action Methods today using an attribute syntax like so:

    image

    Developers often want to apply some filter logic across all controllers within an application.  ASP.NET MVC 3 now enables you to specify that a filter should apply globally to all Controllers within an application.  You can now do this by adding it to the GlobalFilters collection.  A RegisterGlobalFilters() method is now included in the default Global.asax class template to provide a convenient place to do this (it is then called by the Application_Start() method):

    image

    The filter resolution logic in MVC 3 is flexible so that you can configure a global filter that only applies conditionally if certain conditions are met (for example: debugging is enabled, or if a request uses a particular http verb, etc).  Filters can also now be resolved from a Dependency Injection (DI) container – more on that below.

    New Dynamic ViewModel Property

    ASP.NET MVC Controllers have supported a “ViewData” property that enables you to pass data to a view template using a late-bound dictionary API.  For example:

    image

    The “ViewData” API is still supported in ASP.NET MVC 3.  MVC 3 augments it, though, with a new “ViewModel” property on Controller that is of type “dynamic” – and which enables you to use the new dynamic language support within VB and C# to pass ViewData items using a slightly cleaner syntax than the current dictionary API.  Now you can alternatively write the following code to achieve the same result as above:

    image

    You do not need to define any strongly-typed classes to use the ViewModel property.  Because it is a “dynamic” property you can instead just get/set properties on it and it will resolve them dynamically at runtime.  It internally stores the property name/value pairs within the ViewData dictionary.

    New ActionResult Types

    ASP.NET MVC 3 “Preview 1” includes several new ActionResult types and corresponding helper methods.

    HttpNotFoundResult

    The new HttpNotFoundResult class is used to indicate that a resource requested by the current URL was not found. It returns a 404 HTTP status code to the calling client. You can optionally use the new HttpNotFound() helper method on Controller to return an instance of this action result type, as shown in the following example:

    image

    Permanent Redirects

    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.  In conjunction with this change, the Controller class now has three new methods for performing permanent redirects: RedirectPermanent(), RedirectToRoutePermanent(), and RedirectToActionPermanent().  These methods return an instance of HttpRedirectResult with the Permanent property set to true.

    HttpStatusCodeResult

    The new HttpStatusCodeResult class can be used to set an explicit response status code and description. 

    JavaScript and AJAX Improvements

    ASP.NET MVC 3 includes built-in JSON binding support that enables action methods to receive JSON-encoded data and model-bind it to action method parameters. 

    To see this feature in action, consider the jQuery client-side JavaScript below.  It defines a “save” event handler that will be invoked when a save button is clicked on the client.  The code within the event handler constructs a client-side JavaScript “product” object with three fields whose values are retrieved from HTML input elements.  It then uses jQuery’s .ajax() method to POST a JSON based request containing the product to a /Store/UpdateProduct URL on the server:

    image

    ASP.NET MVC 3 now enables you to implement the /Store/UpdateProduct URL on the server using an action method like below:

    image

    The UpdateProduct() action method above accepts a strongly-typed Product object as a parameter.  ASP.NET MVC 3 can now automatically bind the incoming JSON post values to the .NET Product type on the server – without you having to write any custom binding or marshalling logic.  ASP.NET MVC’s built-in model and input validation features all work as you’d expect with this.

    We think this capability will be particularly useful going forward with scenarios involving client templates and data binding (like I’ve previously blogged about here).  Client templates will enable you to format and display a single data item or set of data items by using templates that execute on the client.  ASP.NET MVC 3 will enable you to easily connect client templates with action methods on the server that return and receive JSON data.

    Other JavaScript/AJAX Improvements in the Future

    Future preview refreshes of ASP.NET MVC 3 will include better support for unobtrusive JavaScript.  ASP.NET MVC 3 will also directly support the jQuery Validation library from within its built-in validation helper methods.

    Model Validation Improvements

    ASP.NET MVC 2 came with significant model validation improvements.  You can read my previous blog post to learn more about them.

    ASP.NET MVC 3 extends this work further, and adds support for several of the new validation features introduced within the System.ComponentModel.DataAnnotations namespace in .NET 4. In particular:

    • MVC 3 supports the new .NET 4 DataAnnotations metadata attributes such as DisplayAttribute.
    • MVC 3 supports the improvements made to the ValidationAttribute class in .NET 4.  The ValidationAttribute class was improved in .NET 4 to support a new IsValid overload that provides more information about the current validation context, such as what object is being validated.  This enables richer scenarios where you can validate the current value based on another property of the model. 
    • MVC 3 supports the new IValidatableObject interface introduced in .NET 4.  The IValidatableObject interface enables you to perform model-level validation, and enables you to provide validation error messages specific to the state of the overall model, or between two properties within the model. 

    Below is an example of using the IValidatableObject interface built-into .NET 4 to implement a custom validation method on a class.  This method can apply validation rules across multiple properties and yield back multiple validation errors (and optionally include both an error message like below as well as a list of property names that caused the violation):

    image

    ASP.NET MVC 3 now honors the IValidateObject interface when model binding (in addition to all of the other validation approaches it already supported with MVC 2), and will retrieve validation errors from it and automatically flag/highlight impacted fields within a view using the built-in HTML form helpers:

    image

    ASP.NET MVC 3 also introduces a new IClientValidatable interface that allows ASP.NET MVC to discover at runtime whether a validator has support for client validation.  This interface has been designed so that it can be integrated with a variety of validation frameworks.  MVC 3 also introduces a new IMetadataAware interface that simplifies how you can contribute to the ModelMetadata creation process. 

    Dependency Injection Improvements

    ASP.NET MVC 3 provides better support for applying Dependency Injection (DI) and integrating with Dependency Injection/IOC containers.

    In “Preview 1”, we’ve added support for dependency injection in the following places:

    • Controllers (registering & injecting controller factories, injecting controllers)
    • Views (registering & injecting view engines, injecting dependencies into view pages)
    • Action Filters (locating & injecting filters)

    For future previews we are investigating adding dependency injection support for:

    • Model Binders (registering & injecting)
    • Value Providers (registering & injecting)
    • Validation Providers (registering & injecting)
    • Model metadata Providers (registering & injecting)

    ASP.NET MVC 3 will support the Common Service Locator library, and any DI container that supports it’s IServiceLocator interface.  This will make it really easy to integrate any DI container that supports the Common Service Locator with ASP.NET MVC.

    Note: In Preview 1, we redefined the CSL interface in our codebase, and didn’t include the CSL DLL in our setup. This means that existing implementations of CSL won’t “just work” with “preview 1” – instead they’ll have to recompile their CSL implementations against our interface to make them work. Future preview refreshes will make this CSL library dependency easier, and avoid this extra step.

    Brad Wilson is starting a great blog series on ASP.NET MVC 3’s Dependency Injection Support.  Below are links to his first few articles about it:

    Click here to download a simple ASP.NET MVC 3 example that demonstrates how to use the popular Ninject Dependency Injection Container with ASP.NET MVC 3. 

    Downloads and Links

    Click here to download ASP.NET MVC 3 Preview 1.  Post feedback/issues about it in the ASP.NET MVC Forum.

    Once ASP.NET MVC 3 is installed, you can download and run the simple Razor sample I demonstrated in the blog post above. 

    Read my previous “Razor” blog post to learn more about how it works and its syntax.  Also read my recent EF4 Code-First and EF4 Code-First Schema Mapping posts to learn more about the database code and clean model layer I built using EF4 Code-First and SQL Express within the above sample.

    Summary

    We are excited to get today’s ASP.NET MVC 3 “Preview 1” release in people’s hands, and start receiving feedback on it. 

    Our primary goal with these early preview releases is to get feedback – both on what you like/dislike, and what you find missing/incomplete.  This feedback is super valuable – and ultimately makes the final product much, much better.  If you do install today’s “Preview 1” build, please post your feedback and any bugs/issues you find to the ASP.NET MVC forum at http://forums.asp.net.  The team will be monitoring this forum closely, and will be happy to help with anything you run into. 

    We will then iterate on the feedback you send us, and further refine ASP.NET MVC 3 in future preview refreshes.

    Hope this helps,

    Scott

    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

  • Entity Framework 4 “Code-First”: Custom Database Schema Mapping

    Last week I blogged about the new Entity Framework 4 “code first” development option.  The EF “code-first” option enables a pretty sweet code-centric development workflow for working with data.  It enables you to:

    • Develop without ever having to open a designer or define an XML mapping file
    • Define model objects by simply writing “plain old classes” with no base classes required
    • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything

    In last week’s blog post I demonstrated how to use the default EF4 mapping conventions to enable database persistence.  These default conventions work very well for new applications, and enable you to avoid having to explicitly configure anything in order to map classes to/from a database. 

    In today’s blog post I’m going to discuss how you can override the default persistence mapping rules, and use whatever custom database schema you want.  This is particularly useful for scenarios involving existing databases (whose schema is already defined and potentially can’t be changed) as well as for scenarios where you want your model shape to be different than how you want to persist it within a relational database.

    Quick Recap of our NerdDinner Sample

    In my blog post last week I walked through building a simple “NerdDinner” application from scratch, and demonstrated the productivity gains EF “code first” delivers when working with data. 

    image

    Below are the two model classes we created to represent data within the application.  They are “plain old CLR objects” (aka “POCO”) that only expose standard .NET data types:

    image

    We then created a “NerdDinners” class to help map these classes to/from a database.  “NerdDinners” derives from the DbContext class provided by the EF “code first” library and exposes two public properties:

    image

    We used the default EF4 “code first” conventions to enable database persistence.  This means that the “Dinners” and “RSVPs” properties on our “NerdDinners” class map to tables with the same names within our database.  Each property on our “Dinner” and “RSVP” model classes in turn map to columns within the “Dinners” and “RSVPs” tables.

    Below is the database schema definition for the “Dinners” table within our database:

    image

    Below is the database schema definition for the “RSVPs” table within our database:

    image

    We did not have to configure anything in order to get this database persistence mapping with EF4 “code first” – this occurs by default simply by writing the above three classes.  No extra configuration is required.

    Enabling Custom Database Persistence Mappings with EF4

    EF4 “Code First” enables you to optionally override its default database persistence mapping rules, and configure alternative ways to map your classes to a database.

    There are a few ways to enable this.  One of the easiest approaches is to override the “OnModelCreating” method defined on the DbContext base class:

    image

    The OnModelCreating method above will be called the first time our NerdDinners class is used within a running application, and it is passed a “ModelBuilder” object as an argument.  The ModelBuilder object can be used to customize the database persistence mapping rules of our model objects.  We’ll look at some examples of how to do this below.

    EF only calls the “OnModelCreating” method once within a running application – and then automatically caches the ModelBuilder results.  This avoids the performance hit of model creation each time a NerdDinners class is instantiated, and means that you don’t have to write any custom caching logic to get great performance within your applications.

    Scenario 1: Customize a Table Name

    Let’s now look at a few ways we can use the OnModelCreating method to customize the database persistence of our models.  We will begin by looking at a pretty common scenario – where we want to map a model class to a database schema whose table names are different than the classes we want to map them to. 

    For example, let’s assume our database uses a pattern where a “tbl” prefix is appended to the table names.  And so instead of a “Dinners” table we have a “tblDinners” table in the database: 

    image

    We want to still map our clean “Dinners” model class to this “tblDinners” table – and do so without having to decorate it with any data persistence attributes:

    image

    We can achieve this custom persistence mapping by overriding the “OnModelCreating” method within our NerdDinners context class, and specify a custom mapping rule within it like so:

    image

    The code within our OnModelCreating() method above uses a Fluent API design – which is a style of API design that employs method chaining to create more fluid and readable code.  We are using the ModelBuilder object to indicate that we want to map the “Dinner” class to the “tblDinners” table. 

    And that is all the code we need to write.  Now our application will use the “tblDinners” table instead of the “Dinners” table anytime it queries or saves Dinner objects.  We did not have to update our Dinner or RSVP model classes at all to achieve this – they will continue to be pure POCO objects with no persistence knowledge.

    Trying out the Above Change

    If you downloaded the completed NerdDinner sample from my previous blog post, you can modify it to include the above custom OnModelCreating() method and then re-run it to see the custom database persistence in action.

    We enabled the automatic database creation/recreation feature within EF “code-only” with the previous blog post.  This means that when you re-run the downloaded NerdDinner application immediately after making the above OnModelCreating() code change, you’ll notice that the SQL CE database is updated to have a “tblDinners” table instead of a “Dinners” table.  This is because EF detected that our model structure changed, and so re-created the database to match our model structure.  It honored our custom OnModelCreating() mapping rule when it updated it – which is why the table is now “tblDinners” instead of “Dinners”.

    Several people asked me at the end of my first blog post whether there was a way to avoid having EF auto-create the database for you.  I apparently didn’t make it clear enough that the auto-database creation/recreation support is an option you must enable (and doesn’t always happen).  You can always explicitly create your database however you want (using code, .sql deployment script, a SQL admin tool, etc) and just point your connection string at it – in which case EF won’t ever modify or create database schema.

    I showed the auto-database creation feature in the first blog post mostly because I find it a useful feature to take advantage of in the early stages of a new project.  It is definitely not required, and many people will choose to never use it.

    Importantly we did not have to change any of the code within the Controllers or Views of our ASP.NET MVC application.  Because our “Dinner” class did not change they were completely unaffected by the database persistence change.

    Scenario 2: Customize Column/Property Mappings

    Let’s now look at another common scenario – one where we want to map a model class to a database schema whose table and column names are different than the classes and properties we want to map them to. 

    For example, let’s assume our “tblDinners” database table contains columns that are prefixed with “col” – and whose names are also all different than our Dinner class:

    image

    We still want to map our clean “Dinners” model class to this “tblDinners” table – and do so without having to decorate it with any data persistence attributes:

    image

    We can achieve this custom persistence by updating our “OnModelCreating” method to have a slightly richer mapping rule like so:

    image

    The above code uses the same .MapSingleType() and .ToTable() fluent method calls that we used in the previous scenario.  The difference is that we are also now specifying some additional column mapping rules to the MapSingleType() method.  We are doing this by passing an anonymous object that associates our table column names with the properties on our Dinner class. 

    The dinner parameter we are specifying with the lambda expression is strongly-typed – which means you get intellisense and compile-time checking for the “dinner.” properties within the VS code editor.  You also get refactoring support within Visual Studio – which means that anytime you rename one of the properties on the Dinner class - you can use Visual Studio’s refactoring support to automatically update your mapping rules within the above context menu (no manual code steps required). 

    Scenario 3: Splitting a Table Across Multiple Types

    Relational tables within a database are often structured differently than how you want to design your object-oriented model classes.  What might be persisted as one large table within a database is sometimes best expressed across multiple related classes from a pure object-oriented perspective – and often you want the ability to split or shred tables across multiple objects related to a single entity.

    For example, instead of a single “colAddr” column for our address, let’s assume our “tblDinners” database table uses multiple columns to represent the “address” of our event:

    image

    Rather than surface these address columns as 4 separate properties on our “Dinner” model class, we might instead want to encapsulate them within an “Address” class and have our “Dinner” class exposes it as a property like so:

    image

    Notice above how we’ve simply defined an “Address” class that has 4 public properties, and the “Dinner” class references it simply by exposing a public “Address” property.  Our model classes are pure POCO with no persistence knowledge.

    We can update our “OnModelCreating” method to support a mapping of this hierarchical class structure to a single table in the database using a rule like so:

    image

    Notice how we are using the same mapping approach we used in the previous example – where we map table column names to strongly-typed properties on our model object.  We are simply extending this approach to support complex sub-properties as well.  The only new concept above is that we are also calling modelBuilder.ComplexType<Address>() to register our Address as a type that we can use within mapping expressions.

    And that is all we have to write to enable table shredding across multiple objects.

    Download an Updated NerdDinner Sample with Custom Database Persistence Rules

    You can download an updated version of the NerdDinner sample here.  It requires VS 2010 (or the free Visual Web Developer 2010 Express).

    You must download and install SQL CE 4 on your machine for the above sample to work.  You can download the EF Code-First library here.  Neither of these downloads will impact your machine.

    Summary

    The CTP4 release of the “EF Code-First” functionality provides a pretty nice code-centric way to work with data.  It brings with it a lot of productivity, as well as a lot of power.  Hopefully these two blog posts provides a glimpse of some of the possibilities it provides. 

    You can download the CTP4 release of EF Code-First here.  To learn even more about “EF Code-First” check out these blog posts by the ADO.NET team:

    Hope this helps,

    Scott

    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

  • VS 2010 Productivity Power Tools Update (with some cool new features)

    Last month I blogged about the VS 2010 Productivity Power Tools Extensions – a free set of Visual Studio 2010 extensions that provide some really nice additional functionality.

    The initial Visual Studio Productivity Power Tools release included a bunch of really useful productivity enhancements – including a much faster “Add Reference” dialog, lots of code editor additions and enhancements, and some nice IDE improvements around document tab management.  You can learn more about these features in my previous blog post.

    VS 2010 Productivity Power Tools Update

    Yesterday we shipped an update to the VS 2010 Productivity Power Tools which adds some nice new features and enhancements.

    If you already have the VS 2010 Productivity Power Tools installed, you can update it to the latest release by choosing Visual Studio’s “Tools->Extension Manager” menu command.  This will bring up the VS 2010 Extension Manager – which allows you to browse and download new extensions.  If you click the “Updates” tab on the left-hand side of the dialog it also allows you to see any updates that are available for extensions you already have installed within your IDE.

    Simply click the “Update” button for the Productivity Power Tools extension and it will download and install an update for it:

    image

    If you don’t already have the VS 2010 Productivity Power Tools installed, you can download and install it here.

    Sean has a nice blog post that describes all of this week’s productivity power tool updates and additions.  Below are a few of the highlights:

    Tools Options Support

    The top feature request with the productivity power tools has been to have the ability to turn on/off individual features and extensions it provides. 

    With last month’s release you couldn’t easily turn individual features on and off.  Starting with this week’s update you can use Tools->Options within VS 2010, and use a new Productivity Power Tools section to easily enable/disable each feature individually:

    image

    In addition to enabling/disabling individual features, you can also tweak/edit their settings (including color schemes and behavior).

    Solution Navigator

    Solution Navigator is a new VS 2010 tool window provided with this week’s update.  It acts like an enhanced Solution Explorer.  It merges functionality from Solution Explorer, Class View, Object Browser, Call Hierarchy, Navigate To, and Find Symbol References all into one tool window – and is pretty darn cool.  Here are just two scenarios of how you can take advantage of it:

    File + Class Explorer in One

    You can use the “Solution Navigator” to browse your project just like you would with the standard “Solution Explorer” tool window today.  Except instead of ending with only file sub-nodes, you can now expand them to see classes as well as individual methods and members within them. Clicking on one of the sub-nodes will navigate you immediately to the appropriate code block within the code editor.

    For example, below we’ve expanded the \Controllers folder within an ASP.NET MVC project and drilled into the AccountController.cs file – which has a AccountController class within it.  We can now drill into that class within the “Solution Navigator” to see a listing of all of its members – and double-click any of them to jump to it within the code editor:

    image

    Filter Solution

    You might have noticed the search box that is at the top of the Solution Navigator above.  You can search within it to quickly filter your solution view. 

    For example, below I’ve entered the string “Log” – which causes the “Solution Navigator” to automatically filter to only show those files and members that contain the word “Log” in their names (everything else is hidden within the explorer).  Notice below how my filtered views displays a “view template” file named “LogOn.cshtml”, the three “LogXYZ” methods within my AccountController class, the LogOnModel class within the AccountModels.cs file, and several tests within my test project whose names contain Log:

    image

    You can double click any of the filtered files or members to immediately navigate to it within the code editor.

    Quick Access

    Quick Access is a new VS 2010 tool window that allows you to quickly search for and execute common tasks within the IDE.  Ever wondered where a particular menu command is located?  Or ever struggled to find a specific option within the Tools->Options dialog?  Just enter it within Quick Access and it will help you locate it:

    image

    Clicking any of the items within the list will execute the command, or take you to the appropriate place in the IDE where it lives (in the case of Tools->Options settings):

    image

    Above I searched for “format” and brought up all the tools->options format settings.  Clicking the “Text Editor->C#->Formatting->New Lines” item within the list opens up the Tools-Options dialog to that exact option location.

    Summary

    I’ve only touched on a few of the improvements with this week’s update.  Read Sean’s blog post for even more details on the updates and improvements.

    If you haven’t installed the free VS 2010 Productivity Power Tools, I highly recommend doing so – I think you’ll find some useful extensions that you’ll like.  If you already have last month’s release installed, you can easily update it to this week’s release to take advantage of even more cool features – as well as benefit from bug fixes and performance improvements.

    Hope this helps,

    Scott

    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

  • Code-First Development with Entity Framework 4

    .NET 4 ships with a much improved version of Entity Framework (EF) – a data access library that lives in the System.Data.Entity namespace.

    When Entity Framework was first introduced with .NET 3.5 SP1, developers provided a lot of feedback on things they thought were incomplete with that first release.  The SQL team did a good job of listening to this feedback, and really focused the EF that ships with .NET 4 on addressing it. 

    Some of the big improvements in EF4 include:

    • POCO Support: You can now define entities without requiring base classes or data persistence attributes.
    • Lazy Loading Support: You can now load sub-objects of a model on demand instead of loading them up front.
    • N-Tier Support and Self-Tracking Entities: Handle scenarios where entities flow across tiers or stateless web calls.
    • Better SQL Generation and SPROC support: EF4 executes better SQL, and includes better integration with SPROCs
    • Automatic Pluralization Support: EF4 includes automatic pluralization support of tables (e.g. Categories->Category).
    • Improved Testability: EF4’s object context can now be more easily faked using interfaces.
    • Improved LINQ Operator Support: EF4 now offers full support for LINQ operators.

    Visual Studio 2010 also includes much richer EF designer and tooling support. The EF designer in VS 2010 supports both a “database first” development style – where you construct your model layer on a design surface from an existing database.  It also supports a “model first” development style – where you first define your model layer using the design surface, and can then use it to generate database schema from it.

    Code-First Development with EF

    In addition to supporting a designer-based development workflow, EF4 also enables a more code-centric option which we call “code first development”.  Code-First Development enables a pretty sweet development workflow.  It enables you to:

    • Develop without ever having to open a designer or define an XML mapping file
    • Define your model objects by simply writing “plain old classes” with no base classes required
    • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
    • Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping

    EF’s “code first development” support is currently enabled with a separate download that runs on top of the core EF built-into .NET 4.  CTP4 of this “code-first” library shipped this week and can be downloaded here

    It works with VS 2010, and you can use it with any .NET 4 project (including both ASP.NET Web Forms and ASP.NET MVC).

    Step by Step Tutorial: Building NerdDinner using a Code-First Approach

    Last year I wrote an ASP.NET MVC 1.0 tutorial that was published both online and in a book.  The tutorial walked through creating a simple application, called “NerdDinner”, which provides an easy way for people to organize, host and RSVP for dinners online.  You can read my original ASP.NET V1 NerdDinner tutorial here.  An updated version of the tutorial is also included in the new Professional ASP.NET MVC 2 book.

    The NerdDinner tutorial used a “database first approach” where the database schema was defined first, and then we used a Visual Studio designer to create our LINQ to SQL / LINQ to Entities model objects that mapped to it.  

    Below I’m going to demonstrate how we could instead use a “code first approach” using EF4 to build the NerdDinner model layer and database schema, and construct a CRUD application using ASP.NET MVC.

    image

    We will walkthrough building this application step-by-step.  A download link to a completed version of the sample is available at the end of this blog post.

    Step 1: Create a New Empty ASP.NET MVC 2 Application

    We’ll start by creating a new ASP.NET MVC 2 Project within Visual Studio 2010.  Choose File->New Project and use the “ASP.NET MVC 2 Empty Web Application” project template to do this.

    This will create an empty ASP.NET MVC 2 project that does not have any controllers, models or views within it:

    image

    We’ll next work to define our NerdDinner “model” – which refers to the objects that represent the data of our application, as well as the corresponding domain logic that integrates validation and business rules with it.  The model is the "heart" of an MVC-based application, and fundamentally drives the behavior of it.  We’ll create this model layer using the new EF4 “Code First” capabilities.

    Step 2: Create our Model

    Let’s assume we do not already have a database defined, and that we are building our new NerdDinner application completely from scratch.

    We do not need to start with a database

    When using a code-first development workflow, we do not need to begin our application by creating a database or specifying schema.  Instead we can begin by writing standard .NET classes that define the domain model objects that are most appropriate for our application – without having to worry about intermixing data persistence logic within them.

    Creating Model Classes

    NerdDinner is a small application, and our data storage needs with it are pretty simple.  We want to be able to define and store “Dinners” that refer to specific events that people can attend.  We also want to be able to define and store “RSVP” acceptances, which are used to track a person’s interest in attending a particular Dinner.

    Let’s create two classes (Dinner and RSVP) to represent these concepts.  We’ll do this by adding two new classes to our ASP.NET MVC project - “Dinner” and “RSVP”:

    image

    The above “Dinner” and “RSVP” model classes are “plain old CLR objects” (aka POCO).  They do not need to derive from any base classes or implement any interfaces, and the properties they expose are standard .NET data-types.  No data persistence attributes or data code has been added to them. 

    The ability to define model classes without having to tie them to a particular database, database API, or database schema implementation is really powerful – and provides us with much more data access flexibility.  It allows us to focus on our application/business needs without having to worry about persistence implementation.  It also gives us the flexibility to change our database schema or storage implementation in the future – without having to re-write our model objects, or the code that interacts with them.

    Creating a Context Class to Handle Database Persistence

    Now that we’ve defined our two POCO model classes, let’s create a class that we can use to handle the retrieval/persistence of Dinner and RSVP instances from a database. 

    We’ll name this class “NerdDinners”. It derives from the DbContext base class, and publishes two public properties – one that exposes our Dinner objects, and one that exposes our RSVP objects:

    image

    The DbContext and DbSet classes used above are provided as part of the EF4 Code-First library.  You’ll need to add a reference to the System.Data.Entity.CTP assembly that is installed into the \Program Files\Microsoft ADO.NET Entity Framework Feature CTP4\Binaries directory to reference these classes.  You’ll also want to add a “using System.Data.Entity” namespace statement at the top of your “NerdDinners” class file.

    That is all the code we need to write

    The above three classes contain all of the code necessary to implement a basic model and data persistence layer for our NerdDinner application.  We do not need to configure any additional database schema mapping information, nor run any tools, nor edit any XML files, nor use any designers in order to start using our classes to retrieve, update, and save data into a database.

    Convention Based Persistence Mapping

    We do not need to write any additional code, nor create any XML files, nor use any tools in order to map our model classes to and from a database.  How, you might ask, is that possible?

    By default, EF code-first supports a “convention over configuration” approach that enables you to rely on common mapping conventions instead of having to explicitly configure things.  You can override these conventions if you want to provide custom database mapping rules.  But if you instead just use the default conventions you’ll find that the amount of code you have to write is really small, and the common 90% of scenarios “just work” the way you’d expect them to without any extra code or configuration.

    In our example above, our NerdDinners context class will by default map its “Dinners” and “RSVPs” properties to “Dinners” and “RSVPs” tables within a database.  Each row within the Dinners table will map to an instance of our “Dinner” class.  Likewise, each row within the RSVPs table will map to an instance of our “RSVP” class.  Properties within the “Dinner” and “RSVP” classes in turn map to columns within the respective “Dinners” and “RSVPs” database tables.

    Other default conventions supported by EF include the ability to automatically identify primary-key and foreign keys based on common naming patterns (for example: an ID or DinnerID property on the Dinner class will be inferred as the primary key).  EF also includes smart conventions for wiring-up association relationships between models.  The EF team has a blog post that talks more about how the default set of conventions work here.

    Code Examples of How to Use Our Model

    The three classes we created earlier contain all of the code necessary to implement our model and data persistence for NerdDinner.  Let’s now look at a few code examples of how we can use these classes to perform common data scenarios:

    Query Using LINQ Expressions

    We can write LINQ query expressions to retrieve data from a database using the following code.  Below we are using a LINQ expression to retrieve all dinners that occur in the future:

    image

    We can also take advantage of relationships between Dinners and RSVPs when writing our LINQ expressions.  Notice below how our “where” statement filters by dinners whose RSVP count is greater than 0:

    image

    Note that the “where” filter in the above query (where we are retrieving only those Dinners who have at least one RSVP) executes in the database server – making the query and the amount of data we retrieve very efficient.

    Retrieving a Single Instance

    We can use LINQ’s Single() method with a lambda query to retrieve a single instance of a Dinner using code like below:

    image

    Alternatively, we can also take advantage of a Find() method that EF “code-first” exposes that allows you to easily retrieve an instance based on its ID:

    image

    Adding a new Dinner

    The code below demonstrates how to create and add a new Dinner to the database.  All we need to do is to “new” a Dinner object, set properties on it, and then add it to the Dinners property of our NerdDinners context object.  The NerdDinner context class supports a “unit of work” pattern that enables you to add multiple models to the context, and then call “SaveChanges()” on it to persist all of the changes to a database as a single atomic transaction.

    image

    Updating a Dinner

    The code below demonstrates how to retrieve a Dinner, update one of its properties, and then save the changes back to the database:

    image

    Step 3: Create a ASP.NET MVC Controller that uses our Model

    Let’s now look at a more complete scenario involving our model, where we use a controller class to implement the functionality necessary to publish a list of upcoming dinners, and enable users to add new ones:

    image

    We’ll implement this functionality by right-clicking on the “Controllers” folder and choose the “Add->Controller” menu command.  We’ll name our new controller “HomeController”.

    We’ll then add three “action methods” within it that work with the NerdDinners model we created earlier using EF “Code-First”:

    image

    The “Index” action method above retrieves and renders a list of upcoming dinners. 

    The “Create” action methods allow users to add new dinners.  The first “Create” method above handles the “HTTP GET” scenario when a user visits the /Home/Create URL, and send back a “New Dinner” form to fill out.  The second “Create” method handles the “HTTP POST” scenario associated with the form – and handles saving the dinner in the database.  If there are any validation issues it redisplays the form back to the user with appropriate error messages.

    Adding Views for our Controllers

    Our next step will be to add two “View templates” to our project – one for “Index” and one for “Create”. 

    We’ll add the “Index” view to our project by moving our cursor within the Index action method of our controller, and then right-click and choose the “Add View” menu command.  This will bring up the “Add View” dialog.  We’ll specify that we want to create a strongly-typed view, and that we are passing in a IEnumerable list of “Dinner” model objects to it:

    image

    When we click “Add”, Visual Studio will create a /Views/Home/Index.aspx file.  Let’s then add the following code to it – which generates a <ul> list of Dinners, and renders a hyperlink that links to our create action:

    image

    We’ll then add the “Create” view to our project by moving our cursor within the Create action method of our controller, and then right-click and choose the “Add View” menu command.  Within the “Add View” dialog we’ll specify that we want to create a strongly-typed view, and that we are passing it a Dinner object.  We’ll also indicate that we want to “scaffold” using a “Create” template:

    image

    When we click “Add”, Visual Studio will create a /Views/Home/Create.aspx file with some scaffold-generated content within it that outputs an HTML <form> for a “Dinner” object.  We’ll tweak it slightly and remove the input element for the DinnerID property.  Our final view template content will look like this:

    image

    We have now implemented all of the code we need to write within our Controller and Views to implement the Dinner listing and Dinner creation functionality within our web application.

    Step 4: The Database

    We’ve written our code.  Now let’s run the application. 

    But what about the database?

    We don’t have a database yet – and haven’t needed one so far because our “code first” development workflow hasn’t required us to have one to define and use our model classes. 

    But we will need a database when we actually run our application and want to store our Dinner and RSVP objects.  We can create the database one of two ways:

    1. Manually create and define the schema ourselves using a database tool (e.g. SQL Management Studio or Visual Studio)
    2. Automatically create and generate the schema directly from our model classes using the EF Code-First library

    This second option is pretty cool and is what we are going to use for our NerdDinner application.

    Configuring our Database Connection String

    To begin with, we’ll setup a connection-string to point to where we want our database to live.  We’ll do this by adding a “NerdDinners” connection-string entry to our application’s web.config file like so: 

    image 

    By default, when you create a DbContext class with EF code-first, it will look for a connection-string that matches the name of the context-class.  Since we named our context class “NerdDinners”, it will by default look for and use the above “NerdDinners” database connection-string when it is instantiated within our ASP.NET application.

    Taking advantage of SQL CE 4

    You can use many different databases with EF code-first – including SQL Server, SQL Express and MySQL.

    Two weeks ago I blogged about the work we are also doing to enable the embedded SQL CE 4 database engine to work within ASP.NET.  SQL CE 4 is a lightweight file-based database that is free, simple to setup, and can be embedded within your ASP.NET applications.  It supports low-cost hosting environments, and enables databases to be easily migrated to SQL Server.

    SQL CE can be a useful option to use when you are in the early stages of defining (and redefining) your model layer – and want to be able to quickly create and recreate your database as you do so.  We’ll use SQL CE 4 to begin with as we develop our NerdDinner application.  We can later optionally change the connection-string to use SQL Express or SQL Server for production deployment – without having to modify a single line of code within our application.

    The connection-string I specified above points to a NerdDinners.sdf database file, and specifies the SQL CE 4 database provider.  In order for this to work you need to install SQL CE 4 – either via the Standalone SQL CE Installer or by installing WebMatrix (which includes it built-in).  SQL CE 4 is a small download that only takes a few seconds to install.

    Important: In the connection-string above I’m indicating that we want to create the NerdDinners.sdf file within the |DataDirectory| folder – which in an ASP.NET application is the \App_Data\ folder immediately underneath the application directory.  By default the “Empty ASP.NET MVC Web Application” project template does not create this directory.  You will need to explicitly create this directory within your project (right click on the project and choose the “Add->ASP.NET Folder->Add_Data” menu item).

    Automatic Database Schema Creation

    EF code-first supports the ability to automatically generate database schema and create databases from model classes – enabling you to avoid having to manually perform these steps.

    This happens by default if your connection-string points to either a SQL CE or SQL Express database file that does not already exist on disk.  You do not need to take any manual steps for this to happen.

    To see this in action, we can press F5 to run our NerdDinner application.  This will launch a browser at the root “/” URL of our application.  You should see a screen like below rendered back:

    image

    The “/” URL to our application invoked the HomeController.Index() action method – which instantiated and queried our NerdDinners context object to retrieve all upcoming Dinners from our database.  Because the NerdDinners.sdf database file we pointed our connection-string to didn’t already exist, the EF code-first library automatically generated it for us.  It used our NerdDinners context object to automatically infer the database schema for the database it generated. 

    To see the SQL CE database file that was generated, click the “Show all Files” icon within the Visual Studio solution explorer, and then press the “Refresh” button and expand the App_Data folder:

    image 

    We will be shipping an update to VS 2010 in the future that enables you to open up and edit SQL CE 4 databases within the “Server Explorer” tab (just like you do with SQL databases today).  This will enable you to easily see (and optionally tweak) the schema and contents of the database.  Until then you can optionally use the database tools within WebMatrix to examine the SQL CE 4 database file’s contents. 

    We did not specify any custom persistence mapping rules with our NerdDinners context – so the database that was generated followed the default EF code-first naming conventions to map the schema.  If we had specified any custom mapping rules, though, the EF code-first library would have honored those and generated a database that matched them. 

    Just to refresh our memory – here are the two POCO model classes and the NerdDinners context class that we defined earlier:

    image

    Below are the tables that were added when we ran our application and the database was automatically created based on the above model:

    image 

    The definition of the “Dinners” table looks like below.  The column names and data-types map to the properties of the Dinner class we defined.  The DinnerID column has also been configured to be both a primary key and an identity column:

    image

    The definition of the “RSVPs” table looks like below.  The column names and data-types map to the properties of the RSVP class we defined.  The RsvpID column has also been configured to be both a primary key and an identity column:

    image

    A one to many primary key/foreign key relationship was also established between the Dinners and RSVPs tables.  The EF code-first library inferred that this should be established because our Dinner class has an ICollection<RSVP> property named RSVPs, and the RSVP class has a Dinner property.  

    Populating the Database with some Dinners

    Let’s now create and add some Dinners to our database.  We’ll do this by clicking the “Create New Dinner” link on our home-page to navigate to our “Create” form:

    image

    When we click the “Create” button, our new Dinner will be saved in the database.  We can repeat this multiple times to register several different Dinners.  Each new Dinner we create will be persisted within our database and show up in our Home listing of upcoming dinners:

    image 

    Step 5: Changing our Model

    We are going to continually evolve and refactor our model as our application grows.  The EF code-only library includes some nice development features that make it easier to coordinate this evolution with a development database.

    Adding a new Property to the Dinner Model

    Let’s walkthrough making a simple change to our Dinner class.  Specifically, we’ll add an additional property to our Dinner class called “Country”:

    image

    Now that we’ve made this change, let’s press F5 in Visual Studio to build and re-run the application.  When we do this we’ll see the below error message:

    image

    This error message occurs because we’ve changed the structure of our Dinner class, and our model object is now no longer the same shape as the “Dinners” table we automatically created within our database. 

    When EF automatically creates a database for you, it by default adds an “EdmMetadata” table to the database that tracks the shape of the model objects that were used to automatically create the database schema for you: 

    image

    The error message above occurs when EF detects that you’ve made a change to a model object and it is now out of sync with the database it automatically created for you. 

    Re-synchronizing our Model Classes with the Database

    There are a couple of ways we can “re-sync” our model objects and our database:

    • We can manually update our database schema to match our models
    • We can manually delete our database file, re-run the application, and have EF automatically re-create the database
    • We can enable a feature of EF code-first that automatically updates our database for us whenever we change our models

    Let’s look at how we can use this last automatic option with our NerdDinner application.

    The RecreateDatabaseIfModelChanges Feature

    CTP 4 of the EF Code First library includes a useful development-time feature that enables you to automatically re-create your database anytime you make modifications to your model classes.  When you enable it, EF identifies when any of the model classes that were used to automatically create a database are modified, and when that happens can re-create your database to match the new model class shape – without you having to take any manual steps to do so.

    This capability is especially useful when you are first developing an application, since it gives you the freedom and flexibility to quickly refactor and restructure your model code however you want - without having to do any manual work to keep your database schema in sync along the way.  It works especially well with SQL CE – since it is a file-based database that can be dropped and recreated on the fly in under a second.  This can enable an incredibly fluid development workflow.

    The easiest way to enable this capability is to add a Database.SetInitializer() call to the Application_Start() event handler within our Global.asax class:

    image

    This tells EF to re-create our NerdDinners.sdf database to match our NerdDinners model anytime our model classes change shape.  Now when we re-run our application we will no longer get that error message telling us that our model classes and database are out of sync.  EF will instead automatically re-create a database for us that matches our new model class shape, and our application will run fine:

    image

    Seeding Initial Data in Automatically Created Databases

    One of the things you might have noticed in the above screen-shot is that we lost our dinner data when we recreated the database.  This is because the automatic “RecreateDatabaseIfModelChanges” behavior isn’t intended for production scenarios where you want to “migrate” existing data from one schema to another.  Instead it is designed for development scenarios where you want the database to be quickly and automatically updated for you – without you having to take any manual steps or specify migration rules to do so. 

    Note: We are separately working to provide better data migration support for scenarios where you are working with production data and want to version the schema.  We think of that as a different scenario than this early development-time feature that I’m describing here.  The data migration capability isn’t enabled yet with this week’s CTP.

    EF supports the ability for us to optionally “seed” our generated database with default/test data anytime the database is created/recreated.  I find this feature really useful since it enables me to refactor a model, and then quickly run the application to try out a scenario – without having to enter in a bunch of test data manually to do so.

    We can “seed” our NerdDinners database with default data by writing a “NerdDinnersIntializer” class like below.  I’m using it to create two “sample dinners” and adding them to our database like so:

    image

    We can then update the Database.Initializer() call we added to our Global.asax to use this “NerdDinnersInitializer” class at startup:

    image

    And now anytime we make a change to one of our NerdDinner model classes, the database will be automatically dropped and recreated to match our models, and we’ll have two dinners already seeded in the database for testing purposes:

    image

    Easy Refactoring

    The above features make it really easy to evolve and refactor your code at development time – without having to use tools or run scripts to manually keep your database in sync with your code changes.

    Because our model classes, LINQ expressions, and “seed” test data are all strongly typed, we can also take advantage of refactoring tool support inside Visual Studio to quickly and automatically apply changes across our code base in a quick and easy way.

    Step 6: Adding Validation Rules

    We’ve built a nice, simple data-entry application.

    One problem with it, though, is that we don’t currently have any type of input validation in place to ensure that fields are filled out correctly within our Create Dinner form.  Let’s fix that.

    Adding Validation using DataAnnotations

    Validation rules in an ASP.NET MVC based application are usually best expressed within a model.  This enables them to be maintained in a single place, and enforced across any number of controllers and views that might interact with them.  ASP.NET MVC enables you to implement validation rules using a variety of different mechanisms, and is flexible enough to support just about any validation scheme you want to use. 

    ASP.NET MVC 2 includes built-in support for using .NET’s System.ComponentModel.DataAnnotations library of validation rules – which enable you to declaratively apply validation rules to model classes using validation attributes.  You can learn more about this capability in a previous blog post I wrote.  We’ll take advantage of this approach to enable input validation for our NerdDinner application.

    Let’s go back to the Dinner class we defined earlier and add some validation attributes to its properties (note: we need to add a “using System.ComponentModel.DataAnnotations” namespace as well):

    image

    The [Required] validation attribute indicates that a particular property must be specified.  The [StringLength] validation attribute allows us to indicate a maximum length for a particular string property.  The [RegularExpression] validation attribute allows us to indicate that a particular string property must match a specified regular expression in order to be valid – in this case an email address.

    Each of the validation attributes supports an “ErrorMessage” property – which allows us to specify an error message that should be displayed if the validation fails.  This can either be hard-coded as a string (like above) or pulled from a resource – enabling it to be easily localized.

    Referencing some CSS and JavaScript files

    The last step will be to go back to our Create.aspx view template and add a <link> reference to a Site.css file in our project, as well as two <script> elements that reference two JavaScript files in our project.  We’ll also add one line of code to call Html.EnableClientValidation() before our <form> element is rendered:

    image

    These changes will ensure that any validation error messages that are displayed in the page are styled (to make them more visible), and that the validation rules we apply on our model will be applied both on the client and on the server.

    Running the Application

    Let’s re-run the application and try to create a new Dinner.  Let’s begin by pushing the “Create” button with no values filled out.  We’ll find that we now see the validation error messages we applied to our model showing up in the browser:

    image

    Because we enabled client-side validation with ASP.NET MVC (that was the one line of code we wrote above), our error messages will update and change in real-time:

    image

    Notice above how our validation error message changed once our “Title” became longer than 20 characters.  This is because we have a [StringLength] property on our Dinner.Title property that indicates a maximum allowed size of 20 characters.  As we started entering a value within the “HostedBy” textbox, our error message likewise changed from the “[Requred]” error message (which asks you to enter your email address) to the “[RegularExpression]” error message (which is telling us we don’t have a valid email address).

    These validation rules work both within the browser (via JavaScript) and on the server (enabling us to protect ourselves even if someone tries to bypass the JavaScript validation) – without us having to make any changes to our controller class.  The ability to specify these rules once within our model, and have them apply everywhere, is extremely powerful – and will enable us to continue to evolve our application in a very clean way. 

    You can learn more about these ASP.NET MVC 2 Model Validation features and how they work here.

    Download

    Click here to download and run the above NerdDinnerReloaded sample we’ve built in this blog post.  It requires VS 2010 (or the free Visual Web Developer 2010 Express). 

    Important: You must download and install SQL CE 4 on your machine for the above sample to work.  You can download the EF Code-First library here.  Neither of these downloads will impact your machine.

    Summary

    This week’s CTP4 release of the “EF Code-First” functionality provides a pretty nice code-centric way to work with data.  It brings with it a lot of productivity, as well as a lot of power.  In today’s tutorial I focused mostly on some of the new productivity enhancements provided with the CTP4 release.  There are many more scenarios we could drill into including its Fluent API for enabling custom persistence mapping rules, its improved testability support, and other more advanced capabilities.

    You can download this week’s CTP4 release of EF Code-First here.  To learn even more about “EF Code-First” check out these blog posts by the ADO.NET team:

    Hope this helps,

    Scott

    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

  • Introducing WebMatrix

    Last week I published several blog posts that covered some new web development technologies we are releasing:

    • IIS Developer Express: A lightweight web-server that is simple to setup, free, works with all versions of Windows, and is compatible with the full IIS 7.5.

    • SQL Server Compact Edition: A lightweight file-based database that is simple to setup, free, can be embedded within your ASP.NET applications, supports low-cost hosting environments, and enables databases to be optionally migrated to SQL Server.

    • ASP.NET “Razor”: A new view-engine option for ASP.NET that enables a code-focused templating syntax optimized around HTML generation.  You can use “Razor” to easily embed VB or C# within HTML.  It’s syntax is easy to write, simple to learn, and works with any text editor.

    My posts last week covered how you’ll be able to take maximum advantage of these technologies using professional web development tools like Visual Studio 2010 and Visual Web Developer 2010 Express, and how these technologies will make your existing ASP.NET Web Forms and ASP.NET MVC development workflows even better.

    Today we are also announcing a new lightweight web development tool that also integrates the above technologies, and makes it even easier for people to get started with web development using ASP.NET.  This tool is free, provides core coding and database support, integrates with an open source web application gallery, and includes support to easily publish/deploy sites and applications to web hosting providers.

    We are calling this new tool WebMatrix, and the first preview beta of it is now available for download.

    What is in WebMatrix?

    WebMatrix is a 15MB download (50MB if you don’t have .NET 4 installed) and is quick to install.

    The 15MB download includes a lightweight development tool, IIS Express, SQL Compact Edition, and a set of ASP.NET extensions that enable you to build standalone ASP.NET Pages using the new Razor syntax, as well as a set of easy to use database and HTML helpers for performing common web-tasks.  WebMatrix can be installed side-by-side with Visual Studio 2010 and Visual Web Developer 2010 Express.

    Note: Razor support within ASP.NET MVC applications is not included in this first beta of WebMatrix – it will instead show up later this month in a separate ASP.NET MVC Preview - which will also include Visual Studio tooling support for it.

    Getting Started with WebMatrix

    WebMatrix is a task-focused tool that is designed to make it really easy to get started with web development.  It minimizes the number of concepts someone needs to learn in order to get simple things done, and includes and integrates all of the pieces necessary to quickly build Web sites.

    When you run WebMatrix it starts by displaying a screen like below.  The three icons on the right-hand side provide the ability to create new Web sites – either using an existing open-source application from a web application gallery, from site templates that contain some default pages you can start from, or from an empty folder on disk:

    image

    Create a Web Site using an Existing Open Source Application in the Web Gallery

    Let’s create a new Web site.  Instead of writing the site entirely ourselves, let’s use the Web Gallery and take advantage of the work others have done already.

    We’ll begin by clicking the “Site from Web Gallery” link on the WebMatrix home-screen.  This will launch the below UI – which allows us to browse an online gallery of popular open-source applications that we can easily start from, tweak/customize, and then deploy using WebMatrix.  The applications within the gallery includes both ASP.NET and PHP applications:

    image

    We can filter by category (Blog, CMS, eCommerce, etc) or simply scroll through the entire list.  For this first site let’s create a blog. We’ll build it using the popular BlogEngine.NET open source project:

    image

    When we select BlogEngine.NET and click “Next”, WebMatrix will identify (and offer to download) the required components that need to be installed on my local development machine in order for BlogEngine.NET to run.

    IIS Express is included with WebMatrix, so I already have a web-server (and don’t need to-do anything in order to configure it).  SQL Compact Edition is also included with WebMatrix, so I also have a light-weight database (and don’t need to-do anything in order to configure it).  Because SQL Compact is brand new, most projects in the Web Gallery don’t support it yet.  We expect most projects in the Web Gallery will add it as an option though in the future.  If a project requires either SQL Express or MySQL as a database, and you don’t have them installed, they will show up in the dependencies list below, and WebMatrix will offer to automatically download, install, and configure them for you.

    PHP applications in the web gallery (like WordPress, Drupal, Joomla and SugarCRM – all of which are there) will download and install both PHP and MySQL.

    Because I already have SQL Express installed on my machine, the only thing in my download list is BlogEngine.NET itself:

    image

    When I click the “I Accept” button, WebMatrix will download everything we need and install it on our machine:

    image

    When we click the “OK” button, WebMatrix will open up our new BlogEngine.NET project and display a site overview page for us:

    image

    This view within WebMatrix provides an overview of the project, and some quick links to-do common things with it (we’ll look at these more in a bit).

    To start – we’ll click the “Run” button in the Ribbon bar at the top.  Clicking the “Run” button will launch the site using the default browser you have configured on your system.  Alternatively, you can click to expand the list and pick which installed browser you want to run the site with.  Clicking the “Open in All Browsers” option will launch multiple browsers for you at once:

    image

    IIS Express is included as part of WebMatrix – and WebMatrix automatically configures IIS Express to run the project when it is opened within the tool (no extra steps or configuration required). 

    Running BlogEngine.NET will launch a browser and bring up the default page for the application (see below).  BlogEngine.NET by default ships with a home page that includes instructions on how to customize the site:

    image

    If you read the text it describes how the default adminsitrator password is “admin”/”admin”, and how you can login and customize the look and feel and content of the site.  Let’s login, then use the online admin tool to customize some of the basic settings of the site (the name, about the author, etc) and post two quick blog posts to get the site started:

    image

    The beauty is that I didn’t have to write any code (nor see any code for that matter) and was able to get the basics of our site up and running in only a few minutes.  This experience is a pretty consistent with all of the other applications within the web gallery.  They are all designed such that you can quickly install them using WebMatrix, run them locally, and then use their built-in admin tools to tweak/customize their core content and structure.

    Customizing the Code and Content Further

    Now that we’ve configured the basics of our blogging site, let’s now look at how we can customize it even further. To-do that let’s go back to WebMatrix and click on the “Files” node within the left-hand navigation bar of the tool:

    image

    This will open a file-system explorer view on the left-hand side of the tool, and allow us to browse the site, and open/edit/add/delete its files. 

    Most of the applications within the web gallery support a concept of “themes” and enable developers to tweak/customize the layout, styling and UI of the application.  Above I’ve drilled into BlogEngine.NET’s “themes” folder and opened the Site.Master file to customize the “standard” theme’s master layout.  We could tweak/customize it, hit save, and then run the site again to see our changes applied (note: pressing F12 is the keyboard short-cut to re-run the application). 

    Deploying a Site to a Hoster

    WebMatrix provides a lightweight, integrated work environment that allows us to run and tweak sites locally.  After we’ve finished customizing it, and have added some default content to the database, we’ll want to publish it to a hosting provider so that others can access our blog on the Internet. 

    WebMatrix includes built-in publishing support that makes it easy to deploy Web sites and Web applications to remote hosters.  WebMatrix supports using both FTP and FTP/SSL as well as the Microsoft Web Deploy (aka MSDeploy) infrastructure to easily deploy sites to both low-cost shared hosting providers, as well as virtual dedicated/dedicated hosting providers.

    To publish a site using WebMatrix, simply expand the “Publish” icon within the top-level ribbon UI:

    image

    When we select the “Configure” option it will bring up the following UI that allows us to configure where we want to deploy our site:

    image

    If you don’t already have a hosting provider, you can click the “find web hosting” link at the top of the publish dialog to bring up a list of available hosting providers to choose from:

    image

    Hosting providers are now offering Windows hosting plans that include ASP.NET + SQL Server for as cheap as $3.50/month (and these inexpensive offers include support for ASP.NET 4, ASP.NET MVC 2, Web Deploy, URL Rewrite and other features). 

    The “find web hosting” link this week includes a bunch of hosting providers who are also offering special free accounts that you can use with WebMatrix – enabling you to try it out at no cost (they also have everything setup to work well on the server-side with WebMatrix and are testing their offers with the WebMatrix publishing tools).

    Once you sign-up for a hosting provider, you can then choose from a variety of ways to publish your site to it:

    image

    FTP and FTP/SSL enable you to easily publish the local files of your site over to a remote server. 

    The “Web Deploy” option supports publishing both your site files and the database content – and is the recommended deployment option if your hoster supports it.  When the “Web Deploy” option is selected, WebMatrix will list all of the local databases within your project and provide you with the option to specify the connection-string at the remote hosting provider where your database should be deployed for production:

    image

    Note: By default BlogEngine.NET uses XML files to store content and settings (and doesn’t require a database).  With the current BlogEngine.NET on the web gallery you can just enter

    "Data Source=empty;database=empty;uid=empty;pwd=empty" as the remote database connection string in order to publish the site without needing to setup a database.

    When you click “Publish”, WebMatrix will display a preview of the deployment changes:

    image

    Note: because BlogEngine.NET doesn’t need a database we’ll keep the database deployment checkbox unchecked.  If we did want to transfer a database we could select it in the publishing preview wizard and WebMatrix will automatically transfer both the site files and the database schema+data to the remote host, deploy the database to the hosting server, and then update your published web.config connection-string to point to the production location. 

    Once we click “continue” WebMatrix will start the publishing process for our site, and after it completes our site will then be live on the Internet.  No extra steps are required.

    Site Updates

    In addition to initial deployments, WebMatrix also supports incremental file updates on subsequent publishes.  Make a change to a local file, click the Publish button again, and WebMatrix will calculate the differences between your local site and your published one and only transfer the files that have been modified (notice that the database by default will not be redeployed to avoid overwriting any data on the remote host):

    image

    Clicking the “continue” button above will only transfer the one modified file.  This makes updating even large sites easy and fast.

    Create a Custom Web Site with Code

    I’ve walked through how to create a new Web site using an open source application within the web gallery.  Let’s now look at how we can alternatively use WebMatrix to do some development of a custom site.

    The two right-most icons on the WebMatrix home-screen provide an easy way to create a new site that is either based on a simple template of pages, or an empty site with no content:

    image

    Let’s click the “Site From Template” icon and create a new site based on a template.  We’ll select the “Empty Site” template and name the site we want to create with it “FirstSite”:

    image

    When we click the “ok” button WebMatrix will load a site for us, and display a site overview page that contains links to common tasks:

    image

    Let’s click either the “Files” icon in the left-hand navigation bar or the “Browse your Files” link in the middle overview-screen. Selecting either of these will show us the file explorer.  The “Empty Site” template actually does have one file in it by default – a file named Index.cshtml.  We can double-click it to open it within the WebMatrix text editor:

    image

    Files with a .cshtml or .vbhtml extension are ones that use the new “Razor” template syntax that I blogged about last week.  You can use Razor files either as the view files for an ASP.NET MVC based application, or alternatively you can also use them as standalone pages within an ASP.NET Web site.  We are referring to these pages as simply “ASP.NET Web Pages” – and you can add them to both new projects as well as optionally drop them into existing ASP.NET Web Forms and ASP.NET MVC based applications.

    Why ASP.NET Web Pages?

    ASP.NET Web Pages built using Razor provide a simple, low concept count, way to do web development.  Many people will likely argue that they are not as powerful, nor have as many features, as an ASP.NET Web Forms or ASP.NET MVC based application.  This is true - they don’t have as many features, nor do they expose as rich a programming model.

    But they are conceptually very easy to understand, are lightweight to get started with, and for many audiences provide the easiest way to learn programming and begin to understand the basics of .NET development with VB or C#.  ASP.NET Web Pages are also convenient to use when all you need is some basic server scripting and data display/manipulation behavior, and you want to quickly put a site together.

    Building our First Simple ASP.NET Web Page

    Let’s build a simple page that lists out some content we are storing in a database. 

    If you are a professional developer who has spent years with .NET you will likely look at the below steps and think – this scenario is so basic - you need to understand so much more than just this to build a “real” application. What about encapsulated business logic, data access layers, ORMs, etc?  Well, if you are building a critical business application that you want to be maintainable for years then you do need to understand and think about these scenarios.

    Imagine, though, that you are trying to teach a friend or one of your children how to build their first simple application – and they are new to programming.  Variables, if-statements, loops, and plain old HTML are still concepts they are likely grappling with. Classes and objects are concepts they haven’t even heard of yet. Helping them get a scenario like below up and running quickly (without requiring them to master lots of new concepts and steps) will make it much more likely that they’ll be successful – and hopefully cause them to want to continue to learn more.

    One of the things we are trying to-do with WebMatrix is reach an audience who might eventually be able to be advanced VS/.NET developers – but who find the first learning step today too daunting, and who struggle to get started. 

    We’ll start by adding some HTML content to our page.  ASP.NET Web Pages typically start as just HTML files.  For this sample we’ll just add a static list to the page:

    image

    Just like with our previous scenario, IIS Express has been automatically configured to run the project we are editing – and we do not need to configure or setup anything for our web-server to run our site.

    We can press “F12” or use the “Run” button in the Ribbon toolbar to launch it in the browser.  As you’d expect, this will bring up a simple static page of our movies:

    image

    Working with Data

    Pretty basic so far.  Let’s now convert this page to use a database, and make the movie listing dynamic instead of having it just be a static list.

    Create a Database

    We’ll start by clicking the “Databases” tab within the left-hand navigation bar of WebMatrix.  This will bring up a simple database editor:

    image

    SQL Server Compact Edition ships with WebMatrix – and so is always available to use within projects.  Because it can be embedded within an application, it can also be easily copied and used in a remote hosting environment (no extra deployment or setup steps required – just publish up the database file with FTP or Web Deploy and you are good to go).

    Note: In addition to supporting SQL CE, the WebMatrix database tools below also work against SQL Express, SQL Server, as well as with MySQL. 

    We can create a new SQL CE database by clicking the “Add a Database to your site” link (either in the center of the screen or by using the “New Database” icon at the top in the ribbon).  This will add a “FirstSite.sdf” database file under an \App_Data directory within our application directory. 

    image

    We can then click the “New Table” icon within the Ribbon to create a new table to store our movie data.  We can use the “New Column” button in the Ribbon to add three columns to the table – Id, Name and Year.

    Note: for the first beta you have to use the property grid editor at the bottom of the screen to configure the columns – a richer database editing experience will show up in the next beta. 

    We’ll make Id the primary key by setting the “Is Primary Key” property to true:

    image

    We’ll then hit “save” and name the table “Movies”.  Once we do this it will show up under our Tables node on the left hand side. 

    Let’s then click the “Data” icon on the ribbon to edit the data in the table we just created, and add a few rows of movie data to it:

    image

    And now we have a database, with a table, with some movie data we can use in it.

    Using our Database within an ASP.NET Web Page

    ASP.NET Web Pages can use any .NET API or VB/C# language feature.  This means you can use the full power of .NET within any Web site or application built with it.  WebMatrix also includes some additional .NET libraries and helpers that you can optionally take advantage of for common tasks.

    One of these helpers is a simple database API that allows you to write SQL code against a database.  Let’s use it within our page to query our new Movies table and retrieve and display all of the movies within it.  To-do this we’ll go back to the Files tab in WebMatrix, and add the below code to our Index.cshtml file:

    image

    As you can see – the page is conceptually pretty simple (and doesn’t require understanding any deep object-oriented concepts).  We have two lines of code at the top of the file.

    The first line of code opens the database.  Database.Open() first looks to see if there is a connection-string named “FirstSite” in a web.config file – and if so will connect and use that as the database (note: right now we do not have any web.config file at all).  Alternatively, it looks in the \App_Data folder for a SQL Express database file named “FirstSite.mdf” or a SQL Compact database file name “FirstSite.sdf”.  If it finds either it will open it.  The second line of code performs a query against the database and retrieves all of the Movies within it.  Database.Query() returns back an dynamic list – where each dynamic object in the list is shaped based on the SQL query performed.

    We then have a foreach loop within our <ul> statement, which simply iterates over the movies collection, and outputs each name as a <li> element.  Because movies is a collection of dynamic objects, we can write @movies.Name instead of having to write movies[“Name”].

    When we re-run the page (or just hit refresh on it in the browser) and do a “view source” on the HTML returned to the client, we’ll see the following:

    image

    The list of movies above is now coming out of our database and is dynamic.

    Adding a Simple Filter Clause

    One last step we can do to make our application a little more dynamic is to add simple support to filter the list of movies based on a querystring parameter that is passed in. 

    We can do this by updating our Index.cshtml file to have a little extra code:

    image 

    Above we added a line of code to retrieve a “year” querystring parameter from the Request object.  We are taking advantage of a new “AsInt()” extension helper method that comes with WebMatrix.  This helper returns either the value as an integer, or if it is null returns zero.  We then modified our SELECT query to take a WHERE parameter as an argument.  The syntax we are using ensures that we cannot be hit with a SQL injection attack.

    Lastly, we added an if statement inside our <h1> which will append a (post 1975) message to the <h1> if a year filter is specified.  And now when we run the page again we will see all movies by default:

    image

    And we can optionally pass a “year” querystring parameter to show only those movies after that date:

    image

    Other Useful Web Helpers

    I used the Database helper library that ships with WebMatrix in my simple movie listing sample above. 

    WebMatrix also ships with other useful web helpers that you can take advantage of.  We’ll support these helpers not just within ASP.NET Web Pages – but also within ASP.NET MVC and ASP.NET Web Forms applications.  For example, to embed a live twitter search panel within your application you can write code like below to search tweets:

    image

    This will then display a live twitter feed of tweets that mention “scottgu”:

    image

    Other useful built-in helpers include ones to integrate with Facebook and Google Analytics, Create and Integrate Captchas and Gravitars, perform server-side dynamic charts (using the new Chart capabilities built-into ASP.NET 4), and more.

    All of these helpers will be available for use not only within ASP.NET Web Pages, but also in ASP.NET Web Forms and ASP.NET MVC applications.

    Easy Deployment

    Once we are done building our custom site, we can deploy it just like we did with BlogEngine.NET.  All we need to do is click the “Publish” button within WebMatrix, select a remote hosting provider, and our simple application will be live on the Internet.

    image

    Open in Visual Studio

    Projects created with WebMatrix can also be opened within Visual Studio 2010 and Visual Web Developer 2010 Express (which is free).  These tools provide an even richer set of features for web development, and a work environment more focused on professional development.  WebMatrix projects can be opened within Visual Studio simply by clicking the “Visual Studio” icon on the top-right of Ribbon UI:

    image

    This will launch VS 2010 or Visual Web Developer 2010 Express, and open it to edit the current Web site that is open within WebMatrix.  We’ll be shipping an update to VS 2010/VWD 2010 in the future that adds editor and project-system support for IIS Express, SQL CE, and the new Razor syntax.

    How to Learn More

    Click here to learn more about WebMatrix.  An early beta of WebMatrix can now be downloaded here

    You can read online tutorials and watch videos about WebMatrix by visiting the www.asp.net web-site.  Today’s beta is a first preview of a lot of this technology, and so the documentation and samples will continue to be refined in the weeks and months ahead.  We will also obviously be refining the feature-set based on your feedback and input.

    Summary

    IIS Express, SQL CE and the new ASP.NET “Razor” syntax bring with them a ton of improvements and capabilities for professional developers using Visual Studio, ASP.NET Web Forms and ASP.NET MVC.

    We think WebMatrix will be able to take advantage of these technologies to facilitate a simplified web development workload that is useful beyond professional development scenarios – and which enables even more developers to be able to learn and take advantage of ASP.NET for a wider variety of scenarios on the web.

    Hope this helps,

    Scott

  • Introducing “Razor”

    One of the things my team has been working on has been a new view engine option for ASP.NET.

    ASP.NET MVC has always supported the concept of “view engines” – which are the pluggable modules that implement different template syntax options.  The “default” view engine for ASP.NET MVC today uses the same .aspx/.ascx/.master file templates as ASP.NET Web Forms.  Other popular ASP.NET MVC view engines used today include Spark and NHaml.

    The new view-engine option we’ve been working on is optimized around HTML generation using a code-focused templating approach. The codename for this new view engine is “Razor”, and we’ll be shipping the first public beta of it shortly.

    Design Goals

    We had several design goals in mind as we prototyped and evaluated “Razor”:

    • Compact, Expressive, and Fluid: Razor minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.

    • Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of concepts. You use all your existing language and HTML skills.

    • Is not a new language: We consciously chose not to create a new imperative language with Razor. Instead we wanted to enable developers to use their existing C#/VB (or other) language skills with Razor, and deliver a template markup syntax that enables an awesome HTML construction workflow with your language of choice.

    • Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old text editor (notepad works great).

    • Has great Intellisense: While Razor has been designed to not require a specific tool or code editor, it will have awesome statement completion support within Visual Studio. We’ll be updating Visual Studio 2010 and Visual Web Developer 2010 to have full editor intellisense for it.

    • Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).

    We’ve spent the last few months building applications with it and doing lots of usability studies of it with a variety of volunteers (including several groups of non-.NET web developers). The feedback so far from people using it has been really great.

    Choice and Flexibility

    One of the best things about ASP.NET is that most things in it are pluggable. If you find something doesn’t work the way you want it to, you can swap it out for something else.

    The next release of ASP.NET MVC will include a new “Add->View” dialog that makes it easy for you to choose the syntax you want to use when you create a new view template file.  It will allow you to easily select any of of the available view engines you have installed on your machine – giving you the choice to use whichever view approach feels most natural to you:

    AddView9

    Razor will be one of the view engine options we ship built-into ASP.NET MVC.  All view helper methods and programming model features will be available with both Razor and the .ASPX view engine. 

    You’ll also be able to mix and match view templates written using multiple view-engines within a single application or site.  For example, you could write some views using .aspx files, some with .cshtml or .vbhtml files (the file-extensions for Razor files – C# and VB respectively), and some with Spark or NHaml.  You can also have a view template using one view-engine use a partial view template written in another.  You’ll have full choice and flexibility.

    Hello World Sample with Razor

    Razor enables you to start with static HTML (or any textual content) and then make it dynamic by adding server code to it.  One of the core design goals behind Razor is to make this coding process fluid, and to enable you to quickly integrate server code into your HTML markup with a minimum of keystrokes.

    To see a quick example of what I mean by minimizing keystrokes, let’s create a simple “hello world” sample that outputs a message like so:

    image

    Building it with .ASPX Code Nuggets

    If we were to build the above “hello world” sample using ASP.NET’s existing .ASPX markup syntax, we might write it using <%= %> blocks to indicate “code nuggets” within our HTML markup like so:

    image

    One observation to make about this “hello world” sample is that each code nugget block requires 5 characters (<%= %>) to denote the start and stop of the code sequence.  Some of these characters (in particular the % key – which is center top on most keyboards) aren’t the easiest to touch-type.

    Building it with Razor Syntax

    You denote the start of a code block with Razor using a @ character.  Unlike <% %> code nuggets, Razor does not require you to explicitly close the code-block:

    image

    The Razor parser has semantic knowledge of C#/VB code used within code-blocks – which is why we didn’t need to explicitly close the code blocks above.  Razor was able to identify the above statements as self-contained code blocks, and implicitly closed them for us.

    Even in this trivial “hello world” example we’ve managed to save ourselves 12 keystrokes over what we had to type before.  The @ character is also easier to reach on the keyboard than the % character which makes it faster and more fluid to type. 

    Loops and Nested HTML Sample

    Let’s look at another simple scenario where we want to list some products (and the price of each product beside it):

    image

    Building it with .ASPX Code Nuggets

    If we were to implement this using ASP.NET’s existing .ASPX markup syntax, we might write the below code to dynamically generate a <ul> list with <li> items for each product inside it:

    image 

    Building it with Razor Syntax

    Below is how to generate the equivalent output using Razor:

    image

    Notice above how we started a “foreach” loop using the @ symbol, and then contained a line of HTML content with code blocks within it.  Because the Razor parser understands the C# semantics in our code block, it was able to determine that the <li> content should be contained within the foreach and treated like content that should be looped.  It also recognized that the trailing } terminated the foreach statement.

    Razor was also smart enough to identify the @p.Name and @p.Price statements within the <li> element as server code – and execute them each time through the loop. Notice how Razor was smart enough to automatically close the @p.Name and @p.Price code blocks by inferring how the HTML and code is being used together.

    The ability to code like this without having to add lots of open/close markers throughout your templates ends up making the whole coding process really fluid and fast.

    If-Blocks and Multi-line Statements

    Below are a few examples of other common scenarios:

    If Statements

    Like our foreach example above, you can embed content within if statements (or any other C# or VB language construct), without having to be explicit about the code block’s begin/end.  For example:

    image

    Multi-line Statements

    You can denote multiple lines of code by wrapping it within a @{ code } block like so:

    image 

    Notice above how variables can span multiple server code blocks – the “message” variable defined within the multi-line @{ } block, for example, is also being used within the @message code block.  This is conceptually the same as the <% %> and <%= %> syntax within .aspx markup files.

    Multi-Token Statements

    The @( ) syntax enables a code block to have multiple tokens.  For example, we could re-write the above code to concatenate a string and the number together within a @( code ) block:

    image 

    Integrating Content and Code

    The Razor parser has a lot of language smarts built-into it – enabling you to rely on it to do the heavily lifting, as opposed to you having to explicitly do it yourself. 

    Does it break with email addresses and other usages of @ in HTML?

    Razor’s language parser is clever enough in most cases to infer whether a @ character within a template is being used for code or static content.  For example, below I’m using a @ character as part of an email address:

    image

    When parsing a file, Razor examines the content on the right-hand side of any @ character and attempts to determine whether it is C# code (if it is a CSHTML file) or VB code (if it is a VBHTML file) or whether it is just static content.  The above code will output the following HTML (where the email address is output as static content and the @DateTime.Now is evaluated as code:

    image

    In cases where the content is valid as code as well (and you want to treat it as content), you can explicitly escape out @ characters by typing @@.

    Identifying Nested Content

    When nesting HTML content within an if/else, foreach or other block statement, you should look to wrap the inner content within an HTML or XML element to better identify that it is the beginning of a content block.

    For example, below I’ve wrapped a multi-line content block (which includes a code-nugget) with a <span> element:

    image

    This will render the below content to the client – note that it includes the <span> tag:

    image

    You can optionally wrap nested content with a <text> block for cases where you have content that you want to render to the client without a wrapping tag:

    image

    The above code will render the below content to the client – note that it does not include any wrapping tag:

    image 

    HTML Encoding

    By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.

    Layout/MasterPage Scenarios – The Basics

    It is important to have a consistent look and feel across all of the pages within your web-site/application.  ASP.NET 2.0 introduced the concept of “master pages” which helps enable this when using .aspx based pages or templates.  Razor also supports this concept using “layout pages” – which allow you to define a common site template, and then inherit its look and feel across all the views/pages on your site.

    Simple Layout Example

    Below is a simple example of a layout page – which we’ll save in a file called “SiteLayout.cshtml”.  It can contain any static HTML content we want to include in it, as well as dynamic server code.  We’ll then add a call to the “RenderBody()” helper method at the location in the template where we want to “fill in” specific body content for a requested URL:

    image

    We can then create a view template called “Home.cshtml” that contains only the content/code necessary to construct the specific body of a requested page, and which relies on the layout template for its outer content:

    image

    Notice above how we are explicitly setting the “LayoutPage” property in code within our Home.cshtml file.  This indicates that we want to use the SiteLayout.cshtml template as the layout for this view.  We could alternatively indicate the layout file we want to use within a ASP.NET MVC Controller invoking Home.cshtml as a view template, or by configuring it as the default layout to use for our site (in which case we can specify it in one file in our project and have all view templates pick it up automatically).

    When we render Home.cshtml as a view-template, it will combine the content from the layout and sub-page and send the following content to the client:

    image

    Compact, Clean, Expressive Code

    One of the things to notice in the code above is that the syntax for defining layouts and using them from views/pages is clean and minimal.  The code screen-shots above of the SiteLayout.cshtml and Home.cshtml files contain literally all of the content in the two .cshtml files – there is no extra configuration or additional tags, no <%@ Page%> prefix, nor any other markup or properties that need to be set.

    We are trying to keep the code you write compact, easy and fluid.  We also want to enable anyone with a text editor to be able to open, edit and easily tweak/customize them.  No code generation or intellisense required.

    Layout/MasterPage Scenarios – Adding Section Overrides

    Layout pages optionally support the ability to define different “sections” within them that view templates based on the layout can then override and “fill-in” with custom content.  This enables you to easily override/fill-in discontinuous content regions within a layout page, and provides you with a lot of layout flexibility for your site.

    For example, we could return to our SiteLayout.cshtml file and define two sections within our layout that the view templates within our site can optionally choose to fill-in.  We’ll name these sections “menu” and “footer” – and indicate that they are optional (and not required) within our site by passing an optional=true parameter to the RenderSection() helper call (we are doing this using the new C# optional parameter syntax that I’ve previously blogged about).

    image

    Because these two sections are marked as “optional”, I’m not required to define them within my Home.cshtml file.  My site will continue to work fine if they aren’t there. 

    Let’s go back into Home.cshtml, though, and define a custom Menu and Footer section for them.  The below screenshot contains all of the content in Home.cshtml – there is nothing else required in the file.  Note: I moved setting the LayoutPage to be a site wide setting – which is why it is no longer there.

    image

    Our custom “menu” and “footer” section overrides are being defined within named @section { } blocks within the file.  We chose not to require you to wrap the “main/body” content within a section and instead to just keep it inline (which both saves keystrokes and enables you to easily add sections to your layout pages without having to go back through all your existing pages changing their syntax). 

    When we render Home.cshtml as a view-template again, it will now combine the content from the layout and sub-page, integrating the two new custom section overrides in it, and send down the following content to the client:

    image

    Encapsulation and Re-Use with HTML Helpers

    We’ve covered how to maintain a consistent site-wide look and feel using layout pages.  Let’s now look at how we can also create re-usable “HTML helpers” that enable us to cleanly encapsulate HTML generation functionality into libraries that we can re-use across our site – or even across multiple different sites.

    Code Based HTML Helpers

    ASP.NET MVC today has the concept of “HTML Helpers” – which are methods that can be invoked within code-blocks, and which encapsulate generating HTML.  These are implemented using pure code today (typically as extension methods).  All of the existing HTML extension methods built with ASP.NET MVC (both ones we’ve built and ones built by others) will work using the “Razor” view engine (no code changes required):

    image

    Declarative HTML Helpers

    Generating HTML output using a code-only class approach works – but is not ideal.

    One of the features we are looking to enable with Razor is an easy way to create re-usable HTML helpers using a more declarative approach.  Our plan is to enable you to define reusable helpers using a @helper { } declarative syntax like below. 

    image

    You’ll be able to place .cshtml files that contain these helpers into a Views\Helpers directory and then re-use them from any view or page in your site (no extra steps required):

    image

    Note above how our ProductListing() helper is able to define arguments and parameters.  This enables you to pass any parameters you want to them (and take full advantage of existing languages features like optional parameters, nullable types, generics, etc).  You’ll also get debugging support for them within Visual Studio.

    Note: The @helper syntax won’t be in the first beta of Razor – but is something we hope will be enabled with the next drop.  Code-based helpers will work with the first beta.

    Passing Inline Templates as Parameters

    One other useful (and extremely powerful) feature we are enabling with Razor is the ability to pass “inline template” parameters to helper methods.  These “inline templates” can contain both HTML and code, and can be invoked on-demand by helper methods.

    Below is an example of this feature in action using a “Grid” HTML Helper that renders a DataGrid to the client:

    image

    The Grid.Render() method call above is C#.  We are using the new C# named parameter syntax to pass strongly-typed arguments to the Grid.Render method - which means we get full statement completion/intellisense and compile-time checking for the above syntax.

    The “format” parameter we are passing when defining columns is an “inline template” – which contains both custom html and code, and which we can use to customize the format of the data.  What is powerful about this is that the Grid helper can invoke our inline template as a delegate method, and invoke it as needed and as many times as it wants. In the scenario above it will call it each time it renders a row in the grid – and pass in the “item” that our template can use to display the appropriate response.

    This capability will enable much richer HTML helper methods to be developed.  You’ll be able to implement them using both a code approach (like the way you build extension methods today) as well as using the declarative @helper {} approach.

    Visual Studio Support

    As I mentioned earlier, one of our goals with Razor is to minimize typing, and enable it to be easily edited with nothing more than a basic text editor (notepad works great).  We’ve kept the syntax clean, compact and simple to help enable that.

    We have also designed Razor so that you get a rich code editing experience within Visual Studio.  We will provide full HTML, JavaScript and C#/VB code intellisense within Razor based files:

    image

    Notice above how we are providing intellisense for a Product object on the “@p.” code embedded within the <li> element inside a foreach loop.  Also notice how our \Views folder within the Solution Explorer contains both .aspx and .cshtml view templates.  You can use multiple view engines within a single application – making it easy to choose whichever syntax feels best to you.

    Summary

    We think “Razor” provides a great new view-engine option that is streamlined for code-focused templating.  It a coding workflow that is fast, expressive and fun.  It’s syntax is compact and reduces typing – while at the same time improving the overall readability of your markup and code.  It will be shipping as a built-in view engine with the next release of ASP.NET MVC.  You can also drop standalone .cshtml/.vbhtml files into your application and run them as single-pages – which also enables you to take advantage of it within ASP.NET Web Forms applications as well.

    The feedback from developers who have been trying it out the last few months has been extremely positive.  We are going to be shipping the first public beta of it shortly, and are looking forward to your feedback on it.

    Hope this helps,

    Scott

    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

  • New Embedded Database Support with ASP.NET

    Earlier this week I blogged about IIS Express, and discussed some of the work we are doing to make ASP.NET development easier from a Web Server perspective.

    In today’s blog post I’m going to continue the simplicity theme, and discuss some of the work we are also doing to enable developers to quickly get going with database development.  In particular, I’m pleased to announce that we’ve just completed the engineering work that enables Microsoft’s free SQL Server Compact Edition (SQL CE) database to work within ASP.NET applications.  This enables a light-weight, easy to use, database option that now works great for ASP.NET web development.

    Introducing SQL Server Compact Edition 4

    SQL CE is a free, embedded, database engine that enables easy database storage.  We will be releasing the first public beta of SQL CE Version 4 very shortly. Version 4 has been designed and tested to work within ASP.NET Web applications.

    Works with Existing Data APIs

    SQL CE works with existing .NET-based data APIs, and supports a SQL Server compatible query syntax.  This means you can use existing data APIs like ADO.NET, as well as use higher-level ORMs like Entity Framework and NHibernate with SQL CE.  Pretty much any existing data API that supports the ADO.NET provider model will work with it.

    This enables you to use the same data programming skills and data APIs you know today.

    No Database Installation Required

    SQL CE does not require you to run a setup or install a database server in order to use it.  You can now simply copy the SQL CE binaries into the \bin directory of your ASP.NET application, and then your web application can run and use it as a database engine.  No setup or extra security permissions are required for it to run.  You do not need to have an administrator account on the machine.  It just works.

    Applications you build can redistribute SQL CE as part of them.  Just copy your web application onto any server and it will work.

    Database Files are Stored on Disk

    SQL CE stores databases as files on disk (within files with a .sdf file extension). You can store SQL CE database files within the \App_Data folder of your ASP.NET Web application - they do not need to be registered in order to use them within your application. 

    The SQL CE database engine then runs in-memory within your application.  When your application shuts down the database is automatically unloaded.

    Web Hosting Scenarios Are Now Supported with SQL CE 4

    SQL CE 4 can now run in “medium trust” ASP.NET 4 web hosting scenarios – without a hoster having to install anything. Hosters do not need to install SQL CE or do anything to their servers to enable it.

    This means you can build an ASP.NET Web application that contains your code, content, and now also a SQL CE database engine and database files – all contained underneath your application directory.  You can now deploy an application like this simply by using FTP to copy it up to an inexpensive shared web hosting account – no extra database deployment step or hoster installation required.

    SQL CE will then run within your application at the remote host.  Because it runs in-memory and saves its files to disk you do not need to pay extra for a SQL Server database.

    Visual Studio 2010 and Visual Web Developer 2010 Express Support

    VS 2010 and Visual Web Developer 2010 Express will add SQL CE 4 tooling support for ASP.NET scenarios in an update we’ll be rolling out in the future.  This will enable you to add SQL CE database files to your ASP.NET projects, use the Visual Studio Server Explorer to create and edit tables in them, and use higher-level designers like Entity Framework (see below) to model and map the database to classes that you can then query and program against using LINQ.

    image

    This means that in addition to using the same data APIs you know today, you will also be able to easily use the same development tools you already know with SQL CE.

    Supports Both Development and Production

    SQL CE can be used for both development scenarios and light-usage production usage scenarios.  With the SQL CE 4 release we’ve done the engineering work to ensure that SQL CE won’t crash or deadlock when used in a multi-threaded server scenario (like ASP.NET).  This is a big change from previous releases of SQL CE – which were designed for client-only scenarios and which explicitly blocked running in web-server environments.  Starting with SQL CE 4 you can use it in a web-server as well. 

    There are no license restrictions with SQL CE.

    Easy Migration to SQL Server 

    SQL CE is an embedded database – which makes it ideal for development and light-usage scenarios.  For high-volume sites and applications you’ll probably want to migrate it to use SQL Server Express (which is free), SQL Server or SQL Azure.  These servers enable much better scalability, more development features (including features like Stored Procedures – which aren’t supported with SQL CE), as well as more advanced data management capabilities.

    We’ll ship migration tools that enable you to optionally take SQL CE databases and easily upgrade them to use SQL Server Express, SQL Server, or SQL Azure.  You will not need to change your code when upgrading a SQL CE database to SQL Server or SQL Azure.  Our goal is to enable you to be able to simply change the database connection string in your web.config file and have your application just work.

    Summary

    SQL CE 4 provides an easy, lightweight database option that you’ll now be able to use with ASP.NET applications.  It will enable you to get started on projects quickly – without having to install a full database on your local development box.  Because it is a compatible subset of the full SQL Server, you write code against it using the same data APIs (ADO.NET, Entity Framework, NHibernate, etc).

    You will be able to easily deploy SQL CE based databases to a remote hosting account and use it to run light-usage sites and applications. As your site traffic grows you can then optionally upgrade the database to use SQL Server Express (which is free), SQL Server or SQL Azure – without having to change your code. 

    We’ll be shipping the first public beta of SQL CE 4 (along with IIS Express and several more cool things I’ll be blogging about shortly) next week.

    Hope this helps,

    Scott

  • May 20th Links: ASP.NET MVC, ASP.NET, .NET 4, VS 2010, Silverlight

    Here is the latest in my link-listing series.  Also check out my VS 2010 and .NET 4 series and ASP.NET MVC 2 series for other on-going blog series I’m working on.

    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    ASP.NET MVC

    • ASP.NET MVC with jTemplates Part 1 and Part 2: Steve Gentile has a nice two-part set of blog posts that demonstrate how to use the jTemplate and DataTable jQuery libraries to implement client-side data binding with ASP.NET MVC.

    • How to Configure VS 2010 Code Coverage for ASP.NET MVC Unit Tests: Visual Studio enables you to calculate the “code coverage” of your unit tests.  This measures the percentage of code within your application that is exercised by your tests – and can give you a sense of how much test coverage you have.  Gunnar Peipman demonstrates how to configure this for ASP.NET MVC projects.

    • Shrinkr URL Shortening Service Sample: A nice open source application and code sample built by Kazi Manzur that demonstrates how to implement a URL Shortening Services (like bit.ly) using ASP.NET MVC 2 and EF4.  More details here.

    • Creating RSS Feeds in ASP.NET MVC: Damien Guard has a nice post that describes a cool new “FeedResult” class he created that makes it easy to publish and expose RSS feeds from within ASP.NET MVC sites.

    ASP.NET

    .NET 4

    • Entity Framework 4 Video Series: Julie Lerman has a nice, free, 7-part video series on MSDN that walks through how to use the new EF4 capabilities with VS 2010 and .NET 4.  I’ll be covering EF4 in a blog series that I’m going to start shortly as well.

    • Getting Lazy with System.Lazy: System.Lazy and System.Lazy<T> are new features in .NET 4 that provide a way to create objects that may need to perform time consuming operations and defer the execution of the operation until it is needed.  Derik Whittaker has a nice write-up that describes how to use it.

    • LINQ to Twitter: Nifty open source library on Codeplex that enables you to use LINQ syntax to query Twitter.

    Visual Studio 2010

    • Using Intellitrace in VS 2010: Chris Koenig has a nice 10 minute video that demonstrates how to use the new Intellitrace features of VS 2010 to enable DVR playback of your debug sessions.

    • How to maintain control of your code using Layer Diagrams: Another great blog post by Jennifer Marsman that demonstrates how to setup a “layer diagram” within VS 2010 to enforce clean layering within your applications.  This enables you to enforce a compiler error if someone inadvertently violates a layer design rule.

    • Collapse Selection in Solution Explorer Extension: Useful VS 2010 extension that enables you to quickly collapse “child nodes” within the Visual Studio Solution Explorer.  If you have deeply nested project structures this extension is useful.

    Silverlight and Windows Phone 7

    Hope this helps,

    Scott

    P.S. If you haven’t already, check out this month’s "Find a Hoster” page on the www.asp.net website to learn about great (and very inexpensive) ASP.NET hosting offers.

  • jQuery Templates and Data Linking (and Microsoft contributing to jQuery)

    The jQuery library has a passionate community of developers, and it is now the most widely used JavaScript library on the web today.

    Two years ago I announced that Microsoft would begin offering product support for jQuery, and that we’d be including it in new versions of Visual Studio going forward. By default, when you create new ASP.NET Web Forms and ASP.NET MVC projects with VS 2010 you’ll find jQuery automatically added to your project.

    A few weeks ago during my second keynote at the MIX 2010 conference I announced that Microsoft would also begin contributing to the jQuery project.  During the talk, John Resig -- the creator of the jQuery library and leader of the jQuery developer team – talked a little about our participation and discussed an early prototype of a new client templating API for jQuery.

    In this blog post, I’m going to talk a little about how my team is starting to contribute to the jQuery project, and discuss some of the specific features that we are working on such as client-side templating and data linking (data-binding).

    Contributing to jQuery

    jQuery has a fantastic developer community, and a very open way to propose suggestions and make contributions.  Microsoft is following the same process to contribute to jQuery as any other member of the community.

    As an example, when working with the jQuery community to improve support for templating to jQuery my team followed the following steps:

    1. We created a proposal for templating and posted the proposal to the jQuery developer forum (http://forum.jquery.com/topic/jquery-templates-proposal and http://forum.jquery.com/topic/templating-syntax ).
    2. After receiving feedback on the forums, the jQuery team created a prototype for templating and posted the prototype at the Github code repository (http://github.com/jquery/jquery-tmpl ).
    3. We iterated on the prototype, creating a new fork on Github of the templating prototype, to suggest design improvements. Several other members of the community also provided design feedback by forking the templating code.

    There has been an amazing amount of participation by the jQuery community in response to the original templating proposal (over 100 posts in the jQuery forum), and the design of the templating proposal has evolved significantly based on community feedback.

    The jQuery team is the ultimate determiner on what happens with the templating proposal – they might include it in jQuery core, or make it an official plugin, or reject it entirely.  My team is excited to be able to participate in the open source process, and make suggestions and contributions the same way as any other member of the community.

    jQuery Template Support

    Client-side templates enable jQuery developers to easily generate and render HTML UI on the client.  Templates support a simple syntax that enables either developers or designers to declaratively specify the HTML they want to generate.  Developers can then programmatically invoke the templates on the client, and pass JavaScript objects to them to make the content rendered completely data driven.  These JavaScript objects can optionally be based on data retrieved from a server.

    Because the jQuery templating proposal is still evolving in response to community feedback, the final version might look very different than the version below. This blog post gives you a sense of how you can try out and use templating as it exists today (you can download the prototype by the jQuery core team at http://github.com/jquery/jquery-tmpl or the latest submission from my team at http://github.com/nje/jquery-tmpl). 

    jQuery Client Templates

    You create client-side jQuery templates by embedding content within a <script type="text/html"> tag.  For example, the HTML below contains a <div> template container, as well as a client-side jQuery “contactTemplate” template (within the <script type="text/html"> element) that can be used to dynamically display a list of contacts:

    image

    The {{= name }} and {{= phone }} expressions are used within the contact template above to display the names and phone numbers of “contact” objects passed to the template.

    We can use the template to display either an array of JavaScript objects or a single object. The JavaScript code below demonstrates how you can render a JavaScript array of “contact” object using the above template. The render() method renders the data into a string and appends the string to the “contactContainer” DIV element:

    image

    When the page is loaded, the list of contacts is rendered by the template.  All of this template rendering is happening on the client-side within the browser:

    image 

    Templating Commands and Conditional Display Logic

    The current templating proposal supports a small set of template commands - including if, else, and each statements. The number of template commands was deliberately kept small to encourage people to place more complicated logic outside of their templates.

    Even this small set of template commands is very useful though. Imagine, for example, that each contact can have zero or more phone numbers. The contacts could be represented by the JavaScript array below:

    image

    The template below demonstrates how you can use the if and each template commands to conditionally display and loop the phone numbers for each contact:

    image

    If a contact has one or more phone numbers then each of the phone numbers is displayed by iterating through the phone numbers with the each template command:

    image

    The jQuery team designed the template commands so that they are extensible. If you have a need for a new template command then you can easily add new template commands to the default set of commands.

    Support for Client Data-Linking

    The ASP.NET team recently submitted another proposal and prototype to the jQuery forums (http://forum.jquery.com/topic/proposal-for-adding-data-linking-to-jquery). This proposal describes a new feature named data linking. Data Linking enables you to link a property of one object to a property of another object - so that when one property changes the other property changes.  Data linking enables you to easily keep your UI and data objects synchronized within a page.

    If you are familiar with the concept of data-binding then you will be familiar with data linking (in the proposal, we call the feature data linking because jQuery already includes a bind() method that has nothing to do with data-binding).

    Imagine, for example, that you have a page with the following HTML <input> elements:

    image

    The following JavaScript code links the two INPUT elements above to the properties of a JavaScript “contact” object that has a “name” and “phone” property:

    image

    When you execute this code, the value of the first INPUT element (#name) is set to the value of the contact name property, and the value of the second INPUT element (#phone) is set to the value of the contact phone property. The properties of the contact object and the properties of the INPUT elements are also linked – so that changes to one are also reflected in the other.

    Because the contact object is linked to the INPUT element, when you request the page, the values of the contact properties are displayed:

    image

    More interesting, the values of the linked INPUT elements will change automatically whenever you update the properties of the contact object they are linked to.

    For example, we could programmatically modify the properties of the “contact” object using the jQuery attr() method like below:

    image

    Because our two INPUT elements are linked to the “contact” object, the INPUT element values will be updated automatically (without us having to write any code to modify the UI elements):

    image

    Note that we updated the contact object above using the jQuery attr() method. In order for data linking to work, you must use jQuery methods to modify the property values.

    Two Way Linking

    The linkBoth() method enables two-way data linking. The contact object and INPUT elements are linked in both directions. When you modify the value of the INPUT element, the contact object is also updated automatically.

    For example, the following code adds a client-side JavaScript click handler to an HTML button element. When you click the button, the property values of the contact object are displayed using an alert() dialog:

    image

    The following demonstrates what happens when you change the value of the Name INPUT element and click the Save button. Notice that the name property of the “contact” object that the INPUT element was linked to was updated automatically:

    image

    The above example is obviously trivially simple.  Instead of displaying the new values of the contact object with a JavaScript alert, you can imagine instead calling a web-service to save the object to a database. The benefit of data linking is that it enables you to focus on your data and frees you from the mechanics of keeping your UI and data in sync.

    Converters

    The current data linking proposal also supports a feature called converters. A converter enables you to easily convert the value of a property during data linking.

    For example, imagine that you want to represent phone numbers in a standard way with the “contact” object phone property. In particular, you don’t want to include special characters such as ()- in the phone number - instead you only want digits and nothing else. In that case, you can wire-up a converter to convert the value of an INPUT element into this format using the code below:

    image

    Notice above how a converter function is being passed to the linkFrom() method used to link the phone property of the “contact” object with the value of the phone INPUT element. This convertor function strips any non-numeric characters from the INPUT element before updating the phone property.  Now, if you enter the phone number (206) 555-9999 into the phone input field then the value 2065559999 is assigned to the phone property of the contact object:

    image

    You can also use a converter in the opposite direction also. For example, you can apply a standard phone format string when displaying a phone number from a phone property.

    Combining Templating and Data Linking

    Our goal in submitting these two proposals for templating and data linking is to make it easier to work with data when building websites and applications with jQuery. Templating makes it easier to display a list of database records retrieved from a database through an Ajax call. Data linking makes it easier to keep the data and user interface in sync for update scenarios.

    Currently, we are working on an extension of the data linking proposal to support declarative data linking. We want to make it easy to take advantage of data linking when using a template to display data.

    For example, imagine that you are using the following template to display an array of product objects:

    image

    Notice the {{link name}} and {{link price}} expressions. These expressions enable declarative data linking between the SPAN elements and properties of the product objects. The current jQuery templating prototype supports extending its syntax with custom template commands. In this case, we are extending the default templating syntax with a custom template command named “link”.

    The benefit of using data linking with the above template is that the SPAN elements will be automatically updated whenever the underlying “product” data is updated.  Declarative data linking also makes it easier to create edit and insert forms. For example, you could create a form for editing a product by using declarative data linking like this:

    image

    Whenever you change the value of the INPUT elements in a template that uses declarative data linking, the underlying JavaScript data object is automatically updated. Instead of needing to write code to scrape the HTML form to get updated values, you can instead work with the underlying data directly – making your client-side code much cleaner and simpler.

    Downloading Working Code Examples of the Above Scenarios

    You can download this .zip file to get with working code examples of the above scenarios.  The .zip file includes 4 static HTML page:

    • Listing1_Templating.htm – Illustrates basic templating.
    • Listing2_TemplatingConditionals.htm – Illustrates templating with the use of the if and each template commands.
    • Listing3_DataLinking.htm – Illustrates data linking.
    • Listing4_Converters.htm – Illustrates using a converter with data linking.

    You can un-zip the file to the file-system and then run each page to see the concepts in action.

    Summary

    We are excited to be able to begin participating within the open-source jQuery project.  We’ve received lots of encouraging feedback in response to our first two proposals, and we will continue to actively contribute going forward.  These features will hopefully make it easier for all developers (including ASP.NET developers) to build great Ajax applications.

    Hope this helps,

    Scott

    P.S. [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

  • Visual Studio 2010 Extension Manager (and the new VS 2010 PowerCommands Extension)

    This is the twenty-third in a series of blog posts I’m doing on the VS 2010 and .NET 4 release.

    Today’s blog post covers some of the extensibility improvements made in VS 2010 – as well as a cool new "PowerCommands for Visual Studio 2010” extension that Microsoft just released (and which can be downloaded and used for free).

    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    Extensibility in VS 2010

    VS 2010 provides a much richer extensibility model than previous releases.  Anyone can build extensions that add, customize, and light-up the Visual Studio 2010 IDE, Code Editors, Project System and associated Designers.

    VS 2010 Extensions can be created using the new MEF (Managed Extensibility Framework) which is built-into .NET 4.  You can learn more about how to create VS 2010 extensions from this this blog post from the Visual Studio Team Blog.

    VS 2010 Extension Manager

    Developers building extensions can distribute them on their own (via their own web-sites or by selling them). 

    Visual Studio 2010 also now includes a built-in “Extension Manager” within the IDE that makes it much easier for developers to find, download, and enable extensions online.  You can launch the “Extension Manager” by selecting the Tools->Extension Manager menu option:

    image

    This loads an “Extension Manager” dialog which accesses an “online gallery” at Microsoft, and then populates a list of available extensions that you can optionally download and enable within your copy of Visual Studio:

    image

    There are already hundreds of cool extensions populated within the online gallery.  You can browse them by category (use the tree-view on the top-left to filter them).  Clicking “download” on any of the extensions will download, install, and enable it.

    PowerCommands for Visual Studio 2010

    This weekend Microsoft released the free PowerCommands for Visual Studio 2010 extension to the online gallery.  You can learn more about it here, and download and install it via the “Extension Manager” above (search for PowerCommands to find it).

    The PowerCommands download adds dozens of useful commands to Visual Studio 2010.  Below is a screen-shot of just a few of the useful commands that it adds to the Solution Explorer context menus:

    image

    Below is a list of all the commands included with this weekend’s PowerCommands for Visual Studio 2010 release:

    • Enable/Disable PowerCommands in Options dialog
      This feature allows you to select which commands to enable in the Visual Studio IDE. Point to the Tools menu, then click Options. Expand the PowerCommands options, then click Commands. Check the commands you would like to enable.
      Note: All power commands are initially defaulted Enabled.

    • Format document on save / Remove and Sort Usings on save
      The Format document on save option formats the tabs, spaces, and so on of the document being saved. It is equivalent to pointing to the Edit menu, clicking Advanced, and then clicking Format Document. The Remove and sort usings option removes unused using statements and sorts the remaining using statements in the document being saved.
      Note: The Remove and sort usings option is only available for C# documents. Format document on save and Remove and sort usings both are initially defaulted OFF.
    • Clear All Panes
      This command clears all output panes. It can be executed from the button on the toolbar of the Output window.
    • Copy Path
      This command copies the full path of the currently selected item to the clipboard. It can be executed by right-clicking one of these nodes in the Solution Explorer:
      The solution node; A project node; Any project item node; Any folder.
    • Email CodeSnippet
      To email the lines of text you select in the code editor, right-click anywhere in the editor and then click Email CodeSnippet.
    • Insert Guid Attribute
      This command adds a Guid attribute to a selected class. From the code editor, right-click anywhere within the class definition, then click Insert Guid Attribute.
    • Show All Files
      This command shows the hidden files in all projects displayed in the Solution Explorer when the solution node is selected. It enhances the Show All Files button, which normally shows only the hidden files in the selected project node.
    • Undo Close
      This command reopens a closed document , returning the cursor to its last position. To reopen the most recently closed document, point to the Edit menu, then click Undo Close. Alternately, you can use the CtrlShiftZ shortcut.
      To reopen any other recently closed document, point to the View menu, click Other Windows, and then click Undo Close Window. The Undo Close window appears, typically next to the Output window. Double-click any document in the list to reopen it.
    • Collapse Projects
      This command collapses a project or projects in the Solution Explorer starting from the root selected node. Collapsing a project can increase the readability of the solution. This command can be executed from three different places: solution, solution folders and project nodes respectively.
    • Copy Class
      This command copies a selected class entire content to the clipboard, renaming the class. This command is normally followed by a Paste Class command, which renames the class to avoid a compilation error. It can be executed from a single project item or a project item with dependent sub items.
    • Paste Class
      This command pastes a class entire content from the clipboard, renaming the class to avoid a compilation error. This command is normally preceded by a Copy Class command. It can be executed from a project or folder node.
    • Copy References
      This command copies a reference or set of references to the clipboard. It can be executed from the references node, a single reference node or set of reference nodes.
    • Paste References
      This command pastes a reference or set of references from the clipboard. It can be executed from different places depending on the type of project. For CSharp projects it can be executed from the references node. For Visual Basic and Website projects it can be executed from the project node.
    • Copy As Project Reference
      This command copies a project as a project reference to the clipboard. It can be executed from a project node.
    • Edit Project File
      This command opens the MSBuild project file for a selected project inside Visual Studio. It combines the existing Unload Project and Edit Project commands.
    • Open Containing Folder
      This command opens a Windows Explorer window pointing to the physical path of a selected item. It can be executed from a project item node
    • Open Command Prompt
      This command opens a Visual Studio command prompt pointing to the physical path of a selected item. It can be executed from four different places: solution, project, folder and project item nodes respectively.
    • Unload Projects
      This command unloads all projects in a solution. This can be useful in MSBuild scenarios when multiple projects are being edited. This command can be executed from the solution node.
    • Reload Projects
      This command reloads all unloaded projects in a solution. It can be executed from the solution node.
    • Remove and Sort Usings
      This command removes and sort using statements for all classes given a project. It is useful, for example, in removing or organizing the using statements generated by a wizard. This command can be executed from a solution node or a single project node.
    • Extract Constant
      This command creates a constant definition statement for a selected text. Extracting a constant effectively names a literal value, which can improve readability. This command can be executed from the code editor by right-clicking selected text.
    • Clear Recent File List
      This command clears the Visual Studio recent file list. The Clear Recent File List command brings up a Clear File dialog which allows any or all recent files to be selected.
    • Clear Recent Project List
      This command clears the Visual Studio recent project list. The Clear Recent Project List command brings up a Clear File dialog which allows any or all recent projects to be selected.
    • Transform Templates
      This command executes a custom tool with associated text templates items. It can be executed from a DSL project node or a DSL folder node.
    • Close All
      This command closes all documents. It can be executed from a document tab.

    How to temporarily disable extensions

    Extensions provide a great way to make Visual Studio even more powerful, and can help improve your overall productivity.  One thing to keep in mind, though, is that extensions run within the Visual Studio process (DevEnv.exe) and so a bug within an extension can impact both the stability and performance of Visual Studio. 

    If you ever run into a situation where things seem slower than they should, or if you crash repeatedly, please temporarily disable any installed extensions and see if that fixes the problem.  You can do this for extensions that were installed via the online gallery by re-running the extension manager (using the Tools->Extension Manager menu option) and by selecting the “Installed Extensions” node on the top-left of the dialog – and then by clicking “Disable” on any of the extensions within your installed list:

    image

    Hope this helps,

    Scott

  • April 30th Links: ASP.NET, ASP.NET MVC, Visual Studio 2010

    Here is the latest in my link-listing series.

    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    ASP.NET

    ASP.NET MVC

    • Code Snippets for ASP.NET MVC 2 in VS 2010: Raj Kaimal documents some of the new code snippets for ASP.NET MVC 2 that are now built-into Visual Studio 2010.  Read this article to learn how to do common scenarios with fewer keystrokes.

    Visual Studio 2010

    • SharePoint Development with VS 2010: Beth Massi links to a bunch of nice “How do I?” videos that that demonstrate how to use the SharePoint development support built-into VS 2010.

    • Using the WPF Tree Visualizer in VS 2010: Zain blogs about the new WPF Tree Visualizer supported by the VS 2010 debugger.  This makes it easier to visualize WPF control hierarchies within the debugger.

    • TFS 2010 Power Tools Released: Brian Harry blogs about the cool new TFS 2010 extensions released with this week’s TFS 2010 Power Tools release.

    • What is New with T4 in VS 2010: T4 is the name of Visual Studio’s template-based code generation technology.  Lots of scenarios within VS 2010 now use T4 for code generation customization. Two examples are ASP.NET MVC Views and EF4 Model Generation.  This post describes some of the many T4 infrastructure improvements in VS 2010.

    Hope this helps,

    Scott

    P.S. If you haven’t already, check out this month’s "Find a Hoster” page on the www.asp.net website to learn about great (and very inexpensive) ASP.NET hosting offers.

  • VS 2010 Debugger Improvements (BreakPoints, DataTips, Import/Export)

    This is the twenty-first in a series of blog posts I’m doing on the VS 2010 and .NET 4 release.  Today’s blog post covers a few of the nice usability improvements coming with the VS 2010 debugger. 

    The VS 2010 debugger has a ton of great new capabilities.  Features like Intellitrace (aka historical debugging), the new parallel/multithreaded debugging capabilities, and dump debuging support typically get a ton of (well deserved) buzz and attention when people talk about the debugging improvements with this release.  I’ll be doing blog posts in the future that demonstrate how to take advantage of them as well. 

    With today’s post, though, I thought I’d start off by covering a few small, but nice, debugger usability improvements that were also included with the VS 2010 release, and which I think you’ll find useful.

    Breakpoint Labels

    VS 2010 includes new support for better managing debugger breakpoints.  One particularly useful feature is called “Breakpoint Labels” – it enables much better grouping and filtering of breakpoints within a project or across a solution. 

    With previous releases of Visual Studio you had to manage each debugger breakpoint as a separate item. Managing each breakpoint separately can be a pain with large projects and for cases when you want to maintain “logical groups” of breakpoints that you turn on/off depending on what you are debugging.  Using the new VS 2010 “breakpoint labeling” feature you can now name these “groups” of breakpoints and manage them as a unit.

    Grouping Multiple Breakpoints Together using a Label

    Below is a screen-shot of the breakpoints window within Visual Studio 2010.  This lists all of the breakpoints defined within my solution (which in this case is the ASP.NET MVC 2 code base):

    image

    The first and last breakpoint in the list above breaks into the debugger when a Controller instance is created or released by the ASP.NET MVC Framework.

    Using VS 2010, I can now select these two breakpoints, right-click, and then select the new “Edit labels…” menu command to give them a common label/name (making them easier to find and manage):

    image

    Below is the dialog that appears when I select the “Edit labels” command.  We can use it to create a new string label for our breakpoints or select an existing one we have already defined.  In this case we’ll create a new label called “Lifetime Management” to describe what these two breakpoints cover:

    image

    When we press the OK button our two selected breakpoints will be grouped under the newly created “Lifetime Management” label:

    image

    Filtering/Sorting Breakpoints by Label

    We can use the “Search” combobox to quickly filter/sort breakpoints by label.  Below we are only showing those breakpoints with the “Lifetime Management” label:

    image

    Toggling Breakpoints On/Off by Label

    We can also toggle sets of breakpoints on/off by label group.  We can simply filter by the label group, do a Ctrl-A to select all the breakpoints, and then enable/disable all of them with a single click:

    image

    Importing/Exporting Breakpoints

    VS 2010 now supports importing/exporting breakpoints to XML files – which you can then pass off to another developer, attach to a bug report, or simply re-load later. 

    To export only a subset of breakpoints, you can filter by a particular label and then click the “Export breakpoint” button in the Breakpoints window:

    image

    Above I’ve filtered my breakpoint list to only export two particular breakpoints (specific to a bug that I’m chasing down).  I can export these breakpoints to an XML file and then attach it to a bug report or email – which will enable another developer to easily setup the debugger in the correct state to investigate it on a separate machine. 

    Pinned DataTips

    Visual Studio 2010 also includes some nice new “DataTip pinning” features that enable you to better see and track variable and expression values when in the debugger. 

    Simply hover over a variable or expression within the debugger to expose its DataTip (which is a tooltip that displays its value)  – and then click the new “pin” button on it to make the DataTip always visible:

    image

    You can “pin” any number of DataTips you want onto the screen.  In addition to pinning top-level variables, you can also drill into the sub-properties on variables and pin them as well. 

    Below I’ve “pinned” three variables: “category”, “Request.RawUrl” and “Request.LogonUserIdentity.Name”.  Note that these last two variable are sub-properties of the “Request” object.

    image 

    Associating Comments with Pinned DataTips

    Hovering over a pinned DataTip exposes some additional UI within the debugger:

    image

    Clicking the comment button at the bottom of this UI expands the DataTip - and allows you to optionally add a comment with it:

    image

    This makes it really easy to attach and track debugging notes:

    image

    Pinned DataTips are usable across both Debug Sessions and Visual Studio Sessions

    Pinned DataTips can be used across multiple debugger sessions.  This means that if you stop the debugger, make a code change, and then recompile and start a new debug session - any pinned DataTips will still be there, along with any comments you associate with them. 

    Pinned DataTips can also be used across multiple Visual Studio sessions.  This means that if you close your project, shutdown Visual Studio, and then later open the project up again – any pinned DataTips will still be there, along with any comments you associate with them.

    See the Value from Last Debug Session (Great Code Editor Feature)

    How many times have you ever stopped the debugger only to go back to your code and say:

    $#@! – what was the value of that variable again???

    One of the nice things about pinned DataTips is that they keep track of their “last value from debug session” – and you can look these values up within the VB/C# code editor even when the debugger is no longer running

    DataTips are by default hidden when you are in the code editor and the debugger isn’t running.  On the left-hand margin of the code editor, though, you’ll find a push-pin for each pinned DataTip that you’ve previously setup:

    image

    Hovering your mouse over a pinned DataTip will cause it to display on the screen.  Below you can see what happens when I hover over the first pin in the editor - it displays our debug session’s last values for the “Request” object DataTip along with the comment we associated with them:

    image

    This makes it much easier to keep track of state and conditions as you toggle between code editing mode and debugging mode on your projects.

    Importing/Exporting Pinned DataTips

    As I mentioned earlier in this post, pinned DataTips are by default saved across Visual Studio sessions (you don’t need to do anything to enable this).

    VS 2010 also now supports importing/exporting pinned DataTips to XML files – which you can then pass off to other developers, attach to a bug report, or simply re-load later.

    image

    Combined with the new support for importing/exporting breakpoints, this makes it much easier for multiple developers to share debugger configurations and collaborate across debug sessions.

    Summary

    Visual Studio 2010 includes a bunch of great new debugger features – both big and small. 

    Today’s post shared some of the nice debugger usability improvements. All of the features above are supported with the Visual Studio 2010 Professional edition (the Pinned DataTip features are also supported in the free Visual Studio 2010 Express Editions) 

    I’ll be covering some of the “big big” new debugging features like Intellitrace, parallel/multithreaded debugging, and dump file analysis in future blog posts. 

    Hope this helps,

    Scott

    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

  • Tip/Trick: Fix Common SEO Problems Using the URL Rewrite Extension

    Search engine optimization (SEO) is important for any publically facing web-site.  A large % of traffic to sites now comes directly from search engines, and improving your site’s search relevancy will lead to more users visiting your site from search engine queries.  This can directly or indirectly increase the money you make through your site.

    This blog post covers how you can use the free Microsoft URL Rewrite Extension to fix a bunch of common SEO problems that your site might have.  It takes less than 15 minutes (and no code changes) to apply 4 simple URL Rewrite rules to your site, and in doing so cause search engines to drive more visitors and traffic to your site.  The techniques below work equally well with both ASP.NET Web Forms and ASP.NET MVC based sites.  They also works with all versions of ASP.NET (and even work with non-ASP.NET content).

    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    Measuring the SEO of your website with the Microsoft SEO Toolkit

    A few months ago I blogged about the free SEO Toolkit that we’ve shipped.  This useful tool enables you to automatically crawl/scan your site for SEO correctness, and it then flags any SEO issues it finds.  I highly recommend downloading and using the tool against any public site you work on.  It makes it easy to spot SEO issues you might have in your site, and pinpoint ways to optimize it further.

    Below is a simple example of a report I ran against one of my sites (www.scottgu.com) prior to applying the URL Rewrite rules I’ll cover later in this blog post:

    seo9_thumb_28660B78[1] 

    Search Relevancy and URL Splitting

    Two of the important things that search engines evaluate when assessing your site’s “search relevancy” are:

    1. How many other sites link to your content.  Search engines assume that if a lot of people around the web are linking to your content, then it is likely useful and so weight it higher in relevancy.
    2. The uniqueness of the content it finds on your site.  If search engines find that the content is duplicated in multiple places around the Internet (or on multiple URLs on your site) then it is likely to drop the relevancy of the content.

    One of the things you want to be very careful to avoid when building public facing sites is to not allow different URLs to retrieve the same content within your site.  Doing so will hurt with both of the situations above. 

    In particular, allowing external sites to link to the same content with multiple URLs will cause your link-count and page-ranking to be split up across those different URLs (and so give you a smaller page rank than what it would otherwise be if it was just one URL).  Not allowing external sites to link to you in different ways sounds easy in theory – but you might wonder what exactly this means in practice and how you avoid it.

    4 Really Common SEO Problems Your Sites Might Have

    Below are 4 really common scenarios that can cause your site to inadvertently expose multiple URLs for the same content.  When this happens external sites linking to yours will end up splitting their page links across multiple URLs - and as a result cause you to have a lower page ranking with search engines than you deserve.

    SEO Problem #1: Default Document

    IIS (and other web servers) supports the concept of a “default document”.  This allows you to avoid having to explicitly specify the page you want to serve at either the root of the web-site/application, or within a sub-directory.  This is convenient – but means that by default this content is available via two different publically exposed URLs (which is bad).  For example:

    http://scottgu.com/

    http://scottgu.com/default.aspx

    SEO Problem #2: Different URL Casings

    Web developers often don’t realize URLs are case sensitive to search engines on the web.  This means that search engines will treat the following links as two completely different URLs:

    http://scottgu.com/Albums.aspx

    http://scottgu.com/albums.aspx

    SEO Problem #3: Trailing Slashes

    Consider the below two URLs – they might look the same at first, but they are subtly different. The trailing slash creates yet another situation that causes search engines to treat the URLs as different and so split search rankings:

    http://scottgu.com

    http://scottgu.com/

    SEO Problem #4: Canonical Host Names

    Sometimes sites support scenarios where they support a web-site with both a leading “www” hostname prefix as well as just the hostname itself.  This causes search engines to treat the URLs as different and split search rankling:

    http://scottgu.com/albums.aspx/

    http://www.scottgu.com/albums.aspx/

    How to Easily Fix these SEO Problems in 10 minutes (or less) using IIS Rewrite

    If you haven’t been careful when coding your sites, chances are you are suffering from one (or more) of the above SEO problems.  Addressing these issues will improve your search engine relevancy ranking and drive more traffic to your site.

    The “good news” is that fixing the above 4 issues is really easy using the URL Rewrite Extension.  This is a completely free Microsoft extension available for IIS 7.x (on Windows Server 2008, Windows Server 2008 R2, Windows 7 and Windows Vista).  The great thing about using the IIS Rewrite extension is that it allows you to fix the above problems *without* having to change any code within your applications. 

    You can easily install the URL Rewrite Extension in under 3 minutes using the Microsoft Web Platform Installer (a free tool we ship that automates setting up web servers and development machines).  Just click the green “Install Now” button on the URL Rewrite Spotlight page to install it on your Windows Server 2008, Windows 7 or Windows Vista machine:

    image

    Once installed you’ll find that a new “URL Rewrite” icon is available within the IIS 7 Admin Tool:

    image

    Double-clicking the icon will open up the URL Rewrite admin panel – which will display the list of URL Rewrite rules configured for a particular application or site:

    image

    Notice that our rewrite rule list above is currently empty (which is the default when you first install the extension).  We can click the “Add Rule…” link button in the top-right of the panel to add and enable new URL Rewriting logic for our site. 

    Scenario 1: Handling Default Document Scenarios

    One of the SEO problems I discussed earlier in this post was the scenario where the “default document” feature of IIS causes you to inadvertently expose two URLs for the same content on your site.  For example:

    http://scottgu.com/

    http://scottgu.com/default.aspx

    We can fix this by adding a new IIS Rewrite rule that automatically redirects anyone who navigates to the second URL to instead go to the first one.  We will setup the HTTP redirect to be a “permanent redirect” – which will indicate to search engines that they should follow the redirect and use the new URL they are redirected to as the identifier of the content they retrieve. 

    Let’s look at how we can create such a rule.  We’ll begin by clicking the “Add Rule” link in the screenshot above.  This will cause the below dialog to display:

    image

    We’ll select the “Blank Rule” template within the “Inbound rules” section to create a new custom URL Rewriting rule.  This will display an empty pane like below:

    image

    Don’t worry – setting up the above rule is easy.  The following 4 steps explain how to do so:

    Step 1: Name the Rule

    Our first step will be to name the rule we are creating.  Naming it with a descriptive name will make it easier to find and understand later.  Let’s name this rule our “Default Document URL Rewrite” rule:

    image

    Step 2: Setup the Regular Expression that Matches this Rule

    Our second step will be to specify a regular expression filter that will cause this rule to execute when an incoming URL matches the regex pattern.   Don’t worry if you aren’t good with regular expressions - I suck at them too. The trick is to know someone who is good at them or copy/paste them from a web-site. 

    Below we are going to specify the following regular expression as our pattern rule:

    (.*?)/?Default\.aspx$

    This pattern will match any URL string that ends with Default.aspx. The "(.*?)" matches any preceding character zero or more times. The "/?" part says to match the slash symbol zero or one times. The "$" symbol at the end will ensure that the pattern will only match strings that end with Default.aspx. 

    Combining all these regex elements allows this rule to work not only for the root of your web site (e.g. http://scottgu.com/default.aspx) but also for any application or subdirectory within the site (e.g. http://scottgu.com/photos/default.aspx.  Because the “ignore case” checkbox is selected it will match both “Default.aspx” as well as “default.aspx” within the URL.

    image 

    One nice feature built-into the rule editor is a “Test pattern” button that you can click to bring up a dialog that allows you to test out a few URLs with the rule you are configuring:

    image

    Above I've added a “products/default.aspx” URL and clicked the “Test” button.  This will give me immediate feedback on whether the rule will execute for it. 

    Step 3: Setup a Permanent Redirect Action

    We’ll then setup an action to occur when our regular expression pattern matches the incoming URL:

    image

    In the dialog above I’ve changed the “Action Type” drop down to be a “Redirect” action.  The “Redirect Type” will be a HTTP 301 Permanent redirect – which means search engines will follow it.

    I’ve also set the “Redirect URL” property to be:

    {R:1}/

    This indicates that we want to redirect the web client requesting the original URL to a new URL that has the originally requested URL path - minus the "Default.aspx" in it.  For example, requests for http://scottgu.com/default.aspx will be redirected to http://scottgu.com/, and requests for http://scottgu.com/photos/default.aspx will be redirected to http://scottgu.com/photos/

    The "{R:N}" regex construct, where N >= 0, is called a regular expression back-reference and N is the back-reference index. In the case of our pattern "(.*?)/?Default\.aspx$", if the input URL is "products/Default.aspx" then {R:0} will contain "products/Default.aspx" and {R:1} will contain "products".  We are going to use this {R:1}/ value to be the URL we redirect users to. 

    Step 4: Apply and Save the Rule

    Our final step is to click the “Apply” button in the top right hand of the IIS admin tool – which will cause the tool to persist the URL Rewrite rule into our application’s root web.config file (under a <system.webServer/rewrite> configuration section):

    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Default Document" stopProcessing="true">
                        <match url="(.*?)/?Default\.aspx$" />
                        <action type="Redirect" url="{R:1}/" />
                    </rule>

                </rules>
            </rewrite>
        </system.webServer>
    </configuration>

    Because IIS 7.x and ASP.NET share the same web.config files, you can actually just copy/paste the above code into your web.config files using Visual Studio and skip the need to run the admin tool entirely.  This also makes adding/deploying URL Rewrite rules with your ASP.NET applications really easy.

    Step 5: Try the Rule Out

    Now that we’ve saved the rule, let’s try it out on our site.  Try the following two URLs on my site:

    http://scottgu.com/

    http://scottgu.com/default.aspx

    Notice that the second URL automatically redirects to the first one.  Because it is a permanent redirect, search engines will follow the URL and should update the page ranking of http://scottgu.com to include links to http://scottgu.com/default.aspx as well.

    Scenario 2: Different URL Casing

    Another common SEO problem I discussed earlier in this post is that URLs are case sensitive to search engines on the web.  This means that search engines will treat the following links as two completely different URLs:

    http://scottgu.com/Albums.aspx

    http://scottgu.com/albums.aspx

    We can fix this by adding a new IIS Rewrite rule that automatically redirects anyone who navigates to the first URL to instead go to the second (all lower-case) one.  Like before, we will setup the HTTP redirect to be a “permanent redirect” – which will indicate to search engines that they should follow the redirect and use the new URL they are redirected to as the identifier of the content they retrieve.

    To create such a rule we’ll click the “Add Rule” link in the URL Rewrite admin tool again.  This will cause the “Add Rule” dialog to appear again:

    image

    Unlike the previous scenario (where we created a “Blank Rule”), with this scenario we can take advantage of a built-in “Enforce lowercase URLs” rule template.  When we click the “ok” button we’ll see the following dialog which asks us if we want to create a rule that enforces the use of lowercase letters in URLs:

    image

    When we click the “Yes” button we’ll get a pre-written rule that automatically performs a permanent redirect if an incoming URL has upper-case characters in it – and automatically send users to a lower-case version of the URL:

    image

    We can click the “Apply” button to use this rule “as-is” and have it apply to all incoming URLs to our site. 

    Because my www.scottgu.com site uses ASP.NET Web Forms, I’m going to make one small change to the rule we generated above – which is to add a condition that will ensure that URLs to ASP.NET’s built-in “WebResource.axd” handler are excluded from our case-sensitivity URL Rewrite logic.  URLs to the WebResource.axd handler will only come from server-controls emitted from my pages – and will never be linked to from external sites.  While my site will continue to function fine if we redirect these URLs to automatically be lower-case – doing so isn’t necessary and will add an extra HTTP redirect to many of my pages. 

    The good news is that adding a condition that prevents my URL Rewriting rule from happening with certain URLs is easy.  We simply need to expand the “Conditions” section of the form above

    image

    We can then click the “Add” button to add a condition clause.  This will bring up the “Add Condition” dialog:

    image

    Above I’ve entered {URL} as the Condition input – and said that this rule should only execute if the URL does not match a regex pattern which contains the string “WebResource.axd”.  This will ensure that WebResource.axd URLs to my site will be allowed to execute just fine without having the URL be re-written to be all lower-case.

    Note: If you have static resources (like references to .jpg, .css, and .js files) within your site that currently use upper-case characters you’ll probably want to add additional condition filter clauses so that URLs to them also don’t get redirected to be lower-case (just add rules for patterns like .jpg, .gif, .js, etc).  Your site will continue to work fine if these URLs get redirected to be lower case (meaning the site won’t break) – but it will cause an extra HTTP redirect to happen on your site for URLs that don’t need to be redirected for SEO reasons.  So setting up a condition clause makes sense to add.

    When I click the “ok” button above and apply our lower-case rewriting rule the admin tool will save the following additional rule to our web.config file:

    <configuration>
        <system.webServer>
            <rewrite>
                <rules>

                    <rule name="Default Document" stopProcessing="true">
                        <match url="(.*?)/?Default\.aspx$" />
                        <action type="Redirect" url="{R:1}/" />
                    </rule>

                    <rule name="Lower Case URLs" stopProcessing="true">
                        <match url="[A-Z]" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                            <add input="{URL}" pattern="WebResource.axd" negate="true" />
                        </conditions>
                        <action type="Redirect" url="{ToLower:{URL}}" />
                    </rule>

                </rules>
            </rewrite>
        </system.webServer>
    </configuration>

    Try the Rule Out

    Now that we’ve saved the rule, let’s try it out on our site.  Try the following two URLs on my site:

    http://scottgu.com/Albums.aspx

    http://scottgu.com/albums.aspx

    Notice that the first URL (which has a capital “A”) automatically does a redirect to a lower-case version of the URL. 

    Scenario 3: Trailing Slashes

    Another common SEO problem I discussed earlier in this post is the scenario of trailing slashes within URLs.  The trailing slash creates yet another situation that causes search engines to treat the URLs as different and so split search rankings:

    http://scottgu.com

    http://scottgu.com/

    We can fix this by adding a new IIS Rewrite rule that automatically redirects anyone who navigates to the first URL (that does not have a trailing slash) to instead go to the second one that does.  Like before, we will setup the HTTP redirect to be a “permanent redirect” – which will indicate to search engines that they should follow the redirect and use the new URL they are redirected to as the identifier of the content they retrieve. 

    To create such a rule we’ll click the “Add Rule” link in the URL Rewrite admin tool again.  This will cause the “Add Rule” dialog to appear again:

    image

    The URL Rewrite admin tool has a built-in “Append or remove the trailing slash symbol” rule template. 

    When we select it and click the “ok” button we’ll see the following dialog which asks us if we want to create a rule that automatically redirects users to a URL with a trailing slash if one isn’t present:

    image

    When we click the “OK” button we’ll get a pre-written rule that automatically performs a permanent redirect if the URL doesn’t have a trailing slash – and if the URL is not processed by either a directory or a file. 

    Like within our previous lower-casing rewrite rule we’ll add one additional condition clause that will exclude WebResource.axd URLs from being processed by this rule.  This will avoid an unnecessary redirect for happening for those URLs.

    This will save the following additional rule to our web.config file:

    <configuration>
        <system.webServer>
            <rewrite>
                <rules>

                    <rule name="Default Document" stopProcessing="true">
                        <match url="(.*?)/?Default\.aspx$" />
                        <action type="Redirect" url="{R:1}/" />
                    </rule>

                    <rule name="Lower Case URLs" stopProcessing="true">
                        <match url="[A-Z]" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                            <add input="{URL}" pattern="WebResource.axd" negate="true" />
                        </conditions>
                        <action type="Redirect" url="{ToLower:{URL}}" />
                    </rule>

                    <rule name="Trailing Slash" stopProcessing="true">
                        <match url="(.*[^/])$" />
                        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                            <add input="{URL}" pattern="WebResource.axd" negate="true" />
                        </conditions>
                        <action type="Redirect" url="{R:1}/" />
                    </rule>

                </rules>
            </rewrite>
        </system.webServer>
    </configuration>

    Try the Rule Out

    Now that we’ve saved the rule, let’s try it out on our site.  Try the following two URLs on my site:

    http://scottgu.com

    http://scottgu.com/

    Notice that the first URL (which has no trailing slash) automatically does a redirect to a URL with the trailing slash.  Because it is a permanent redirect, search engines will follow the URL and update the page ranking.

    Scenario 4: Canonical Host Names

    The final SEO problem I discussed earlier are scenarios where a site works with both a leading “www” hostname prefix as well as just the hostname itself.  This causes search engines to treat the URLs as different and split search rankling:

    http://www.scottgu.com/albums.aspx

    http://scottgu.com/albums.aspx

    We can fix this by adding a new IIS Rewrite rule that automatically redirects anyone who navigates to the first URL (that has a www prefix) to instead go to the second URL.  Like before, we will setup the HTTP redirect to be a “permanent redirect” – which will indicate to search engines that they should follow the redirect and use the new URL they are redirected to as the identifier of the content they retrieve. 

    To create such a rule we’ll click the “Add Rule” link in the URL Rewrite admin tool again.  This will cause the “Add Rule” dialog to appear again:

    image

    The URL Rewrite admin tool has a built-in “Canonical domain name” rule template. 

    When we select it and click the “ok” button we’ll see the following dialog which asks us if we want to create a redirect rule that automatically redirects users to a primary host name URL:

    image

    Above I’m entering the primary URL address I want to expose to the web: scottgu.com.  When we click the “OK” button we’ll get a pre-written rule that automatically performs a permanent redirect if the URL has another leading domain name prefix. 

    This will save the following additional rule to our web.config file:

    <configuration>
        <system.webServer>
            <rewrite>
                <rules>

                    <rule name="Cannonical Hostname">
                        <match url="(.*)" />
                        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                            <add input="{HTTP_HOST}" pattern="^scottgu\.com$" negate="true" />
                        </conditions>
                        <action type="Redirect" url="
    http://scottgu.com/{R:1}" />
                    </rule>

                    <rule name="Default Document" stopProcessing="true">
                        <match url="(.*?)/?Default\.aspx$" />
                        <action type="Redirect" url="{R:1}/" />
                    </rule>

                    <rule name="Lower Case URLs" stopProcessing="true">
                        <match url="[A-Z]" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                            <add input="{URL}" pattern="WebResource.axd" negate="true" />
                        </conditions>
                        <action type="Redirect" url="{ToLower:{URL}}" />
                    </rule>

                    <rule name="Trailing Slash" stopProcessing="true">
                        <match url="(.*[^/])$" />
                        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                            <add input="{URL}" pattern="WebResource.axd" negate="true" />
                        </conditions>
                        <action type="Redirect" url="{R:1}/" />
                    </rule>

                </rules>
            </rewrite>
        </system.webServer>
    </configuration>

    Try the Rule Out

    Now that we’ve saved the rule, let’s try it out on our site.  Try the following two URLs on my site:

    http://www.scottgu.com/albums.aspx

    http://scottgu.com/albums.aspx

    Notice that the first URL (which has the “www” prefix) now automatically does a redirect to the second URL which does not have the www prefix.  Because it is a permanent redirect, search engines will follow the URL and update the page ranking.

    4 Simple Rules for Improved SEO

    The above 4 rules are pretty easy to setup and should take less than 15 minutes to configure on existing sites you already have. 

    The beauty of using a solution like the URL Rewrite Extension is that you can take advantage of it without having to change code within your web-site – and without having to break any existing links already pointing at your site.  Users who follow existing links will be automatically redirected to the new URLs you wish to publish.  And search engines will start to give your site a higher search relevancy ranking – which will list your site higher in search results and drive more traffic to it.

    Customizing your URL Rewriting rules further is easy to-do either by editing the web.config file directly, or alternatively, just double click the URL Rewrite icon within the IIS 7.x admin tool and it will list all the active rules for your web-site or application:

    image

    Clicking any of the rules above will open the rules editor back up and allow you to tweak/customize/save them further.

    Summary

    Measuring and improving SEO is something every developer building a public-facing web-site needs to think about and focus on.  If you haven’t already, download and use the SEO Toolkit to analyze the SEO of your sites today.

    New URL Routing features in ASP.NET MVC and ASP.NET Web Forms 4 make it much easier to build applications that have more control over the URLs that are published.  Tools like the URL Rewrite Extension that I’ve talked about in this blog post make it much easier to improve the URLs that are published from sites you already have built today – without requiring you to change a lot of code.

    The URL Rewrite Extension provides a bunch of additional great capabilities – far beyond just SEO - as well.  I’ll be covering these additional capabilities more in future blog posts.

    Hope this helps,

    Scott

  • Visual Studio 2010 and .NET 4 Released

    The final release of Visual Studio 2010 and .NET 4 is now available.

    Download and Install Today

    MSDN subscribers, as well as WebsiteSpark/BizSpark/DreamSpark members, can now download the final releases of Visual Studio 2010 and TFS 2010 through the MSDN subscribers download center. 

    If you are not an MSDN Subscriber, you can download free 90-day trial editions of Visual Studio 2010

    Or you can can download the free Visual Studio express editions of Visual Web Developer 2010, Visual Basic 2010, Visual C# 2010 and Visual C++.  These express editions are available completely for free (and never time out).  If you are looking for an easy way to setup a new machine for web-development you can automate installing ASP.NET 4, ASP.NET MVC 2, IIS, SQL Server Express and Visual Web Developer 2010 Express really quickly with the Microsoft Web Platform Installer (just click the install button on the page).

    What is new with VS 2010 and .NET 4

    Today’s release is a big one – and brings with it a ton of new feature and capabilities.

    One of the things we tried hard to focus on with this release was to invest heavily in making existing applications, projects and developer experiences better.  What this means is that you don’t need to read 1000+ page books or spend time learning major new concepts in order to take advantage of the release.  There are literally thousands of improvements (both big and small) that make you more productive and successful without having to learn big new concepts in order to start using them. 

    Below is just a small sampling of some of the improvements with this release:

    Visual Studio 2010 IDE 

    Visual Studio 2010 now supports multiple-monitors (enabling much better use of screen real-estate).  It has new code Intellisense support that makes it easier to find and use classes and methods. It has improved code navigation support for searching code-bases and seeing how code is called and used.  It has new code visualization support that allows you to see the relationships across projects and classes within projects, as well as to automatically generate sequence diagrams to chart execution flow. 

    The editor now supports HTML and JavaScript snippet support as well as improved JavaScript intellisense. The VS 2010 Debugger and Profiling support is now much, much richer and enables new features like Intellitrace (aka Historical Debugging), debugging of Crash/Dump files, and better parallel debugging.  VS 2010’s multi-targeting support is now much richer, and enables you to use VS 2010 to target .NET 2, .NET 3, .NET 3.5 and .NET 4 applications.  And the infamous Add Reference dialog now loads much faster.

    TFS 2010 is now easy to setup (you can now install the server in under 10 minutes) and enables great source-control, bug/work-item tracking, and continuous integration support.  Testing support (both automated and manual) is now much, much richer.  And VS 2010 Premium and Ultimate provide much better architecture and design tooling support.

    VB and C# Language Features

    VB and C# in VS 2010 both contain a bunch of new features and capabilities.  VB adds new support for automatic properties, collection initializers, and implicit line continuation support among many other features.  C# adds support for optional parameters and named arguments, a new dynamic keyword, co-variance and contra-variance, and among many other features.

    ASP.NET 4 and ASP.NET MVC 2

    With ASP.NET 4, Web Forms controls now render clean, semantically correct, and CSS friendly HTML markup. Built-in URL routing functionality allows you to expose clean, search engine friendly, URLs and increase the traffic to your Website.  ViewState within applications can now be more easily controlled and made smaller. Client IDs rendered by server controls can now be controlled.  ASP.NET Dynamic Data support has been enhanced.  More controls, including rich charting and data controls, are now built-into ASP.NET 4 and enable you to build applications even faster.  New starter project templates now make it easier to get going with new projects.  SEO enhancements make it easier to drive traffic to your public facing sites.  And web.config files are now clean and simple.

    ASP.NET MVC 2 is now built-into VS 2010 and ASP.NET 4, and provides a great way to build web sites and applications using a model-view-controller based pattern. ASP.NET MVC 2 adds features to easily enable client and server validation logic, provides new strongly-typed HTML and UI-scaffolding helper methods.  It also enables more modular/reusable applications.  The new <%: %> syntax in ASP.NET makes it easier to HTML encode output.  Visual Studio 2010 also now includes better tooling support for unit testing and TDD.  In particular, “Consume first intellisense” and “generate from usage" support within VS 2010 make it easier to write your unit tests first, and then drive your implementation from them.

    Deploying ASP.NET applications gets a lot easier with this release. You can now publish your Websites and applications to a staging or production server from within Visual Studio itself. Visual Studio 2010 makes it easy to transfer all your files, code, configuration, database schema and data in one complete package. VS 2010 also makes it easy to manage separate web.config configuration files settings depending upon whether you are in debug, release, staging or production modes.

    WPF 4 and Silverlight 4

    WPF 4 includes a ton of new improvements and capabilities including more built-in controls, richer graphics features (cached composition, pixel shader 3 support, layoutrounding, and animation easing functions), a much improved text stack (with crisper text rendering, custom dictionary support, and selection and caret brush options).  WPF 4 also includes a bunch of support to enable you to take advantage of new Windows 7 features – including multi-touch and Windows 7 shell integration.

    Silverlight 4 will launch this week as well.  You can watch my Silverlight 4 launch keynote streamed live Tuesday (April 13th) at 8am Pacific Time.  Silverlight 4 includes a ton of new capabilities – including a bunch for making it possible to build great business applications and out of the browser applications.  I’ll be doing a separate blog post later this week (once it is live on the web) that talks more about its capabilities.

    Visual Studio 2010 now includes great tooling support for both WPF and Silverlight.  The new VS 2010 WPF and Silverlight designer makes it much easier to build client applications as well as build great line of business solutions, as well as integrate and bind with data.  Tooling support for Silverlight 4 with the final release of Visual Studio 2010 will be available when Silverlight 4 releases to the web this week.

    SharePoint and Azure

    Visual Studio 2010 now includes built-in support for building SharePoint applications.  You can now create, edit, build, and debug SharePoint applications directly within Visual Studio 2010.  You can also now use SharePoint with TFS 2010.

    Support for creating Azure-hosted applications is also now included with VS 2010 – allowing you to build ASP.NET and WCF based applications and host them within the cloud.

    Data Access

    Data access has a lot of improvements coming to it with .NET 4.  Entity Framework 4 includes a ton of new features and capabilities – including support for model first and POCO development, default support for lazy loading, built-in support for pluralization/singularization of table/property names within the VS 2010 designer, full support for all the LINQ operators, the ability to optionally expose foreign keys on model objects (useful for some stateless web scenarios), disconnected API support to better handle N-Tier and stateless web scenarios, and T4 template customization support within VS 2010 to allow you to customize and automate how code is generated for you by the data designer. 

    In addition to improvements with the Entity Framework, LINQ to SQL with .NET 4 also includes a bunch of nice improvements

    WCF and Workflow

    WCF includes a bunch of great new capabilities – including better REST, activation and configuration support.  WCF Data Services (formerly known as Astoria) and WCF RIA Services also now enable you to easily expose and work with data from remote clients.

    Windows Workflow is now much faster, includes flowchart services, and now makes it easier to make custom services than before.  More details can be found here.

    CLR and Core .NET Library Improvements

    .NET 4 includes the new CLR 4 engine – which includes a lot of nice performance and feature improvements.  CLR 4 engine now runs side-by-side in-process with older versions of the CLR – allowing you to use two different versions of .NET within the same process.  It also includes improved COM interop support. 

    The .NET 4 base class libraries (BCL) include a bunch of nice additions and refinements.  In particular, the .NET 4 BCL now includes new parallel programming support that makes it much easier to build applications that take advantage of multiple CPUs and cores on a computer.  This work dove-tails nicely with the new VS 2010 parallel debugger (making it much easier to debug parallel applications), as well as the new F# functional language support now included in the VS 2010 IDE.  .NET 4 also now also has the Dynamic Language Runtime (DLR) library built-in – which makes it easier to use dynamic language functionality with .NET.  MEF – a really cool library that enables rich extensibility – is also now built-into .NET 4 and included as part of the base class libraries. 

    .NET 4 Client Profile

    The download size of the .NET 4 redist is now much smaller than it was before (the x86 full .NET 4 package is about 36MB).  We also now have a .NET 4 Client Profile package which is a pure sub-set of the full .NET that can be used to streamline client application installs.

    Visual C++

    VS 2010 includes a bunch of great improvements for C++ development.  This includes better C++ Intellisense support, MSBuild support for projects, improved parallel debugging and profiler support, MFC improvements, and a number of language features and compiler optimizations.

    My VS 2010 and .NET 4 Blog Series

    I’ve been cranking away on a blog series the last few months that highlights many of the new VS 2010 and .NET 4 improvements.  The good news is that I have about 20 in-depth posts already written.  The bad news (for me) is that I have about 200 more to go until I’m done!  I’m going to try and keep adding a few more each week over the next few months to discuss the new improvements and how best to take advantage of them.

    Below is a list of the already written ones that you can check out today:

    Stay tuned to my blog as I post more.  Also check out this page which links to a bunch of great articles and videos done by others.

    VS 2010 Installation Notes

    If you have installed a previous version of VS 2010 on your machine (either the beta or the RC) you must first uninstall it before installing the final VS 2010 release.  I also recommend uninstalling .NET 4 betas (including both the client and full .NET 4 installs) as well as the other installs that come with VS 2010 (e.g. ASP.NET MVC 2 preview builds, etc).  The uninstalls of the betas/RCs will clean up all the old state on your machine – after which you can install the final VS 2010 version and should have everything just work (this is what I’ve done on all of my machines and I haven’t had any problems).

    The VS 2010 and .NET 4 installs add a bunch of new managed assemblies to your machine.  Some of these will be “NGEN’d” to native code during the actual install process (making them run fast).  To avoid adding too much time to VS setup, though, we don’t NGEN all assemblies immediately – and instead will NGEN the rest in the background when your machine is idle.  Until it finishes NGENing the assemblies they will be JIT’d to native code the first time they are used in a process – which for large assemblies can sometimes cause a slight performance hit.

    If you run into this you can manually force all assemblies to be NGEN’d to native code immediately (and not just wait till the machine is idle) by launching the Visual Studio command line prompt from the Windows Start Menu (Microsoft Visual Studio 2010->Visual Studio Tools->Visual Studio Command Prompt).  Within the command prompt type “Ngen executequeueditems” – this will cause everything to be NGEN’d immediately.

    How to Buy Visual Studio 2010

    You can can download and use the free Visual Studio express editions of Visual Web Developer 2010, Visual Basic 2010, Visual C# 2010 and Visual C++.  These express editions are available completely for free (and never time out).

    You can buy a new copy of VS 2010 Professional that includes a 1 year subscription to MSDN Essentials for $799.  MSDN Essentials includes a developer license of Windows 7 Ultimate, Windows Server 2008 R2 Enterprise, SQL Server 2008 DataCenter R2, and 20 hours of Azure hosting time.  Subscribers also have access to MSDN’s Online Concierge, and Priority Support in MSDN Forums.

    Upgrade prices from previous releases of Visual Studio are also available.  Existing Visual Studio 2005/2008 Standard customers can upgrade to Visual Studio 2010 Professional for a special $299 retail price until October.  You can take advantage of this VS Standard to Professional upgrade promotion here.

    Web developers who build applications for others, and who are either independent developers or who work for companies with less than 10 employees, can also optionally take advantage of the Microsoft WebSiteSpark program.  This program gives you three copies of Visual Studio 2010 Professional, 1 copy of Expression Studio, and 4 CPU licenses of both Windows 2008 R2 Web Server and SQL 2008 Web Edition that you can use to both develop and deploy applications with at no cost for 3 years.  At the end of the 3 years there is no obligation to buy anything.  You can sign-up for WebSiteSpark today in under 5 minutes – and immediately have access to the products to download.

    Summary

    Today’s release is a big one – and has a bunch of improvements for pretty much every developer.  Thank you everyone who provided feedback, suggestions and reported bugs throughout the development process – we couldn’t have delivered it without you. 

    Hope this helps,

    Scott

    P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

  • JavaScript Intellisense Improvements with VS 2010

    This is the twentieth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. 

    Today’s blog post covers some of the nice improvements coming with JavaScript intellisense with VS 2010 and the free Visual Web Developer 2010 Express.  You’ll find with VS 2010 that JavaScript Intellisense loads much faster for large script files and with large libraries, and that it now provides statement completion support for more advanced scenarios compared to previous versions of Visual Studio.

    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    Improved JavaScript Intellisense

    Providing Intellisense for a dynamic language like JavaScript is more involved than doing so with a statically typed language like VB or C#.  Correctly inferring the shape and structure of variables, methods, etc is pretty much impossible without pseudo-executing the actual code itself – since JavaScript as a language is flexible enough to dynamically modify and morph these things at runtime. 

    VS 2010’s JavaScript code editor now has the smarts to perform this type of pseudo-code execution as you type – which is how its intellisense completion is kept accurate and complete.  Below is a simple walkthrough that shows off how rich and flexible it is with the final release.

    Scenario 1: Basic Type Inference

    When you declare a variable in JavaScript you do not have to declare its type.  Instead, the type of the variable is based on the value assigned to it.  Because VS 2010 pseudo-executes the code within the editor, it can dynamically infer the type of a variable, and provide the appropriate code intellisense based on the value assigned to a variable.

    For example, notice below how VS 2010 provides statement completion for a string (because we assigned a string to the “foo” variable):

    image

    If we later assign a numeric value to “foo” the statement completion (after this assignment) automatically changes to provide intellisense for a number:

    image

    Scenario 2: Intellisense When Manipulating Browser Objects

    It is pretty common with JavaScript to manipulate the DOM of a page, as well as work against browser objects available on the client. 

    Previous versions of Visual Studio would provide JavaScript statement completion against the standard browser objects – but didn’t provide much help with more advanced scenarios (like creating dynamic variables and methods).  VS 2010’s pseudo-execution of code within the editor now allows us to provide rich intellisense for a much broader set of scenarios.

    For example, below we are using the browser’s window object to create a global variable named “bar”.  Notice how we can now get intellisense (with correct type inference for a string) with VS 2010 when we later try and use it:

    image

    When we assign the “bar” variable as a number (instead of as a string) the VS 2010 intellisense engine correctly infers its type and modifies statement completion appropriately to be that of a number instead:

    image

    Scenario 3: Showing Off

    Because VS 2010 is psudo-executing code within the editor, it is able to handle a bunch of scenarios (both practical and wacky) that you throw at it – and is still able to provide accurate type inference and intellisense.

    For example, below we are using a for-loop and the browser’s window object to dynamically create and name multiple dynamic variables (bar1, bar2, bar3…bar9).  Notice how the editor’s intellisense engine identifies and provides statement completion for them:

    image

    Because variables added via the browser’s window object are also global variables – they also now show up in the global variable intellisense drop-down as well:

    image

    Better yet – type inference is still fully supported.  So if we assign a string to a dynamically named variable we will get type inference for a string.  If we assign a number we’ll get type inference for a number. 

    Just for fun (and to show off!) we could adjust our for-loop to assign a string for even numbered variables (bar2, bar4, bar6, etc) and assign a number for odd numbered variables (bar1, bar3, bar5, etc):

    image

    Notice above how we get statement completion for a string for the “bar2” variable. 

    Notice below how for “bar1” we get statement completion for a number:

    image 

    This isn’t just a cool party trick…

    While the above example is a bit contrived, the approach of dynamically creating variables, methods and event handlers on the fly is pretty common with many Javascript libraries.  Many of the more popular libraries use these techniques to keep the size of script library downloads as small as possible.  VS 2010’s support for parsing and pseudo-executing libraries that use these techniques ensures that you get better code Intellisense out of the box when programming against them.

    Summary

    Visual Studio 2010 (and the free Visual Web Developer 2010 Express) now provide much richer JavaScript intellisense support.  This support works with pretty much all popular JavaScript libraries.  It should help provide a much better development experience when coding client-side JavaScript and enabling AJAX scenarios within your ASP.NET applications.

    Hope this helps,

    Scott

    P.S. You can read my previous blog post on VS 2008’s JavaScript Intellisense to learn more about our previous JavaScript intellisense (and some of the scenarios it supported).  VS 2010 obviously supports all of the scenarios previously enabled with VS 2008.

More Posts Next page »

This Blog

Syndication

Powered by Community Server, by Telligent Systems
'