Monday, February 27, 2012

Create Entity Framework Data Context for LINQPad 4

In what I hope to be my last prerequisite post for Entity Framework on LINQPad, I will create a Data Context for my Entity Model Assembly.

I like to use LINQPad as a snippet editor because of its cool Dump() extension method. This platform makes it easy to play What If with a new technology.

For the purpose of these steps, I’m going to pretend you are using the assembly we created in [last post]. So here are the steps:

  1. Open LINQPad 4
  2. Click on Add Connection
  3. In the Choose Data Context window, choose Entity Framework.
    Choose Data Context
  4. In the LINQPad Connection window, Browse for your EF Model Assembly
  5. In the Choose Custom Type:
    • In Custom Type Name you should see PubsModel.pubsEntities
    • In Entity Data Model, choose From Same Assembly, PubsModel should be in the list below
    • Click OK
    Choose Custom Type
  6. Accept the remaining defaults by clicking OK.LINQPad Connection

Sunday, February 26, 2012

Building an EF 4 Model Assembly for Pubs DB

For this EF building block, I am going to build a Model Assembly. This assembly will contain the Model for the famous Pubs database. You can download Pubs along with Northwind from Microsoft.

I like the idea of separating my model for the rest of my app. I will use this model to LINQPad (and perhaps WinForms, WPF, etc.). I can link it directly to my UI or through a labyrinth of assemblies that I put between my UI (if I even have one).

Since you don’t have to write any actual code, the steps below should work for both C# and VB. They were tested on both Express Editions.

So here we go:

  1. Create a new Project, call it PubsModel
    I like to use the pattern [SomeName]Model, where SomeName may be the name of the application or database.
  2. Delete Class1.cs or Class1.vb
    Microsoft want to be helpful, I’ve probably destroyed a thousand Class1s
  3. Project => Add New Item. (Alt+Shift+A)
  4. Select ADO.NET Entity Data Model
  5. Name it PubsModel.edmx
  6. In the Entity Data Model Wizard, select Generate from database
  7. In the next window, select pubs.mdf. If pubs.mdf is not on the list, you will need to click New Connection to add it to the list.
    Since this is Visual Studio Express, I am only allowed to make a Microsoft SQL Server Database File connection.
  8. Set the value for Save entity connection settings in App.Config as: to pubsEntities.
  9. Visual Studio asks you if you want to make a local copy of the database file.
    I usually answer “No” so I can play with the data with Microsoft SQL Server Management Studio. Of course any change I make to the data will affect the “Master” database.
  10. Select Tables, Views and Stored Procedures.
  11. Keep the defaults for Plurlaize or singularize generated object names and Include foreign key columns in the model.
  12. Set Model Namespace to pubsModel
  13. Click Finish.

After some churning and reformatting, you will get a model that looks like this

.pubs_model

Saturday, February 25, 2012

Starting LINQPad 4 from Visual Studio Express

As I am writing this year’s Code Camp presentation about Entity Framework, I’ve come across a problem: I want to use Visual Studio Express 2010 AND I want to demonstrate Linq to Entities using LINQPad 4. If I were using a commercial version of Visual Studio, I could use Start Action = Start external program. I can’t just launch LINQPad and edit my project because LINQPad would lock my assembly and Visual Studio would refuse to build a new one.

So, to work around this limitation, I added a console project that would launch LINQPad and wait for it to return.

C#:

