x86 .Net Assembly, Scala, and a x64 processor. Oh My!

While playing around with Scala.Net today I ran into an interesting problem. I was trying to build some Scala code against an assembly built for x86 and I got an exception when I ran the executable:

Unhandled Exception: System.BadImageFormatException: Could not load file or assembly […]. An attempt was made to load a program with an incorrect format…

After a bunch of internet searches, and some help from Bill Wagner, I got this working. The executable needs to be set to run in 32 bit mode. This can be done with the corflags tool. corflags will exist in your path from a Visual Studio terminal. The trick is:

corflags <Executable name> /32Bit+

After that everything worked.

Posted in .Net, Scala | Comments Off on x86 .Net Assembly, Scala, and a x64 processor. Oh My!

Calling Scala from C#

Yesterday, I figured out how to call some C# code from Scala. It is a small leap to then call Scala from C#. The process just gets turned around: instead of creating a C# class library and referencing it from Scala, you create a dll from Scala code and reference it in .Net.

First, I built a class in Scala similar to my C# class from yesterday:

class ScalaSpeaker {

    def Speak() {

        println("Hello");

    }

    

    def Speak(name: String) {

        println("Hi, " + name + ", glad you could join us!")

    }

}

Just like before, the Scala needs to be compiled to MSIL. There are fewer arguments needed because the Scala is not referencing any other dlls and does not contain the entry point for the executable:

<Scala.Net directory>\bin\scalacompiler.exe

–target:msil

–Xassem-extdirs <Scala.Net directory>\bin

<scala files>

Where:

  • <Scala.Net directory> is the directory where the Scala.Net SVN repository was checked out to

After the MSIL has been generated, it can be turned into a dll:

ilasm /DLL <MSIL file>

Notice the /DLL flag for ilasm, this is where the magic happens.

After running ilasm, the new Scala dll can be referenced in a .Net application. I created a console application and added a reference to the dll. For the application to run propertly there are a few more dlls that need to be referenced, all of which can be found in the bin directory of the SVN repository:

CSharpFilesForBootstrap.dll

IKVM.OpenJDK.Core.dll

jfisl.dll

scalalib.dll

scalaruntime.dll

The C# is very straight forward, and surprisingly doesn’t require any extra using statements:

using System;

namespace CallScala

{

    class Program

    {

        static void Main(string[] args)

        {

            var speaker = new ScalaSpeaker();

            speaker.Speak();

            speaker.Speak("Jim");

        }

    }

}

Posted in .Net, C#, Scala | 3 Comments

Getting Started with Scala.Net

Reporting from the Programming Summer Camp in Crested Butte, Colorado. This has got to be one of the better places in the world to code. We had a great warm up bike ride this morning, then settled in for an afternoon of coding. I spent my time figuring out Scala.Net with the goal of calling some C# code from Scala.

The Scala.net compiler is in an SVN repository located at: http://lampsvn.epfl.ch/svn-repos/scala/scala-experimental/trunk/bootstrap

I started by writing a small C# class library. I created one class with a couple of methods. This is pretty standard “getting up to speed” stuff:

using System;

 

namespace Echidna

 

{

 

    public class Speaker

 

    {

 

        public void Speak()

 

        {

 

            Console.WriteLine("Hi there.");

 

        }

 


 

        public void Speak(string name)

 

        {

 

            Console.WriteLine(string.Format("Hi, {0}, glad you could join us.", name));

 

        }

 

    }

 

}

 

Next, I dove into the Scala. For this experiment all I needed was an object whose Main created an instances of my C# class and called its methods:

import Echidna.Speaker

 


 

object Test {

 

    def main(args: Array[String]) {

 

        val speaker = new Speaker()

 


 

        speaker.Speak

 

        speaker.Speak("Joe")

 

    }

 

}

 

