Getting the best performance out of your development machine

by Geert 2. May 2013 22:41

Working with a slow development machine can be very frustrating. At least, it frustrates me a lot. During the years I have developed software, I gathered some tweaks to get the best performance out of your build machine. Here are the tips.

Keep in mind that in most cases, it’s the hard disk that is the bottle neck. Compiling source code requires a lot of small random write access to your disks, so make sure they are as fast as possible.

Buy new hardware

Most developers tend to forget this, but we are developers. We don’t need a lot, just a computer and a visual studio license once in the two years. I know it is very easy to not buy a new machine to save your some money, but you really have to tickle yourself once in a while (or let your boss do it!). From the average salary of a developer, it should be perfectly possible to give yourself a new machine every 3 years and have more joy in writing code.

The last hardware I recently bought is listed below:

  • Motherboard: MSI Big Bang Xpower II iX79, SATA600 RAID (you can actually buy a much cheaper motherboard if you also purchase the raid controller and need less RAM)
  • CPU: Intel Core i7 3960X Extreme 3.30GHz 15MB Box
  • RAM: Kingston 4x8GB, DDR3, PC19200, CL11, Beast, XMP (2 times)
  • Raid controller: Intel PCI-e Adapter RS25DB080 SAS/SATA RAID
  • Disks: Samsung SSD 2.5", 256GB, SATA600, 840 Series Pro (4 times, set to RAID 5)

Then I installed ESXi on it. This way I can connect to my development machine from anywhere in the world if I have to. And the good part is that you can add additional virtual machines. Need a build server? You got it. Need a web hosting server? You got it. All on the same machine.

Before this, I just ran virtual machines on my own computer. This is no longer necessary and I can even use a tablet to develop software if a fast fix is required.

Turn off indexing

Indexing can be very useful for people that don’t know how to use a computer or where to store their files. However it has a major performance on a development machine. Assuming that you are a good developer and you know where to find your file, it is best to turn off indexing on your development disk:

image

Exclude source directory from the virus scanner

Every time a new temporary file is created for compilation, the virus scanner gets an event and checks the file. You are probably using Windows Defender since that is installed by default, but any virus scanner should be able to add a directory to ignore. Below is an image on how to do this in Windows Defender:

image

Final hard disk benchmark

Below is the final I/O benchmark of the machine. I could not perform a write test because I have multiple partitions and the tool does not support that.

image

Have more tips?

Do you have more tips to improve the performance of your development machine? Let me know and I will add them.

Tags:

C# Development | Visual Studio

Ensuring the integrity of an IoC container

by Geert 12. April 2013 00:18

Note that while this feature is implemented in Catel, the technology can be implemented by any IoC container. This feature is called "integrity checker" and will ensure you with useful information about type registration paths. This protection mechanism is very useful in complex applications. When people start building services, sometimes they accidentally inject other services that via injection to other services cause a stack overflow. Debugging and determining which type is causing the issue can be very time-consuming. To make the example a bit more simple, below are a few classes which demonstrate a common issue in enterprises.

   1:  public class X
   2:  {
   3:      public X(Y y) { }
   4:  }
   5:   
   6:  public class Y
   7:  {
   8:      public Y(Z z) { }
   9:  }
  10:   
  11:  public class Z
  12:  {
  13:      public Z(X x) { }
  14:  }

Note how a round-trip of dependencies is created which will result in a StackOverflowException somewhere in your code. Below is a graphical example what happens. Note that the dotted line is showing the circular dependency causing the StackOverflowException.

StackOverflowExample

TypeRequestInfo

The first step for the integrity checker is to make sure that it knows what types are being requested from the ServiceLocator (which will be instantiated by the TypeFactory if required). This class contains all the information about a type being created by the TypeFactory:

  • Type
  • Tag (optional, can be used to differentiate different instances of the same type registration)

TypeRequestPath

Now we have detailed information about the types being constructed, it is very important to keep track of the types which are being created by the TypeFactory. During the construction of a type, the TypeFactory will request the ServiceLocator for a type, which will ask the TypeFactory to construct the type again. Each time the TypeFactory starts constructing a type (and currently has a TypeRequestPath), it will create a new instance of the TypeRequestInfo and add it to the TypeRequestPath. The diagram below shows how the TypeRequestPath will evolve.

Evolving of the TypeRequestPath

Once the TypeRequestPath will contain a duplicate instance of a TypeRequestInfo, it will become invalid (which means there is a circular type dependency).

Note that this is a very simple example, but normally a type will have several services injected which can have dependencies on their own as well which can cause a very complex type request path

Checking the integrity of the type request

To resolve and construct a type, a lot of communication will happen between the TypeFactory and the ServiceLocator. This flow is show in the diagram below.

ServiceLocatory and TypeFactory communication

As you can see, there is a lot of communication between the ServiceLocator and TypeFactory. In the TypeRequestPath example we already saw how the path will become invalid when it contains a duplicate instance of the TypeRequestInfo. The TypeRequestPath will then throw a CircularDependencyException with all the necessary information to solve the issue:

