Reshef’s tip of the day

.net development tips

Archive for November, 2007

Tip of the day: DictionaryAdapter

Sunday, November 25th, 2007

The is a part of the Castle project but can be used as a standalone assembly.

The dictionary adapter lets you wrap a dictionary with an interface definition and access that dictionary through the interface. This gives the advantage of typed data access on top of a dictionary and don’t forget the intellisense in the IDE.

The example I will use shows the use of a dictionary adapter in order to enable access to configuration data.  It contains a class:

/// 
/// This class uses configuration.
/// Instead of accessing the configuration directly,
/// it receives it in the constructor.
/// 
public class DataBaseAccess
{
    private IDataBaseAccessConfig m_config;

    /// The configuration that
    /// this class uses to access the database.
    /// 
    public DataBaseAccess(IDataBaseAccessConfig config)
    {
        m_config = config;
    }

    public void ConnectToDataBase()
    {
        Console.WriteLine("Server Ip: {0}", m_config.ServerIp);
        Console.WriteLine("DataBase: {0}", m_config.DataBaseName);
        Console.WriteLine("User: {0}", m_config.UserName);
        Console.WriteLine("Password: {0}", m_config.Password);
        Console.ReadLine();
    }
}

As you can see, this class expects a config object that implements the the IDataBaseAccessConfig interface. This interface is defined as:

/// 
/// Defines the data for data base access.
/// 
public interface IDataBaseAccessConfig
{
    string ServerIp { get;}
    string DataBaseName { get;}
    string UserName { get;}
    string Password { get;}
}

In the example, the database access data is defined in the appSettings section of the application configuration file. In order to pass it to the DataBaseAccess class, it is being wrapped like this:

// In real world example the factory should be cached.
// Create the adapter on top of the configuration dictionary.
IDataBaseAccessConfig configAdapter =
    new DictionaryAdapterFactory().
        GetAdapter(configData);

where the configAdapter is passed.

Now what happened here? The DictionaryAdapterFactory emit code in runtime that implements a wrapper class that implemets the IDataBaseAccessConfig interface and this class, when a property is being read, gets the value for the dictionary that is wrapped, in this case, the configData dictionary.

What is it good for?

1) In my opinion, it is nicer to access an interface rather than passing a configuration dictionary to the class which involves querying the data by using string literals.

2) When passing the data through the constructor instead of accessing the ConfigurationManager directly in the code we make our code better by preventing access to singletons, therefore making the code testable and agnostic to the real implementation, may it be the application configuration file, configuration defined in the database or any other implementation.

3) Intellisense…

The example solution is here

Tip of the day #2: Dynamic proxies

Sunday, November 25th, 2007

A dynamic proxy is an approach that is not fully natively supported in .net but natively exists in java.

What a proxy means, is to wrap an object with with wrapper that intercepts call to that object and does something in addition.

What is it good for? A naive example is to add a proxy that log calls to methods of an object.

A more real world example is to use proxy in an O/R mapper. The mapper can create proxies on top of the domain object and intercept calls to properties in order to fetch data from the db and track changes to the data that will later be persisted (NHibernate works this way).

The idea of dynamic proxy is to provide an implementation of an interceptor and attach it to the proxy. From now on, all calls to methods will pay through the interceptor which, for the logging example, logs every call to the method. Concrete examples can be found in the link at the bottom of this post.

The .net native implementation for dynamic proxies is by using ContextBoundObject or MarsalByRefObject. This approach is limited since you have to inherit from one of these classes which is not clean.

There are several implementations of dynamic proxies that do not interfere with inheritance hierarchy of your code.
Here are some examples:

1) Castle DynamicProxy

2) DynamicProxy.NET

3) LinFu

Tip of the day: Mutual exclusion when Remoting

Sunday, November 25th, 2007

Another tip from Gal:"

Just a small tip that might have saved me a few good hours:

A Mutex can be released only by the thread that originally locked it.

A semaphore can be released by any thread.

I used a mutex at the beginning, while locking and releasing on different threads, and at the threadpool desire, got ("sometimes" is the WORST one) an

ApplicationException - Object synchronization method was called from an unsynchronized block of code.

Usually this means that the mutex is not locked but still tries to be released – check this out.

But in my case (first remoting call locks an object and the second releases), it was just that a mutex was the wrong sync method, and a semaphore quickly solved the problem.

As mentioned in the link, the error message need some work."

Tip of the day: ThreadStatic attribute

Sunday, November 25th, 2007

According to the msdn documentation, the ThreadStatic attribute "Indicates that the value of a static field is unique for each thread."

A practical use for it can be a registrar implementation. A registrar can be used as a static entry point to store context data for say, a request that is being processed by several classes that need to share data.

Implementation example:

