# Thursday, January 01, 2009

So, a year ago to the day, I posted my review of 2007 with a look towards 2008. To continue that age old tradition, I will now review 2008.

Learning

I started off the month by stating that I wanted to learn some new languages, primarily Python and Ruby. I’m sad to say that I haven’t made it past the 5th python challenge yet. I pretty much got distracted, which is a lame excuse. On the other hand, instead of learning languages, I’ve learned a ton about editing in VIM and even a little about Emacs (though I have to use viper or vimpulse to be at all productive in Emacs). I’m even using ViEmu in Visual Studio. The Vim key-bindings have become muscle memory now and I consider that a positive thing. I’m still going to try to learn other languages this year, but I’m going to need a project to work on before I can become proficient.

FSDNUG

This year, a very exciting thing for me was the formation of FSDNUG. Michael Paladino pretty much did all of the work, but he lets me call myself a co-leader. Raymond Lewallen opened up the FSDNUG meetings by speaking about Behavior Driven Development. I didn’t really grok BDD at that point, but I’m learning. I most definitely prefer the context/specification style of naming specs over traditional TDD test names.

Conferences

I was fortunate enough to attend both Tech Ed and DevLink this year. I even told people at DevLink that I’d be attending CodeMash, but I sadly won’t be able to make it after all. I have no doubts that it will be an amazing conference, though, and wish I could be there.

Presentations

I presented on PowerShell three times in 2008. Once to FSDNUG, once to MNUG and then once to Harding University CS students. My presentations pretty much took up all of September. It was a great experience and I’m looking forward to speaking to the Shreveport .NET User Group in March!

Posts

My post on “real world debugging witn WinDbg” post was featured on the Tech Ed bloggers site, which led to me being selected as a “featured Tech Ed blogger” for a day. I was also excited to have my PowerShell thumbnail script mentioned on the PowerScripting Podcast.

In closing…

All in all, a really great year. I noted in 2007, that it had been the year of the most growth for me as a developer. That was true… at least until 2008. My opinion right now is that there is no such thing as a good developer, only a better developer. This saying comes from a discussion I had with a coworker a few months back where we came to the conclusion that there isn’t such a thing as a good design or architecture, only a better design or architecture – all because we’ll inevitably have learned a better way to do things in the future.

I hope everyone has a great 2009!

posted on Thursday, January 01, 2009 2:13:41 PM (Central Standard Time, UTC-06:00)  #    Comments [1]
# Wednesday, December 31, 2008

Last week, the PowerShell team released PowerShell v2 CTP3. And, of course, there was much rejoicing. I’ve got quite a bit I’d like to blog about regarding PowerShell, but I couldn’t wait to share one feature I love.

PowerShell ISE Themes.

Okay, so, it doesn’t actually ship with themes. But you can create them. Let me provide some background. The “ISE” in PowerShell ISE stands for Integrated Scripting Environment and is based on the upcoming WPF editor that will ship with Visual Studio 2010. Here is a screenshot of it.

image

As you can see, there are three panes included: one that allows you to edit PS1 scripts (with syntax highlighting and tab completion included), one that displays the output of your commands (whether from the script editor or the command pane), and one that allows you to type in commands (the equivalent of the prompt you get in the console host).

I’ll admit, when I heard about the graphical host, I thought it was nice but I really didn’t think I’d use it much. I use gVim to edit my scripts and have the console up all day. Why did I need another editor? I didn’t get really excited until I saw all of the customizations that you can do with it.

The $psISE variable offers up a wealth of options. I’m particularly fond of the Options property off of $psISE. I’ll let the screenshot describe why:

image

Looks different, eh? Below is the code to get it to work:

# PowerShell ISE version of the VIM blackboard theme at 
# http://www.vim.org/scripts/script.php?script_id=2280

# fonts
$psISE.Options.FontName = 'DejaVu Sans Mono'
$psISE.Options.FontSize = 16

# output pane
$psISE.Options.OutputPaneBackground = '#FF000000'
$psISE.Options.OutputPaneTextBackground = '#FF000000'
$psISE.Options.OutputPaneForeground = '#FFFFFFFF'

