LP on .NET

June 30, 2009

Now that’s a Property Name!

Filed under: .NET,C#,Humor,Visual Studio,WCF — Larry Parker @ 4:07 pm

Wow, I just came across a property in .NET that is over 100 characters long!  Check this out:

private void Application_Startup(object sender, StartupEventArgs e)
{
    var x = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;

In fact, it looks like System.ServiceModel.MessageSecurityVersion has all kinds of lovely property names:

untitled

Good thing for IntelliSense!  🙂

June 21, 2009

Extension Methods

Filed under: .NET,C#,Microsoft,Software Development — Larry Parker @ 9:30 pm

One really nice feature introduced in C# 3.0 (.NET 3.5 / Visual Studio 2008) is something called extension methods.  This was a language feature made to support LINQ, but you can also use it to write your own custom extension methods.

For example, with extension methods you can do something like this:

if (!"joe@smith.com".IsValidEmail())
    return false;

Without extension methods, this would not be possible because even if you could subclass from the String type (which you can’t because it’s sealed) and added the IsValidEmail method, the “joe@smith.com” literal would still be a string.

So extension methods can be very helpful in adding new functionality to existing types, but I also find them useful for changing the syntax of existing methods that just don’t seem to “make sense”.   One such method is the String.IsNullOrEmpty static method.

To use this, you need to do something like this:

if (String.IsNullOrEmpty(firstName))

That’s not very “programmer friendly” because you have to indicate the String class, call a method, and then finally pass in the string as the parameter.

Wouldn’t it make more sense to be able to do something like this?

if (firstName.IsNullOrEmpty())

Not only is it less to type, but it’s more intuitive because you’re calling a method on an instance variable, instead of passing the instance variable into a static method.

The good news is that with extension methods, this is very easy to do:

public static Boolean IsNullOrEmpty(this String value)
{
    return String.IsNullOrEmpty(value);
}

This is as simple as it gets because the implementation of this just calls the original static method.  But you can put anything you wish in your own extension methods – it’s your code.

Hope this helps.

June 19, 2009

Development Environment Install Log

Filed under: .NET,Software Development,technology,Visual Studio — Larry Parker @ 3:58 pm

I’ve been programming for over twenty years, but it wasn’t until the last couple of years that I became disciplined enough to maintain a log of what I install on my development machine.

It’s amazing how useful an audit trail like this can be over the course of several months:

 

06/11/2009

– Installed XP SP2 Support Tools

    Installed from http://www.microsoft.com/downloads/details.aspx?FamilyId=49AE8576-9BB9-4126-9761-BA8011FABF38&displaylang=en

    Installed into C:\Program Files\Support Tools\

05/29/2009

– Installed Sandcastle May 2008 Release (Version 2.4.10520)

    Installed from http://sandcastle.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=13873

    Installed into C:\Program Files\Sandcastle\

Last Fall I got a new development machine at work and it was a simple matter to reinstall exactly what I needed by following the entries in my log.

It’s also useful for troubleshooting problems that seemingly come out of nowhere and inevitably get traced back to the latest CTP you just installed (well, now I use virtual machines for those).  🙂

The extra couple of minutes it takes to record the changes in the log can sometimes be annoying, but I have found that it is well worth the time and effort.

June 17, 2009

LINQ Queries the Easy Way

Filed under: .NET,LINQ,SQL Server — Larry Parker @ 1:14 pm

A colleague recently approached me about a LINQ query he wrote that was a bit challenging since it traversed about a half dozen tables in the database.  He had it working but it was very long (several dozen lines) and he was curious if there was a better way.

The query he wrote used the LINQ query syntax instead of the method syntax (sometimes called lambda syntax) .  Query syntax tends to be a bit verbose, while method syntax can be a bit cryptic at times (see here for a comparison of the two styles).  I can’t really say one is “better” than the other, and I find that I use both in many cases, sometimes within the same query.

But more importantly, he was doing joins the “old” way — i.e. his LINQ code looked very much like SQL code.  When I started writing LINQ queries, I took the same approach.  SQL was familiar to me so being able to write strongly-typed SQL code in LINQ was at least a step up.  But writing queries this way is not thinking in LINQ.

I will demonstrate a query that is along the lines of how we ended up translating his original query into something very simple that flowed very nicely.  (His new query ended up being four lines of code instead of the original several dozen.)

Using the ever awesome LINQPad utility as our development environment, and coding against the Northwind database, we have the following challenge:

Retrieve the customer ID and company name for all customers who have ever placed an order that contained a product in the Condiments category.

LINQPad queries execute within the context of the database context, so I won’t be prefixing anything with “db”, “dc”, “ctx”, etc.

The first step is to just get the customer ID and company name:

Customers.Select(o => new {o.CustomerID, o.CompanyName})

This returns 91 rows and generates the following SQL:

SELECT [t0].[CustomerID], [t0].[CompanyName]
FROM [Customers] AS [t0]

Next, we refine the query to only get customers who have placed an order:

Customers.Where(o => o.Orders.Any())
    .Select(o => new {o.CustomerID, o.CompanyName})

This returns 88 rows and generates the following SQL:

SELECT [t0].[CustomerID], [t0].[CompanyName]
FROM [Customers] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [Orders] AS [t1]
    WHERE [t1].[CustomerID] = [t0].[CustomerID]
    )

