Techdays 2010, day 2

It’s over :( And I wrote this post too late.

Day 2 was good. Interesting sessions about the CLR (Bart De Smet) and about MEF (I forgot the guy’s name but he was hilarious).

Now for me this means more programming in the future. I really thing I made my job out of my hobby.

And lastly: nerd dinner! With a hole bunch of people!

Kristof Mattei and Scott Hanselman

Me and Scott Hanselman :D

Techdays 2010, day 1

Alright, my boss allowed me to go to the Techdays 2010 in Belgium :D . And day 1 was good! Very good actually.

I went to the following sessions:

The keynote (wasn’t that interesting, more of an introduction!).

Next session was about Silverlight 4 tour de force with a little WPF 4 on top. Nicely presented, good show, bottom line: unless you need WPF specific features use Silverlight. Why? Easier to deploy and Silverlight encourages to use Service based architecture.

Next up was C# 4.0 and beyond. While the future looks good, and dynamic sure has it’s powers with COM interop I feel like it’s a step back (no intellisense on those objects e.g.). I don’t know why but I’ve always liked the compiler time checking of static languages. But interop with Javascript sure is nice, as is with COM. But you have to find the right balance.

Compiler as a service on the other hand (compared to PHP’s eval (read: evil) is horrible. I already can see code written by beginners (I’m a beginner too, but I’ve seen so much PHP code with eval that I don’t like the language at all anymore…). So I really hope that this feature stays well hidden.

After that I went to EF in .NET 4.0. That was awesome. It really showed the power of EF, so I have a good start to dig into it (I don’t know why, but I like it A LOT).

Application Mangement with Visual Studio 2010 was next on my schedule. Merging, reports, installing TFS 2010 basic… All a breeze. Nothing much to tell about this, will post more when I have Visual Studio 2010.

Lastly: Test Driven Development in 2010. (don’t know why in 2010, it works the same in 2008…). it was good, but it cumbersome to start a project like that.

Now for a coffee and some surfing. First session today starts at 0900, so I need some coffee before that!

-Kristof

Android: delete Amazon MP3

First of all, you need root. I use CyanogenMod on my Nexus One.

To delete the application you hook up the shell:

adb shell
#cd /data/app
#rm com.amazon.mp3.apk

This removes the application but does not remove the system reference.

When you go to Settings > Applications > Manage applications you still will see com.amazon.mp3

To remove that system reference do this:

abd shell
#pm uninstall com.amazon.mp3

Hope it helps.

-Kristof

C# to VB.NET, && and And and AndAlso

There is a difference in operators when a C# developer has to do VB.NET

For example: && vs And.

THEY ARE NOT THE SAME. The && equivalent in VB.NET is AndAlso

If you do this:

Sub Main()
    Dim result = Part1() And Part2()

    Console.ReadLine()
End Sub

Function Part1() As Boolean
    Console.WriteLine("Part 1")
    Return False
End Function

Function Part2() As Boolean
    Console.WriteLine("Part 2")
    Return True
End Function

What do you think it prints?

If And would behave like && in C# it would print

Part 1

But unfortunately BASIC is different (sigh), it prints

Part 1

Part 2

This can be solved by using AndAlso, which is the short circuited version of And.

Entity Framework 4.0 improvements

I’ve been a huge fan of LINQ to SQL. But EF 3.5 (first release) didn’t quite do it for me. I didn’t like the lack of support for foreign keys, no Single() LINQ support,

No Single support

An example of lack of foreign keys:

using(NorthwindEntities northwindEntities = new NorthwindEntities())
{
    Product p = new Product()
                {
                    Category = northwindEntities.Categories.Where(c => c.CategoryID == 1).First,
                    ProductName = "French fries",
                    UnitPrice = 20,
                    Discontinued = false,
                    QuantityPerUnit = "1 kg bag",
                    Supplier = northwindEntities.Suppliers.Where(s => s.SupplierID == 1).First

                };

    northwindEntities.AddToProducts(p);
    northwindEntities.SaveChanges();
}

As you can see you need to fetch  the category and the Supplier seperatly. You can’t just do CategoryID = 1

But when we launch the wizard for EF 4.0 we get this:

Include foreign key columns in the model

Which results in this:

using(NorthwindEntities northwindEntities = new NorthwindEntities())
{
    Product p = new Product()
                {
                    CategoryID = 1,
                    ProductName = "French fries",
                    UnitPrice = 20,
                    Discontinued = false,
                    QuantityPerUnit = "1 kg bag",
                    SupplierID = 1

                };

    northwindEntities.AddToProducts(p);
    northwindEntities.SaveChanges();
}

And there is Single support!

using(NorthwindEntities ne = new NorthwindEntities())
{
    var result = ne.Suppliers.Where(sup => sup.SupplierID == 1).Single();
}

So it just got a little more mature.

I’m hoping to be able to test it (and use it!) more in the future and new projects :)

Hope it helps

-Kristof

VB.NET: getting rid of With statements

Because With clutters your code, you get too much indentations and it removes readability. Now I saw code with 4 to 5 times nested With statements. Pure Horror. So my first job was to remove all these statements. But what if you get ambiguous Methods/Properties?

The documentation is clear on that:

However, because members of outer statements are masked inside the inner statements, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.

This means that in an inner with block you cannot access the members of the outer with block with the . qualified name. You need the full qualified name.

So when you need to de-with your code you start from the outside, taking the most outer block first, solving the references, building, removing the next one, and so on…

But you shouldn’t use With statements in the first place.

Just name your variable if you don’t want to enter the fully qualified name for every statement.

VB.NET, why I don’t like it

A little introduction: I’m working on some legacy VB.NET & Excel project. Pretty old stuff, quite the challenge of getting through the code. I’ve discovered multiple things about VB.NET which I didn’t knew (like the Microsoft.VisualBasic namespace, late binding, Option Strict).

The code I’m working with is cluttered with these kinds of abominations to the .NET framework. The Microsoft.VisualBasic is purely there for legacy VBA developers so that they can easily transfer to VB.NET.

But that doesn’t mean you need to use it in new projects (vbNullString? C’mon…)

I think that this namespace shouldn’t be offered by default anymore in new VB.NET projects. It should be there to merely quickly convert old VBA projects to .NET.

Late binding is another thing which I truly hate. It gets compiled to a bunch of reflection calls which make your code more error prone (no compiler checking!). Although I’ve managed to cast the System.__ComObject to it’s corresponding interface most of the time I had to resort to reflection one time myself (shame shame).

And finally there is this problem of cluttered code, for some reason, when I look at VB.NET code there is SO much text and all the essence get’s lost! While the C# code is so clean.

I will write a post about cleaning up With statements + best practices for nested With Statements from VB.NET code pretty soon.

Multi-Column ListView

Ever wanted to have a multi column ListView in WPF? It’s not that hard once you get to know WPF.

We take a ListView and set the ItemsPanel to UniformGrid:

<Window x:Class="ColumnTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <ListView x:Name="MyList">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="3" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Window>

 

And the backend code:

using System.Windows;

namespace ColumnTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();

            for (int x = 0; x <= 100; x++)
            {
                this.MyList.Items.Add(x);
            }
        }
    }
}

 