using System.Diagnostics; namespace LaunchLinqPad { class Program { private const string LINQPAD_EXE = @"C:\Program Files (x86)\LINQPad4\LINQPad.exe"; static void Main(string[] args) { var process = new Process(); process.StartInfo = new ProcessStartInfo(LINQPAD_EXE);> process.Start(); // Without this, the program will exit immediately process.WaitForExit(); } } }

VB:
Module Module1
    Const LINQPAD_EXE = "C:\Program Files (x86)\LINQPad4\LINQPad.exe"
    Sub Main()
        Dim process As New Process()
        process.StartInfo = New ProcessStartInfo(LINQPAD_EXE)
        process.Start()
        ' Without this, the program will exit immediately
        process.WaitForExit()
    End Sub
End Module

A couple of issues:

  • This doesn’t work with LINQPad 4 (and newer)
  • I can’t step into my code.

Even with these limitations, I find this helpful because doing this endures that LINQPad is closed before I recompile, therefore preventing me from locking up the file that I am building.

Thursday, February 02, 2012

Happy Groundhog Day!

Punxsutawney Phil, some rodent 2,000 miles from me sees his shadow so we get 6 more weeks of winter. Had he not seen it, winter would only 42 days left. I will have my traditional Groundhog Day dinner of pork sausage.

Wednesday, January 11, 2012

Less Than Simple Group By LINQ Queries

Lately I have been going through LINQ. Most of it has been review, however I ran across something that I really didn’t understand. That area: Grouping.

Suppose I wanted to write a LINQ query which would do the following:

SELECT a.city, COUNT(*) AS Count
FROM authors a
GROUP BY a.city
I can easily render this into LINQ as follows (LINQPad C# Expression):
from a in Authors 
group a by a.City into c
select new
{
City = c.Key,
Count = c.Count()
}

When things got just a little bit more complicated, I got lost. Suppose that I wanted to render this query:

SELECT a.au_lname, a.au_fname, a.phone, COUNT(*) AS Count
FROM authors AS a
GROUP BY a.au_lname, a.au_fname, a.phone

I figured out that the Key didn’t need to be a simple type. The type of the Key is determined by the type between by and into in the group clause. So here I create an anonymous type for the key and refer to the properties of Key in the select clause. So I can render it as follows (LINQPad C# Expression):

from a in Authors 
group a by new
{
a.Au_lname,
a.Au_fname,
a.Phone
}
into c
select new
{
Au_lname = c.Key.Au_lname,
Au_fname = c.Key.Au_fname,
Phone = c.Key.Phone,
Count = c.Count()
}

GroupBy() (the extension method that group .. by is translated into) returns an IQueryable of IGrouping(s), a IGrouping is an IEnumerable with a generic Key property tacked on. Since Key is generic, I can pass in a complex type.

NOTE: I haven’t been able to get it to work with a non-anonymous type In LINQ to SQL.

I didn’t use LINQ grouping in my production code. I don’t know if it is because I didn’t understand it or just didn’t need it. If I really needed it I would think I would have pushed harder and learned it earlier…

Saturday, December 31, 2011

Example of Repetitive Comments

Looking through some old code for a project I’m working on I saw a block of code similar to this:

/// <summary>
///
This is MY method
/// </summary>
/// <param name="intValue">
Some Number</param>
/// <param name="stringValue">
Some String</param>
/// <returns>
An empty string</returns>
public string MyMethod( // Returns An empty string
int intValue, // Some Number
string stringValue) // Some String
{
return string.Empty;
}
This code annoys me. Yet I see the problem: the XML comments are just a little too far away from the actual data. I think it would be cool to have tool tips for the parameters described in XML comments. It would have also helped name the parameters better.

Friday, December 16, 2011

Two devices to read a tech book

Last week I bought some technical books from the internet; they were stolen from my front door and I needed them immediately, so I ordered the e-book version. I like e-readers for pure text that is meant to be read in order (novels, histories, etc.), but technical books have diagrams, tables and code samples (“figures”) that may be referenced several pages later. So I decided to try using two devices …

two_dev_code

I use the reader for the text and the tablet for the figures. I don’t like to read lots of text on a tablet because it is backlit. I really like reading plain text on a reader; I bought mine this spring and read the Lord of the Rings (+ the Hobbit) on it. I like reading on it better than reading books.

Since the reader doesn’t support zoom, I like to use the tablet to zoom the figures; actually, the image support on the reader is so bad that it would be difficult to read my current book without viewing images on the tablet.

This is not a supported way to read an e-book and will probably never be. Even with the hassle of juggling two devices it is better than the supported way. It would be nice if I could move between figures without shuffling through the text. Some UX designer better than me needs to do something to improve the tech book reading experience.