Feeds:
Posts
Comments

Archive for the ‘C#4.0 Tips’ Category

As you may know, Windows is virtualizing some parts of the registry under 64 bit.

So if you try to open, for example, this key : “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90”, from a 32 bit C# application running on a 64 bit system, you will be redirected to : “HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\90”

Why ? Because Windows uses the Wow6432Node registry entry to present a separate view of HKEY_LOCAL_MACHINE\SOFTWARE for 32 bit applications that runs on a 64 bit systems.

If you want to explicitly open the 64 bit view of the registry, here is what you have to perform :

You are using VS 2010 and version 4.x of the .NET framework

It’s really simple, all you need to do is, instead of doing :

//Will redirect you to the 32 bit view
RegistryKey sqlsrvKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\90");

do the following :

RegistryKey localMachineX64View = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey sqlsrvKey = localMachineX64View.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\90");

Prior versions of the .NET framework

For the prior versions of the framework, we have to use P/Invoke and call the function RegOpenKeyExW with parameter KEY_WOW64_64KEY

        enum RegWow64Options
        {
            None = 0,
            KEY_WOW64_64KEY = 0x0100,
            KEY_WOW64_32KEY = 0x0200
        }

        enum RegistryRights
        {
            ReadKey = 131097,
            WriteKey = 131078
        }

        /// <summary>
        /// Open a registry key using the Wow64 node instead of the default 32-bit node.
        /// </summary>
        /// <param name="parentKey">Parent key to the key to be opened.</param>
        /// <param name="subKeyName">Name of the key to be opened</param>
        /// <param name="writable">Whether or not this key is writable</param>
        /// <param name="options">32-bit node or 64-bit node</param>
        /// <returns></returns>
        static RegistryKey _openSubKey(RegistryKey parentKey, string subKeyName, bool writable, RegWow64Options options)
        {
            //Sanity check
            if (parentKey == null || _getRegistryKeyHandle(parentKey) == IntPtr.Zero)
            {
                return null;
            }

            //Set rights
            int rights = (int)RegistryRights.ReadKey;
            if (writable)
                rights = (int)RegistryRights.WriteKey;

            //Call the native function >.<
            int subKeyHandle, result = RegOpenKeyEx(_getRegistryKeyHandle(parentKey), subKeyName, 0, rights | (int)options, out subKeyHandle);

            //If we errored, return null
            if (result != 0)
            {
                return null;
            }

            //Get the key represented by the pointer returned by RegOpenKeyEx
            RegistryKey subKey = _pointerToRegistryKey((IntPtr)subKeyHandle, writable, false);
            return subKey;
        }

        /// <summary>
        /// Get a pointer to a registry key.
        /// </summary>
        /// <param name="registryKey">Registry key to obtain the pointer of.</param>
        /// <returns>Pointer to the given registry key.</returns>
        static IntPtr _getRegistryKeyHandle(RegistryKey registryKey)
        {
            //Get the type of the RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the FieldInfo of the 'hkey' member of RegistryKey
            System.Reflection.FieldInfo fieldInfo =
            registryKeyType.GetField("hkey", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //Get the handle held by hkey
            SafeHandle handle = (SafeHandle)fieldInfo.GetValue(registryKey);
            //Get the unsafe handle
            IntPtr dangerousHandle = handle.DangerousGetHandle();
            return dangerousHandle;
        }

        /// <summary>
        /// Get a registry key from a pointer.
        /// </summary>
        /// <param name="hKey">Pointer to the registry key</param>
        /// <param name="writable">Whether or not the key is writable.</param>
        /// <param name="ownsHandle">Whether or not we own the handle.</param>
        /// <returns>Registry key pointed to by the given pointer.</returns>
        static RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
        {
            //Get the BindingFlags for private contructors
            System.Reflection.BindingFlags privateConstructors = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
            //Get the Type for the SafeRegistryHandle
            Type safeRegistryHandleType = typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle");
            //Get the array of types matching the args of the ctor we want
            Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
            privateConstructors, null, safeRegistryHandleCtorTypes, null);
            //Invoke the constructor, getting us a SafeRegistryHandle
            Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });

            //Get the type of a RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the array of types matching the args of the ctor we want
            Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor(
            privateConstructors, null, registryKeyConstructorTypes, null);
            //Invoke the constructor, getting us a RegistryKey
            RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable });
            //return the resulting key
            return resultKey;
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern int RegOpenKeyEx(IntPtr hKey, string subKey, int ulOptions, int samDesired, out int phkResult);

Then we can open our registry key like this :

