Archive for the “Programming” Category

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:

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 ofcourse, if you compile this, it will work since Option Strict is off.

But when you set it on (or port it to C#) for that matter it won’t compile, since chart.Parent returns a type of Object. And the compiler cannot find the .Parent property on Object.

Too bad. How do we solve this?

One option is: casting:

Option Strict On

Imports Microsoft.VisualBasic

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

        Dim workbook As Excel.Workbook = 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.

So I’ve come up with a solution:

(I will continue in C#):

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

propertyInfo.SetValue(someChart, someValue, BindingFlags.SetProperty, null, null, null);

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.

The final solution is:

GetType(Excel.Chart).InvokeMember("ThePropertyYouWant", BindingFlags.SetProperty, null, someChart, new object[] { someValue });

Guess what, this works.

I spent ages on this.

Comments No Comments »

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.

Comments No Comments »

Can be a hassle, that’s why I’m writing this post for you:

First of all some prerequisites:

  • VMware Workstation 7 (6.5 probably will be the same)
  • A VM, XP / Vista / 7, whatever you want
  • Visual Studio 2008 SP1

Second of all: VMware can be a little cryptic with it’s error messages so stay calm!

We start by having our sample application we want to run on the VM:

<screenshot>

Next we click the wrench tool on the VMware toolbar in Visual Studio:

Click the wrench tool

This opens the following dialog:

Virtual Debugger Configuration Pages

For your convenience I highlighted the settings you need to change.

The following order is not the order in the window, but the order that seems the most understandable in my opinion:

Virtual Machine: The VM you want to debug into, just select a suitable vmx.

Remote Debug Monitor Path: The path to Remote Debugger folder on the host computer NOT on the guest! So for 32-bit debugging that would be:

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\x86\msvsmon.exe

Replace x86 with x64 if you require 64-bit debugging.

Shared Folders: This one is not used

Guest Command: The command to be executed on the guest to start the application. This one was quite the hassle for me. If you leave it on the standard it will result in the following (cryptic) error:

A valid executable name has not been specified in Debugger settings. You can change this in Project > Properties > Debugging.

So instead of leaving it on default you enter this;

\\vmware-host\Shared Folders\test\application.exe

Please replace application.exe to the name of your executable!

The last item, Guest Logon Credentials, is the easiest. This should be the username and password you use to log in to the VM.

Next up is setting the shared folder between the guest and the host.

While I tried this with the Shared Folder Item in the window we just filled in, I just can’t seem to get it to work. So I bypassed this.

Go to the settings of the VM (in VMware Workstation –> VM –> Settings (CTRL+D)):

image 

On the second tab, you take shared folders, and click add (as pointed on the picture).

On the wizard I would suggest opening the shared folder in the debug folder of your application and name the shared folder ‘test’

image

Enable the share in the following window, and make it read-write.

Now we can start the debugging from Visual Studio. The application will then be started through the shared folder we just created.

Comments 1 Comment »

Someone pointed me at System.Net.NetworkInformation, which has a lot of interesting objects.

You don’t have to use strings and query the WMI at runtime, which means you get compile time checking!

using System;
using System.Net;
using System.Net.NetworkInformation;

namespace WMITest
{
    internal class Program
    {
        public static int Main(string[] args)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();

                foreach (IPAddress dnsServer in properties.DnsAddresses)
                {
                    Console.WriteLine("{0} ", dnsServer);
                }

                Console.WriteLine("----------------------");
            }

            Console.ReadLine();
            return 0;
        }
    }
}

Hope it helps :)

Comments No Comments »

Ever had this error?

changes to 64-bit applications are not allowed

changes to 64-bit applications are not allowed

This occurs on 64-bit machines when trying to do Edit and Continue (a feature of the .NET CLR) on a 64-bit application.

It’s only available on 32-bit applications.

Now it’s up to the reader to determine if he needs a 64-bit application. 95% of the time the answer will be no.

So for those people I present the solution:

image

It’s quite simple. Go to properties, build and set the platform target to x86. And you’re ready to go Edit and Continue.

Please do read this about Edit and Continue.

Comments No Comments »

Today I experienced the following issue:

I had a class where I would open a SqlConnection, do some actions, and then in the deconstructor I closed the SqlConnection.

~Dumper()
{
    this._sqlConnection.Close();
}

Unfortunately every time my program ran it stopped with this error:

image

Internal .Net Framework Data Provider error 1.

(click to enlarge)

Well it seems that you cannot close a SqlConnection in a ~Deconstructor block.

So the solution is implementing the IDisposable interface

internal class Dumper : IDisposable
{
    private readonly SqlConnection _sqlConnection;

    public Dumper()
    {
        //build and open the connection
        this._sqlConnection = new SqlConnection(Settings.Default.ConnectionString);
        this._sqlConnection.Open();
    }

