A View Inside My Head

Jason's Random Thoughts of Interest


Entity Framework Spatial: First Look

Today, I began to look into the Entity Framework June 2011 CTP which includes first class support for Spatial data types.  The ADO.NET team created an abstraction layer, based on the OGC simple features specification, with a goal being to support spatial implementations from multiple vendors.  As you would expect, SQL Server 2008 Spatial is supported out of the box.

For some reason, I was expecting a lot of work to be done on the client-side within their abstraction data type.  I was pleasantly surprised to see EF pass the heavy lifting to the underlying data store as part of the query.

For instance, I have a table in my database called Facility with a Geography column named [Geocode].  This field contains a point (single latitude/longitude pair) identifying the location of the Facility.  Even though this would normally be represented in client-side code as a SqlGeography type, EF wraps it in the new DbGeography type (i.e., the abstraction data type for ellipsoidal data).

My first query was a LINQ expression to return a list of all facilities that are within 500 miles of a given location:

var q = from f in context.Facilities
let p = DbGeography.Parse("POINT(-83 45)")
where f.Geocode.Distance(p) < 500 * 1609.344
select new { f.FacilityID, wkt=f.Geocode.AsText() };

A couple things about this query:

  1. The default SRID of 4326 is used.  This spatial reference system uses meters for distance, so my predicate needs to convert the 500 miles into meters.  Like the SqlGeography.Parse() method, DbGeography.Parse() will default to 4326.
  2. The return type is an anonymous type.  I wanted to see how the DbGeography type's .AsText() method was executed (i.e., would it be expressed in the resulting query, or would it be handled client side, etc).

When executed, the LINQ expression above generates the following TSQL:

SELECT [Extent1].[FacilityID] AS [FacilityID],
 [Extent1].[Geocode].STAsText() AS [C1]
FROM [dbo].[Facility] AS [Extent1]
WHERE ([Extent1].[Geocode].STDistance(geography::Parse(N'POINT(-83 45)'))) < cast(804672 as float(53))

As you can see, the DbGeography.AsText() was translated into the STAsText() method in the query.  And, as you might expect, the predicate's DbGeography.Distance() was properly translated into STDistance() in the TSQL WHERE clause.

The other thing that I was worried about was not having access to the actual SqlGeography type returned from the database.  I was surprised to see that EF's DbGeography has a property called ProviderValue that returns the native type that the provider supports!

CodeRush: Anonymous Method Refactoring Fun

I recently had to work with some code that I wrote a few years ago, and stumbled upon this:

