Tuesday, January 15, 2008
I'm starting a brand new series of short articles about F#. The plan is to describe features that, for me, make F# a compelling and enjoyable .NET language. So far, I have 10-15 articles in mind, but I'm open to suggestions. If you have any ideas for additional topics, please email them to dustin AT diditwith.net.

The Interactive Environment

Like Python, Ruby and many other programming languages, F# provides an interactive scripting environment. However, F# is different in that the interactive environment is not an interpreter. Instead, it dynamically compiles code on-the-fly.

There are two ways to load this environment:

  • Run fsi.exe from the bin subdirectory of the F# distribution.
  • Load the F# Interactive for Visual Studio add-in from the Visual Studio Add-in Manager.

Once the environment is loaded, a splash screen is displayed. (NOTE: the examples here use fsi.exe.)

MSR F# Interactive, (c) Microsoft Corporation, All Rights Reserved
F# Version 1.9.3.7, compiling for .NET Framework Version v2.0.50727

NOTE:
NOTE: See 'fsi --help' for flags
NOTE:
NOTE: Commands: #r <string>;;    reference (dynamically load) the given DLL.
NOTE:           #I <string>;;    add the given search path for referenced DLLs.

NOTE:           #use <string>;;  accept input from the given file.
NOTE:           #load <string> ...<string>;;
NOTE:                            load the given file(s) as a compilation unit.
NOTE:           #time;;          toggle timing on/off.
NOTE:           #types;;         toggle display of types on/off.
NOTE:           #quit;;          exit.
NOTE:
NOTE: Visit the F# website at http://research.microsoft.com/fsharp.
NOTE: Bug reports to fsbugs@microsoft.com. Enjoy!

>

At this point, it's easy to start typing F# code. To execute code, type a double semi-colon. The following bit of code, when typed into the interactive environment, will instantiate and display a new .NET Windows Form:

> open System.Drawing
- open System.Windows.Forms;;

> let myForm = new Form(Text = "Hello, World!", Visible = true);;

val myForm : Form

The first two lines open the System.Drawing and System.Windows.Forms namespaces. This is analogous to C#'s using and VB's Imports statements. It isn't necessary to reference the System.Drawing.dll or System.Windows.Forms.dll assemblies because they are implicitly referenced by the environment.

The third line instantiates a new Form, sets its Text and Visible properties, and binds it to the name myForm. Because the code is dynamically compiled and executed, the form is displayed immediately.

Hello, World! Form

Now that the form is instantiated, it can be manipulated at runtime.

> myForm.BackColor <- Color.Blue;;
val it : unit = ()

When executed, the above code changes the form like so:

Hello, World! Form (colored)

The F# Interactive Environment is a great way to break out of the standard edit-compile-debug rut and prototype some code. It can even output to a .NET assembly. Run "fsi.exe --help" to see more ways in which the interactive environment can be used.

posted on Tuesday, January 15, 2008 8:06:10 AM (Pacific Standard Time, UTC-08:00)  #    Comments [6]

kick it on DotNetKicks.com
While at CodeMash, I sat down with my good friend Chris Woodruff for a casual podcast interview discussing life, code, being a Microsoft MVP, DevExpress and the CodeMash conference.

CodeMash 2008 Interview with Dustin Campbell

NOTE: This interview is not technical and gets a little off-topic at the end.

In addition, there are several other CodeMash interviews, including:

posted on Tuesday, January 15, 2008 6:10:19 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Monday, January 14, 2008
While at CodeMash, I had the opportunity to sit down with Scott Hanselman and record an episode for his renowned podcast, Hanselminutes. As a follower of the podcast, I was thoroughly flattered to be included among his guest list. The show turned out well, but the experience was definitely nerve-wracking. Here are some tips in case you ever end up in the hot seat across from Scott:
  1. Learn to hold and speak into a microphone. This is critical. During the recording, I kept drifting from the mic, which required editing in post-production.
  2. Be prepared to be disarmed by the interviewer's eloquence. Scott is a very well-spoken guy with a lot of experience. Don't be surprised when he pulls the perfect metaphor out of thin air.
  3. Be aware of your medium. When recording audio, be careful using words to explain a concept that might be better expressed with a visual diagram. Remember: it's a warning sign if you start "talking with your hands."