I’d like to note here that the import is a Scala import statement (not a C# include), so the class name needs to be included. I could also have written “import Echidna._” to get everything from the Echidna namespace. The compiler error did not make it especially obvious that I had messed this up.

With all my code built I could start compiling. Currently, there are two steps to create an executable, but there are plans to get rid of the second step. First, MSIL is created using the Scala.Net compiler:

<Scala.Net directory>\bin\scalacompiler.exe

-target:msil

-Xassem-extdirs <Scala.Net directory>\bin

-Xshow-class <Scala entry class>

-Xassem-path <Dependent Assemblies>
<Scala files>

This is the bare minimum required to compile the Scala into MSIL. I inserted the new lines for ease of reading and to make it more obvious what is going on. Notes:

  • <Scala.Net directory> should be the directory that you pulled the SVN repository into
  • <Scala entry class> is the Scala class that should serve as the entry point for your program. In my case it was “Test”
  • <Dependent Assemblies> are the .Net assemblies your Scala program relies on. In my case this was “Echidna.dll”
  • <Scala files> are your Scala source files. In my case it was “simple.scala”

Next, the MSIL needs to be turned into an executable using ilasm. I opened a Visual Studio command prompt so that ilasm was in my Path:

ilasm Test.msil

The last problem I ran into was that the executable couldn’t find scalalib.dll, so I copied it out of the directory where the compiler is (the same as <Scala.Net directory>.) After this, my executable ran perfectly.

More information on the compiler and it’s capabilities (for example, it does not currently support .Net generics) can be found at: http://lamp.epfl.ch/~magarcia/ScalaNET/2011Q2/PreviewScalaNET.pdf

Posted in .Net, Scala | Comments Off on Getting Started with Scala.Net

Kinect: Getting Started

Microsoft released its Kinect SDK yesterday. It can be found here. I spent yesterday afternoon building my own sample application to explore the API and Microsoft’s samples.

The API documentation is fairly comprehensive and the getting started guide is a quick read (on the Kinect SDK website, not included in the download). The two samples are large and cover all the major points of the API. I think I would have preferred smaller, more targeted samples, but they are still good for figuring out how to use pieces of the API.

The Kinect hardware does quite a bit of processing, so the API is fairly easy to work with. Pulling color image data off of the device is almost trivial:

var kinect = new Runtime();

kinect.Initialize(RuntimeOptions.UseColor);

 

kinect.VideoStream.Open(ImageStreamType.Video,

   2, ImageResolution.Resolution640x480, ImageType.Color);

 

kinect.VideoFrameReady += HandleNewColorVideoFrame;

This is all the code needed to start receiving video from the Kinect. Every time there is a new frame available the “HandleNewColorVideoFrame” method will get called. The EventArgs has a property that contains the image data of the new frame.

The really revolutionary part of the Kinect is the depth map it provides of the scene it can see. For each frame of the depth map video it can create detailed skeletal information about two people in the scene. This skeletal information gives the (X, Y, Z) absolute position of 20 points on the body and the confidence of that absolute position. The confidence is mostly for points that the Kinect cannot directly see. For example, the Kinect will still try to track my hand if I put it behind my back. It is just as easy to get the skeletal data as it is to get the color video image:

kinect = new Runtime();

kinect.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | 

   RuntimeOptions.UseSkeletalTracking);

 

kinect.DepthStream.Open(ImageStreamType.Depth, 2,

  ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);

 

kinect.SkeletonFrameReady += ProcessSkeletonFrame;

ProcessSkeletonFrame will be called every time the Depth video has a new frame. The EventArgs contains a list of all of the skeletons the Kinect has information about.

This is all the code you need to get up and running with a Kinect. It’s pretty awesome that it takes so little to start working with it; however, working with it is by no means easy. There are a lot of considerations that need to be made to make the Kinect a good user experience. In my next post I will go over a couple gotchas that I encountered while building my sample.

Posted in .Net, Kinect | Comments Off on Kinect: Getting Started

Git Immersion

So far in my time at SRT I have used both Mercurial and Bazaar, but I hadn’t gotten around to Git until yesterday. I finished the Git Immersion tutorial by Jim Weirich and would highly suggest going through it. There is a lot of good information in the lessons, even for those of us who are familiar with other distributed version control systems.

I think Git’s idea of tracking changes instead of files is a really cool way to think about source control. Change tracking instead of file tracking allows us to create much more granular commits, giving even more control over multiple versions of our source.

