The C# Memory Model in Theory

The C# memory model makes and shows the code patterns that motivate the guarantees; the second part will detail how the guarantees are achieved on different hardware architectures in the Microsoft .NET Framework 4.5.

One source of complexity in multithreaded programming is that the compiler and the hardware can subtly transform a program’s memory operations in ways that don’t affect the single-threaded behavior, but might affect the multithreaded behavior.

Original:
http://msdn.microsoft.com/en-us/magazine/jj863136.aspx

Advertisements

Showing tooltip on textbox when text exceeds the available size of textbox(Attached Behavior in WPF)

XAML TAG

WPF provides an innovative feature called attached properties, which can be used to add behavior to existing controls. These new properties are not defined on the control being extended, but rather they are defined on a separate object (generally a
DependencyObject). Thus, we end up with a source object that defines the attached properties and a target object on which you attach these properties. The target is the object being extended with new functionality contained in the source. When the attached property is set on the target object, a property change event is fired on the source. The event handler is passed information about the target and the new and old values of the property.
By hooking up property changed handlers, we can add additional behavior by calling methods on the target, changing properties, and listening to events. We look at more detailed examples of using attached properties in Chapter 6, “The Power of Attached Properties.” Keep in mind that…

View original post 392 more words

Thread Safe Generic Weak Dictionary in .NET

If you are about to begin implementing your own version of a thread safe generic weak dictionary – STOP!

As of .NET 4.0, there is already one:

System.Runtime.CompilerServices.ConditionalWeakTable<TKey, TValue>

Now that .NET 4.5 has been made open source few weeks ago, we can look at the comments and more importantly at the implementation of ConditionalWeakTable<TKey, TValue>. Continue reading “Thread Safe Generic Weak Dictionary in .NET”

Design patterns and practices in .NET: the Chain of Responsibility pattern

Exercises in .NET with Andras Nemes

Introduction

The Chain of Responsibility is an ordered chain of message handlers that can process a specific type of message or pass the message to the next handler in the chain. This pattern revolves around messaging between a sender and one more receivers. This probably sounds very cryptic – just like the basic description of design patterns in general – so let’s see a quick example in words.

Suppose we have a Sender that knows the first receiver in the messaging chain, call it Receiver A. Receiver A is in turn aware of Receiver B and so on. When a message comes in to a sender we can only perform one thing: pass it along to the first receiver. Receiver A inspects the message and decides whether it can process it or not. If not then it passes the message along to Receiver B and Receiver B will perform the…

View original post 1,152 more words

Formatting Cheat Sheet

No credit should be given to me, copied from color-of-code

Syntax

Formatting is bound to a type, so depending on which type of object you pass to String.Format, you have different format specifiers.

The index specifies the position of the parameter that shall be used for that format specifier. It can be repeated!

When implementing custom formatting, try to stick to this behaviour for being consistent with the default implementation.

  • Generic, alignment is applied after type formatting, so can be used for all types
    • {index[,alignment][:format]}
  • For numerical values (; separator):
    • {index[,alignment]:format >= 0;format < 0}
    • {index[,alignment]:format > 0;format < 0;format = 0}

Pitfalls and gotchas Continue reading “Formatting Cheat Sheet”

Why put code inside finally statement with empty try statement

When browsing .NET source code you might come across an empty try clause and some code in the finally clause:

try
{
}
finally
{
// few lines of code here
}

The answer is to guarantee the execution of the code in case something calls Abort() on the thread. Since .NET 2.0 execution of the code in the finally statement is guaranteed even if something calls Abort() on the thread. In the earlier versions of.NET it was possible that the finally clause is never executed. I don’t expect to ever write anything that would leverage this, however it still nice to know.

Inversion of Control – Best Practises

Always Create an Interface

Every class that defines operations must have an interface.  The interface should serve as a contract and is particularly useful when mocking the behaviour during unit testing. The interface will also be used for registration with the container.

public class MyService : <strong>IMyService</strong>
{
    public void ProcessBatch(DateTime reportingDate)
    {
        var processor = new BatchProcessor(reportingDate);
        processor.Process();
    }
}

public interface IMyService
{
    void ProcessBatch(DateTime reportingDate);
}

Avoid Instantiating Objects Directly

For example we have the following implementation

public class MyService
{
    public MyService()
    {
    }

    public void ProcessBatch(DateTime reportingDate)
    {
        var processor = <strong>new BatchProcessor(reportingDate);</strong>
        processor.Process();
    }
}

The above code cannot be unit tested in isolation, by testing MyService we inadvertently end up testing BatchProcessor as well. The code could be rewritten as:

public class MyService : IMyService
{
    private readonly IBatchProcessorFactory _batchProcessorFactory;
    public MyService(<strong>IBatchProcessorFactory</strong> <strong>batchProcessorFactory</strong>)
    {
        _batchProcessorFactory = batchProcessorFactory;
    }

    public void ProcessBatch(DateTime reportingDate)
    {
        var processor <strong>= _batchProcessorFactory.Create(reportingDate);</strong>
        processor.Process();
    }
}

