This is the twenty-fifth in a series of blog posts I’m doing on the VS 2010 and .NET 4 release.
Today’s blog post is the first of several posts I’ll be doing that cover some of the improvements we’ve made around web deployment. I’ll provide a high-level overview of some of the key improvements. Subsequent posts will then go into more details about each feature and how best to take advantage of them.
Making Web Deployment Easier
Deploying your web application to a server is something that all (successful) projects need to do. Without good tools to help you, deployment can be a cumbersome task – especially if you need to do it manually.
VS 2010 includes a bunch of improvements that make it much easier to deploy your ASP.NET web applications – and which enable you to build automated deployment procedures that make deployment easily reproducible. The deployment features support not just deploying your web content – but also support customizing your web.config file settings, deploying/updating your databases, and managing your other dependencies. You can kick-off deployments manually – or via automated scripts or as part of an automated build or continuous integration process.
Below is a high-level overview of some of the key new web deployment features in VS 2010. I’ll do subsequent posts that provide more details on how to use/customize each of them.
New “Publish Web” Dialog
Visual Studio 2010 includes a new “Publish Web” dialog that you can use to quickly deploy a web application to a remote server.
You can activate the dialog by right-clicking on an ASP.NET Web Project node within the solution explorer, and then select the “Publish” context menu item:
Selecting this will bring up a “Publish Web” dialog which allows you to configure publish location settings.
Configuring and Saving a Publish Profile
You only need to define your publish settings once – you can then save them as a named “Publish Profile” to enable you to quickly re-use them again later.
Above I’ve created a “ScottGu Site” profile, and configured it to deploy via FTPS (a version of FTP that uses SSL) to a remote server. To deploy over FTPS select the “FTP” node in the drop-down, and then prefix the server location you want to publish to with the “ftps://” prefix.
Note that you can either re-enter your password each time you deploy – or save the password for future uses in a secure location (just click the “Save Password” checkbox to do this.
Web Deploy
In addition to supporting FTP/FTPS, VS 2010 also supports a more powerful publish mechanism called “Web Deploy”. Web Deploy (earlier known as MSDeploy) provides a much more comprehensive publishing and deployment mechanism than FTP. It not only allows you to publish files, but also allows you to publish IIS Web Server Settings, Database Schema/Data, Database Change Scripts, Security ACLs, and much more.
Web Deploy can be used to deploy applications both to a single server, as well as to multiple servers within a web farm. Web Deploy is also now supported by many inexpensive Windows hosting providers (some as cheap as $3.50/month for an ASP.NET + SQL account). You can find great ASP.NET hosters that support Web Deploy by visiting this page: http://asp.net/find-a-hoster.
One Click Publish Toolbar
Clicking the “Publish” button within the “Publish Web” dialog will publish a web application (and optionally associated database schema/content) to a remote web server.
VS 2010 also supports a “one click” publish toolbar that you can add to your IDE to quickly publish/re-publish your project without having to load the “Publish Web” dialog:
Just select your publish profile from the toolbar drop-down and then click the publish icon to the right of it to begin deploying your application.
Web.Config Transformations
In most real-world deployment scenarios, the web.config file you use for development is different than the one you use for production deployment. Typically you want to change environment settings like database connection-strings, making sure debug is turned off, and enabling custom errors so that end-users (and hackers) don’t see the internals of your application.
VS 2010 now makes it easy to customize/tweak/modify your web.config files as part of your publish/deployment process. Specifically, you can now easily have build-configuration specific transformation files that can customize your web.config file prior to the application being deployed:
You can maintain a separate transform file per Visual Studio build-environment. For example, you could configure your project/solution to have a “Debug”, “Staging” and “Release” build configuration – in which case VS will maintain three separate transform files for you. VS will automatically apply the appropriate one at deployment time depending on what your VS environment is set to.
I will dive deeper into how to perform web.config file transformations in a future blog post.
Database Deployment
VS 2010 allows you to optionally deploy a database, along with your web application files, when are using the “Web Deploy” option as your deployment mechanism. Databases deployed this way can include both schema and data, and can optionally also include change scripts to update existing databases.
ASP.NET Web Projects in VS 2010 have a special page within their the “project properties” settings to configure database deployments:
I will dive deeper into how to perform database deployments in future blog posts.
Web Deployment Packages
VS 2010 also supports a packaging option that enables you to package up your ASP.NET Web Application (together with its dependencies like web.config, databases, ACLs, etc) into a .zip based deployment package file that you can optionally hand-off to an IT administrator who can then easily install it either via the IIS Admin Tool or via a command-line/powershell script.
The deployment package you create can optionally expose application configuration settings that can be overridden (like directory locations, database connection-strings, etc). When using the IIS7 Admin Tool, the install wizard can prompt the administrator for each setting to be customized – enabling you to provide a clean customization experience without having to write any custom code to-do so. The settings can also obviously be passed as arguments on the command-line when using a command-line or Powershell script to deploy the application.
To create a web package within Visual Studio 2010, just right click on your ASP.NET Web Project node in the solution explorer and select the “Build Deployment Package” menu item:
This will compile your application, perform appropriate web.config transforms on it, optionally create .sql scripts for your database schema and data files, and then package them all up into a .zip deployment package file. Adjacent to the .zip file you’ll file a deployment script file that you can use to automate deployment of the package to a remote server.
I will dive deeper into how to create web deployment packages in future blog posts.
Continuous Integration with Team Build
Most of the VS 2010 web deployment features that I described above are built on top of MSBuild tasks & targets. The “Team Build” feature of TFS also uses MSBuild, and supports running nightly builds, rolling builds, and enabling continuous integration. This means that you can create deployment packages, or automatically publish your web applications from a Team Build environment.
I will dive deeper into how to enable this in future blog posts.
Summary
Today’s blog post covered some of the new VS 2010 web deployment features at a high-level. All of the above features Iwork with both VS 2010 as well as the free Visual Web Developer 2010 Express Edition.
Hopefully today’s post provided a broad outline of all the new deployment capabilities, and helped set context as to how they are useful. In future posts I’ll go deeper and walkthrough the specifics of how to really take full advantage of them.
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
In every era in recent times there has been one profession that for a short while you could enter without formal training. Autodidacts in the 19th century could read the law without recourse to formal education (see Abe Lincoln). In the early 20th century it was aviation. For a short while in the 1980s and early 1990s, it was computing, thanks to the release of the Apple IIe, the IBM PC and the Mac.
Were it not for that Window® of opportunity, I hate to think what would have become of me. (Hey buddy, can you spare a dime?) But I was very lucky, when I became serious about learning to program all i needed was a book on the 8088 and a book on C, and I was all set to Rock and Roll.
As much as I continue to love to code 30 years later, there are a few aspects I hate:
- Doing a mundane task more than once
- Not remembering how i fixed this problem in the past
- Losing work to crashed disks or stupid irreversible revisions
- Not being able to find subtle text differences in files.
Hence, my 12 essential utilities….
Before We Begin
I assume you have (and use)…
- Visual Studio 2010
- Expression – at a minimum Expression Blend and probably Expression Encoder
- Windows 7
- The essential hardware to run it (see forthcoming list!)
- All the necessary development software available here
If not, stop reading this list and go get em.
While I work on both Windows and the Mac, this list is entirely Windows-centric.
The Top Dozen
# 1. ReSharper or CodeRush
After chatting with whoever was in shouting distance at PDC, I can say that there is nearly universal agreement among all professional programmers world-wide (or at least those within shouting distance) that having CodeRush or Resharper is essential. .
What is wonderfully controversial is which one is better. This is the kind of question you can throw out at a technical presentation and then sit back and enjoy hours of deafening amusement. (Other such questions include C# vs. VB and where a method’s opening brace should go.)
Both ReSharper and CodeRush are Visual Studio add-in products that enormously enhance your productivity and the quality of your code. They do this in ways big and small but the three I consider essential are:
- Making it very easy to refactor your code
- Radically reducing the amount of typing you have to do.
- Finding errors and superfluous code.
That is, you type less and end up with better code. Nice. Neither product is free, but having at least one is essential.
#2 Fiddler and FireBug
Fiddler logs all the HTTP and HTTPs traffic between your computer and the Internet. You can inspect the logged data just as you might in a debugger, and most important it has a scripting system and is extensible with C# (or any .NET language). Even nicer, Fiddler is free and works on IE, Firefox, and just about all the other browsers you can shake a stick at
FireBug is the single most popular web development tool, and for good reason. With it, you can in real time inspect and modify HTML in a web page, make use of a surprisingly powerful javascript debuger and obtain detailed measurements and profiling of network activity. Don’t leave home without it.
#3 Tortoise SVN
If you are on a PC and you are programming, then you must, must use version control. Microsoft makes a great version control system, and if you buy the right version of Visual Studio you get it for free. I use SVN because I did and do a lot of cross platform and open source work and svn is the lingua franca of source control (though keep an eye on Git!).
If you are on a pc and you want SVN as your version control, then the decision tree has only one node: Tortoise SVN – it is free, GPL and works as a shell extension so it is wicked intuitive. Create a directory, check out the latest version and get to work. Each time you want to do more work start with Update and end with Commit.
The key benefits of version control are
- Your files are backed up
- Your changes are backed up so you can decide to go to a previous iteration after you cabbage your code
- Old releases are available for testing as needed
- Your files are backed up
- If more than one programmer is working on different parts of the code, version control lets you put the pieces back together in a sane way
I should mention that I use SVN not only for my source code but for my documents and for my presentations. Having version controlled PowerPoint slides is a terrific thing.
If you want very much the same functionality, but integrated into Visual Studio, take a look at Visual SVN. At $50 it is reasonable, but it ain’t free.
This Just In: I recently found a brilliant cross-platform, incredibly powerful and easy to use SVN client: Syncro SVN 6. I’ve only started to exercise it, but so far it is the best SVN client I’ve seen, especially on the Mac where good SVN clients are scarce. I particularly like their licensing, which is per user, and so you are invited to put it on your Windows machine, your Mac and your Linux box, as long as you use only one at a time. Nice. The client seems to be on sale for 40% off, so I am buying it as I write this.
#4 TimeSnapper
Every great scientist keeps a lab book, in which they write down everything they do. This is critical, so that when something changes they can determine what happened. For years I’ve thought that it would be terrific to keep such a log book so that I could go back and figure out what the heck it was I did way over there that has broken this code way over here
I’m happy to say that this problem is reduced greatly by test-driven development, as I discussed recently in Test Driven Silverlight Body Snatchers. But it is not eliminated entirely.
Over the years I’ve tried a number of approaches, and like every diet on the best seller list, they work perfectly until you stop doing it, which you always do. I tried
- Creating a log of my work on a pre-net-top HP computer
- Creating a running log on a second computer
- Using dictation software to capture a running commentary
- Videotaping my work
Every attempt ended in ignominy.
Then came TimeSnapper. This little program sits in the background and takes a picture of what you are doing, as often as you like, at whatever fidelity you need. It’s all configurable, but I set mine to record just the active application, saving each image as a jpg, with 100% resolution (75% resolution provides an image at 3/4 of the original size), and 75% quality (I can’t see the difference). I instructed TimeSnapper to take an image every 5 seconds and to save 10 days worth.
When I first tried this program, many revisions back, on a slow PC, I did find that it was slowing down Visual Studio. Today, running on a blistering machine (Windows 7 running on Parallels 5 on a 4 Quad Mac with 8 Meg of memory and a pair of wicked fast terrabyte drives) I see zero speed degradation, but I set their new “use very low priority” switch just to make sure.
The images range in size depending on how large the window is, but devoting all of one cinema monitor to Visual Studio, I probably average larger snapshots than most. That said, every 5 seconds = 720 per hour. A bit less as I tell it not to save a new image if nothing has changed, and if I’m out of the VM it sits idle. That said, the images range upwards of 100K, so my worst case scenario is 7200 images in a day times 10 days = 72,000 images at 100K each = 7,200,000,000 bytes or 7.2 Gig; which is peanuts.
Among the things you can do with TimeSnapper is tell it what you count as productive work, and it will report on any time period you like. You can create time reports, and all sorts of other fun stuff, but its killer feature is that you can play back any part of your day like a movie, and more than once you watch as you do something astonishingly stupid.
#5 Instant VB….
Instant VB is by Tangible Software. You point it at a C# application, wait a nanosecond or two, and hey! presto! you have a VB application. Yes, it’s a one-trick pony, but it’s a hell of a trick! They also sell a variety of other converters (VB to C#, C++ to Java, and many others)
When its done, Instant VB offers to bring you to the directory of your original program, your converted program or to launch the converted program. Nice.
I like them because they make an incredibly great product that they keep improving, because they are extraordinarily nice folks and because they listed my unsolicited testimonial first.
#6 ExamDiff Pro
By far the best comparison and merge program I’ve ever seen. You can compare folders (recursively or not) or versions of files, but what makes
ExamDiff Pro stand out is that you can use it right out of the box – the UI is incredibly intuitive, or you can adjust dozens (hundreds?) of settings to meet your particular needs (do you want to consider two files different if there are changes in the amount of white space in lines?)
PrestoSoft offers the free version ExamDiff and the souped up version ExamDiff Pro. The price marked on their site for the Pro version is “$34 or less.” Their web site is terrific, offering extensive information, screenshots and tutorials – everything from “How to compare files” through “How to ignore line numbers in text files.”
I’ve squished this image down and put the files one atop the other rather than side by side to make the image legible (better, though if you click on it to see it full size). Each difference is identified, the summary shows you what you have to do to make the files the same, and you can either use the arrows to migrate the change from one file to the other, or edit directly in the files as you go. It does much more, as well, and its handling of recursive folder and file differences is brilliant, letting you find and fix every change in two complete software solutions.
I routinely replace the file comparison and merge of my source code control with this, as it provides a clearer, faster and easier to use UI.
#7 AutoHotKey
I hate typing the same thing again and again and I miss TSRs (old enough to know what they were??). AutoHotKey solves this problem and a host of others. You can create simple substitutions or complex scripts tied to hot keys. You can use it to remap your keyboard, run scripts, create menus and forms. I just use it for two simple things:
- Macro substitution. If I type @jl it expands instantly to jliberty@microsoft.com (I add the at sign only to have a consistent signal for myself, AutoHotKey doesn’t care. Here is the line in the script that causes the instant substitution:
:*:@jl::jliberty@microsoft.com
The initial colon begins the line. The star * says “substitute immediately, don’t wait for a space.” The second and third colons contain the macro and the final colon begins the substitution text.
- Quick error correction. There are some words I should never misspell. Here’s an excerpt from my AutoHotKey correction file:
::Sliverlight::Silverlight
::Silvelright::Silverlight
::silverlight::Silverlight
::iPhone::Windows Phone 7
::Stacy::Stacey
Thus, were I ever to write Sliverlight as soon as I hit space it would correct to Silverlight.
As noted, there is much more you can do, and fortunately it comes with an extremely well put together help file. Even better, AutoHotKey is free, open source and available in German, French, Italian, Russian, Japanese, Greek, Portuguese, Korean and Chinese versions.
Wikipedia has an excellent article covering AutoHotKey in depth.
My favorite feature in Emacs was yank-pop. If you copied line 1 to the clip board, and then line 20, and then line 5, hitting paste would return
line 5, but if you then hit yank-pop line 5 would be replaced by line 20. That is, it unwound the clipboard stack.
ClipX provides that functionality and a good bit more for Windows – across applications. Its icon sits in the tray waiting for you to click.
When you do, up pops a very long menu of your n most recent clipboard entries where n is a number from 0 to 1024 (the image shows a cropped example)
You can also store permanent clipboard entries for fast retrieval as you can see at the bottom (I’ve disguised the first two as they are passwords).
It isn’t the fanciest of clipboard managers, but it works reliably and, as they say on their site, “it is sweet, it is free, use it.”
#9 Snip It Pro
Based on the reactions I get when I present code at conferences, the entire programming world is looking for a great snippet manager. Snip It Pro is the best I’ve seen. It makes creating and managing snippets (and sets of snippets) a breeze, it gets out of the way when you don’t need it, and while its basic functionality is obvious and intuitive, it has some additional features that are just sweet as pie. One that I personally requested and use all the time is the queue. Right click on a folder and choose Queue snippets and then each paste will paste the next snippet in the folder. Bang, bang, bang! The (excellent) help file offers the following hot-keys for working with queued snippets
CTRL+SHIFT+V – Paste the currently queued snippet and advance to the next one.
CTRL+SHIFT+1 – Move to the previously queued Snippet without pasting anything.
CTRL+SHIFT+2 – Move to the next queued Snippet without pasting anything.
CTRL+SHIFT+C – Ensure the currently queued snippet is in the clipboard. (Useful if you copy or cut another piece of text after advancing the queue).
#10 Evernote
I am a bear of little brain. And there is nothing more annoying when I’m stuck trying to solve a programming problem, than to know that I’ve solved this very problem before, but I haven’t the vaguest idea when or where. I hate solving the same problem twice. What I need is a reliable place to put my notes.
I also get a lot of information streaming in that I know I’ll want some day but not now. I need a place to put that.
When I see something interesting in a magazine (or on a billboard, etc.) I never write down a note, I take a picture – isn’t that what phones are for? I do not want to transcribe that information, but I have to be able to find it.
I work on more than one machine, in more than one location.
Enter, finally, Evernote. Evernote has very many wonderful things to say for itself (including that the basic version is free), but the two killer features for me are:
- It runs on phones, Windows, Mac, and the web.
- You do not need to organize your information on the way in – its search engine is so powerful that you can find what you need nearly instantly. Yes there are multiple notebooks if you want them (I use only one) and there are tags (I use them but for no good reason), so you can organize your information as you add it, but a killer organizer doen’t force you to. I know, absolutely that whatever I put in, I can find quickly just by searching.
That would be plenty, but Evernote has two other nearly incredible features.
- When you add an image, they read the image and index all the words in the image. And they are very very good at that. So I can find that photo I took of that article about that great utility I want.
- You can not only search both within notes and across notes by any word(s) appearing in the note, but you can search by when the note was created or when it was modified, or how it was added (I emailed that note) or whether it contains images or attachments, etc. etc. One of my favorite features appears on the phone version, which let’s me search for every note I added “near here” where I get to define the meaning of “near.” So when I’m in Redmond, I can instantly find 4 years of notes I added within, say, 10 miles of corporate.
Of course, all my versions sync with one another constantly, so all 1500 or so notes are always up to date.
The free version is perfectly good, but I upgraded to pro to give them money. No one should produce a product this good and not be compensated.
#11 Mozy
When all is said and done I’m a big believer in belt & suspenders. And the more valuable the pants, the more belts and suspenders I add. Thus, I keep my source code, presentations and important documents in off-site version control, I do regular on site backups, and I have Mozy backup all my data to their offsite computers, constantly.
Mozy’s deal is unlimited data, and I have it set up to watch every directory that does not have Microsoft proprietary information in it, and back that up as soon as the computer is less than 25% busy. I add a scheduled backup at 2:30 am every day (in the hope I’ll not be working then!). Finally, since everything is a trade-off, I instruct Mozy to throttle its use of the Internet bandwidth to 512KB/Sec between 7am and 1am.
We do what we can.
#12 Mikago
One of the things I truly love about my job is that I work from home. I’m in Massachusetts; my boss is in Oregon and his boss is in Redmond. My co-workers are in San Diego, Washington DC…. you get the idea. To make this work we use Microsoft Communicator and Live meeting (face to face is vital for avoiding confusion) but every once in a while it is incredibly helpful to be able to share a workspace fully, interactively and with great response.
There are a number of good products for doing this (some you even get for free with your operating System) but Mikago stands out for providing extraordinary control, incredible ease of setting up an ad hoc shared desktop, and being free.
For this article, I invited two buddies who did not have Mikogo to share my screen; sending them an email invitation through Mikogo to an event 1 hour later. Total time for each of them from clicking on the link to sharing my screen was under 3 minutes; but that will be faster next time as they saved the small program Mikogo needs.
A truly nifty feature is that when I have control of the screen, they can still click, and an arrow appears on my my screen (with their name attached) so they can ask “What’s this button do?” Shiny.
Please be sure to leave comments with the utilities you find essential as a professional programmer.
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:

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.
Below is a StoreController class that implements the two action methods (“Index” and “Browse”) needed to build the above scenario:
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:
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:
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:
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:
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:
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):
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:
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:
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:
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:
ASP.NET MVC 3 now enables you to implement the /Store/UpdateProduct URL on the server using an action method like below:
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):
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:
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