image2013-4-12 0-8-3

Now you will find the issue in no-time and save yourself a lot of your valuable time!

Tags:

C# | Catel | IoC

Subscribing to change notifications without memory leaks

by Geert 1. March 2013 22:11

You know this feeling? You are doing the best you can to prevent memory leaks by correctly unsubscribing from all events, and then you hit that object from which you cannot determine the lifetime. Well, you have a few options:

  1. Don’t talk about it, maybe your app won’t be used that much so maybe nobody notices.
  2. Try to implement IDisposable, but when to call that, you don’t know the end of life of the object?
  3. Fix the issue, but how?!

Note that this solution works on .NET, Silverlight, Windows Phone and WinRT. It doesn’t matter whether you use ASP.NET MVC, MVVM in WPF of your own custom pattern.

How do I create a memory leak?

Creating a memory leak is very easy. Simply subscribing to change notifications of objects mostly results in large statements such as the one below:

   1:  var itemAsPropertyChanged = obj as INotifyPropertyChanged;
   2:  if (itemAsPropertyChanged != null)
   3:  {
   4:      itemAsPropertyChanged.PropertyChanged += OnPropertyChanged;
   5:  }

 

What is the solution to prevent memory leaks?

You can either use the WeakEventListener in Catel or use the brand new ChangeNotificationWrapper that is now available in the latest prerelease version of Catel on NuGet. The ChangeNotificationWrapper allows the subscription of both the INotifyPropertyChanged and INotifyCollectionChanged interfaces using weak events, thus preventing memory leaks.

Subscribing to events of an observable object

Using the code below, one can subscribe to the PropertyChanged event of an object:

   1:  var wrapper = new ChangeNotificationWrapper(obj);
   2:  wrapper.PropertyChanged += OnPropertyChanged;

Note that it is not required to check whether the object implements INotifyPropertyChanged, the wrapper does it automatically

Subscribing to events of an observable collection

Using the code below, one can subscribe to the CollectionChanged event of an object:

   1:  var wrapper = new ChangeNotificationWrapper(observableCollection);
   2:  wrapper.CollectionChanged += OnCollectionChanged;

Note that it is not required to check whether the object implements INotifyCollectionChanged, the wrapper does it automatically

Advanced scenario with observable collections

Sometimes it is required to watch both changes inside a collection, but also the items inside a collection. For example, there is a list of customers and you are also interested in changes of customers inside a collection. This is fully supported by the ChangeNotificationWrapper using the code below:

   1:  var wrapper = new ChangeNotificationWrapper(observableCustomerCollection);
   2:  wrapper.CollectionChanged += OnCollectionChanged;
   3:  wrapper.CollectionItemPropertyChanged += OnCollectionItemPropertyChanged;

All subscriptions are automatically managed by the ChangeNotificationWrapper when items are added or removed from the collection.

Unsubscribing from events

When you are no longer interested in events from the source object, there are two options:

  1. Just leave them coming, as soon as the objects are no longer used, they will be garbage collected
  2. Unsubscribe using the following code:
   1:  wrapper.UnsubscribeFromAllEvents();


Grabbing the bits

As always, Catel is open-source thus you can either check out the source or grab the latest bits via NuGet.

Tags: , ,

C# | Catel

Entity Framework Unit of Work and repositories

by Geert 27. February 2013 20:11

Catel is an application development platform for C# that was primarily focused on xaml languages (WPF, Silverlight, Windows Phone). The core however is usable by server implementations as well and more and more extensions are being developed. This blog post will give an introduction to the Unit of Work and the repositories that are available in Catel.

Overview of Unit of Work and repositories

The Repository and Unit of Work (UoW) pattern are very useful patterns to create an abstraction level over the DbContext that is provided by Entity Framework. A much heard excuse not to use repositories is that EF itself already works with repositories (the DbContext) and a UoW (in the SaveChanges method). Below are a few examples why it is a good thing to create repositories:

  • Abstract away some of the more complex features of Entity Framework that the end-developer should not be bothered with
  • Hide the actual DbContext (make it internal) to prevent misuse
  • Keep security checks and saving and rollback in a single location
  • Force the use of the Specification pattern on queries

A Unit of Work (UoW) is a a combination of several actions that will be grouped into a transaction. This means that either all actions inside a UoW are committed or rolled back. The advantage of using a UoW is that multiple save actions to multiple repositories can be grouped as a unit.

A repository is a class or service responsible for providing objects and allowing end-developers to query data. Instead of querying the DbContext directly, the DbContext can be abstracted away to provide default queries and force required functionality to all end-developers of the DbContext.

A Unit of Work (UoW) is a a combination of several actions that will be grouped into a transaction. This means that either all actions inside a UoW are committed or rolled back. The advantage of using a UoW is that multiple save actions to multiple repositories can be grouped as a unit.