Which results in:

Uniform Grid Result

C# Late binding,

Today I was working on a project in VB.NET, which I had to convert to C#.

The problem was that they used late binding, they knew that some properties on objects existed, but they couldn’t be deduced by the compiler since the object’s type was Object.

For Example, let’s say we want to get the workbook of a chart.

A chart resides in a ChartObject (the chart.Parent) and a ChartObject resides in a Worksheet.

So chart.Parent.Parent returns the corresponding worksheet.

Like this:

Option Strict Off

Imports Microsoft.VisualBasic

Public Class TestClass
    Public Sub Test()
        Dim chart As Excel.ChartObject

        Dim workbook = chart.Parent.Parent
    End Sub

End Class

Now of course, if you compile this, it will work since Option Strict is off.

But when you set it on (or port it to C#) it won’t compile, since chart.Parent returns a type of Object. And the compiler cannot find the .Parent property on that Object, so we would need to cast to ChartArea to get the .Parent property appropriately, and then cast this result to an Excel.Worksheet.

Option Strict On

Imports Microsoft.VisualBasic

Public Class TestClass
    Public Sub Test()
        Dim chart As Excel.ChartObject

        Dim workbook As Excel.WorkSheet = CType(CType(chart.Parent, Excel.Worksheet).Parent, Excel.Workbook)
    End Sub

End Class

This will work.

Unfortunately sometimes there are properties you can set, but they don’t appear in your Intellisense, so you can’t get/set that property.

If you are using VB.NET with Option Strict Off this is no problem, but again: with Option Strict On or in C# it IS a problem.

Since the late binding internally uses Reflection I thought might fetch the PropertyInfo for that particular property and set it that way:

Dim propertyInfo As PropertyInfo = GetType(Excel.Chart).GetProperty("ThePropertyYouWant")

propertyInfo.SetValue(someChart, someValue, BindingFlags.SetProperty, Nothing, Nothing, Nothing)

This won’t work either, since the compiler cannot find the PropertyInfo of that property, it just doesn’t exist. You will get a NullReferenceException. You can only set it at runtime.

The solution is:

GetType(Excel.Chart).InvokeMember("ThePropertyYouWant", BindingFlags.SetProperty, Nothing, someChart, New Object() {someValue})

This way you just say to the runtime: set that value on that property, don’t try to read the metadata first!

Windows Azure SDK: connecting to non SQLExpress Instance

When you want to build an Azure application, but you don’t have SQL Express installed the build action in Visual Studio will fail.

You will receive the following message in your output window:

Windows Azure Tools: Failed to initialize the Development Storage service. Unable to start Development Storage. Failed to start Development Storage: the SQL Server instance ‘localhost\SQLExpress’ could not be found. Please configure the SQL Server instance for Development Storage using the ‘DSInit’ utility in the Windows Azure SDK.

To fix this you open the Windows Azure SDK Command Prompt:

Windows Azure SDK Command Prompt

And enter the following text:

dsinit /sqlinstance:.

dsinit /sqlinstance:.

This will cause Azure to use the default instance (with no name). You can switch this to whatever you like, just replace the . (dot) by the appropriate MS SQL instance.

The result will look like this:

Development Storage Initialization

Good luck, happy coding.