Scott and I talked about some of the features that make F# such an exciting language. We tried to keep it short on academia so that it would be appealing to any developer. The idea was to start small with some bite-sized concepts. Check it out!

Starting Small with F# with Dustin Campbell

posted on Monday, January 14, 2008 8:16:29 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Wednesday, January 02, 2008
I guess I've been a little busy lately because I completely missed the release of Ultramon™ 3.0.1 Beta 2 back on December 15th. Ultramon is simply the best management tool for multiple monitors available. I would not survive for long in front of my monitor setup without it.

This release has some welcome changes and bug fixes for Windows Vista. The full release notes are here.

posted on Wednesday, January 02, 2008 1:52:50 PM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
Today, while making some changes to my Plaxo Pulse profile, I was presented with the following error message:

Plaxo Error

Coffee immediately shot out of my nose.

Once I regained control of myself (and after taking the screenshot above), I clicked the X, and the message went away. I never did find out what that error actually was.

posted on Wednesday, January 02, 2008 1:13:00 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Tuesday, January 01, 2008
It's a new year! Time to return to my passion: torturing programming languages and making them cry like little children.

This article has bit of everything: Scheme, C# and VB lambda expressions, closures, lambda calculus... the works. By the end, you'll either be enlightened or stark, raving mad.

Happy New Year!

posted on Tuesday, January 01, 2008 1:33:25 PM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

kick it on DotNetKicks.com
 Monday, December 31, 2007

Mug

Hello again, X-mas celebrants! I have just one last verse in my carol to make all of your Visual Studio 2008 experiences bright. Don't let your hearts be saddened because my song is drawing to a close. After today, a new year filled with its own code blessings will be upon us.

My last offering is a simple one—a stocking stuffer, really. It's one last refactoring targeted at Visual Basic developers.

And so, it is with a heavy heart that I begin the last verse of the "Twelve Days of Refactor! X-mas..."

"On the twelfth day of X-mas my true love (DevExpress) gave to me..."

Extract XML Literal to Resource

In my opinion, the most compelling new feature of Visual Basic 9 is XML Literals. We've already seen how Refactor! Pro can be used to manipulate XML Literals to great effect, saving literally hundreds of keystrokes. However, sometimes we don't want to dynamically build XML. Sometimes we simply want to consume a chunk of raw XML.

Module TwelveDaysOfXmas
  Sub Main()
    Dim lBook = <book isbn="12252007">
                 <title>Refactoring: The True Meaning of X-mas</title>
                 <price>$0.00</price>
                 <author>
                   <first-name>Dustin</first-name>
                   <last-name>Campbell</last-name>
                 </author>
               </book>
  End Sub
End Module

If we're not adding embedded expressions to the above XML literal, it really belongs in a resource file. However, moving that XML to a resource is a terrible inconvenience. Thankfully, Refactor! Pro provides the Extract XML Literal to Resource refactoring. When applied to the code above, Extract XML Literal to Resource produces the following:

Module TwelveDaysOfXmas
  Sub Main()
    Dim lBook = XElement.Parse(My.Resources.XMLFile)
  End Sub
End Module

When compared to the acrobatics we've already seen Refactor! Pro perform on XML Literals, this refactoring might seem like a very small thing. It may be simple, but it's incredibly helpful when you need it. The first time that you attempt to move an XML Literal to a resource for translation purposes or any other reason, you'll be thankful that you have Extract XML Literal to Resource to do the job for you.

Check Out This Screencast to See Everything that Extract XML Literal to Resource Handles for You!

And so ends my song. We've taken a merry sleigh ride through many of the new language features available in Visual Studio 2008, and we've seen how Refactor! Pro can help you leverage those features today. It's been my distinct pleasure to be your guide on this journey.