# command pane
$psISE.Options.CommandPaneBackground = '#FF000000'

# script pane
$psISE.Options.ScriptPaneBackground = '#FF000000'

# tokens
$psISE.Options.TokenColors['Command'] = '#FFFFFF60'
$psISE.Options.TokenColors['Unknown'] = '#FFFFFFFF'
$psISE.Options.TokenColors['Member'] = '#FFFFFFFF'
$psISE.Options.TokenColors['Position'] = '#FFFFFFFF'
$psISE.Options.TokenColors['GroupEnd'] = '#FFFFFFFF'
$psISE.Options.TokenColors['GroupStart'] = '#FFFFFFFF'
$psISE.Options.TokenColors['LineContinuation'] = '#FFFFFFFF'
$psISE.Options.TokenColors['NewLine'] = '#FFFFFFFF'
$psISE.Options.TokenColors['StatementSeparator'] = '#FFFFFFFF'
$psISE.Options.TokenColors['Comment'] = '#FFAEAEAE'
$psISE.Options.TokenColors['String'] = '#FF00D42D'
$psISE.Options.TokenColors['Keyword'] = '#FFFFDE00'
$psISE.Options.TokenColors['Attribute'] = '#FF84A7C1'
$psISE.Options.TokenColors['Type'] = '#FF84A7C1'
$psISE.Options.TokenColors['Variable'] = '#FF00D42D'
$psISE.Options.TokenColors['CommandParameter'] = '#FFFFDE00'
$psISE.Options.TokenColors['CommandArgument'] = '#FFFFFFFF'
$psISE.Options.TokenColors['Number'] = '#FF98FE1E'

To use it, I just dot the script into my PowerShell ISE profile (see the $profile variable while in PowerShell ISE) like so (where ./Themes/blackboard.ps1 is the path to the blackboard theme):

. ./Themes/blackboard.ps1

The script is a conversion I did of the vim blackboard theme which itself is a clone of the blackboard theme from TextMate. I’m sure it could use some tweaking, but it works for me for now.

One thing I’m missing so far is how to change the color of the text caret. Because I have a black background, I can’t see where I’ve got focus in the editor! Hopefully the PowerShell team will add an additional property to the Options to change the caret color or, even better, hopefully I’ve just missed the setting :-)

Let me know what you think! I’ve got even more PowerShell profile posts I’m working on so stay tuned.

UPDATE: Based on Joel’s comment, I’ve posted a bug on the Microsoft Connect site for PowerShell. Go vote for it at https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=390304&SiteID=99. Note that you can only access the site if you’ve signed up on Microsoft Connect and added PowerShell as a project.

posted on Wednesday, December 31, 2008 9:17:11 AM (Central Standard Time, UTC-06:00)  #    Comments [5]
# Friday, December 05, 2008

This post presents a problem that has been approached by others before, but I thought I’d offer yet another possible solution. But first, let’s introduce the problem!

In my experience, real world applications (aka NOT demos) don’t display data that was hard-coded in an application. For my part, the data is usually coming from some remote service or endpoint, so I’m either working with some proxy to a WCF, ASMX, or remoting endpoint. It seems that most WPF demos that showcase data-binding imagine a scenario where the data is readily available to the designer which allows them, at design-time, to see what the application might look like with real data loaded.

Check out the below screenshot of an amazing application that I created this morning.

image

As you can tell, I’m displaying a list of accounts by name and balance. The UI on this thing is unbelievable, too, because it also makes the balance red when their balance is below zero. Go WPF!

Seriously, though, I’ve tried to structure this like I might a real application. I’m a huge fan of the CompositeWPF library (*cough* Prism *cough*), so I’m using a Model-View-Presenter approach here, where the View is binding to a PresentationModel. You can see some examples of this in the StockTrader reference application that ships with CompositeWPF. The presenter’s only job is to hook up the data binding to the view and then load the PresentationModel up with data from the service. (Note that it would be very easy to add threading support here so that, while pulling data from IService, we don’t lock up the UI)

public class Presenter  
{  
    private readonly IView _view;  
    private readonly IService _service;  
    private readonly PresentationModel _presentationModel;  
  