A repository is a class or service responsible for providing objects and allowing end-developers to query data. Instead of querying the DbContext directly, the DbContext can be abstracted away to provide default queries and force required functionality to all end-developers of the DbContext.

image

The image above shows that the Unit of Work is the top-level component to be used. Each UoW contains its own DbContext instance. The DbContext can either be injected or will be created on the fly. Then the UoW also contains repositories which always get the DbContext injected. This way, all repositories inside a UoW share the same DbContext.

The DbContextManager

The DbContextManager class allows the sharing of DbContext (with underlying ObjectContext) classes in Entity Framework 5. The good thing about this is that the same context can be used in the same scope without having to recreate the same type of the same context over and over again.

   1:  using (var dbContextManager = DbContextManager<MyEntities>.GetManager())
   2:  {
   3:      var dbContext = dbContextManager.DbContext;
   4:   
   5:      // TODO: handle logic with dbContext here
   6:  }
 

Creating a Unit of Work

A UoW can be created by simply instantiating it. The end-developer has the option to either inject the DbContext or let the DbContextManager take care of it automatically.

   1:  using (var uow = new UnitOfWork<MyDbContext>())
   2:  {
   3:      // get repositories and query away
   4:  }


Creating a repository

A repository can be created very easily by deriving from the EntityRepositoryBase class. Below is an example of a customer repository:

   1:  public class CustomerRepository : EntityRepositoryBase<Customer, int>, ICustomerRepository
   2:  {
   3:      public CustomerRepository(DbContext dbContext)
   4:          : base(dbContext)
   5:      {
   6:      }
   7:  }
   8:   
   9:  public interface ICustomerRepository : IEntityRepository<Customer, int>
  10:  {
  11:  }

 

Retrieving repositories from a Unit of Work

Once a UoW is created, it can be used to resolve repositories. To retrieve a repository from the UoW, the following conditions must be met:

  1. The container must be registered in the ServiceLocator as Transient type. If the repository is declared as non-transient, it will be instantiated as new instance anyway.
  2. The repository must have a constructor accepting a DbContext instance

To retrieve a new repository from the UoW, use the following code:

   1:  using (var uow = new UnitOfWork<MyDbContext>())
   2:  {
   3:      var customerRepository = uow.GetRepository<ICustomerRepository>();
   4:   
   5:      // all interaction with the customer repository is applied to the unit of work
   6:  }

 

Saving a Unit of Work

It is very important to save a Unit of Work. Once the Unit of Work gets out of scope (outside the using), all changes will be discarded if not explicitly saved.

   1:  using (var uow = new UnitOfWork<MyDbContext>())
   2:  {
   3:      var customerRepository = uow.GetRepository<ICustomerRepository>();
   4:   
   5:      // all interaction with the customer repository is applied to the unit of work
   6:   
   7:      uow.SaveChanges();
   8:  }

 

Getting the assemblies and/or code

You can either get the assemblies via NuGet or view the source on codeplex.

Tags: , , , , ,

Catel | C# | Entity Framework

Catel 3.4 is released!

by Geert 15. December 2012 16:43

It has been quite a while, but today a new version of Catel is released. It took us more time then usual, but in return we have a great version ready to be downloaded via the site or via NuGet.

Added WinRT and Windows Phone 8 support

This is probably the most noticeable “feature” of all. Both WinRT and Windows Phone 8 are fully supported with all features that you are familiar with in Catel. This means that we were able to port everything (not really everything, but 90 %) of it to WinRT and all known Windows Phone features to Windows Phone 8.

Performance improvements

For this release, we focused on performance. We made a lot of improvements by tracing and tweaking all the calls thoroughly. Below is a list of tweaks:

  • All reflection calls are now being cached
  • Logging is only executed when there are actually listeners registered
  • ModelBase.LeanAndMeanModel property to (temporarily) suspend both validation and change notifications, great when restoring models from disk
  • Added a FastObservableCollection which allows the adding of a range and only invokes a single event at the end
  • It is now possible to control (globally or per control) whether InfoBarMessageControl and WarningAndErrorValidator controls must be created or MVVM controls
  • Constructors in the ServiceLocator are cached which gives a major performance boost when creating new instances of types with dependency injection

Improved IoC container

The IoC container in Catel, the ServiceLocator, now supports registration of types with a tag. This allows the same type to be registered multiple times.

And much more…

Besides new features, we also fixed over 40 issues in this new release. Not all new features are described in this blog post, so make sure you get the latest version while it’s hot!

Tags:

MVVM | C# | Catel | Windows Phone 7 | Windows Phone 8 | WinRT | WPF | Silverlight


About the Author

Geert van Horrik is an independent freelance software developer since January 1st, 2007. Since then he was been working on several projects from C++ to C# (WPF, Silverlight, ASP.NET, etc). Currently he loves to write his software using WPF (or Silverlight if WPF isn't an option).

Lately, Geert is spending a lot of time on Catel, a free open-source MVVM Framework for WPF and Silverlight. Actually, it's more than "just" an MVVM Framework, it's a complete application library!