Before I take my leave, I have one small piece of advice. If you've been waiting impatiently for the other tool to support for Visual Studio 2008, remember that Refactor! Pro has been there since the very first beta. No matter what that tool vendor may try to tell you, Visual Studio 2008 was not a surprise. Everyone had more than a year to prepare. The only ones taken by surprise were those who weren't paying attention.

And with that, I wish you a continued happy holiday season and hope Refactor! Pro can make your new year bright!

Happy New Year!

posted on Monday, December 31, 2007 10:57:09 AM (Pacific Standard Time, UTC-08:00)  #    Comments [5]

kick it on DotNetKicks.com
 Sunday, December 30, 2007

Mug

Greetings friends! I bring tidings of comfort and joy! That is, you can rest comfortably and joyously, knowing that you don't have to wait for refactorings that leverage the new language features of Visual Studio 2008. These refactorings are available today.

I'm very excited about today's verse. As promised yesterday, I'm back to share some more refactoring possibilities for Visual Basic XML Literals. By the end of the verse, you should have a sense of how powerful these refactorings truly are. If you're a Visual Basic developer, you definitely won't want to miss this!

"On the eleventh day of X-mas my true love (DevExpress) gave to me..."

More Refactoring in XML Literals

Yesterday, we saw how our bread-and-butter refactorings can be used on the inner text of XML tags to create new embedded expressions. This is extremely helpful when trying to make the contents of an XML literal more dynamic. Today, we'll take things a step further to see how we can use Refactor! Pro to manipulate the XML tags themselves.

Module TwelveDaysOfXmas
  Sub Main()
    Dim aPrice As Decimal = 0
    Dim lBook = <book isbn="12252007">
                 <title>Refactoring: The True Meaning of X-mas</title>
                 <price><%= aPrice.ToString("C") %></price>
                 <author>
                   <first-name>Dustin</first-name>
                   <last-name>Campbell</last-name>
                 </author>
               </book>
  End Sub
End Module

Consider the code above. Since Refactor! Pro works on XML tags, we can select the entire <price> tag and apply Extract Method to get the following:

Module TwelveDaysOfXmas
  Private Function GetPrice(ByVal aPrice As Decimal) As XElement
    Return <price><%= aPrice.ToString("C") %></price>
  End Function

  Sub Main()
    Dim aPrice As Decimal = 0
    Dim lBook = <book isbn="12252007">
                 <title>Refactoring: The True Meaning of X-mas</title>
                 <%= GetPrice(aPrice) %>
                 <author>
                   <first-name>Dustin</first-name>
                   <last-name>Campbell</last-name>
                 </author>
               </book>
  End Sub
End Module

A potential complication is the use of aPrice in the embedded expression. Fortunately, Extract Method intelligently analyzes this and declares it as a parameter of the new method.

View Screencast to See Extract Method in Action!

Refactor! Pro's ability to manipulate XML tags makes it easy to dynamically build XML. In fact it can save minutes of menial coding labor.

Take another look at the first code example above. Go ahead. I'll wait.

Now, imagine how much effort it would take to transform that code into this:

Module TwelveDaysOfXmas
  Private Function GetTitle(ByVal aTitle As String) As XElement
    Return <title><%= aTitle %></title>
  End Function

  Private Function GetPrice(ByVal aPrice As Decimal) As XElement
    Return <price><%= aPrice.ToString("C") %></price>
  End Function

  Private Function GetAuthor(ByVal aFirstName As String, _
                             ByVal aLastName As String) As XElement
    Return <author>
             <first-name><%= aFirstName %></last-name>
             <last-name><%= aLastName %></last-name>
           </author>
  End Function

  Private Function GetBook(ByVal aPrice As Decimal, _
                           ByVal aIsbn As String, _
                           ByVal aTitle As String, _
                           ByVal aFirstName As String, _
                           ByVal aLastName As String) As XElement
    Return <book isbn=<%= aIsbn %>>
             <%= GetTitle(aTitle) %>
             <%= GetPrice(aPrice) %>
             <%= GetAuthor(aFirstName, aLastName) %>
           </book>
  End Function

  Sub Main()
    Dim lBook = GetBook(0D, _
                  "12252007", _
                  "Refactoring: The True Meaning of X-mas", _
                  "Dustin", _
                  "Campbell")
  End Sub