    public Presenter(IView view, IService service, PresentationModel presentationModel)  
    {  
        _view = view;  
        _service = service;  
        _presentationModel = presentationModel;  
    }  
  
    public void Run()  
    {  
        _view.Model = _presentationModel;  
        LoadAccounts();  
    }  
  
    private void LoadAccounts()  
    {  
        foreach (var acct in _service.GetAccounts())  
            _presentationModel.Accounts.Add(acct);  
    }  
}

The PresentationModel only exposes an ObservableCollection of Accounts.

public class PresentationModel  
{  
    private readonly ObservableCollection<Account> _accounts = new ObservableCollection<Account>();  
    public ObservableCollection<Account> Accounts  
    {  
        get  
        {  
            return _accounts;  
        }  
    }  
}

The code for Window1.xaml is below.

<Window  
  x:Class="WpfApplication1.Window1"  
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  xmlns:local="clr-namespace:WpfApplication1"  
  Title="Window1"  
  Height="300"  
  Width="300">  
    
  <local:AccountDisplay  
    DataContext="{Binding}" />  
</Window>

I’m just tying the DataContext for my AccountDisplay UserControl to whatever Binding is set to the Window. This allows the data binding to just flow through the rest of the application. This is very flexible. But what about the code behind? It is pretty basic, too.

public partial class Window1 : Window, IView  
{  
    public Window1()  
    {  
        InitializeComponent();  
  
        var presenter = new Presenter(this, new RealService(), new PresentationModel());  
        presenter.Run();  
    }  
 
    #region IView Members  
  
    public object Model  
    {  
        get { return DataContext; }  
        set { DataContext = value; }  
    }  
 
    #endregion  
}

The sample isn’t using CompositeWPF, but if you’re familiar with it, you should realize that it would be very easy to plug it in. In fact, my example is screaming Inversion of Control because of the Dependency Injection that I’m already using with the Presenter. A conversion to using the CompositeWPF would start with replacing the local declaration of the AccountDisplay user control with a region and associated module and you’ll be well on your way.

The real display is in AccountDisplay. Here is its source:

<UserControl  
  x:Class="WpfApplication1.AccountDisplay"  
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  xmlns:local="clr-namespace:WpfApplication1"  
  Height="300"  
  Width="300">  
    
  <UserControl.Resources>  
    <local:BalanceToBrushConverter  
      x:Key="BalanceToBrushConverter" />  
  </UserControl.Resources>  
  
  <ItemsControl  
    ItemsSource="{Binding Path=Accounts}">  
  
    <ItemsControl.ItemTemplate>  
      <DataTemplate>  
  
        <StackPanel  
          Orientation="Horizontal">  
          <Border  
            CornerRadius="5"  
            Padding="5"  
            BorderBrush="Black"  
            BorderThickness="2">  
            <TextBlock  
              Text="{Binding Path=Name}" />  
          </Border>  
          <Border  
            CornerRadius="5"  
            Padding="5"  
            BorderBrush="Black"  
            BorderThickness="2">  
            <TextBlock  
              Foreground="{Binding Path=Balance, Converter={StaticResource BalanceToBrushConverter}}"  
              Text="{Binding Path=Balance}" />  
          </Border>  
        </StackPanel>  
      </DataTemplate>  
    </ItemsControl.ItemTemplate>  
  
  </ItemsControl>  
</UserControl>

Here, I’m just using relative binding (Binding Path=Property) here. This means I’ll pick up data binding from the DataContext, which was set back in Window1.xaml (once again, a result of that flowing data binding).

So, where’s the problem? Let’s look at this from the designer perspective by opening AccountDisplay.xaml in Blend.

image

It… it looks really great. So… white and everything. Anyone know what the problem is? My Presenter is the guy who does the work to return accounts to bind to, but Blend is just showing us the XAML. This is good – we don’t want the fact that we’re designing this to actually run our code and hit our services. But… we still want some test data to design with, right? We could add some data to our XAML file… but then that affects us when we actually run the application. Besides, I personally want test data to match the structure of the model I’m binding to.

Here’s what I’m doing to fix this right now. I added the following 3 lines of code to AccountDisplay.xaml.