    /// <summary>
    /// Some function
    /// </summary>
    /// <param name="param">param</param>
    public void SomeFunction(SomeParameter param)
    {
    }

    public void Dispose()
    {
        this._sqlConnection.Close();
    }
}

And to use it you do this:

using (Dumper dumper = new Dumper())
{
    dumper.SomeFunction(myParam);
}

This will cause dumper to be Disposed after the } and it will no longer be available

Comments 1 Comment »

A friend of mine asked me to generate pages from a List<T>. This is my implementation:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Pager
{
    static class Program
    {
        static void Main()
        {
            List<int> list = new List<int>();

            //add 26 items
            for (int x = 0; x < 26; x++)
            {
                list.Add(x);
            }

            //generate pages
            List<int>[] pagesList = Pager<int>(list, 4);

            Console.WriteLine("Please examine pagesList");
            System.Diagnostics.Debugger.Break();

        }

        /// <summary>
        /// Converts a collection of T to an array of pages
        /// </summary>
        /// <typeparam name="T">The type of items in the list, can be inferred most of the time</typeparam>
        /// <param name="list">The list to page</param>
        /// <param name="itemsPerPage">Items per page</param>
        /// <returns>An array of lists, pages if you will</returns>
        static List<T>[] Pager<T>(ICollection<T> list, int itemsPerPage)
        {
            int pages = (int)Math.Ceiling((double)list.Count / itemsPerPage);

            List<T>[] pagesList = new List<T>[pages];

            for (int currentPage = 0; currentPage < pages; currentPage++)
            {
                pagesList[currentPage] = list.Skip(currentPage * itemsPerPage).Take(itemsPerPage).ToList();
            }

            return pagesList;
        }
    }
}

Comments No Comments »

Some functions expect an array with a minimum size. While this is generally bad coding sometimes you can’t avoid it (e.g. with csv files).

That’s when this piece of code comes in handy: (it’s an extension method, so it only works on .NET 3.5)

public static class ArrayHelper
{
    /// <summary>
    /// Expands an array to the given <paramref name="size"/>
    /// </summary>
    /// <typeparam name="T">The type of the array (not neccesairy, can be infered).</typeparam>
    /// <param name="array">The array</param>
    /// <param name="size">The size it should become</param>
    /// <returns>The array expanded to the given size</returns>
    public static T[] Expand<T>(this T[] array, int size)
    {
        if (size < array.Length)
        {
            throw new ArgumentException("size < array.Length, this will cause data to be truncated, canceling", "size");
        }

        T[] list = new T[size];

        for (int index = 0; index < array.Length; index++)
        {
            list[index] = array[index];
        }

        return list;
    }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        string[] array = new string[] { "test1", "test2", "test3" };

        //array1 has a length of 3
        Console.WriteLine("array.Length = {0}", array.Length); 

        array = array.Expand<string>(10);

        //now array has a length of 10
        Console.WriteLine("array.Length = {0}", array.Length);

        Console.ReadLine();
    }
}

Enjoy :)

Comments No Comments »

This is something I’ve been thinking about a lot. When do I throw an exception? Do I program with exceptions? Do I catch those exceptions.

Consider this piece of code:

public Product GetProduct(int id)
{
    //get the product, or null if not found
    Product p = //...

    return p;
}

Now you can ask yourself the following question:

Is it ok to return null if the product is not found? After all, the calling layer assumes that we’ll be getting a Product, not a null.

So now the calling layer needs to check if the product != null.

It would be exceptional if no product was found.

So in my opinion you throw an exception if no product is found. And that get’s handled in the calling layer.

But on the other hand: if you would just return a null and test on that in the calling layer you would use less resources since exception throwing is expensive.

I’d still go with the first one since it goes better with my consume code thoughts.

But this is an agreement you need to make across your team, and across your API.

Comments 2 Comments »

Something not many people know: when you need to compare 2 strings in C#.NET you can use the == operator overload:

if(firstString == secondString)
{
    //...
}

This is case sensitive. But when you need to ignore the case please don’t use this:

if(firstString.ToLower() == secondString.ToLower())
{
    //...
}

or this:

if(firstString.ToLower().Equals(secondString.ToLower()))
{
    //...
}

A Framework provides you with utilities, please use them. They are usually better than your implementation!

Use this:

if (firstString.Equals(secondString, StringComparison.OrdinalIgnoreCase))
{
    //...
}

StringComparison is an enum. So please look at the options :)

Comments 1 Comment »

And shepherds we shall be, for thee my Lord for thee, power hath descended forth from thy hand, that our feet may swiftly carry out thy command. We shall flow a river forth to thee, and teeming with souls shall it ever be. In nomine Patris, et Filii, et Spiritus Sancti.