End Module

That's pretty insane, isn't it? Well, with Refactor! Pro, this is a snap. In fact, most of the effort is spent typing the names of new variables and methods. The refactorings themselves take only seconds to apply.

Don't Believe Me? Check Out This Screencast!

One point I've saved until now is that Refactor! Pro is the very first tool to offer refactorings for Visual Basic XML Literals. That's just one more compelling reason that Refactor! Pro should be a part of your Visual Studio 2008 installation this holiday season.

Happy Holidays!

posted on Sunday, December 30, 2007 3:58:57 PM (Pacific Standard Time, UTC-08:00)  #    Comments [4]

kick it on DotNetKicks.com
 Saturday, December 29, 2007

Mug

I'm afraid that I have an apology to make. I feel that I've given my Visual Basic friends a raw deal because the verses of my carol thus far have been primarily about C#. Oh sure, the verses usually end with a paragraph or two mentioning how a particular refactoring works in VB, but I haven't devoted a whole verse exclusively to a Visual Basic 9 feature. Until now. Today's verse is dedicated specifically to the coolest new feature of Visual Basic 9: XML Literals.

So, sit back and relax. It's time for a little Visual Basic X-mas cheer!

"On the tenth day of X-mas my true love (DevExpress) gave to me..."

Refactoring in XML Literals

A couple of months ago, I wrote about how we were adding first-class refactoring support for Visual Basic XML Literals. If you're unfamiliar with XML Literals, they allow developers to embed XML directly into their code like so:

Module TwelveDaysOfXmas
  Sub Main()
    Dim lBook = <book isbn="12252007">
                 <title>Refactoring: The True Meaning of X-mas</title>
                 <price><%= 0D.ToString("C") %></price>
                 <author>
                   <first-name>Dustin</first-name>
                   <last-name>Campbell</last-name>
                 </author>
               </book>
  End Sub
End Module

It's the VB Compiler's job to transform the above XML Literal into instances of XElements, XAttributes and XNames from the System.Xml.Linq namespace.

Module TwelveDaysOfXmas
  Sub Main()
    Dim lBook = New XElement("book", _
                    New XAttribute("isbn", "12252007"), _
                    New XElement("title", "Refactoring: The True Meaning of X-mas"), _
                    New XElement("price", 0D.ToString("C")), _
                    New XElement("author", _
                        New XElement("first-name", "Dustin"), _
                        New XElement("last-name", "Campbell")))
  End Sub
End Module

The real power of XML Literals is the ability to embed expressions directly into the XML. In the first code example above, the <price> tag contains an embedded expression.

<price><%= 0D.ToString("C") %></price>

Embedded expressions open the door to dynamic XML generation. Very, very cool.

The only real problem that I have with XML Literals is that embedded expressions are such a pain to write. Not only does the expression itself have to be written, but the delimiters contain no less than five symbols. Granted, VB's IntelliSense fills in the last two after I've typed the first three, but that's still three characters to type with the shift key held down. That's pretty painful. It would be great if a refactoring tool existed that handled this work for us. Oh wait. I work on a refactoring tool that does that very thing. That's right, Refactor! Pro works on XML Literals!

Check out the preview hint for Introduce Local when the contents of the <title> tag are selected:

Introduce Local on Xml Literal Preview Hint

And here's the code after Introduce Local is applied:

Introduce Local on Xml Literal

Visual Basic developers everywhere can rejoice. You no longer have to type <%= again because the bread-and-butter refactorings work in XML Literals!

View Screencast of XML Literal Refactoring in Action!

Tomorrow: more refactorings for XML Literals. You won't want to miss it!

posted on Saturday, December 29, 2007 10:40:08 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Friday, December 28, 2007

Cookies

Welcome back for more X-mas refactoring fun! There are just four more verses in my carol, but I'll make them count. Refactor! Pro can bless your Visual Studio 2008 installation in many more ways, so I'll have to pick the very best.

"On the ninth day of X-mas my true love (DevExpress) gave to me..."