However, I think the way this is implemented in Git makes using it a bit more of a burden. Needing to add each change to a staging area does not feel like  Git “getting out of the way until you need to deal with source control”. I have to either be constantly adding changes to my source control as I make them, or I have to figure out how everything should be committed after I’ve written the code. It also means that every time I want to add changes to source control I have an additional step to take over a more “traditional” source control system. I would much rather see an “opt-out” model of change tracking than an “opt-in” model. Most of the time, all of my changes should be taken together as a single commit. When I do have changes that should be separated into their own commit they are in the minority of the changes that I have made.

Currently, Git has not convinced me to convert from Mercurial, especially since I currently have a few repositories on BitBucket, but I think it is very worth while to know all of the options out there.

Posted in Uncategorized | Comments Off on Git Immersion

Silverlight follow-up: WPF memory leak

In my last post, I wrote about a memory leak that is easy to come by in WPF. I converted the WPF test application I was using to Silverlight to see whether or not Silverlight suffers from the same memory leak.

Turns out it doesn’t! Classes get disposed just as you would expect them to. It’s nice that at least one of these platforms doesn’t have this bug, but I think it’s too bad that we can’t expect consistency between WPF and Silverlight.

Posted in Silverlight, WPF | Comments Off on Silverlight follow-up: WPF memory leak

WPF Gotcha: Easy Memory Leak

I strongly suggest that you implement INotifyPropertyChanged on any class that will be a binding source. I’ve been doing some memory profiling recently and ran into a HashTable outside of my code that was holding on to a reference to one of my view models. Here is Microsoft’s listing on the leak.

The basic idea is that when the source of a binding is a(non-Dependency) property on a class that does not implement INotifyPropertyChanged, WPF creates a ReflectPropertyDescriptor to facilitate the binding. The Microsoft page seems to suggest that this should allow for updating the binding value when the backing property changes, but this doesn’t actually work. The ReflectPropertyDescriptor gets added to a global table and does not get removed, creating a memory leak.

At first glance, it looks like your view model needs to have a reference to the View because of the second condition:

Object X contains a direct reference or an indirect reference to the target of the data-binding operation.

Later there is a note that says that the binding can cause this “indirect reference” to the view:

The reference between object X and the data-binding target is caused by the first condition that is listed in the "Cause" section.

I have created a simple test bed application that shows the problem. Setting a break point in the Finalizer of ViewModelOne shows the memory leak. When INotifyPropertyChanged is not implemented, the Finalizer never gets called. Adding the implementation of INotifyPropertyChanged allows the Finalizer to get called.

The take-away? Make sure you implement INotifyPropertyChanged on view models. Microsoft calls this behavior “by design”. It sounds an awful lot like a bug to me.

Posted in WPF | Comments Off on WPF Gotcha: Easy Memory Leak

Bindable DataGrid Columns

Currently the WPF DataGrid supports two ways in which to generate columns: AutoGenerate and XAML declaration. AutoGenerating columns will produce a column for every property in the ItemsSource class, but the behavior can be altered by using the AutoGeneratingColumn event on DataGrid. Instead of autogenerating columns, they can be declared and bound in XAML.

This was not enough for me. I want to be able to bind to a list in my view model that represents the columns I want to show. I also wanted my columns to use the items in this list as a DataContext so that I could have a column header with interesting behavior. For example, each column could have a context menu with a unique DataContext. To this end I wrote some code so that a DataGrid can be declared like:

<DataGrid 
     t:DataGridColumns.DisplayColumns="{Binding Columns}"
     ItemsSource="{Binding Rows}"
     AutoGenerateColumns="False">
  <t:DataGridColumns.ColumnSettingsTemplate>
    <DataTemplate>
      <t:DataGridColumnSettings 
          ColumnBindingPath="{Binding ColumnPath}">
        <t:DataGridColumnSettings.Header>
          <TextBlock Text="{Binding Header}"/>
        </t:DataGridColumnSettings.Header>
      </t:DataGridColumnSettings>
    </DataTemplate>
  </this:DataGridColumns.ColumnSettingsTemplate>
</DataGrid>

Each item in the Columns list is bound to a DataGridColumnSettings. In this example, the column Header is set to a TextBlock. This can be used to customize the column headers. The items in the DisplayColumn list become the DataContext for the column headers. If the Header just needs to be text, the DataGridColumnSettings can simply be declared like:

<t:DataGridColumnSettings 
         ColumnBindingPath="{Binding ColumnPath}"
         Header="{Binding Header}"/>

Currently this will only create DataGridTextColumns, but it could be extended to create DataGridComboBoxColumns and DataGridCheckBoxColumn. Get the code here. Leave the copyright on it if you want to use it.

Posted in C#, WPF | 6 Comments

Ribbon Tab Definition on UserControl

We’ve been using the Ribbon control provided by Microsoft on a project I’ve been working on. We started with the WPF toolkit Ribbon but recently upgraded to the .Net 4.0 version. The 4.0 version is much better than the WPF Toolkit version, and I would suggest using it.

Some of our views have specific commands available while they are active so we initially created contextual tabs to associate with these views. The contextual tabs were defined in the main RibbonWindow’s XAML:

<r:Ribbon>
  <r:Ribbon.ContextualTabGroups>
    <r:RibbonContextualTabGroup Header="Tab 1"
             Visibility="{Binding TabOneVisible}"/>
    <r:RibbonContextualTabGroup Header="Tab 2"
             Visibility="{Binding TabTwoVisible}"/>
  </r:Ribbon.ContextualTabGroups>
  <r:RibbonTab ContextualTabGroupHeader="Tab 1">
    <r:RibbonGroup Name="Clusters">
      <r:RibbonButton Label="Button"
             Command="{Binding ButtonOneCommand"/>
      <r:RibbonButton Label="Button"
             Command="{Binding ButtonTwoCommand"/>
    </r:RibbonGroup>
  </r:RibbonTab>
  <r:RibbonTab ContextualTabGroupHeader="Tab 2">
    <r:RibbonGroup Name="Clusters">
      <r:RibbonButton Label="Button"
             Command="{Binding ButtonThreeCommand"/>
    </r:RibbonGroup>
  </r:RibbonTab>
</r:Ribbon>

I have multiple problems with this approach. First, it requires the main view to know what actions are available for each sub-view and declare buttons for each of these actions. Additionally, command binding is not quite as elegant as it could be; either chain binding is required, or the main view model must define all the commands. For the chain binding to work, the main view model needs a references to every sub-view model, which should not be necessary.

What I really wanted was for each sub-view to be responsible for defining the actions that can be taken when it is visible. To this end I created a couple of Attached Properties on UserControl. The RibbonTab definitions are moved into the UserControl XAML:

<UserControl
   a:UserControlRibbon.RibbonTab="{DynamicResource Tab}"
   a:UserControlRibbon.RibbonTabDataContext="{Binding}">
  <UserControl.Resources>
    <r:RibbonTab x:Key="Tab"
         Header="Control Tab">
      <r:RibbonGroup>
        <r:RibbonButton Label="Button"
            Command="{Binding ButtonCommand}"/>
      </r:RibbonGroup>
    </r:RibbonTab>
  </UserControl.Resources>
</UserControl>

There are some ways in which this could be better, but I think this provides a much better way for the ribbon to be put together. I had thought about creating a RibbonUserControl similar to RibbonWindow. The RibbonUserControl would have the RibbonTab property, which would move the tab out of the resources and eliminate the two assignments in the UserControl declaration.

Get the code. Feel free to use it, just include the copyright.

Posted in srt, WPF | 9 Comments

WPF – Combo Box SelectedItem Binding

I recently was debugging a strange issue we were seeing with our combo boxes. When the data context changed, the combo box would lose the selected item and appear blank but the list of possible selections would be correct.

I ran across this blog post by Philipp Sumi and thought it deserved more attention. Basically, the order in which you set up your bindings in XAML matters. With a combo box, if you define the ItemsSource binding before the SelectedItem binding, every time the data context changes the SelectedItem on the old data context will get set to null.

Switching these bindings around in the XAML so that the SelectedItem gets bound first and then the ItemsSource fixes both of the issues I was seeing.

Philipp says that this feels like a dirty hack to him, but it feels like a bug in WPF to me.

Posted in srt, WPF | Comments Off on WPF – Combo Box SelectedItem Binding