Minimum Code First Setup

This is the absolute minimum you need to get started with Code-First.

Before I start I assume you have Visual Studio, are familiar with NuGet and have access to some version of SQL Server.

First use NuGet to install EntityFramework. Now you need 2 classes to get started. One to represent the database and the other to represent your table:

[Read more…]

Inline IL in C#

One of the features I liked in C++ was the ability to include inline assembly. Granted I never found much practical use for it but it was a great way to learn assembly without having to write a whole application in it.

Well a very clever Canadian by the name of Roy has now made that possible in C# and VB.NET. Not only is it a great feature but the way he implemented it is very clever and can be applied to do your own IL manipulation of your binaries.

Basically Roy uses the existing Visual Studio tools ildasm and ilasm to decompile your binary into IL, insert your IL code blocks, and recompile the result.

You specify your IL by enclosing it inside an #if directive, like so:

public static int Add(int n, int n2) {
#if IL
    ldarg n
    ldarg n2
    add
    ret
#endif
    return 0; // place holder so method compiles
}

Adding this feature to your project is as simple as adding a post-build step. You can find the whole article here: http://www.codeproject.com/Articles/438868/Inline-MSIL-in-Csharp-VB-NET-and-Generic-Pointers

Invoke base method using reflection

I came across this problem when I was writing a proxy library. I wanted to invoke the method of the base class but was instead invoking the overriden version. I was able to find the answer on Stack Overflow. Here is the code sample of the problem.

class BaseClass {
    public virtual void Test() { 
        Console.WriteLine("Test() from BaseClass"); 
    }
}

class OverridingClass : BaseClass {
    public override void Test() { 
        Console.WriteLine("Test() from OverridingClass"); 
    }
}

public static void Main() {
    var d = new OverridingClass();
    typeof(BaseClass).GetMethod("Test").Invoke(d, null);
}

[Read more…]