Expand Lambda Expression

In my sixth verse, I described a feature of Refactor! Pro that enables developers to leverage the dreaded lambda expressions. That refactoring (Compress to Lambda Expression) provides a way to transform an anonymous method into a lambda expression. Today we're looking at lambda expressions from the opposite perspective—transforming a lambda expression into an anonymous method. Expand Lambda Expression is the refactoring that performs this conversion. Given the lambda expression in the code below...

using System;

namespace TwelveDaysOfXmas
{
  class Program
  {
    static void Main()
    {
      var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      var numberText = Array.ConvertAll<int, string>(numbers, n => n.ToString("x8"));

      foreach (var text in numberText)
        Console.WriteLine(text);
    }
  }
}

Expand Lambda Expression will produce this:

using System;

namespace TwelveDaysOfXmas
{
  class Program
  {
    static void Main()
    {
      var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      var numberText = Array.ConvertAll<int, string>(numbers, delegate(int n)
                                                              {
                                                                return n.ToString("x8");
                                                              });

      foreach (var text in numberText)
        Console.WriteLine(text);
    }
  }
}

I'm sure that some of you are scratching your heads. "Why in the world would I want to do that? Aren't lambda expressions better?" Well, yes. However, transforming a lambda expression into an anonymous method makes other refactorings available. For example, after expanding our lambda expression, we might want to use Name Anonymous Method to make the anonymous method a member of the current type. That way, we're promoting code reuse. Check out the preview hint for Name Anonymous Method below.

Name Anonymous Method Preview Hint

Once Name Anonymous Method is applied, we can give the new method a good name and we're done!

using System;

namespace TwelveDaysOfXmas
{
  class Program
  {
    private static string GetHexText(int n)
    {
      return n.ToString("x8");
    }
    static void Main()
    {
      var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      var numberText = Array.ConvertAll<int, string>(numbers, GetHexText);

      foreach (var text in numberText)
        Console.WriteLine(text);
    }
  }
}

View Screencast of Expand Lambda Expression and Name Anonymous Method in Action!

I must say, it gladdens my heart to know that there is a tool available right now that allows me to refactor the latest and greatest language features of Visual Studio 2008. In fact, we've raised the bar by releasing a major update to Refactor! Pro. That's right, Refactor! Pro 3.0 is now available and ships with 150 refactorings for C#, Visual Basic, C++, ASP .NET, XAML, and even JavaScript. The future is looking very bright indeed!

posted on Friday, December 28, 2007 12:53:10 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Thursday, December 27, 2007

Coffee and Mug

Today, I saw the following tweet on Twitter:

dredding: @jfollas taking coffee away from a developer is like taking away a dominatrix's whip. You just don't do it.

This made me smile—not because of how creepy my friend Dave Redding is (very creepy), but because of how true the sentiment is. At least, it's true for me. Coffee is an addiction that I've fully embraced. It's difficult for me to start a day without that bold flavor. Some developers might choose to get their buzz in another way (and a smaller percentage choose to have none at all), but I've picked coffee as my caffeine-delivery system of choice.

I've really become quite the coffee snob. For me, only the very best coffee will do. I buy my coffee whole bean from Grounds for Thought in Bowling Green, OH. Of all the roasts they produce, Kenya "Gazelle" AA and Papua New Guinea "Mile High" Estate AA+ are definitely my favorites. The Kenya has a nice bite that wakes me up while the New Guinea is smooth all the way down.

But what is it about caffeine that causes many developers crave it so? I mean, aside from the fact that it helps wake us up in the mornings. It certainly doesn't make me a nicer person to be around. In fact, too much makes me downright grouchy. However, the right amount seems to put my brain in a zone that sees problems more clearly. It's almost as if the caffeine gives my think meat the extra zip that it needs to solve problems. Perhaps caffeine unlocks areas of our minds that allow us to be better developers, if only for a moment.

Then again, maybe that's just the coffee talkin'.

posted on Thursday, December 27, 2007 4:48:14 PM (Pacific Standard Time, UTC-08:00)  #    Comments [4]

kick it on DotNetKicks.com