Code showing an anonymous method being used as an Action delegate in Array.ForEach
(Not that it's relevant to the rest of this blog post, but this code was responsible for deleting a Role in a custom membership provider, but due to foreign key relationships without cascading deletes, all of the User/Role assignments had to be deleted first)

Now, in all fairness to myself, there's really nothing wrong with this code.  Array.ForEach<T> requires an Action<T> delegate, and this anonymous method certainly qualifies as one.

However, since the time that I wrote this particular piece of code, I started using Lambda expressions more often.  To be consistent with the rest of the project's code, I should change this anonymous method into a Lambda expression.

Fortunately, CodeRush makes this a breeze!  Simply put your cursor within with anonymous method itself, and then hit your Refactor Key and choose the "Compress to Lambda Expression" refactoring:

Compress to Lambda Expression refactoring
As simple as that, the wordy "delegate" syntax of the anonymous method is compressed into the terse "=>" syntax of a Lambda expression:

Array.ForEach with a Lambda Expression as the Action<T> delegate
But, suppose that you are just learning Lambda expressions, and come across one in code that you don't fully understand.  CodeRush allows you to go the other way, too, and expand a Lambda expression into an anonymous method, which may be easier to understand.  Similar to above, put your cursor on the Lambda expression, hit the Refactor Key, and then choose "Expand Lambda Expression":

Expand Lambda Expression refactoring
Anonymous methods were introduced as a way to inline functionality that otherwise had to exist in its own named method.  This is really only good if that functionality is used one time.  But, what if you discover that the functionality is needed in multiple places?

CodeRush provides a refactoring for anonymous methods called "Name Anonymous Method" that will extract the logic into a named method that can then be called from other code:

Name Anonymous Method refactoring
Activating this refactoring will first display the Target Picker (red arrow and line) so that you can select where to add the new method.  Then, the new method's name can be set by editing the text in the green box that will appear.

Finally, suppose that the opposite is true: you have a named method that is only used in one place, and would prefer to just inline that code.  Or, perhaps you would like to create a one-off modification to an existing method, and don't need the new functionality to be in its own named method.

CodeRush has a refactoring called "Inline Delegate" that replaces a delegate referring to a named method with an anonymous method.  If there is only a single reference to that named method, then this refactoring will also delete the named method altogether.

Inline Delegate refactoring

Since I was already familiar with the anonymous method syntax, CodeRush played an instrumental part in my learning Lambda expressions because I could write an anonymous method and then have it transformed into an equivalent Lambda for me.  But, once I knew Lambdas, I found that I wanted to update my older code in order to replace anonymous methods with the newer syntax, and CodeRush made it a trivial task to do this.

Happy Coding!

CodeRush: Markers

Have you ever become distracted while scrolling through code, or switched to another tab and then forgot what you were working on?  abortion pill online It happens all the time when we try to multitask while coding.  If only there was a call stack for our brains abortion pill online that we could just unwind to find our way back to where we started....

Turns out, there is!

CodeRush includes a feature called "Markers".  These are little placeholders, or breadcrumbs, for your cursor location that can be created just before your focus changes to another part of code.  When you're done with whatever task distracted you, simply hit ESC (or ALT+End) to collect the most recent marker and your cursor will be returned to exactly where it was when the marker was created.

Sometimes, CodeRush will automatically create markers for you during refactoring and template expansions.  These appear as small blue triangles within the newly created code:

Refactored code showing a marker
When you collect a marker, your cursor will be returned to that location, and an animated Locator Beacon will display on top of the cursor to draw your attention to that spot:

Animated bullseye showing the marker collection

But, you can manually drop your own markers, too, by using ALT+Home.  The manually created markers will be red in color:

Red triangle signifies a manually-created marker

Some tricks that you can do with markers:

SHIFT+ALT+Home: Drops a marker at the current cursor location and collects the most recent marker (so you can swap between the locations) Thanks Jay Wren for the clarification.
SHIFT+ALT+PgUp: Select text between the current cursor location and the most recently created marker
SHIFT+ESC: Collect the most recent marker and also paste whatever is in the clipboard at that location

Happy Coding!

CodeRush: CodeRush Tool Window

CodeRush is full of templates.  Thousands of them, when you combine the basic templates with the various types that are supported by each.  How does someone start to learn all of the required mnemonics in order to use CodeRush effectively?

The answer to that is a brilliant feature known as the CodeRush Tool Window:

DevExpress, Tool Windows, CodeRush

(DevExpress menu in Visual Studio, Tool Windows -> CodeRush)

The CodeRush Tool Window provides a context-sensitive list of "next characters" in CodeRush templates that are valid at the cursor's current location.  As you start to work with CodeRush, leave this window open (perhaps on a second monitor) so that you can train yourself.

CodeRush Tool Window docked on the left

In the screenshot above, I have the CodeRush Tool Window docked on the left side of my IDE.  Depending on where my cursor is located, the contents of the window will change.

For example, I can create a new Auto-Implemented Property at the cursor's current location (line 49 in the screenshot).  In the CodeRush Tool Window, I see that mnemonics for Auto-Implemented Properties start with "a", so I can type that character.  But, after typing "a", the contents of the CodeRush window will change:

CodeRush Tool Window after starting a mnemonic

The letter "a" by itself is a valid mnemonic for a CodeRush Template, as indicated by the the green "expansion" frame at the top of the CodeRush Tool Window.  If I were to hit the spacebar here, I'd get code for a new abstract class (a preview of this code appears in the expansion frame).  This is not what I want, so I can look in the list to see if typing more characters results in an appropriate mnemonic.  Note: If you do accidentally expand a wrong template, just perform an Undo (Ctrl-Z) to return to the pre-expansion state of your code.

Suppose that I was trying to create an Auto-Implemented Property of type Boolean.  From the contents of the window, I see that "ab" is listed as "bool", and so I only need to type the second character ("b") and then hit the space bar.

Play around by moving your cursor to various places in your code, and observing how the contents of the CodeRush Tool Window changes.  Try out some of the template mnemonics that are listed to see how they work.  Remember that Undo (Ctrl-Z) will get you back to where you started.

Happy Coding!

CodeRush: Property Templates

There is A LOT of repetition in coding.  To accomplish certain things, you often need to include boilerplate code that is repeated throughout your program. 

Take Properties, for instance.  Defining Properties on a class, especially a lot of them, can be a very tedious task. 

Traditionally, you have to create a member variable of the class to serve as the Property's backing store, and then create the Property itself (with a getter and setter to interact with that member variable).  Lather, rinse, repeat... ad nauseum.

Traditional Property syntax written in C#

This type of work is where CodeRush excels by providing you with mnemonic-driven code templates.  In other words, you type a few characters (the mnemonic), hit the space bar, and it will expand into a much larger snippet of code for you (saving you scores of keystrokes in the process).

The most basic template to help with writing Properties is: p

Move your cursor to somewhere within your class { } block, where defining a Property is legal syntax, and then type 'p' followed by a space.  This will expand into the following:

CodeRush p template expanded
The cursor will be placed in the first orange box, where you can change the data type from "object" to whatever type your Property needs (i.e., "string").  Notice that the Property's type is linked to the backing store's type, so changing one of them will change the other.

The trick with the orange boxes in CodeRush is that you press Enter when you finish editing their contents.  This will remove the orange coloring from that element, and move the focus to the next orange box within the template.  Keep repeating this until there are no more orange boxes left to edit.

Since we knew this was a string Property, we could have saved even more keystrokes by using a mnemonic that included the type: ps

CodeRush ps template expanded

The only real difference between "p" and "ps" is that the type will already be set to "string" for you in the latter.  There are other mnemonic templates that expand into Property definitions for other types, like "pi" for "int" and "pd8" for "DateTime".  (I'll blog about an awesome discovery feature to help you learn these in my next blog post).

But, wait!  There's more!

If you already have a member variable defined (maybe you used the "vs" mnemonic, which expands into a private string variable), and wish to create a Property in your class that uses this variable as a backing store...  well, CodeRush has a trick to help you accomplish that!

private string _MyCoolString;
Simply copy that line of source code into the copy buffer as you normally would (i.e., select the line, and then hit Ctrl-C).  Now, paste it where you would like the Property to be created (i.e., maybe on the line directly below).  Since it's illegal to define this variable twice, CodeRush does something awesome called a Intelligent Paste.  In this case, based on the contents of the copy buffer, it expands a Property template that uses your variable as the backing store!

SmartPaste with property expanded

Similarly, you can also use the "Encapsulate Field" refactoring instead of the Intelligent Paste.  Move your cursor to the line declaring the variable to use as a backing store, and then hit your Refactor Key.  Use the Down Arrow key to move through the list of available refactorings, and press Enter when "Encapsulate Field" is highlighted.

Encapculate Field refactoring
Next, CodeRush will prompt you where you would like to insert the code.  Use the Up and Down arrows to move through valid places where the new code can be inserted.  Press Enter to select the location designated by the Target Picker (red arrow).

Insertion Point
The result will be a new property with a getter and setter that uses your variable as a backing store.

New property inserted

And, finally, as C# evolved, Microsoft recognized that a lot of Properties that were being created were very simple in nature, requiring no logic in the getters and setters other than reading and writing to their backing store.  A new Property syntax was added that did not require a backing store to be explicitly defined (or rather, the compiler actually creates one for you behind the scenes).  This new syntax is referred to as an Auto-Implemented Property.

Similar to the "ps" template, you can use "as" to create an Auto-Implemented Property of type "string". 

CodeRush "as" template expanded
Note: "a" by itself will not expand into an Auto-Implemented Property of type "object" similar to what "p" by itself does.

What? You didn't know about Auto-Implemented Properties, or you want to convert all of your old-style Properties to the new Auto-Implemented Properties?  There happens to be a refactoring for that in CodeRush!

Move your cursor to the Property definition that you would like to convert, and then hit your Refactor Key.  Use the Down Arrow to select "Convert to Auto-implemented Property", and observe the changes that CodeRush will be making to your code (the changes will be painted on top of the code that will be changed).  Press the Enter key, and voila!  No more backing store!

Convert to Auto-implemented Property

(credit goes to Dennis Burton for telling me about this refactoring... which goes to prove that there are way more features in this tool than you'll likely ever master)

Thanks to the magic of CodeRush, you now have many different ways to quickly create properties in your code, saving hundreds (if not thousands) of keystrokes in the process. 

Happy Coding!