Archive for the '.NET' Category

August 29th Links: .NET, ASP.NET, IIS Express, Silverlight, Windows Phone 7

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/EF

  • 5 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.

ASP.NET

  • 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.

ASP.NET MVC

  • 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.

  • 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.

IIS Developer Express

  • 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.

Silverlight and Windows Phone 7

  • 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.

  • 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.

Book Recommendation

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:

ir[1]nutshell

Hope this helps,

Scott

Patch for VS 2010 Find and Replace Dialog Growing

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.

Search and Navigation Tips/Tricks with Visual Studio

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 Search

Most 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:

image

We can then press “Ctrl + i” again to find the next usage of the same term (and continue this repeatedly):

image

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 Term

One 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:

image

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 Selection

Another 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:

image

Pressing “Ctrl + F3” will search for the next instance of the text you have highlighted – allowing you to avoid having to type it:

image

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 Solution

Sometimes 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:

image

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:

image

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 Usages

Most 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”:

image

This will then bring up a “Find Symbol Results” window that list all usages of this type within the current solution:

image

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/Forward

Have 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:

image

Press F12 to navigate to the definition of it.  This opens up a new editor window with the source of the selected type:

image

Now to jump back to where we came from, press “Ctrl + (minus key)” and VS will take us back to where we were:

image

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 File

Ever 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:

image

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:

image

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 Features

Visual 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.

image

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 Improvements

There 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.

Summary

Most 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

Debugging Tips with Visual Studio 2010

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 Breakpoints

Another 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:

image

Then right-click on the breakpoint “red circle” on the left of the editor and select the “Condition…” context menu:

image

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:

image

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.

image

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:

image

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 BreakPoint

A 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:

image

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:

image

This will bring up the following dialog – which allows you to specify what should happen when the breakpoint is hit:

image

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:

image

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 Macro

In 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:

image

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:

image

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:

image

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:

image

Summary

The 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.

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

“Unplugged” online chat with me this Wednesday

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

Some nice code editor features provided by the VS 2010 Power Tool Extensions

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:

image

Clicking the hyperlink will immediately navigate you to the definition of the type/member within your code:

image

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:

image

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:

image

Triple Click Selection

Another 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:

image

When the “Triple Click” extension is enabled you can now also triple-click on a line to automatically select the entire line:

image

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 Movement

Another “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:

image

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):

image

This is another one of those features that Word has had for awhile – and which is nice to now have in VS.

Column Guides

Column 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):

image

Then right-click and choose the “Guidelines->Add Guideline” menu command:

image

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:

image

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 Update

In 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:

  • Poor performance with Solution Navigator searches on large projects. In this revision, we’ve made some optimizations to the search algorithm. Search will also now only be initiated after two characters are typed in the search box.
  • Items in Solution Folders were not sorted.  In this revision, they are sorted alphabetically.
  • Invoking Quick Access could cause a crash on some machine configurations. This issue has been resolved in the current revision.
  • Ctrl+1 & Ctrl+2 were not configurable in the Solution Navigator, which blocked the ability to type @ on some keyboards. This revision provides the Edit.ShowSolutionNavigatorPopupForSelection & Edit.ShowSolutionNavigatorPopupForFile commands which can be rebound using Tools => Options => Environment => Keyboard.

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. 

Summary

If 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

Using EF “Code First” with an Existing Database

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:

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

In 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 Database

EF “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 Project

Let’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:

image

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 Assembly

Our 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:

image

Step 3: Northwind Database

You 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:

image

Step 4: Create our Model Layer

Now 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:

image

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 int? and Decimal? means – that indicates they are nullable types).  Nullable columns within a database table should be represented within the model class as Nullable properties if they are value types:

image

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:

image

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 String

We’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 Classes

Let’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:

image

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: 

image 

And now when we run the project and navigate to the Products.aspx page we’ll get a listing of our Products like so:

image

We now have a simple application that uses EF “code first” against an existing database. 

Download Sample

You can download a completed version of the above sample here.  It assumes you have EF “code first” CTP4 and SQL Express installed.

Additional Code Examples

Below 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):

image

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:

image

Inserting a New Category

The code below demonstrates how to add a new Category to the Database:

image

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:

image

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.

image

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 Rules

When 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.

Summary

I’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

London “Guathon” Event with Me on August 13th

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.

Content

The 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.

Registration

The 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

VS 2010 Web Deployment

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

Today’s blog post is the first of several posts I’ll be doing that cover some of the improvements we’ve made around web deployment.  I’ll provide a high-level overview of some of the key improvements.  Subsequent posts will then go into more details about each feature and how best to take advantage of them.

Making Web Deployment Easier