<local:Designer.DataContext>  
  <local:BlendPresentationModel />  
</local:Designer.DataContext>

That doesn’t tell you much, so I’ll show you the Designer class that is being referenced now.

/// <summary>  
/// Allows the use of design-time only data binding... seems to only work  
/// in Blend and not the VS designer...  
/// </summary>  
public static class Designer  
{  
    public static readonly DependencyProperty DataContextProperty =  
        DependencyProperty.RegisterAttached("DataContext", typeof (object), typeof (Designer),  
                                            new PropertyMetadata(OnDataContextChanged));  
  
    private static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)  
    {  
        SetDataContext(d, e.NewValue);  
    }  
  
    public static void SetDataContext(DependencyObject d, object value)  
    {  
        var element = d as FrameworkElement;  
        if (element == null) return;  
  
        if (DesignerProperties.GetIsInDesignMode(element))  
            element.DataContext = value;  
    }

    public static object GetDataContext(DependencyObject d)
    {
        var element = d as FrameworkElement;
        if (element == null) return null;

        if (!DesignerProperties.GetIsInDesignMode(element))
            return null;

        return element.DataContext;
    }  
}

A few of things to note. I have a Dependency Property called DataContext first. I’m using a Dependency Property so that WPF data binding works. It can take any object (hence the typeof(object) parameter. When it changes, I call off to SetDataContext with the new value. Next important thing to note – DesignerProperties.GetIsInDesignMode. I try to cast the owner of my Designer instance (which is typically going to be a UserControl or Window or other UI element) to a FrameworkElement. I’m using FrameworkElement because it is the highest object in the hierarchy that provides the DataContext property. Then, if we’re in Design mode, I override the DataContext with my Designer DataContext.

In the XAML, what ends up getting set is a BlendPresentationModel, which looks like this:

public class BlendPresentationModel : PresentationModel  
{  
    public BlendPresentationModel()  
    {  
        var accounts = new List<Account>  
                           {  
                               new Account  
                                   {  
                                       Name = "Bob's Stuff",  
                                       Balance = 1000000  
                                   },  
                               new Account  
                                   {  
                                       Name = "Cheap Skate",  
                                       Balance = -100  
                                   }  
                           };  
        foreach (var acct in accounts)  
            Accounts.Add(acct);  
    }  
}

With my approach, I’ve created an object that inherits from my PresentationModel, so the object I’m binding my UI to is the same type that I’m using when running, but I’m providing test data instead. This is what it looks like in Blend now:

image

In one of my projects, I’ve been dropping these guys around in various UserControls and even one at the top level Window so that I can see what it all looks like together. So far, it is working well.

The biggest problem I’ve got with this solution so far is that the Visual Studio designer doesn’t render the test data. I would guess that this would be fixed at some point – honestly, the rendering of XAML should be the same between Blend and Visual Studio and, if it isn’t, it should be fixed.

Karl Shifflett posts a solution to this as well – my solution is basically just my own take on what he’s already done, so thanks to him for the initial idea. I wasn’t using Resources for binding, which is the primary reason I started with my own solution.

Also, Laurent Bugnion has a great article on various methods to accomplish this as well. I particularly like the feature he shares where Blend can create sample data. I’m very hopeful that this functionality is improved and expanded in future versions of Blend.

I hope this post helps out! Also, if I’m doing something that doesn’t make sense or if there is a better way to do something, please let me know.

UPDATE:
Thanks to Brian Genisio for the suggestion to add the GetDataContext method to my Designer class.

posted on Friday, December 05, 2008 1:13:38 PM (Central Standard Time, UTC-06:00)  #    Comments [4]
# Thursday, December 04, 2008

Thought I’d share the below LINQ statement I wrote recently:

var filesToBeMoved =  
    from networkFile in network  
    join localFile in local  
        on networkFile.Name equals localFile.Name into localToNetwork  
    from localMatchesNetwork in localToNetwork.DefaultIfEmpty()  
    // Handle files that are on the network but don't exist locally  
    where localMatchesNetwork == null  
          // Handle files that are newer on the network that they are locally  
          || (localMatchesNetwork.LastWriteTime < networkFile.LastWriteTime)  
    select networkFile;  
  
foreach (var file in filesToBeMoved)  
    file.MoveTo(_directoryProvider.LocalDirectory);

In this case, the files that are being returned are actually IFileProvider instances, which are basically wrappers around the System.IO.File instances for testability.

Oh, and this post is an excuse to see if I set SyntaxHighlighter up correctly :-)