RegistryKey sqlsrvKey = _openSubKey(Registry.LocalMachine, @"SOFTWARE\Microsoft\Microsoft SQL Server\90", false, RegWow64Options.KEY_WOW64_64KEY);

As you can see, the framework 4 make our life easier 🙂

Read Full Post »

Introduction:

IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.
As a matter of fact every system does not make assumptions about what other systems do or should do, so no side effect when replacing a system by another one.

Let’s have a first example showing classes having strong dependencies between them. Here we have a main class Singer, which let us know the song style and what formation it is.

public class Song
{
  public string GetStyle()
  {
      return "Rock n Roll !";
  }
}

public class LineUp
{
  public string GetFormation()
  {
      return "Trio";
  }
}

public class Singer
{
  Song song;
  LineUp lineUp;

  public Singer()
  {
      song = new Song();
      lineUp = new LineUp();
  }

  public string Sing()
  {
      return "Singer sings " + song.GetStyle() + " and it is a " +  lineUp.GetFormation();
  }
}

here’s the Main method :

Singer singer = new Singer();
Console.WriteLine(singer.Sing());

As result we have : singer sings Rock n Roll ! and it is a Trio
But what would we do if we want to hear another song?? Hearing the same one is good but at the end it could break your tears!!

Implementation of interfaces to replaces instanciate classes (Song, LineUp), and by this way uncoupling main class Singer with the others.

public interface ISong
{
  public string GetStyle();
}

public interface ILineUp
{
  public string GetFormation();
}

public class Song : ISong
{
  public string ISong.GetStyle()
  {
      return "Hip Hop !";
  }
}

public class LineUp : ILineUp
{
  public string ILineUp.GetFormation()
  {
      return "Solo";
  }
}

public class Singer
{
  ISong _isong;
  ILineUp _ilineup;

  public string Singer(ISong is, ILineUp il)
  {
      _isong = is;
      _ilineup = il;
  }

  public string Sing()
  {
      return Singer sings " + _isong.GetStyle() + "it is a " +  _ilineup.GetFormation();
  }
}

here’s the Main method : Now if we want to here another artist, we just have to
instanciate so many class that we want

//Creating dependencies
Song oldsong = new Song();
LineUp oldlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(oldsong,oldlineup);
Console.WriteLine(singer.Sing());

//Creating dependencies
Song newsong = new Song();
LineUp newlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(newsong,newlineup);
Console.WriteLine(singer.Sing());

Thanks for reading !!

Read Full Post »

Introduction:

In the .Net 4.0 we can find a new class Parallel containing many static methods to help us in parallel programing. System.Threading.Parallel provides one For static method which will be the main point of this article.
As a matter of fact at the end of this article you’ll find a link redirecting you in one where we explain you how to implement this static method in C# .Net 2.0!!

Loop For in a C# 2.0 bloc code

public static void MethodWithoutParallel()
{
      List<string>lstInForLoop = new List<string>();
      for(int i =0;<20;i++)
      {
            lstInForLoop.Add(i.ToString());
            //simulate a heavy instruction
            Thread.SpinWait(10);
       }
}

Loop Parallel.For in a C#4.0 bloc code

public static void MethodWithParallel()
{
      List<string>lstInParallelLoop = new List<string>();
      Parallel.For(0, 20, (int i) =>
      {
             lstInParallelLoop.Add(i.ToString());
             //simulate a heavy instruction
             Thread.SpinWait(10);
      });
}

Now let’s compare the timing of these two methods

class Program
{
   public static void Main(string[] args)
   {
      DateTime startTime;
      TimeSpan duration;

      startTime = DateTime.Now;
      MethodWithParallel();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithParallel done in {0}", duration.TotalMilliseconds + " ms");

      startTime = DateTime.Now;
      MethodWithoutParallel ();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithoutParallel  done in {0}", duration.TotalMilliseconds + " ms");

      Console.Read();
    }
}

Output

with Thread.SpinWait method

Running in parallel performs processing time by half !!!
There are endeed dependencies on your hardware (according to the number of cores etc…)

However, let’s remove the Thread.SpinWait static method and run our loops again.

Output

without Thread.SpinWait method

The loop for inside MethodWithoutParallel performs better than the Parallel.For loop inside MethodWithParallel. It makes evidence that it must not be systematically used.
First of all, always find out where are the expensive instructions and if they can be perform thanks to a little step (or chunk) in your loop.

Now let’s have a look on how to provide a Parallel.For loop in C#2.0

Enjoy :)!!

Read Full Post »