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]
.NET/WPF/EF5 Little C#/.NET Wonders that Make Code Better: Nice blog post from James that highlights 5 nice language/framework tips you can take advantage of within your apps. I’m betting a lot of people didn’t know about the StopWatch class.
WPF Ribbon Control Released: The WPF team recently released the final V1 release of the WPF Ribbon control. This makes it easy to build ribbon-based applications. Also read this WPF team blog post for lots of great details on what it enables.
EF4 .Include() Method w/ Lambda Support: Ever wanted to use a Lambda expression instead of a string parameter when eagerly loading associations in EF4 using the Include() method? This blog post shows you how you can.
Performance Tuning tricks for ASP.NET and IIS7 Part 1 and Part 2: Mads has a nice set of posts that detail some great performance optimization tips you can use with ASP.NET and IIS7.
Better ViewState Management in ASP.NET 4 with the ViewStateMode Property: Scott Mitchell has a good article that discusses the new ViewStateMode property supported on ASP.NET 4 controls. This provides much more control over how viewstate is used within a page.
Filtering Data using ASP.NET 4’s QueryExtender Control: Scott Mitchell has a nice article that talks about the new <asp:QueryExtender> control in ASP.NET 4 that makes enabling dynamic querying against a LinqDataSource or EntityDataSource really easy.
Techniques to Avoid Duplicate URLs: Scott Mitchell has another great article that discusses techniques you can use within ASP.NET to avoid exposing duplicate URLs to the same content within your web-sites. These can help improve your search engine traffic.
Automatically pre-populate fields for Insert in ASP.NET 4: Scott Hunter has a nice blog post that discusses how to specify default values for insert with data controls in ASP.NET 4.
MvcContrib Template Gallery: Download 58 pre-built ASP.NET MVC Template Gallery styles that you can use to customize the look and feel of your applications. All available under a Community Commons license.
Step into the ASP.NET MVC Source Code with the VS Debugger: Nice blog post by Gunnar that describes how to use VS 2010’s built-in symbol server support to enable you to step into the ASP.NET MVC Framework source code when debugging.
Installation Options for ASP.NET MVC: Jon has a good post that describes how to install ASP.NET MVC 2 on a server. There are a couple of options you can use for servers that don’t already have ASP.NET MVC installed – the easiest is to just enable the “Copy Local” flag on System.Web.Mvc.dll and install it in the \bin directory.
Visual Studio Support for IIS Express, SQL 4 Compact Edition, and Razor syntax: Channel 9 video with Damian Edwards and Scott Hanselman that discusses the support coming to enable IIS Express, SQL 4 CE, and Razor syntax support within Visual Studio 2010.
How to Use IIS Express with VS today: Kamran has a nice blog post that describes how you can use IIS Express with Visual Studio today – without having to wait for the official Visual Studio patch to enable it.
Developers Roadmap for Windows Phone 7: The Windows Phone 7 team blogs about the release timeframe for Windows Phone 7 and the Visual Studio and Expression Blend tools for targeting it. The official developer release will be on September 16th.
Windows Phone 7 in 7 Minutes: Really nice set of 7 minute videos that enable you to quickly understand and learn Windows Phone 7 and the development fundamentals behind it.
Windows Phone 7 Jumpstart Training: Nice list of free training sessions you can watch online to learn how to build Windows Phone 7 applications using Silverlight and XNA.
Silverlight Panorama and Pivot Controls for Windows Phone 7: Jeff has a great post that discusses the awesome new Panorama and Pivot controls for Silverlight that will be part of the final Windows Phone 7 developer release.
Using XNA from Silverlight on Windows Phone 7: Good blog post from Mike that demonstrates how to use XNA APIs from Silverlight applications on Windows Phone 7. This post demonstrates how to use the XNA audio framework from Silverlight.
Creating High Performance Silverlight Applications for Windows Phone 7: This is a great whitepaper written by my team that discusses best practices for building Silverlight applications that run well on Windows Phone 7.
Performance of Silverlight on Windows Phone 7: A nice podcast with Scott Hanselman that discusses tips and techniques to enable smooth applications and great experiences on Windows Phone 7.
People often ask me for .NET book recommendations. Below is one book I always keep close by and find super-useful. If you are looking for a good one-volume C# and .NET Base Class Library reference, C# 4.0 in a Nutshell a great one:
Hope this helps,
Scott
One of the top reported Microsoft Connect issues with VS 2010 has been an issue with the Find and Replace dialog – which grows 16px each time you use it (which is pretty annoying).
The Visual Studio team recently released a patch that fixes this issue. You can download and apply it here.
Hope this helps,
Scott
P.S. A few people reported issues installing the patch if they had an older version of the Silverlight 4 tools installed. If you see an error message that says you need an update to Visual Studio to support Silverlight 4, you can fix it by installing the latest Silverlight 4 tools release.
This is the twenty-seventh in a series of blog posts I’m doing on the VS 2010 and .NET 4 release.
Today’s blog post continues on from the Debugging Tips post I did last week, and covers some useful searching and navigation tips/tricks you can take advantage of within Visual Studio. These tips were ones that my friend Scott Cate (who has blogged dozens of great VS tips and tricks here) recently recommended to me as good tips that most developers using Visual Studio don’t seem to know about (even though most have been in the product for awhile).
Hopefully this post will help you discover them if you aren’t already taking advantage of them. They are all easy to learn, and can help save you a bunch of time.
Ctrl + i - Incremental SearchMost developers using Visual Studio are familiar with the “Find dialog” that you can launch by pressing the “Ctrl + F” key within the IDE. A surprisingly large number of developers, though, aren’t familiar with the “Incremental Search” capability within Visual Studio. This enables you to search within your current document, and enables you to do so without having to bring up a dialog.
Using Incremental Search
To enable incremental search, just type “Ctrl + i” within the editor. This will subtly change your cursor, and cause your status bar at the bottom left of the IDE to change to “Incremental search: (search term)” – you can then type the search term you are searching for and the editor will search for it from the current source location you are on (no dialog required).
Below we did an incremental search for the term “action” and VS highlighted the first usage it found within the file:
We can then press “Ctrl + i” again to find the next usage of the same term (and continue this repeatedly):
Pressing “Ctrl + Shift + i” will reverse direction on the search, and allow us to skip backwards.
You can press the “Esc” key at any point to escape out of incremental search. More details on incremental search can be found here.
F3 and Shift+F3 – Find Using Previous Search TermOne neat tip to know about incremental search is that after you press the ESC key to escape out of it, it will add the term you searched for to the find stack within the IDE. The search term you used will show up within the “find” drop-down within the VS "standard toolbar:
You can always press the F3 key within Visual Studio to repeat the last performed search at a later point. This is particularly useful for scenarios where you search for something, make a code change, and then want to continue from that point in the code. Just press F3 and you’ll repeat the last search (in this case “action”) from that new point in the document – no need to re-type it.
Pressing “Shift + F3” will do a reverse search (from the current cursor location in the editor) of the last search term used. You can easily toggle using F3/Shift+F3 to search forward and backwards within your document.
Ctrl + F3 - Find Using Current SelectionAnother neat searching trick that you can use to avoid having to type your search term is to simply highlight a word (or part of a word) within the code editor, and then press “Ctrl + F3” to search for the next usage of it within the current file:
Pressing “Ctrl + F3” will search for the next instance of the text you have highlighted – allowing you to avoid having to type it:
Like before, you can use “Ctrl + Shift + F3” to perform a reverse search if you so choose, to search backwards within the document.
Ctrl + Shift + F – Find in SolutionSometimes you want to search across your entire solution.
“Ctrl + F” will bring up the find dialog and default it to search within the current document. “Shift + Ctrl + F” will bring up the find dialog and default it to instead search across the entire solution:
Doing a search like this will bring up the “Find Results” window within the IDE and allow you to navigate to each found instance of the term:
You can double-click each item in the “Find Results” window to navigate to that instance of the search term you searched for.
One tip a lot of people don’t know about is the ability to press “F8” or “Shift + F8” to navigate to the next/previous instance of that search term in the list. This can make navigating through them much faster/easier, and avoid you having to use the mouse.
Shift + F12 - Find UsagesMost developers using Visual Studio know how to highlight a type and press F12 to “go to definition”. This will bring up the definition of a class/type, and is a useful way to navigate to where it is defined.
Many developers don’t know about “Shift + F12” – which brings up all usages of a particular type. This enables you to quickly see how a particular type is used. To take advantage of it, simply select or move the cursor onto a type and press “Shift + F12”:
This will then bring up a “Find Symbol Results” window that list all usages of this type within the current solution:
Like with the previous tip, you can use “F8” and “Shift F8” to navigate forward/backward within each item within the list.
Ctrl + Minus and Shift + Ctrl + Minus - Navigate Backward/ForwardHave you ever navigated to a different code file, looked at something, and then wanted to navigate back to where you came from? For example, you use F12 to “go to definition” and then want to return back to the code that used it?
A feature that a lot of people don’t know about in VS is the “Navigate Backwards” keystroke – “Ctrl + (minus key)”. This will navigate to the previous document/location on the navigation stack.
To see this in action, try selecting a type in Visual Studio. Below I’ve selected the “IController” interface:
Press F12 to navigate to the definition of it. This opens up a new editor window with the source of the selected type:
Now to jump back to where we came from, press “Ctrl + (minus key)” and VS will take us back to where we were:
If you want to move forward in the navigation stack (which in this case would take us back to the IController.cs file), then press the “Shift + Ctrl + (minus key)”.
Sara Ford has a good blog post that talks more about this feature, and explains the conditions when a new location is pushed onto the navigation stack.
Ctrl + Alt + (down arrow) - Navigate to an Open FileEver have a ton of files open within the IDE, and want an easy way to navigate between them?
One useful key sequence you can use is “Ctrl + Alt + (down arrow)” – this will cause a drop-down to appear within VS that lists all open files within it:
You can use the arrow keys to select the file you want to navigate to – or better yet just start typing the file-name and Visual Studio will highlight it for you within the list. For example, above I typed “Mo” and Visual Studio highlighted “ModelBinder.cs”. Pressing the “enter” key will navigate me to that file:
This provides a nice, convenient, way to navigate between files without having to use the mouse or take your hands off the keyboard. And remember that “Ctrl + (minus)” can be used to navigate you back to where you came from.
Navigate To, View Call Hierarchy, and Highlight References FeaturesVisual Studio 2010 brings with it a bunch of new code navigation and searching features – including the new “Navigate To” dialog, “View Call Hierarchy” feature and Highlighted References Feature.
![]()
I previously blogged about these three new VS 2010 features here. If you haven’t already read this post and explored these capabilities, I highly recommend doing so – they are some great additions.
Other Editor ImprovementsThere are a ton of other code editor improvements in VS 2010 – many of them ones I’ve blogged about before. Here are links to a few of my previous VS 2010 editor blog posts:
Also check out the other blog posts I’ve done in this VS 2010 and .NET 4 Improvements series.
SummaryMost of the above features have actually been in Visual Studio for several releases – but are ones that a surprising number of developers don’t know about. Hopefully this blog post helps provide a convenient way to get started with them if you didn’t already know they existed. If you need help remembering the keystrokes – print out a copy of the VS 2010 Keybindings Poster and keep it near your monitor.
To learn even more cool Visual Studio tips/tricks, subscribe to Scott Cate’s excellent Visual Studio Tips blog series (which is already up to 83 awesome tips and tricks). Also subscribe to Sara Ford’s blog – she has an awesome set of tips/tricks that go back years.
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
This is the twenty-sixth in a series of blog posts I’m doing on the VS 2010 and .NET 4 release.
Today’s blog post covers some useful debugging tips that you can use with Visual Studio. My friend Scott Cate (who has blogged dozens of great VS tips and tricks here) recently highlighted these to me as good tips that most developers using Visual Studio don’t seem to know about (even though most have been in the product for awhile). Hopefully this post will help you discover them if you aren’t already taking advantage of them. They are all easy to learn, and can help save you a bunch of time.
Run to Cursor (Ctrl + F10)Often I see people debugging applications by hitting a breakpoint early in their application, and then repeatedly using F10/F11 to step through their code until they reach the actual location they really want to investigate. In some cases they are carefully observing each statement they step over along the way (in which case using F10/F11 makes sense). Often, though, people are just trying to quickly advance to the line of code they really care about – in which case using F10/F11 isn’t the best way to do this.
Instead, you might want to take advantage of the “run to cursor” feature that the debugger supports. Simply position your cursor on the line in your code that you want to run the application to, and then press the Ctrl + F10 keys together. This will run the application to that line location and then break into the debugger – saving you from having to make multiple F10/F11 keystrokes to get there. This works even if the line of code you want to run to is in a separate method or class from the one you are currently debugging.
Conditional BreakpointsAnother common thing we often see in usability studies are cases where developers set breakpoints, run the application, try out some input, hit a breakpoint, and manually check if some condition is true before deciding to investigate further. If the scenario doesn’t match what they are after, they press F5 to continue the app, try out some other input, and repeat the process manually.
Visual Studio’s conditional breakpoint capability provides a much, much easier way to handle this. Conditional breakpoints allow you to break in the debugger only if some specific condition that you specify is met. They help you avoid having to manually inspect/resume your application, and can make the whole debugging process a lot less manual and tedious.
How to Enable a Conditional Breakpoint
Setting up a conditional breakpoint is really easy. Press F9 in your code to set a breakpoint on a particular line:
Then right-click on the breakpoint “red circle” on the left of the editor and select the “Condition…” context menu:
This will bring up a dialog that allows you indicate that the breakpoint should only be hit if some condition is true. For example, we could indicate that we only want to break in the debugger if the size of the local paginatedDinners list is less than 10 by writing the code expression below:
Now when I re-run the application and do a search, the debugger will only break if I perform a search that returns less than 10 dinners. If there are more than 10 dinners then the breakpoint won’t be hit.
Hit Count Feature
Sometimes you only want to break on a condition the Nth time it is true. For example: only break the 5th time less than 10 dinners is returned from a search.
You can enable this by right-clicking on a breakpoint and selecting the “Hit count…” menu command.
This will bring up a dialog that allows you to indicate that the breakpoint will only be hit the Nth time a condition is met, or every N times it is met, or every time after N occurrences:
Machine/Thread/Process Filtering
You can also right-click on a breakpoint and select the “Filter..” menu command to indicate that a breakpoint should only be hit if it occurs on a specific machine, or in a specific process, or on a specific thread.
TracePoints – Custom Actions When Hitting a BreakPointA debugging feature that a lot of people don’t know about is the ability to use TracePoints. A TracePoint is a breakpoint that has some custom action that triggers when the breakpoint is hit. This feature is particularly useful when you want to observe behavior within your application without breaking into the debugger.
I’m going to use a simple Console application to demonstrate how we might be able to take advantage of TracePoints. Below is a recursive implementation of the Fibonacci sequence:
In the application above, we are using Console.WriteLine() to output the final Fibonacci sequence value for a specific input. What if we wanted to observe the Fibonacci recursive sequence in action along the way within the debugger – without actually pausing the execution of it? TracePoints can help us easily do this.
Setting up a TracePoint
You can enable a TracePoint by using F9 to set a breakpoint on a line of code, and then right-click on the breakpoint and choose the “When Hit…” context menu command:
This will bring up the following dialog – which allows you to specify what should happen when the breakpoint is hit:
Above we’ve specified that we want to print a trace message anytime the breakpoint condition is met. Notice that we’ve specified that we want to output the value of the local variable “x” as part of the message. Local variables can be referenced using the {variableName} syntax. There are also built-in commands (like $CALLER, $CALLSTACK, $FUNCTION, etc) that can be used to output common values within your trace messages.
Above we’ve also checked the “continue execution” checkbox at the bottom – which indicates that we do not want the application to break in the debugger. Instead it will continue running – with the only difference being that our custom trace message will be output each time the breakpoint condition is met.
And now when we run the application, we’ll find that our custom trace messages automatically show up in the “output” window of Visual Studio – allowing us to follow the recursive behavior of the application:
You can alternatively wire-up a custom trace listener to your application - in which case the messages you print from your TracePoints will be piped to it instead of the VS output window.
TracePoints – Running a Custom MacroIn a talk I gave last week in London, someone in the audience asked whether it was possible to automatically output all of the local variables when a TracePoint was hit.
This capability isn’t built-in to Visual Studio – but can be enabled by writing a custom Macro in Visual Studio, and then wiring up a TracePoint to call the Macro when it is hit. To enable this, open up the Macros IDE within Visual Studio (Tools->Macros->Macros IDE menu command). Then under the MyMacros node in the project explorer, select a module or create a new one (for example: add one named “UsefulThings”). Then paste the following VB macro code into the module and save it:
Sub DumpLocals()
Dim outputWindow As EnvDTE.OutputWindow
outputWindow = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput).Object
Dim currentStackFrame As EnvDTE.StackFrame
currentStackFrame = DTE.Debugger.CurrentStackFrame
outputWindow.ActivePane.OutputString("*Dumping Local Variables*" + vbCrLf)
For Each exp As EnvDTE.Expression In currentStackFrame.Locals
outputWindow.ActivePane.OutputString(exp.Name + " = " + exp.Value.ToString() + vbCrLf)
Next
End Sub
The above macro code loops through the current stack frame and dumps all local variables to the output window.
Using our custom DumpLocals Custom Macro
We can then take advantage of our custom “DumpLocals” macro using the simple addition application below:
We’ll use F9 to set a breakpoint on the return statement within our “Add” method above. We’ll then right-click on the breakpoint and select the “When hit” menu command:
This will bring up the following dialog. Unlike before where we used the “Print a message” checkbox option and manually specified the variables we wanted to output, this time we’ll instead select the “Run a macro” checkbox and point to the custom UsefulThings.DumpLocals macro we created above:
We’ll keep the “continue execution” checkbox selected so that the program will continue running even when our TracePoints are hit.
Running the Application
And now when we press F5 and run the application, we’ll see the following output show up in the Visual Studio “output” window when our Add method is invoked. Note how the macro is automatically listing the name and value of each local variable when the TracePoint is hit:
SummaryThe Visual Studio debugger is incredibly rich. I highly recommend setting aside some time to really learn all of its features. The above tips and tricks are but a few of the many features it provides that most people are actually unaware of.
I’ve previously blogged about other VS 2010 Debugger Improvements (including DataTip pinning, Import/Export of Breakpoints, Preserving Last Value Variables, and more). I’ll be doing more blog posts in the future about the new VS 2010 Intellitrace and Dump File Debugging support as well. These provide a bunch of additional cool new capabilities that can make debugging applications (including ones in production) a lot easier and more powerful.
Also make sure to check out Scott Cate’s excellent Visual Studio 2010 Tips and Tricks series to learn more about how to best take advantage of Visual Studio. He has an absolutely awesome set of free videos and blog posts.
And also check out Jim Griesmer’s great series on Visual Studio Debugging Trips and Tricks. He has a ton of good tips and tricks you can take advantage of.
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
I just got back from my trip to India and the UK last week – and will be returning to more regular blogging shortly.
This Wednesday (August 18th) I’m going to be doing another online LIDNUG chat session. The chat will be from 10:00am to 11:30am Pacific Time. I do these chats a few times a year and they tend to be pretty good. Attendees can submit any questions they want to me, and listen to me answer them live via LiveMeeting. You can learn more about it here and join the chat and ask questions at the appropriate time with this link.
Hope to get a chance to chat with some of you there!
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
I’ve blogged in the past about the VS 2010 Productivity Power Tool Extensions – a free set of Visual Studio 2010 extensions that provide some nice additional functionality.
You can read my previous blog posts about it here and here. In today’s post I’m going to briefly highlight a few small, but nice, code editor capabilities that are enabled when you install the free extensions (and which I didn’t highlight in my previous blog posts).
Ctrl+Click “Go to Definition”One of the small, but useful, features that I find myself using a lot with the extensions is the "Ctrl + Click” go to definition feature.
For those of you who haven’t tried it, it enables you to quickly navigate to the definition of a member or type within your code. You can accomplish the same behavior out of the box with Visual Studio by right-clicking on a member/type and then choosing the “Go to Definition” context menu item – or by moving your cursor over a type/member and then pressing the F12 key. But for some reason I’ve found the Ctrl+Click gesture provided by the VS 2010 Power Tool Extensions more natural and faster to use (since for my keyboard the F12 key requires a split-second extra finger move to use – whereas the control key is always in easy reach).
To try out the “Ctrl+Click” behavior, just hold down the “Ctrl” key and use your mouse to hover over a type or member in your code. When the extension is enabled you’ll find that this causes a hyperlink to appear under each type/member you hover over:
Clicking the hyperlink will immediately navigate you to the definition of the type/member within your code:
Note that the “go-to-definition” feature in VS can also be used on a type that you don’t have source access to. For example, like with the DbSet<T> collection I used in my EF “code-first” blog post yesterday:
When you click a type referenced from a binary library, VS will automatically generate a class definition based on the signature compiled into the assembly:
Triple Click SelectionAnother one of the “small but useful” features provided with the power tool extensions that I find myself using a lot is the “triple click” feature.
Today with VS you can double-click on a word to automatically select it:
When the “Triple Click” extension is enabled you can now also triple-click on a line to automatically select the entire line:
This behavior has been supported in Word for awhile. Until I saw that there was a power tools extension for it I didn’t actually realize that VS didn’t already do it by default. Well – now you can.
“Alt Up/Down Arrow” Line MovementAnother “small but useful” feature provided by the power tool extensions is the ability to easily move lines of code up/down within the editor.
Simply select either a single line of code, or a block of multiple lines of code, within the editor:
Then hold down the “alt” key, and press either the up or down arrow on your keyboard. This will cause the editor to move the selected code up or down within the editor (without you having to copy/paste or move anything around manually):
This is another one of those features that Word has had for awhile – and which is nice to now have in VS.
Column GuidesColumn guidelines allow you display a vertical band within the code editor. This is useful to help identify the maximum size a single line of text should be within your code (for example: to avoid wrapping when printing it out).
The power tool extensions enable you to add a column guide pretty easily. Just cursor over in your code editor to where you want the guideline to be (note: you can see the exact line column count at the bottom of the editor):
Then right-click and choose the “Guidelines->Add Guideline” menu command:
This will then cause VS to show a column guide-line in all code editor windows at that column width – making it easier to see when you’ve written code or a comment that wraps beyond that:
If you want to remove a guideline, you need to move your editor cursor to be at the same column width as the guideline. You can then right-click and use the “Guidelines->Remove Guideline” command to remove it.
Extensions UpdateIn case you missed it, the Visual Studio team last week made a minor update to the VS 2010 Productivity Power Tool Extensions to fix a few bugs and performance issues that people reported with the last release.
Sean has a blog post with more details about the update here. The update included fixes for:
If you have a previous build of the Power Tool Extensions installed you use the “Tools->Extension Manager” menu command, select the power tools extension and then click the “update” button to upgrade to the latest build.
SummaryIf you haven’t tried out the VS 2010 Productivity Power Tool Extensions yet, I’d encourage you to give it a try. It includes some nice additional functionality which can help save you keystrokes and time as you work within Visual Studio. I’ve only covered a few of the features in this post and my previous two posts – there are a lot more cool things in there that I haven’t blogged about yet.
You can also now enable/disable each individual feature within the extensions pack – allowing you to selectively choose what you want to use. Use the “Tools->Options” menu command, and navigate to the “Power Productivity Tools” tree-view item to enable/disable individual features.
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
Last month I blogged about the new Entity Framework 4 “code first” development option. EF “code-first” enables a pretty sweet code-centric development workflow for working with data. It enables you to:
In my initial blog post I introduced EF “code-first” and demonstrated how to use the default EF4 mapping conventions to create a new database. 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. I then did a second custom database schema mapping blog post that discussed how you can override the default persistence mapping rules, and enable custom database schemas.
In today’s blog post I’m going to cover a question that several people asked me recently, which is: “how do I use EF code-first with an existing database?”
Using EF Code-First with an Existing DatabaseEF “Code First” works great with existing databases, and enables a very nice code-centric development approach with them. In particular, it enables you to use clean “plain old classes” (aka POCO) for your model objects, and cleanly map them to/from the database using either the default mapping conventions or by overriding them with custom schema mapping rules.
Below are step by step instructions on how you can use EF “Code First” with an existing database.
Step 1: Create a new ASP.NET Web Application ProjectLet’s begin by creating a new ASP.NET Web Application Project. My previous two EF “code first” blog posts used ASP.NET MVC – for this blog post I’ll use ASP.NET Web Forms. Note that all of the EF concepts are identical regardless of whichever type of ASP.NET application you use.
We’ll use “File->New Project” within VS 2010 (or the free Visual Web Developer 2010 Express) and choose the “ASP.NET Web application” project template to create the new application.
The new “ASP.NET Web Application” project in VS 2010 is a nice starter template that provides a default master-page layout with CSS design (I blogged about this new starter project template in a previous blog post). When it is created you’ll find it contains a few default files within it:
We don’t need these default files (we could instead just use the “Empty ASP.NET Web Application” project template) – but they’ll make our simple app look a little prettier by default so we’ll use them.
Step 2: Reference the EF Code First AssemblyOur next step will be to add a reference to the EF Code First library to our project. Right click on the “references” node within the Solution Explorer and choose “Add Reference”.
You’ll reference the “Microsoft.Data.Entity.Ctp.dll” assembly that is installed within the “\Program Files\Microsoft ADO.NET Entity Framework Feature CTP4\Binaries\” directory when you download and install the EF Code First library. After adding this reference you’ll see it show up in your project’s references window like below:
Step 3: Northwind DatabaseYou can skip this step if you have a SQL Server database with Northwind (or another database) installed.
If you don’t have Northwind already installed then you can download it here. You can either use the .SQL files it includes to install it into a SQL database, or copy the Northwind.mdf SQL Express file into the \App_Data directory of your application:
Step 4: Create our Model LayerNow we’ll write our model classes and use EF “code first” to map them to our Northwind database. Below is all of the code we need to write to enable this – no other code is required:
Below are some details about what all this code does and how it works:
POCO Model Classes
EF “code first” enables us to use “plain old CLR objects” (aka POCO) to represent entities within a database. This means that we do not have to derive our model classes from a base class, nor implement any interfaces or attributes on them. This enables us to keep our model classes clean and “persistence ignorant”.
Above we’ve defined two POCO classes - “Product” and “Category” – that we’ll use to represent the “Products” and “Categories” tables within our Northwind database. The properties on these two classes map to columns within the tables. Each instance of a Product or Category class represents a row within the respective database tables.
Nullable Columns
Notice that some of the properties within the “Product” class are defined as nullable (this is what Decimal? means – that indicates it is a nullable type). Nullable columns within a database table should be represented within the model class as Nullable properties if they are value types:
You can also optionally omit specifying nullable columns entirely from a model class if you don’t need to access it. For example, the Product table within Northwind has a “QuantityPerUnit” column that is a nullable nvarchar, and a “UnitsOnOrder” column that is a nullable smallint. I’ve omitted both of these properties from the “Product” class I defined above. Because they are nullable within the database I can still retrieve, insert, update and delete Products without problems.
Association Properties and Lazy Loading
EF “code-first” makes it easy to take advantage of primary-key/foreign-key relationships within the database, and expose properties on our model classes that enable us to traverse between model classes using them.
Above we exposed a “Category” property on our Product class, and a “Products” property on our Category class. Accessing these properties enables us to use the PK/FK relationship between the two tables to retrieve back model instances. Notice how the properties themselves are still “POCO” properties and do not require us to use any EF-specific collection type to define them.
Association properties that are marked as “virtual” will by default be lazy-loaded. What this means is that if you retrieve a Product entity, its Category information will not be retrieved from the database until you access its Category property (or unless you explicitly indicate that the Category data should be retrieved when you write your LINQ query to retrieve the Product object).
EF Context Class
Once we’ve created our “Product” and “Category” POCO classes, we used EF “code first” to create a “context” class that we can use to map our POCO model classes to/from tables within the database:
The “Northwind” class above is the context class we are using to map our Product and Category classes to/from the database. It derives from the DbContext base class provided by EF “code-first”, and exposes two properties that correspond to tables within our database. For this sample we are using the default “convention over configuration” based mapping rules to define how the classes should map to/from the database.
We could alternatively override the “OnModelCreating” method and specify custom mapping rules if we wanted the object model of our model classes to look differently than our database schema. My previous blog EF “code first” post covers how to do this.
Step 5: Configuring our Database Connection StringWe’ve written all of the code we need to write to define our model layer. Our last step before we use it will be to setup a connection-string that connects it with our database.
In my initial EF “code first” blog post I discussed a cool option that EF “code first” provides that allows you to have it auto-create/recreate your database schema for you. This is a option that can be particularly useful for green-field development scenarios – since it allows you to focus on your model layer early in the project without having to spend time on updating your database schema after each model change.
Importantly, though, the auto-create database option is just an option – it is definitely not required. If you point your connection-string at an existing database then EF “code first” will not try and create one automatically. The auto-recreate option also won’t be enabled unless you explicitly want EF to do this – so you don’t need to worry about it dropping and recreating your database unless you’ve explicitly indicated you want it to do so.
For this blog post we will not auto-create the database. Instead, we’ll point at the existing Northwind database we already have. To do this we’ll add a “Northwind” connection-string to our web.config file like so:
<connectionStrings>
<add name="Northwind"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\northwind.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
EF “code first” uses a convention where context classes by default look for a connection-string that has the same name as the context class. Because our context class is called “Northwind” it by default looks for a “Northwind” connection-string to use. Above our Northwind connection-string is configured to use a local SQL Express database. You can alternatively point it at a remote SQL Server.
Step 6: Using our Model ClassesLet’s now write a (very) simple page that uses our Northwind model classes to display some data from our database.
We’ll begin by adding a new page to our ASP.NET project. Right-click on the web project and choose Add->New Item, then select the “Web Form using Master Page” item template. We’ll name the page “Products.aspx” and have it use the “Site.master” master-page that is included by default with the ASP.NET Web Project starter template.
We’ll add a <asp:GridView> control to our new Products.aspx page. We’ll configure it to show just the name and price of our Products:
Within our code-behind file we can then write the following LINQ query against our model classes to retrieve all active products from our database, and bind them to the above GridView control:
And now when we run the project and navigate to the Products.aspx page we’ll get a listing of our Products like so:
We now have a simple application that uses EF “code first” against an existing database.
Download SampleYou can download a completed version of the above sample here. It assumes you have EF “code first” CTP4 and SQL Express installed.
Additional Code ExamplesBelow are some additional code examples that demonstrate how we could use our Northwind model for other common scenarios.
Query Across Relations
The LINQ query below demonstrates retrieve a sequence of Product objects based on the name of the Category they belong to. Notice below how we can write LINQ queries that span both the Product and a sub-property of its associated Category object. The actual filter is all done in the database engine itself – so only Product objects get returned to the middle tier (making it efficient):
Use the Find method to retrieve a single Product
In addition to allowing you to write LINQ queries, EF “Code First” also supports a “Find()” method on DbSet<T> collections that allows you to write code like below to retrieve a single instance based on its ID:
Inserting a New Category
The code below demonstrates how to add a new Category to the Database:
Notice how we create the Category object, assign properties to it, then add it to the Context’s Categories collection. We then call SaveChanges() on the context to persist updates to the database.
Inserting a New Category and Product (and associating them)
The code below demonstrates how to create a new Category and a new Product, associate the Product so that it belongs to the new Category, and then save both to the Database:
Notice above how we are able to have the new Product reference the newly created Category by assigning its “Category” property to point to the Category instance. We do not need to explicitly set the CategoryID foreign key property – this will be done automatically for us when we persist the changes to the database.
EF uses an pattern called “unit of work” – which means that it can track multiple changes to a context, and then when “SaveChanges()” is called it can persist all of them together in a single atomic transaction (which means all the changes succeed or none of them do). This makes it easier to ensure that your database can’t be left in an inconsistent state – where some changes are applied and others aren’t.
In the code snippet above both the Category and the Product will both be persisted, or neither of them will (and an exception will be raised).
Update a Product and Save it Back
The code below demonstrates how to retrieve and update a Product, and then save it back to the database. Earlier I demonstrated how to use the Find() method to retrieve a product based on its ProductID. Below we are using a LINQ query to retrieve a specific product based on its ProductName.
We could make any number of changes (to any existing objects, as well as add new ones). When we call SaveChanges() they will all be persisted in a single transaction back to the database.
Default Conventions vs. Custom Mapping RulesWhen we created the Product and Category classes earlier, we used the default conventions in EF “Code-First” to map the classes to/from the database. This avoided the need for us to specify any custom mapping rules, and kept our code really concise.
There will definitely be times when you don’t like the shape of the database your are mapping, though, and want to have your model’s object model be different. Refer back to my Custom Database Schema Mapping blog post for examples of how to use EF to specify custom mapping rules. These all work equally well when mapping existing databases.
SummaryI’m pretty excited about the EF "Code-First” functionality and think it 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 particular I like it because it helps keep code really clean, maintainable, and allows you to do a lot concisely. Hopefully these last three blog posts about it provides a glimpse of some of the possibilities it provides – both for new and existing databases.
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
The (awesome) UK developer community is holding an all day event with me in London on August 13th. The event is free to attend, and the venue will be in Central London (at the ODEON Covent Garden). The website for the event is here.
ContentThe event will be a packed day of presentations covering VS 2010, ASP.NET 4, ASP.NET MVC, and Silverlight for Windows Phone 7. Below is the list of talks:
VS 2010 and ASP.NET 4 (90 minutes)
A demo heavy talk that covers some of the new features and capabilities within Visual Studio 2010 and ASP.NET 4, and how you can best take advantage of them.
ASP.NET MVC 2 (90 minutes)
A demo heavy talk that covers using ASP.NET MVC 2 with Visual Studio 2010. We’ll spend 90 minutes building a new ASP.NET MVC 2 application starting from File->New Project, and explain the core concepts behind ASP.NET MVC, as well as how to take advantage of the new features shipped with ASP.NET MVC 2.
Windows Phone 7 Development (90 minutes)
In this session we’ll take a look at Windows Phone 7 and the developer ecosystem, from the capabilities and unique features of the platform to the development frameworks and tools you have at your disposal. Along the way we’ll build a simple application or two and explore how people can buy your finished masterpiece.
Web Development Futures: ASP.NET MVC 3, SQL CE and IIS Express (90 minutes)
In this session we’ll covers some of the new web technologies shipping in the near future. Learn about some of the improvements coming with ASP.NET MVC 3, the new “Razor” template syntax, “Code-First” EF4, SQL CE and IIS Express.
RegistrationThe event is free and only has a few hundred seats – which means they will likely fill up fast (likely in a few hours – or even minutes – if past history is any indication). So if you want to attend I recommend signing up quickly.
Registration will open tomorrow (Tuesday August 3nd) at 2pm (UK time). The website for the event and registration is here.
Hope to see some of you there!
Scott
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 EasierDeploying 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” DialogVisual 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 TransformationsIn 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 DeploymentVS 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 PackagesVS 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 BuildMost 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.
SummaryToday’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
Earlier this week the Visual Studio team released updated VS 2010 Keyboard Shortcut Posters. These posters are print-ready documents (that now support standard paper sizes), and provide nice “cheat sheet” tables that can help you quickly lookup (and eventually memorize) common keystroke commands within Visual Studio.
This week’s updated posters incorporate a number of improvements:
The posters are in PDF format – enabling you to easily download and print them using whichever paper size is in your printer.
Download the PostersYou can download the VS 2010 Keybinding posters in PDF format here.
Posters are available for each language. Simply look for the download that corresponds to your language preference (note: CSharp = C#, VB = VB, FSharp = F#, CPP = C++).
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
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 3As 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 ImprovementsASP.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 EngineEarlier 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:
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 ImprovementsASP.NET MVC 3 “Preview 1” includes several nice controller-specific enhancements.
Global FiltersASP.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 PropertyASP.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 TypesASP.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 ImprovementsASP.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 ImprovementsASP.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:
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 ImprovementsASP.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:
For future previews we are investigating adding dependency injection support for:
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 LinksClick 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. Listen to Scott Hanselman’s Podcast about ASP.NET MVC 3 with Phil Haack, and watch this Scott Hanselman Channel 9 video about ASP.NET MVC 3.
SummaryWe 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
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:
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 SampleIn 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.
![]()
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:
![]()
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:
![]()
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:
![]()
Below is the database schema definition for the “RSVPs” table within our database:
![]()
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 EF4EF4 “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:
![]()
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 NameLet’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:
![]()
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:
![]()
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:
![]()
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 ChangeIf 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 MappingsLet’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:
![]()
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:
![]()
We can achieve this custom persistence by updating our “OnModelCreating” method to have a slightly richer mapping rule like so:
![]()
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 TypesRelational 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:
![]()
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:
![]()
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:
![]()
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 RulesYou 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.
SummaryThe 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
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:
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 SampleIn 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.
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:
![]()
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:
![]()
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:
Below is the database schema definition for the “RSVPs” table within our database:
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 EF4EF4 “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:
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 NameLet’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:
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:
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:
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 ChangeIf 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 MappingsLet’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:
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:
We can achieve this custom persistence by updating our “OnModelCreating” method to have a slightly richer mapping rule like so:
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 TypesRelational 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:
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:
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:
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 RulesYou 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.
SummaryThe 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
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 UpdateYesterday 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:
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 SupportThe 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:
In addition to enabling/disabling individual features, you can also tweak/edit their settings (including color schemes and behavior).
Solution NavigatorSolution 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:
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:
You can double click any of the filtered files or members to immediately navigate to it within the code editor.
Quick AccessQuick 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:
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):
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.
SummaryI’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
.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:
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 EFIn 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:
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 ApproachLast 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.
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 ApplicationWe’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:
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 ModelLet’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”:
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:
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 MappingWe 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 ModelThe 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:
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:
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:
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:
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.
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:
Step 3: Create a ASP.NET MVC Controller that uses our ModelLet’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:
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”:
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:
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:
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:
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:
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 DatabaseWe’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:
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:
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:
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:
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:
Below are the tables that were added when we ran our application and the database was automatically created based on the above model:
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:
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:
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:
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:
Step 5: Changing our ModelWe 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”:
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:
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:
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:
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:
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:
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:
We can then update the Database.Initializer() call we added to our Global.asax to use this “NerdDinnersInitializer” class at startup:
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:
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 RulesWe’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):
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:
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:
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:
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.
DownloadClick 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.
SummaryThis 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
Earlier today we shipped the beta of the Windows Phone 7 Developer Tools. You can download them here.

