Silverlight 4 debugging and Firefox 3.6.4+

I’ve been stuck on this for a few days.

At the moment, Firefox 3.6.4 (and newer) have a new functionality called ‘Crash protection’, which is quite nice.

For customers.

It now runs the plugins in a separate process called ‘plugin-container.exe’ (look in your task manager).

Task manager plugin-container.exe

But for developers it’s quite the hassle, since Visual Studio attaches itself to Firefox but NOT to this process. So no more Silverlight debugging for you!

Luckily there are two options for you!

The first option is the most straight forward, but has to be done each time. Use Visual Studio to attach itself to plugin-container.exe, refresh the website, and BAM, you’re up and running!

Attach to Process

On the next screen click ‘plugin-container.exe’. There might be 2, if so, select the one with ‘Silverlight’ in the ‘Type’ column:

Attach to Process Window

And hit ‘Attach’.

While this solution is adequate for when you need to debug it one time at a day, but for me, I only debug in Firefox, and when necessary I use Internet Explorer. For that you can go to your ‘about:config’ in Firefox, disable ‘dom.ipc.plugins.enabled.npctrl.dll’ (set it to false).

Enabling SQL Server 2008 (R2) access over Network

First: enable SQL Server itself to be accessed over the network

  1. Open SQL Server Configuration Manager
  2. Expand SQL Server Network Configuration and click Protocols for MSSQLSERVER
  3. Doubleclick TCP/IP
  4. Set Enabled to Yes

extra info on part one
(click for large size)

Secondly: change the Windows Firewall to allow incoming connections on the TCP port of SQL Server

  1. Open Windows Firewall with Advanced Security
  2. Click on New Rule

firewall explanation
(click for large size)

Now in the wizard you set the type of the rule to Port.

Choose TCP or UDP port

Hit Next.

On the second window you set the Specific local ports to 1433:

Which TCP Port

Hit Next.

Allow the connection.

Allow the connection

Hit Next.

Now enable the checkboxes you want to. I set mine only to Private. Because I only need to access the SQL on my laptop at home:

When does this rule apply?

Hit Next.

New name for the rule

Hit Finish and you’re ready to develop SQL over network :)

Small update on enabling shares in Windows 7.

Execute this line in the CMD as Administrator (start > type ‘cmd’ > hit control+shift+enter) and paste this line (rightmousebutton > paste).

reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\ /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1

Be sure to DISABLE your Homegroup and to enable file sharing in the Network & Sharing Center

VB.NET Casting vs C# casting

Since I’m still working on a VB.NET I start to understand the language more and more. It feels like working with PHP. There are so many hacks, many things happen without you knowing that it happens.

Consider the following classes defined:

class Foo {}
class Bar : Foo
{
    internal static Foo GetInstance()
    {
        return new Bar();
    }
}

In C# you would have:

Console.WriteLine(Bar.GetInstance() as Bar);

the ‘as’ operator tries to cast foo to an instance of Bar. If that doesn’t succeed it returns null.

The code gets compiled to something like this:

{
    Foo __foo = Bar.GetInstance();
    Console.WriteLine(__foo is Bar ? (Bar)__foo : (Bar)null);
}

Doing a cast:

Console.WriteLine((Bar)Bar.GetInstance());

Throws an exception if we cannot cast. So you need to do a try catch around it.

Those are the casting operators in C#.

VB.NET has a little bit more stuff.

I will list them briefly:

CType(obj, Type), DirectCast(obj, Type), TryCast(obj, Type) and some predefined functions like CBool, CStr, Cint.

DirectCast(obj, Type) is the equivalent of the (Type)obj. No problem. TryCast(obj, Type) is the equivalent of obj as Type. No problem either. The problem arrises when we use CType and or one of those predefined functions.

You’d expect CBool(obj) to result in (you cannot do TryCast on a valuetype, hence the DirectCast) DirectCast(obj, Boolean). But no.

Consider the following code:

Dim boolTest As Object = False
Console.WriteLine(CBool(boolTest))

When compiled it gets converted to this:

Dim boolTest As Object
boolTest = CBool(0)
Console.WriteLine(Conversions.ToBoolean(boolTest))