public interface IBatchProcessorFactory
{
    void IBatchProcessor Create(DateTime reportingDate);
}

public class BatchProcessorFactory : IBatchProcessorFactory
{
    public IBatchProcessor Create(DateTime reportingDate)
    {
        return new BatchProcessor(reportingDate);
    }
}

Now, in order to test the logic of MyService, we can mock IBatchProcessor and just test that the Process method is called on the instance!

Avoid Passing Primitives in Constructor

public class MyService : IMyService
{
    private readonly string _connectionString;
    public MyService(<strong>string connectionString</strong>)
    {
        _connectionString = connectionString;
    }

    public void Save()
    {
        using(var connection = <strong>new SqlConnection(_connectionString))</strong>
        {
            // Do some work
        }
    }
}

We should change it to:

public class MyService : IMyService
{
    private readonly IConnectionStringProvider _connectionStringProvider;
    public MyService(<strong>IConnectionStringProvider connectionStringProvider</strong>)
    {
        _connectionFactory = connectionFactory;
    }

    public void Save()
    {
        using(var connection <strong>= new SqlConnection(_connectionStringProvider.GetConnectionString()))</strong>
        {
            // Do some work
        }
    }
}

* Alternatively we could use a Factory pattern to get a connection instance

Don’t Pass Container in the Constructor

public class MyService : IMyService
{
    private readonly ISqlConnectionFactory _connectionFactory;
    public MyService(<strong>IUnityContainer container</strong>)
    {
        _connectionFactory = <strong>container.Resolve<ISqlConnectionFactory>();</strong>
    }
}

Instead pass the interface into the constructor:

public class MyService : IMyService
{
    private readonly ISqlConnectionFactory _connectionFactory;
    public MyService(<strong>ISqlConnectionFactory connectionFactory</strong>)
    {
        _connectionFactory = connectionFactory;
    }
}

The IoC container will resolve the references automatically:

var container = new UnityContainer();
container.Register<ISqlConnectionFactory, SqlConnectionFactory>();
container.Register<IMyService, MyService>();
//…
var myService = container.Resolve<IMyService>();

Avoid Named Instances

public class RiskDbSqlConnectionFactory : ISqlConnectionFactory
{
}
public class StaticDataSqlConnectionFactory : ISqlConnectionFactory
{
}

container.Register<ISqlConnectionFactory, RiskDbSqlConnectionFactory>(“RiskDB”);
container.Register<ISqlConnectionFactory, StaticDataSqlConnectionFactory>(“StaticDB”);

Instead use different interfaces to differentiate:


public class RiskDbSqlConnectionFactory : ISqlConnectionFactory, IRiskDbSqlConnectionFactory
{
}

public class StaticDataSqlConnectionFactory : ISqlConnectionFactory, IStaticDataSqlConnectionFactory
{
}

container.Register<IRiskDbSqlConnectionFactory, RiskDbSqlConnectionFactory>();
container.Register<IStaticDataSqlConnectionFactory, StaticDataSqlConnectionFactory>();

Avoid Static References

public class MyService : IMyService
{
    public void DoSomething()
    {
        SaveData(<strong>DateTime.Now</strong>);
    }
}

If you have to use a static property or a method in the code write a wrapper. For example:

public interface IDateTimeProvider
{
     DateTime GetCurrentTime();
}

public class DatetimeProvider : IDateTimeProvider
{
    public DateTime GetCurrentTime()
    {
        return DateTime.Now;
    }
}

public class MyService : IMyService
{
    private readonly IDateTimeProvider _dateTimeProvider;
    public MyService(IDateTimeProvider dateTimeProvider)
    {
        _dateTimeProvider = dateTimeProvider;
    }

    public void DoSomething()
    {
        SaveData(_dateTimeProvider.GetCurrentTime());
    }
}

This technique gives you an opportunity to mock DateTime to any value during unit testing

Interface Segregation (Liskov Principle)

Consider splitting large interfaces into smaller ones

public class Repository : IRepository
{
    public Item Load()
    {
    }

    public void Update(Item item)
    {
    }
}

This could be converted to 2 interfaces IItemLoader and IItemUpdater . The class definition would look like this:

public class Repository : IRepository, IItemLoader, IItemUpdater

Lifetime Management

If you need to make sure there is only going to be one instance of a particular type you have to register you class with ContainerControlledLifetimeManager instance.

container.Register<IMyService, MyService>(new ContainerControlledLifetimeManager())

Then the resolve method would return 1 instance of the class. If nothing is specified then a new instance will be created each time.

If you need to register an already existing instance then do the following:

var myService = new MyService();
container.RegisterInstance(typeof(IMyService), myService, new ContainerControlledLifetimeManager());

Thread-safe Singleton Without any Synchronisation Primitives

This example demonstrates how to create a singleton without doing any synchronisation

public class LockingExample
{
    public static StringBuilder Resource
    {
        get { return InnerResourceContainer.Resource; }
    }

    private static class InnerResourceContainer
    {
        public static readonly StringBuilder Resource = new StringBuilder();
    }
}

Blog at WordPress.com.

Up ↑