The Windows Phone Developer Tools Beta includes:
Integrated with the development tools is a phone emulator that enables you to easily develop and test Windows Phone 7 applications on your laptop or desktop machine – without requiring a phone device. It is hardware accelerated, supports multi-touch events on multi-touch capable monitors, and provides a really easy way to debug and try out your phone applications.
Devices for DevelopersIn addition to testing applications within the emulator, we are also this month starting to ship pre-release phones to developers. You can learn more about this program and sign-up to receive one from this blog post from the Windows Phone 7 team.
Learning MoreI previously blogged a nice step-by-step tutorial that covers how to build a Twitter search application using Visual Studio 2010 Express for Windows Phone. It provides a nice introduction on how you can easily use Silverlight and the Visual Studio Tools for Windows Phone to quickly build applications. You can read and follow the tutorial here.
Read today’s blog post from the Windows Phone 7 team which provides more details on today’s release. It also mentions two new Silverlight controls – a Panorama and Pivot control - which will enable you to easily implement the new Windows Phone 7 navigation style. These controls are not implemented in today’s beta, but will be released as an update in a few weeks.
If you have used the previous Windows Phone 7 CTPs, also make sure to read Jaime’s Migrating Applications from the Windows Phone April CTP Refresh to the Beta blog post. It provides a wealth of details on how to update code that you’ve already written.
Uninstalling Previous CTP BitsUpdate: Some people have reported problems with uninstalling the previous CTP of the Windows Phone 7 Developer tools. Amit has a blog post here that discusses how to fix this. Aaron also has a blog post that discusses how to remove XNA Game Studio in the event that you have a partial install of it that you need to clean up.
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
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.NETExtending ASP.NET Output Caching: Scott Mitchell has a nice article that discusses how to take advantage of ASP.NET 4’s extensible cache provider API to implement richer output caching mechanisms. Also check out my article on ASP.NET 4 output caching improvements here.
Installing and Configuring Windows Server AppFabric and “Velocity” Memory Cache: Scott Hanselman has a nice blog post that describes how to install and configure Windows Server AppFabric – which is a free application server offering from Microsoft. In less than 10 minutes you can enable its “Velocity” memory cache, and use it within your ASP.NET applications.
Preventing Users From Copying Text From and Pasting It Into TextBoxes: Scott Mitchell has a useful article that discusses how to disable copy/paste within ASP.NET forms. Useful for scenarios where you want to avoid people inadvertently duplicating a bad email registration address.
Building a Store Locator ASP.NET Application Using Google Maps API: Scott Mitchell has a nice set of articles that discuss how to use the Google Maps API within an ASP.NET application to implement a Store Locator service. Also check out Part 2 and Part 3 of his series.
ASP.NET 4 SEO Improvements: Nice article from Scott Mitchell that describes some of the search engine optimization (SEO) improvements provided with ASP.NET 4. Also check out my previous blog post on this topic.
More details about SQL Compact Edition 4: Rob blogs more details about the recently released SQL CE 4 beta – which is available both as a standalone install as well as integrated within WebMatrix. SQL CE 4 enables you to use an embedded database within your ASP.NET applications. I blogged an overview of it here.
Online ASP.NET MVC Conference: Eric Hexter shares details about the free ASP.NET MVC virtual online conference being held on July 22nd. It is free to attend, and doesn’t require you to travel!
Rules for ASP.NET MVC Views: Chris has a good blog post that discusses some recommendations on how to create and use View templates within an ASP.NET MVC application.
ASP.NET MVC 2 Localization Guide: Adam has a great blog post that describes how to build localizable applications using ASP.NET MVC.
Anti-Forgery Request Recipes for ASP.NET MVC and AJAX: Dixon has a nice blog post that describes some recipes and best practices for protecting yourself from common security issues when using AJAX with ASP.NET MVC.
jQuery jqGrid Plugin: Elijah has a nice video and article that describes how to enable Add, Edit and Delete scenarios with the jQuery jqGrid Plugin and ASP.NET MVC.
Error Handling in MVC with ELMAH: Michael has a nice blog post that describes how to setup and configure the popular ELMAH library with ASP.NET MVC. ELMAH is a great OSS library that enables you to easily capture and review errors on production sites.
Stepping into ASP.NET MVC Source Code: Gunnar has a nice blog post that describes how to configure Visual Studio 2010 so that you can easily step into the ASP.NET MVC and .NET source code within the debugger.
jQuery Essentials: Nice online slide-show that does a great job of providing an overview of jQuery and how to use it.
jQuery Code Snippets for VS 2010: Check out this cool (free) library of 131 jQuery code snippets that you can use within VS 2010. Pretty sweet!
7 jQuery Articles on MSDN: Elijah has links to 7 nice articles he has written for MSDN that cover jQuery.
Building a Simple Forms Application using the Silverlight Tool for VS 2010 and WCF RIA Services: Mark has a really nice tutorial that walks through how to build a simple data forms application using Silverlight, VS 2010 and WCF RIA Services.
Tips and Tricks for Working with the WPF and Silverlight Designers in VS 2010: Karl has a great blog post that describes some useful tips/tricks you can take advantage of with VS 2010 when using the WPF and Silverlight designer.
How to Enable the Binding Builder in WPF and Silverlight Applications: Another nice post from Karl that discusses how to take maximum advantage of the data sources window in VS 2010.
Blend 4 and Sketchflow Improvements: Nice blog post from Christian that talks about some of the great improvements provided with Blend 4 and Sketchflow.
HTTP Duplex Messaging Improvements in Silverlight 4: Nice blog post that describes some of the improvements provided with Silverlight 4 to enable better “server push” scenarios – where servers can push messages to Silverlight clients without requiring the client to explicitly poll.
Snippet Designer: A cool extension for Visual Studio 2010 that enables you to quickly create and author reusable code snippets.
StyleCop 4.4 Release Candidate: The new release of StyleCop 4.4 is now at the release candidate stage. StyleCop analyzes C# source code to enforce style and consistency guidelines. This new version supports C# 4.0 and VS 2010.
Comparing SQL Data: Nice blog post by Zubair that demonstrates some of the data features in Visual Studio 2010 Ultimate for comparing SQL Data and Schema.
Hope this helps,
Scott
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 WebMatrixWebMatrix 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:
Create a Web Site using an Existing Open Source Application in the Web GalleryLet’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:
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:
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:
When I click the “I Accept” button, WebMatrix will download everything we need and install it on our machine:
When we click the “OK” button, WebMatrix will open up our new BlogEngine.NET project and display a site overview page for us:
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:
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:
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:
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:
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 HosterWebMatrix 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:
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:
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:
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:
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:
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:
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):
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 CodeI’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:
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”:
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:
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:
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 PageLet’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:
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:
Working with DataPretty 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:
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.
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:
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:
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:
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:
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:
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:
And we can optionally pass a “year” querystring parameter to show only those movies after that date:
Other Useful Web HelpersI 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:
This will then display a live twitter feed of tweets that mention “scottgu”:
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 DeploymentOnce 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.
Open in Visual StudioProjects 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:
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 MoreClick 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.
SummaryIIS 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
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
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 GoalsWe 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 FlexibilityOne 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:
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 RazorRazor 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 this let’s create a simple “hello world” sample that outputs a message like so:
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:
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:
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 SampleLet’s look at another simple scenario where we want to list some products (and the price of each product beside it):
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:
Building it with Razor Syntax
Below is how to generate the equivalent output using Razor:
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 StatementsBelow 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:
Multi-line Statements
You can denote multiple lines of code by wrapping it within a @{ code } block like so:
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:
Integrating Content and CodeThe 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:
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:
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:
This will render the below content to the client – note that it includes the <span> tag:
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:
The above code will render the below content to the client – note that it does not include any wrapping tag:
HTML Encoding
By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.
Layout/MasterPage Scenarios – The BasicsIt 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:
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:
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:
Compact, Clean, Expressive CodeOne 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 OverridesLayout 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).
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.
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:
Encapsulation and Re-Use with HTML HelpersWe’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):
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.
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):
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:
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 SupportAs 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:
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.
SummaryWe 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
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 4SQL 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.
Shared 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.
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.
SummarySQL 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
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