Deploying your web application to a server is something that all (successful) projects need to do.  Without good tools to help you, deployment can be a cumbersome task – especially if you need to do it manually.

VS 2010 includes a bunch of improvements that make it much easier to deploy your ASP.NET web applications – and which enable you to build automated deployment procedures that make deployment easily reproducible.  The deployment features support not just deploying your web content – but also support customizing your web.config file settings, deploying/updating your databases, and managing your other dependencies.  You can kick-off deployments manually – or via automated scripts or as part of an automated build or continuous integration process.

Below is a high-level overview of some of the key new web deployment features in VS 2010.  I’ll do subsequent posts that provide more details on how to use/customize each of them.

New “Publish Web” Dialog

Visual Studio 2010 includes a new “Publish Web” dialog that you can use to quickly deploy a web application to a remote server.

You can activate the dialog by right-clicking on an ASP.NET Web Project node within the solution explorer, and then select the “Publish” context menu item:

image

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.

image

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:

image

Just select your publish profile from the toolbar drop-down and then click the publish icon to the right of it to begin deploying your application. 

Web.Config Transformations

In most real-world deployment scenarios, the web.config file you use for development is different than the one you use for production deployment.  Typically you want to change environment settings like database connection-strings, making sure debug is turned off, and enabling custom errors so that end-users (and hackers) don’t see the internals of your application.

VS 2010 now makes it easy to customize/tweak/modify your web.config files as part of your publish/deployment process.  Specifically, you can now easily have build-configuration specific transformation files that can customize your web.config file prior to the application being deployed:

image

You can maintain a separate transform file per Visual Studio build-environment.  For example, you could configure your project/solution to have a “Debug”, “Staging” and “Release” build configuration – in which case VS will maintain three separate transform files for you.  VS will automatically apply the appropriate one at deployment time depending on what your VS environment is set to.

I will dive deeper into how to perform web.config file transformations in a future blog post.

Database Deployment

VS 2010 allows you to optionally deploy a database, along with your web application files, when are using the “Web Deploy” option as your deployment mechanism. Databases deployed this way can include both schema and data, and can optionally also include change scripts to update existing databases.

ASP.NET Web Projects in VS 2010 have a special page within their the “project properties” settings to configure database deployments:

image

I will dive deeper into how to perform database deployments in future blog posts.

Web Deployment Packages

VS 2010 also supports a packaging option that enables you to package up your ASP.NET Web Application (together with its dependencies like web.config, databases, ACLs, etc) into a .zip based deployment package file that you can optionally hand-off to an IT administrator who can then easily install it either via the IIS Admin Tool or via a command-line/powershell script. 

The deployment package you create can optionally expose application configuration settings that can be overridden (like directory locations, database connection-strings, etc).  When using the IIS7 Admin Tool, the install wizard can prompt the administrator for each setting to be customized – enabling you to provide a clean customization experience without having to write any custom code to-do so.  The settings can also obviously be passed as arguments on the command-line when using a command-line or Powershell script to deploy the application.

To create a web package within Visual Studio 2010, just right click on your ASP.NET Web Project node in the solution explorer and select the “Build Deployment Package” menu item:

image

This will compile your application, perform appropriate web.config transforms on it, optionally create .sql scripts for your database schema and data files, and then package them all up into a .zip deployment package file.  Adjacent to the .zip file you’ll file a deployment script file that you can use to automate deployment of the package to a remote server.

I will dive deeper into how to create web deployment packages in future blog posts.

Continuous Integration with Team Build

Most of the VS 2010 web deployment features that I described above are built on top of MSBuild tasks & targets. The “Team Build” feature of TFS also uses MSBuild, and supports running nightly builds, rolling builds, and enabling continuous integration. This means that you can create deployment packages, or automatically publish your web applications from a Team Build environment.

I will dive deeper into how to enable this in future blog posts.

Summary

Today’s blog post covered some of the new VS 2010 web deployment features at a high-level.  All of the above features Iwork with both VS 2010 as well as the free Visual Web Developer 2010 Express Edition.

Hopefully today’s post provided a broad outline of all the new deployment capabilities, and helped set context as to how they are useful. In future posts I’ll go deeper and walkthrough the specifics of how to really take full advantage of them.

Hope this helps,

Scott

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

Visual Studio 2010 Keyboard Shortcuts

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.

image

This week’s updated posters incorporate a number of improvements:

  • Letter-sized (8.5”x11”) print ready versions are now available
  • A4-sized (210×297mm) print ready versions are now available
  • The goofy people pictures on them are gone (thank goodness)

The posters are in PDF format – enabling you to easily download and print them using whichever paper size is in your printer.

Download the Posters

You 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