public static class Registrar
{
   [ThreadStatic]
   private static Dictionary<string, object>
      m_registrar = null;

   private static Dictionary<string, object>
      LocalDictionary
   {
      get
      {
         if (m_registrar == null)
         {
            m_registrar =
               new Dictionary<string, object>();
         }
         return m_registrar;
      }
   }

   public static object Get(string key)
   {
      return LocalDictionary[key];
   }

   public static void Set(string key, object value)
   {
      LocalDictionary[key] = value;
   }
}

Now since the m_registrar is marked with ThreadStatic attribute, is static per thread, which means that no locking is required and no data corruption can occur.

A real world example for using such strategy is HttpContext.Items

Gilad pointed out two important points:

- ASP.NET is changing threads under the hood so don’t use it there since u will most probably get your data corrupted. The HttpContext knows how to handle that so use it.

- When using a thread pool, the threads are not killed and so when a thread completes execution and returned to the pool, the static data is still kept. In this case u should use an execution wrapper than clears the per thread static data after the thread complete execution.

Tip of the day: Interlocked

Sunday, November 25th, 2007

The Interlocked class in .net is a static class that provides type operation that are performed atomically.

By providing this, it can help solve simple multithreading scenarios since:

1) It removes the chance of deadlocks that can be caused by using the lock keyword.

2) It has better performance than the lock keyword.

3) Simpler (and less) syntax.

Lets take a look at a scenario where you would like to count how many times a method is called while a program runs (multithreaded environment):

private static int methodCallsCounter = 0;
…

public void SomeMethod()
{
    System.Threading.Interlocked.
        Increment(ref methodCallsCounter);
    …
}

The Interlocked class has a set of methods to manipulate data. A complete documentation and a full example can be found here.

Talking about multithreading and locks, I suggest reading this. It describes very important points about locking.

Tip of the day: Friend assemblies

Sunday, November 25th, 2007

The internal keyword (C#) is defined as the way to restrict access to members only to types in same assembly.

But, since the .net framework 2.0, there is a way to to define an assembly as a friend assembly. This can be done by specifying

[assembly:InternalsVisibleTo("friend assembly")]

in the AssemblyInfo.cs file (or in any other file).

After specifying this, the friend assembly can access the internals of the assembly marked with this attribute.

I can see two useful thing that can be achieved:

1) Better encapsulation of course.

2) Enable access for unit testing by using this strategy.

The msdn documentation is here.

Tip of the day #2: ref/out key words for reference types

Sunday, November 25th, 2007

This tip is the courtesy of Gal.

It surprised and embarrassed me to realize that I didn’t know it.

When a reference type is passed to a method without using the ref or out keywords, a new reference is created inside the method and it points to the same location in the memory as the reference that was passed so we have two "pointers" to the same location in memory.

In case the the reference inside the method is set to a different location, the reference that was passed does not change.

When the ref/out keywords are used, we have only one reference inside and outside the method so if the reference is changed to point to another location and it happens inside the method, the outer reference is changed too.

Basic stuff…

Tip of the day: Data Type aliasing

Sunday, November 25th, 2007

There is a feature in .net that is not commonly remembered and it is Data Type aliasing.

What it means is that u give a data type a different name.

I can see two uses for it:
1) Enhance code readability:

Instead of having very long type declarations such as when using generic types inside generic types, u can assign an alias to that declaration. Here is an example:

    // Aliasing
    using HashOfHashes =
        Dictionary>>;

    public class AliasExample
    {
        HashOfHashes m_hash;

        public AliasExample()
        {
            m_hash = new HashOfHashes();
        }

        public HashOfHashes MyHash
        {
            get
            {
                return m_hash;
            }
        }
    }

2) Alias data types that are prone to change:


An example is an identifier property of class. It can save a lot find&replace when changing code like changing the identifier of a member from int to Guid and it better shows intent. For example:

    // Aliasing
    using MemberIdentidfier = Guid;

    public class MemberWithAlias
    {
        private MemberIdentidfier m_id;
        private string m_name;

        public MemberWithAlias
                (MemberIdentidfier id)
        {
            m_id = id;
        }

        public MemberIdentidfier Id
        {
            get { return m_id; }
        }

        public string Name
        {
            get { return m_name; }
            set { m_name = value; }
        }
    }

Tip of the day: Primitive but efficient way for profiling (on development machine)

Sunday, November 25th, 2007

Small thing I read about. It is so simple and obvious but I never thought about it…

In the lack of a decent profiler,

if u observe that a certain process takes a large amount of time (such as system startup),

start the debugger and while the time consuming task is running, click the pause button in VS.

Now take a look at the call stack to see which method take the time to execute.

Jajah is the VoIP player that brought you web-activated telephony.