posted on Thursday, December 04, 2008 7:55:44 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
# Wednesday, November 19, 2008

I’ve been doing some WPF work lately. WPF is ridiculously powerful and provides a lot more than WinForms. On the other hand – wow, the learning curve is quite steep. I think I’m improving, though.

So, the scenario. I wanted to be able to let a user click on an item in a ListBox and drag across, selecting multiple items in the process. Basically, I want to emulate the behavior that the Outlook calendar provides.

I ended up coding up the following XAML to get the behavior:

<ListBox
  x:Name="myListBox"
  SelectionMode="Multiple"
  ItemsSource="{Binding Path=SomeIEnumerableOnMyDataContext}"
  >
  <ListBox.Resources>
    <Style
      TargetType="{x:Type ListBoxItem}"
      >
      <EventSetter
        Event="PreviewMouseLeftButtonDown"
        Handler="ListBoxItem_PreviewMouseLeftButtonDown" />
      <EventSetter
        Event="PreviewMouseUp"
        Handler="ListBoxItem_PreviewMouseUp" />
      <EventSetter
        Event="PreviewMouseMove"
        Handler="ListBoxItem_PreviewMouseMove" />
      <EventSetter
        Event="PreviewMouseRightButtonDown"
        Handler="ListBoxItem_PreviewMouseRightButtonDown" /> 
    </Style>
</ListBox>

The problem with this code is that Blend (currently v2 SP1) doesn’t like EventSetters.

image

I wanted to keep the events hooked up so that, while testing, I could keep the behavior but, at the same time, I want to be able to at least try to design in blend. So I took to implementing the above XAML in code.

Sacha Barber has a good article on converting from XAML to code and back that helped a lot but it didn’t get me quite there.

Here is how to programmatically create one of the EventSetters in code:

var style = new Style(typeof (ListBoxItem)); 
 
style.Setters.Add(
    new EventSetter(PreviewMouseLeftButtonDownEvent,
                    new MouseButtonEventHandler(OnPreviewMouseLeftButtonDown)));

It’s pretty straightforward, but actually hooking this style into my ListBox was what got me confused next.

Setting the ListBox’s style to my style instance didn’t work and then I got stuck on how to plug my style into the ListBox’s ResourceDictionary (via the Resources property). The XAML doesn’t specify a Key anywhere, but the Resources’s Add method requires a key. I tried creating my own key and also specifying a null key, but I still didn’t get the behavior I wanted.

StackOverflow’s goal of being the place for one-off questions like this is starting to work because I stumbled across my answer via Google. I didn’t realize that, in the above XAML, when the Style specifies its TargetType, the type is implicitly the Key in the ResourceDictionary.

So the solution is this:

Resources.Add(typeof (ListBoxItem), style);

Easy enough.

posted on Wednesday, November 19, 2008 12:01:01 PM (Central Standard Time, UTC-06:00)  #    Comments [2]
# Tuesday, October 28, 2008

I decided to download the Visual Studio 2010 and .NET Framework 4.0 CTP tonight. It comes packaged in a virtual machine (not sure if it is Vista or what yet… I’m going to bed before running it).

And… it is big. Really big.

Pictures are worth a thousand words… in this case, they’re worth just over 30 GB.

image

Wow.

posted on Tuesday, October 28, 2008 10:16:42 PM (Central Daylight Time, UTC-05:00)  #    Comments [0]
# Saturday, October 11, 2008

I was working with a lot of images for a website today and I needed to quickly create thumbnails for each one. I did a quick Google search on PowerShell and creating thumbnails, but I gave up after about a minute… yeah, I probably got impatient, but oh well.

Anyway, here it is:

get-childitem *.jpg | foreach {
    $full = [System.Drawing.Image]::FromFile("$(resolve-path $_)");
    $thumb = $full.GetThumbnailImage(72, 72, $null, [intptr]::Zero);
    $thumb.Save("$(resolve-path $_).thumb.jpg" );
    $full.Dispose();
    $thumb.Dispose();
}

Obviously, you likely wouldn’t hardcode the height and width for the thumbnail, but would probably base it off of the original image (i.e. varying it off of whether the image was wide or tall). But, I didn’t need to. That’s up to you to figure out :-)

posted on Saturday, October 11, 2008 5:21:14 PM (Central Daylight Time, UTC-05:00)  #    Comments [4]
# Tuesday, September 30, 2008

I promised the slides, notes and links from my Memphis .NET User Group talk, so here they are… and wow, they haven’t really changed much from when I gave the PowerShell talk to the FSDNUG group. So, I’ll just link to the zip of the presentation from that talk.

The primary slide that I added to my presentation was entirely related to a StackOverflow question entitled, “how do you use PowerShell.”

I felt that the talk went fairly well, but I did have to rush towards the end because I added an overview of some real scripts that I use, but I didn’t remove enough of my prior content… thus, the rush. :-)  No big deal, though. I did get the feeling that there were a few people who didn’t really feel that PowerShell applied to them, but hey, that’s fine. At least there weren’t any tomatoes!

I’ll be presenting one more time (as far as I know) this year at Harding University. I’m looking forward to it, too. I’ll be presenting for the Computing Seminar on October 9. The last time I spoke before Seminar was in 2003 when I talked about “Smart Client Software.” That was when it was for college credit! I’m planning on changing the talk up a little to direct it more towards CS students instead of professional developers. I imagine it will be a slightly different audience than the typical .NET User Group, too. We’ll see.

Back on the MNUG talk, thanks to Randy for driving and thanks to Colin for inviting me to speak. It was fun!

posted on Tuesday, September 30, 2008 8:13:41 AM (Central Daylight Time, UTC-05:00)  #    Comments [0]
# Wednesday, September 24, 2008

Colin is risking it I say. How is he risking it you might ask? By asking me to speak to the Memphis .NET User Group!

I think he’s crazy, but whatever.

Randy Walker and I will be traveling to Memphis, TN tomorrow night where I’ll be presenting on PowerShell. Randy is coming out to meet with the founding members of the Northeast Arkansas .NET User Group, which is very cool. Regarding my presentation, it will likely be a similar presentation to what I gave to the FSDNUG group, but I’m hoping to have more script examples. I think I gave the Fort Smith group a good picture of PowerShell, but I don’t think I showed them nearly as many practical uses of PowerShell as I would have liked. I’ve got a folder of scripts now, some that I’ve written for myself and a few that we’re using at work, that I’ll be showing and walking through during the presentation.

If you’re in the area, come on out!

posted on Wednesday, September 24, 2008 1:42:45 PM (Central Daylight Time, UTC-05:00)  #    Comments [0]
# Monday, September 08, 2008

Tonight, I presented on PowerShell to the Fort Smith .NET User Group. It was my first presentation/speech since college! Fortunately, it seems to have gone over well and I think I helped drive some interest in PowerShell. Here are my slides and other relevant links for any of those who attended.

PowerShell Homepage and Download

PowerShell Blog

PowerShell Community Extensions

PowerTab

Start-Demo script that I used to automate some of the demos

Many thanks to Chris Green for allowing me to use some of the content from the presentation that he shared at Tech Ed 2007 Australia. Thanks also to Ben Pearce for his great PowerShell cheat sheet. Final thanks to Michael Paladino for helping me with a run-through of my presentation ahead of time.

I've zipped up my PowerPoint presentation along with my demo.txt (to go along with the Start-Demo script), the source for my PipelineDemo program, and my custom ps1xml file. You can get the zip with the presentation contents here. The PowerPoint presentation has a lot of relevant links that I didn't explicitly post here.

I hope everyone enjoyed the talk! I enjoyed giving it!

Let me know if you have any comments on ways that I could improve.

posted on Monday, September 08, 2008 10:27:38 PM (Central Daylight Time, UTC-05:00)  #    Comments [3]