You can take a look at the Conversions class with Reflector. It’s located in the Microsoft.VisualBasic dll (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.VisualBasic.dll) and the full name is Microsoft.VisualBasic.CompilerServices.Conversions.

Reflector Visual Basic

CBool should just try a DirectCast in my opinion.

But CType has some more nuisances. We are still using the Foo and Bar classes defined above.

Consider this code:

Dim foo As Foo = Bar.GetInstance()
Console.WriteLine(CType(foo, Bar))

Gets compiled to:

Dim foo As Foo
Console.WriteLine(DirectCast(Bar.GetInstance, Bar))

Great, it uses DirectCast. So if the conversion fails it throws an exception…

Now the catch:

Dim test As Object = String.Empty
Console.WriteLine(CType(test, String))

You’d EXPECT it to do a DirectCast but no, this is what gets emmited:

Dim test As Object
Console.WriteLine(Conversions.ToString(String.Empty))

Again a roundtrip you don’t see…

That’s why I don’t like VB.NET. Too much happens behind the screens.

I know that you can program VB.NET without all of this (use DirectCast and TryCast yourself). But the problem is that all legacy developers use these functions because they don’t know better.

I wish these features where deprecated and only available for projects converted from VB6 code.

Property setters and side effects

I ran into this little problem last week. I had a class with some properties and they were implemented like this:

class Foo
{
    private int _bar;

    public int Bar
    {
        get
        {
            return this._bar;
        }
        set
        {
            this._bar = value;
            this.DoSomeThing();
        }
    }

    private void DoSomeThing()
    {
        /* blah */
    }
}

Setting the value of Bar to something triggers DoSomeThing, whether the value of _bar is changed or not. (setting _bar to 5 when it is 5 will still trigger DoSomeThing, for example a UI refresh).

You can avoid this by doing this in your property:

class Foo
{
    private int _bar;

    public int Bar
    {
        get
        {
            return this._bar;
        }
        set
        {
            if (this._bar != value)
            {
                this._bar = value;
                DoSomeThing();
            }
        }
    }

    private void DoSomeThing()
    {
        /* blah */
    }
}

This makes sure that you don’t execute the value when the value hasn’t changed.

This occurs in particular in Excel when trying to update the CurrentPageName of a DataField in a PivotTable. I need to check if the value has changed, and then, if it has changed, assign it.

Dispose and Finalizing, done the right way

I created this class to make life a little bit easier for me.

You are free to use it as you wish!

How to use:

Override this class, override ReleaseManaged() and ReleaseUnmanaged() with the appropriate code, and you are good to go.

namespace SuperDisposeImplementation
{
    using System;

    /// <summary>
    /// Override this class for easy releasing of managed and unmanaged code.
    /// </summary>
    /// <remarks>
    /// By Kristof Mattei
    /// Use as you wish
    /// I don't hold the copyright
    /// Combined from code I found everywhere.
    /// </remarks>
    public abstract class SuperDispose : IDisposable
    {
        /// <summary>
        /// True if managed resources are already cleaned up, false if not
        /// </summary>
        private bool _disposed;

        #region IDisposable Members

        /// <summary>
        /// Implementation of IDisposable.Dispose(). Don't make virtual
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        #endregion

        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        /// <param name="disposing">True when called from the Dispose, false when called from the ~. Don't call yourself</param>
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    this.ReleaseManaged();
                }

                // Dispose unmanaged resources.
                this.ReleaseUnmanaged();

                // disposing has been done, make sure we don't dispose the managed ones again.
                this._disposed = true;
            }
        }

        /// <summary>
        /// Override this method, and release unmanaged resources in that method
        /// </summary>
        protected abstract void ReleaseUnmanaged();

        /// <summary>
        /// Override this method, and release managed resources in that method
        /// </summary>
        protected abstract void ReleaseManaged();

        /// <summary>
        /// Use C# destructor syntax for finalization code.
        /// This destructor will run only if the Dispose method
        /// does not get called.
        /// It gives your base class the opportunity to finalize.
        /// Do not provide destructors in types derived from this class.
        /// </summary>
        ~SuperDispose()
        {
            // make sure we don't dispose managed resources, hence the false
            // this is because we can't control the called order of
            this.Dispose(false);
        }
    }
}

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.