Notice how the LINQ Any operator was translated into a SQL “WHERE EXISTS”.

Now things get a bit more complicated because we only want orders that contain condiments, but the query still flows very nicely:

Customers.Where(o => o.Orders.Any(o2 => o2.OrderDetails
    .Any(o3 => o3.Product.Category.CategoryName == "Condiments")))
    .Select(o => new {o.CustomerID, o.CompanyName})

The final result set is 68 customers, with the SQL looking like this:

SELECT [t0].[CustomerID], [t0].[CompanyName]
FROM [Customers] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [Orders] AS [t1]
    WHERE (EXISTS(
        SELECT NULL AS [EMPTY]
        FROM [OrderDetails] AS [t2]
        INNER JOIN [Products] AS [t3] ON [t3].[ProductID] = [t2].[ProductID]
        LEFT OUTER JOIN [Categories] AS [t4] ON [t4].[CategoryID] = [t3].[CategoryID]
        WHERE ([t4].[CategoryName] = @p0) AND ([t2].[OrderID] = [t1].[OrderID])
        )) AND ([t1].[CustomerID] = [t0].[CustomerID])
    )

Note how LINQ generates the JOINs in the SQL for us.  There was no need to explicitly do a join in the LINQ code.  Instead, we used the navigation properties that are created for us (provided your database has foreign keys!).

So the final result was a fairly straightforward LINQ query using method syntax that got translated into some pretty nice SQL (pretty much what I would have written myself).

There are always many ways to write LINQ queries, and I recommend experimenting directly in LINQPad to see what makes the most sense for you.  You’ll find that as you start thinking more in LINQ, as opposed to SQL, that the queries become much simpler.

Hope this helps.

June 11, 2009

Wireshark

Filed under: Networking,technology — Larry Parker @ 10:48 pm

If you need a good packet sniffer, Wireshark is a very handy utility, and the price is right (free).  You can download it here.

I used it all day at work today to look at packets going across the wire sent from my WCF code.  It was especially useful to verify that SSL transport security was indeed activated.  I could see the Client Hello and Server Hello handshake in action and also verify that the packets were encrypted (whereas prior to using SSL I would see the plain-text SOAP messages).

I’m really impressed with how Wireshark displays the packets and breaks them up into the various Internet Protocol Suite components (e.g. Ethernet Frame II, IP, TCP, etc.).  It’s a great learning tool.

Cannot Paste into Microsoft Virtual PC

Filed under: Microsoft,technology — Larry Parker @ 4:18 pm

I’ve been using Microsoft Virtual PC 2007 for various things, and it’s been working well.  But one thing that really annoys me is that I can’t copy from my host desktop machine and paste into the virtual PC (nor can I copy from the virtual PC and paste into the host machine).  This has become frustrating enough that I finally googled it and came up with this article.

The simple workaround is to just Remote Desktop into the virtual PC.  Works for me!  🙂

Windows XP SP2 Support Tools and httpcfg.exe

Filed under: Microsoft,technology — Larry Parker @ 11:51 am

I’m doing some work with WCF and SSL and need to configure a port with an SSL certificate on the server.  To do this, you need the httpcfg.exe utility, available with Windows XP SP2 Support Tools.

So I downloaded it, installed it, looked in C:\Program Files\Support Tools, and no httpcfg.exe.  What’s the deal?

It turns out that when you install Support Tools, you need to select Optional Tools from the setup wizard (it’s disabled by default).

untitled

So just make sure you select the feature to get httpcfg.exe (and the other optional tools).  Hope this helps.

June 10, 2009

Generating Method Stubs in Visual Studio

Filed under: .NET,Microsoft,technology,Visual Studio — Larry Parker @ 3:17 pm

I’ve been using Visual Studio for years and just stumbled upon a very useful feature – generating method stubs.  You can read more about it here, but say you’re in the middle of coding and want to call a method that you haven’t written yet.  That’s what I was just doing a few minutes ago, but instead of doing the usual and moving out of the current block of code in the editor to create a new method, I decided to just code the method call the way it seemed it should be.

Then I right-clicked on the method call for the unwritten method, and to my delight I saw this:

untitled

A Generate Method Stub menu item gets added to the context menu!  I clicked on it and the following code was automatically generated for me:

private static XElement TransformQueryElement(ushort queryNum, XElement origQueryElem)
{
    throw new NotImplementedException();
}

Exactly what I needed!  Thanks Microsoft.  🙂

June 1, 2009

Funny NullReference Documentation

Filed under: .NET,Humor,technology,Visual Studio — Larry Parker @ 2:01 pm

Here’s some funny documentation I saw via Intellisense while creating a NullReferenceException:

untitled

And this whole time I thought my exceptions were being read by monkeys!  🙂

Blog at WordPress.com.