Subscribe: Programming
Preview: Programming



Copyright: Lance Robinson

ADO.NET Entity Framework – Code First Development Pattern

Thu, 14 Apr 2011 07:42:00 GMT

Originally posted on:’s a quick start introduction to the ADO.NET Entity Framework Code First Development Pattern.  For a more complete (but still intro) walkthrough, check out ScottGu’s blog. At the time of this writing, you’ll need the EF 4.1 Release Candidate.  After EF 4.1 is released you’ll no doubt be able to find it on the ADO.NET team blog. 1.  Create a new empty ASP.NET MVC2 Web Application, add a reference to System.Data.Entity.  If using the EF4.1 RC - add a reference to the EntityFramework dll that comes installed with it. 2.  Add the model classes you’d like to represent your data objects.  For example if you need to represent game nights, you might create a class called Game with properties that describe the game night date, location, and other information. 3.  Create a “Context Class” that inherits DbContext, which contains nothing but DbSet public properties.  For example if you created in step 2 a class called “Game”, here you’d have a property defined as: public DbSet Games { get; set; } At this point, EF code first will make certain assumptions (which we can override later if necessary) that allow us to write less code: - The context class will map its properties (those DbSet properties) to tables with the same names (a Games table, in our example). - Each row in that table will map to an instance of the model class (a Game instance, in our example).  - Properties in the model class are columns in the table. - A property in the model class with the name “Id” or “Id” will be made the primary key. - Relationships between tables are inferred if one model class has a property with the name “Id”. 4.  Add a controller to see EF Code First in action.  For example, add Index (to just return a list of our game nights) and Create actions (to create a new game night). 5.  Add the views (Index: strongly typed IEnumerable of Game, Create: strongly typed Game – content Create). 6.  Create the database.  One of those EF Code First assumptions is that it will automatically look for a connection string with the same name as the context class (eg, Games).  Scott Guthrie recommends the use of SQL CE 4 for early development, and moving to SQL Server or SQL Express closer to the time of deployment. Important:  IF you’re using SQL CE or SQL Express, and your connection string points to a database file that does not yet exist, it will be automatically created for you! Updating The Model If you update the model (lets say we add a new property to our Game class), you’ll get an error the next time you attempt to run the application (“context has changed since the database was created”.  EF Code First can handle this too:  in Global.asax, add the following to the Application_Start event handler: Database.SetInitializer<>(new RecreateDatabaseIfModelChanges<>()); RegisterRoutes(RouteTable.Routes); Gu gives a nice tip – create a custom class that implements RecreateDatabaseIfMOdelChanges< and overrides the Seed function to add “seed” rows to the database with default data.  This way when we recreate the database after a model update, the database isn’t empty – but is seeded with our default data.  Use this new custom class in the call to SetInitializer instead of RecreateDatabaseIfModelChanges. Technorati Tags: ASPNET,MVC,Entity Framework,EF,Code First [...]

Visual Studio 2010 Find and Replace With Regular Expressions

Thu, 10 Mar 2011 22:07:24 GMT

Originally posted on:

Here is a quick notes about using regular expressions in the VS2010 Find Replace dialog. 

1.  To create a backreference, use curly braces (“{“ and “}” ) instead of regular parentheses.

2.  To use the captured backreference, use \1\2 etc, where \1 is the first captured value, \2 is the second captured value, etc.


I want to find*:

info.setFieldValue(param1, param2);

and replace it with:

SetFieldValue(info, param1, param2);

To do this, I can use the following find/replace values:

Find what:

{[a-zA-Z0-9]+}.setFieldValue\({[a-zA-Z0-9., ]+}\);

Replace with:

SetFieldValue(\1, \2);

Use Regular Expressions is checked, of course.

*If you’re wondering why I’d want to do this – because I don’t have control over the setFieldValue function – its in a third party library that doesn’t behave in a very friendly manner.


Creating Team Foundation Work Items With PowerShell

Wed, 26 Jan 2011 15:58:22 GMT

Originally posted on:

Here is the simple function I added to my powershell profile:




function create-tfstask ($desc) {
 tfpt workitem /new $workItemType /collection:$serverUrl /fields:"Title=$($desc);Assigned To=$assignee;AreaId=$areaId;IterationId=$iterationId"



To find the AreaId and IterationId for your project/versions, just look at a bug you know is setup correctly:

PS C:\> tfpt query /collection:http://3bs001vsteam:8080/tfs /wiql:"select AreaId,IterationId from workitems where ID = 879"

Next I hooked this into my existing "todo" function by adding a new case in its $target switch statement for “tfs”, which calls my create-tfstask function and returns.  Updated todo function:

function todo {
  param([string] $target = "work",
        [string] $msg )
  $emailFrom = ""
  #combine all the cmd line args into one "message"
  if ($args -ne "") {
    $msg = $msg + " " + $args
  #what is the target of the message?
  switch ($target)
    "work" { $target = "" }
    "home" { $target = "" }
    "tfs" { create-tfstask $msg; return }
  $subject = "Todo: " + $msg
  $body = $msg
  $smtpServer = "3bs001exch"	
  $smtp = new-object Net.Mail.SmtpClient($smtpServer, 25)
  $smtp.Send($emailFrom, $target, $subject, $body)
Technorati Tags: ,,

How do I rollback a TFS check-in?

Tue, 21 Dec 2010 16:24:04 GMT

Originally posted on:

I can never remember how to rollback a check-in, and there all kinds of mess in search results about this (change between different versions of TFS etc), so I thought I’d just put this here so I won’t forget anymore.  :)  Thanks to @manningj, TFS genius.

Just drop to the command line and use tf.exe.


tf rollback /changeset:12345

For more on the tf.exe commands:

tf help



PowerShell – Recycle All IIS App Pools

Thu, 16 Dec 2010 20:59:17 GMT

Originally posted on:

With a little help from Shay Levy’s post on Stack Overflow and the MSDN documentation, I added this handy function to my profile to automatically recycle all IIS app pools.

function Recycle-AppPools {
    [string] $server = "3bhs001",
    [int] $mode = 1, # ManagedPipelineModes: 0 = integrated, 1 = classic

 $iis = [adsi]"IIS://$server/W3SVC/AppPools"
$iis.psbase.children | %{
$pool = [adsi]($_.psbase.path);
   if ($pool.AppPoolState -eq 2 -and $pool.ManagedPipelineMode -eq $mode) {
   # AppPoolStates:  1 = starting, 2 = started, 3 = stopping, 4 = stopped         





Setting a Master Page Dynamically

Tue, 17 Aug 2010 19:04:10 GMT

Originally posted on:

To set an ASPNET master page dynamically, use the Page_PreInit function and set the Page.MasterPageFile property.  For example:

protected void Page_PreInit(object sender, EventArgs e)
  this.Page.MasterPageFile = "~/MasterPages/" + mymaster + ".Master";

In the above example, mymaster should be set by whatever your requirements dictate – read from DB/CMS/whatever.  The page (aspx) itself shouldn’t have any other reference to the master page (ie, no “MasterPageFile attribute in the page directive), however it will still need the content placeholders, of course.

Technorati Tags:

PowerShell TruncateAtWhitespace Function

Mon, 16 Aug 2010 19:30:13 GMT

Originally posted on:’s a TruncateAtWhitespace function that takes an incoming parameter value and an incoming max length, and returns a substring broken at a whitespace position.  This way if you have “Lance has a blog” and you need to truncate it to 8 characters or less, you get “Lance” instead of “Lance ha”. function TruncateAtWhitespace{ param( [string]$value, [int]$maxlength=200 ) $maxlength-=3; #allow for "..." suffix if ($value.Length -le $maxlength) { return ($value + "..."); } $closestwhitespaceindex = [int]$value.Substring(0, $maxlength).LastIndexOf(" "); if ($closestwhitespaceindex -gt 0) { $value = $value.Substring(0, $closestwhitespaceindex) + "..."; } else { $value = $value.Substring(0, $maxlength); } return $value; } Technorati Tags: PowerShell [...]

Amazon SimpleDB Developer Tools

Tue, 03 Feb 2009 14:46:27 GMT

Originally posted on:

According to a recent Amazon survey, “Developer Tools” were the most requested improvement for SimpleDB.  /n software’s Amazon Integrator fits the bill for developers building in .NET, ASP.NET, .NETCF, Java, JSP, C++, C++ Builder, Delphi, VB6 (ActiveX), and even classic ASP.  You can download a free trial version, which includes demos and API documentation for the SimpleDB component as well as the included AWS, EC2, S3, and SQS components.

Technorati Tags: , ,

TwitterMinder and Flickr->Twitter scripts

Thu, 28 Aug 2008 17:58:30 GMT

Originally posted on:

If you’re an RSSBus user who is using my Google Calendar –> Twitter or Flickr –> Twitter services, you might notice a minor change to both.  I changed Twitterminder so that tweets resulting from Google Calendar entries are prepended with “GCal: “.  I did the same thing with the Flickr->Twitter script, it will now prepend “Flickr: “.

Related: How to call these services from your own applications.
Related:  How I converted TwitterMinder into Flickr->Twitter by changing 4 lines of code.


CSharp TruncateAtWhitespace Function

Mon, 16 Aug 2010 19:28:56 GMT

Originally posted on:’s a TruncateAtWhitespace function that takes an incoming parameter value and an incoming max length, and returns a substring broken at a whitespace position.  This way if you have “Lance has a blog” and you need to truncate it to 8 characters or less, you get “Lance” instead of “Lance ha”. /// /// Truncate at the end of a word /// /// The original string /// The maximum length of string to return /// A substring of the original, broken at the end of a word public static string TruncateAtWhitespace(string value, int maxlength) { maxlength = maxlength - 3; //allow for ending "..." if (value.Length <= maxlength) return value + "..."; int closestwhitespaceindex = value.Substring(0, maxlength).LastIndexOf(" "); if (closestwhitespaceindex > 0) { value = value.Substring(0, closestwhitespaceindex) + "..."; } else { value = value.Substring(0, maxlength); } return value; } Technorati Tags: ASPNET,C# [...]