Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Sunday, April 7, 2013

Lazy Evaluation And Infinite Data Structures In C#

Today I was reading the "Functional programming with Haskell" tutorial by Rob Harrop. In this article Rob also shows the ability of Haskell to handle the so called Infinite Data Structures using an infinite list of prime numbers as an example. The author defines infinite data structures as "data structures that abstract the details of some infinite stream of data". Due to Haskells support for lazy evaluation such infinite lists can be treated like normal lists. While reading the article I was wondering if I can do the same thing in C#. Though it's an eagerly evalutated language (means: the expression gets evaluated as soon as you assign it to a variable) using the yield keyword you can deal with infinite data structures:
public class Primes {
  public IEnumerable<int> All () {
    int number = 2;
    while (true) {
      while (!IsPrime (number)) ++number;
      yield return number++;
    }
  }

  public bool IsPrime (int number) {
    if(number < 3) return true;
    var seq = Enumerable.Range (2, number - 2);
    Func<int, int, bool> divides = (n,p) => n % p == 0;
    return seq.All(p => !divides (number, p));
  }
}
The Primes.All() method returns an "infinite" list of prime numbers. Thank to the yield keyword the numbers are not computed until you really use them, e.g. you can get the first ten prime numbers by:
var primes = new Primes ();
var firstTenPrimes = primes.All().Take(10);
With the power of the LINQ framework the Primes.All() method even becomes a "one liner":
public IEnumerable<int> All () {
  return Enumerable.Range (2, int.MaxValue - 1)
                   .Where (IsPrime);
}
I really like these functional features in C# :)

Tuesday, July 31, 2012

Slow Cheetah - XML transforms for config files

Today I have found another nice visual studio extension: Slow Cheetah. Using this extension you can transform configuration files during the build. It's really useful if you want to change the contents of your config files depending on the build configuration, e.g. adapting connection strings, paths, hostnames, wcf settings etc. With Slow Cheetah you can transform all kind of configuraion files in your project not only the app.config or the web.config.

Thursday, June 16, 2011

DDD Exchange 2011

Videos of sessions from DDD Exchange 2011 are now online on skillsmatter.com: DDD Exchange 2011 SkillCast videos. Great stuff! Definitely worth watching! Among others Udi Dahan talking about Composite Applications and Domain Models and showing how to turn monolithic applications with big and cluttered models into composite applications with lean domain models using Bounded Contexts. Also Greg Young showing great things you can do with tests and Event Sourcing: Assert.That(We.Understand).

Friday, April 15, 2011

ReSharper's Object Initializer Quick Fix and IDisposable

This week I had to realize that not every Resharper suggestion is really useful. Some quick fixes carelessly applied can even introduce flaws into your code. The quick fix I have in mind is Resharpers suggestion to use an object initializer instead of creating an instance with subsequent assignments to its properties. Applying this quick fix to following code:
var person = new Person();
person.Name = "John";
person.Lastname = "Doe";
would change it to:
ver person = new Person {
     Name = "John", Lastname = "Doe" };
This quick fix is really handy and can imho improve the readability of the code. But it should not be applied when the type is an IDisposable! Why? An object initializer just creates a temporary instance of Person initializes the properties and then assignes this temporary variable to the variable person. Something like that:
var temp = new Person();
temp.Name = "John";
temp.Lastname = "Doe";
var person = temp;
The problem is that if an exception is thrown during the properties initialization you have no chance to dispose the new instance because you have no access to that temporary local variable. It's created by the compiler and is therefore not visible in you c# code. Even if you put the object initializer inside a try catch block or an using directive you will have a problem: http://ayende.com/Blog/archive/2009/01/15/avoid-object-initializers-amp-the-using-statement.aspx.

Things learned:

  1. Never use object initializers with types implementing IDisposable
  2. Resharper is a great tool but you should never apply quick fixes blindly. Think for yourself. Don't let the tools do the thinking for you ;)

Tuesday, March 8, 2011

ReSharper: remove unused references.

Today I was cleaning up unused references in a Visual Studio solution. Thanks to ReSharper it was not as tedious as I fought at first. Another great feature provided by this tool saved me a couple of minutes (or maybe hours):  http://www.jetbrains.com/resharper/features/navigation_search.html#Find_ReferencedDependent_Code.
To use it select the referenced assembly in the solution browser and choose "Find Code Dependent on Module" from the context menu. If the assembly isn't used anywhere in the current project ReSharper will show a message box saying: "Code dependent on module XXXXXXX was not found". In this case you can remove this reference safely.

Tuesday, March 1, 2011

Magic GUIDs, ReSharper and more...

Here are some tricks I discovered today:


  • Magic GUIDs: Creating unit tests in Visual Studio is quite easy when you are doing it 'the right way'. But sometimes when I want to write tests first and create a new project for them I mistakenly choose the class library project type instead of a unit test project. However these are two different project types so when I try to run my tests from the class library project the Visual Studio won't find them. Fortunately you can convert an existing visual studio class library project to unit tests project: http://blog.drorhelper.com/2008/12/how-to-convert-net-class-library-to-ms.html
  • ReSharper: There is a great new feature in ReSharper 5.0 called value tracking.
  • Another nice ReSharper feature useful when you want to restructure you code: Move code elements up and down: [Ctrl]+[Alt]+[Shift]+[Up|Down]. You can move single lines but also entire methods.
  • Sourcemaking: A website with lots of stuff about design pattern, antipatterns and refactoring: http://sourcemaking.com/

Monday, February 7, 2011

Dynamic base address for a WCF service

Last week I've learned a nice 'trick' that allows to specify a dynamic base address for a WCF service in the configuration file. When you want to run a WCF service you need to specify the base address for the service host. You can do this in a config file or directly in your code when creating a ServiceHost instance: http://msdn.microsoft.com/en-us/library/ms733749.aspx.
Now if you are deploying your service to many machines you must either adjust the host name for each machine during/after the installation or you set the host name to 'localhost'. The problem with the last option is that if you are also exposing metadata then the MEX client will get some endpoint addresses with 'localhost' as host name and will try to call this service on its local machine unless you adjust the host name while creating a proxy.
A handy solution for this problem is to use a so called 'weak wildcard' for the host name part of the base address:
<system.serviceModel>
  <services>
    <host>
      <baseAddresses>
        <add baseaddress="net.tcp://*:1234/svc" />
      </baseAddresses>
    </host>
  </services>
</system.serviceModel>
That's it. The framework will replace the wild card with the name of the host the service is actually running on.
Edit: The solution works only with base-addresses not with endpoint addresses!

Friday, November 28, 2008

Auto-incrementing version numbers with Visual Studio

There are lots of web sites describing how to achieve this. Surprisingly most of them are "roll your own" solutions including custom add-ins, MSBuild-tasks or even custom tools.
But there is an obviously little-known feature in Visual Studio that allready provides this functionality. All you have to do is to edit the AssemblyInfo.cs file in project. Just replace the line [assembly: AssemblyVersion( "1.0.0.0" )]; with [assembly: AssemblyVersion( "1.0.*" )]; and remove the line [assembly: AssemblyFileVersion( "1.0.0.0" )];. You still have the possibility to manually set the major and minor version numbers (first two numbers). The build and the revision number (the last two) will be incremented automatically after each build. Thanks to Marc Charbonneau for telling the world ;) about this feature in his blog.
Edit: It seem like the auto-incrementing the assembly version has an annoying side-effect when applied to an assembly with custom ui controls or WF activities: https://connect.microsoft.com/VisualStudio/feedback/details/568672. The Visual Studio fails to release the handle to that dll during the build.

Sunday, October 26, 2008

Synchronizing Workflow Instances

In a multi threaded program, where different threads use a shared resource, the access to this shared resource needs to be synchronized. Most if not all programming languages or parallel programming systems provide some kind of synchronization mechanisms which help the programmer to protect shared resources and avoid race conditions. Unfortunately the Workflow Foundation (a system that is inherently multi threaded) does not provide a way to synchronize activities across workflow instances out of the box. Of course there is the SynchronizationScopeActivity, but it's only usefull when you need to synchronize parallel activities running in the same workflow instance.
One good reason for the absence of this kind of feature is the fact that if you have a shared resource then you usually access it through a runtime service. Synchronizing the access to the resource is the responsibility of the runtime service and not the responsibility of the workflow.
But nevertheless if you need to synchronize workflow activities across multiple instances or even different workflows you may find this usefull. It's an activity similar to the SynchronizationScopeActivity provided by WF except it synchronizes its child activities between different instances of a workflow.
To use this activity in you workflows you need to add an instance of a runtime service (CustomWorkflowActivities.SynchronizationService) provided with the activity to the workflow runtime first:
WorkflowRuntime workflowRuntime = new WorkflowRuntime();
workflowRuntime.AddService(
  new CustomWorkflowActivities.SynchronizationService(
    workflowRuntime));
Then just insert a RealSynchronizationScope activity into your workflow, set its SharingName property to some unique-within-the-workflow-engine string, and drag activities you wish to synchronize onto the RealSynchronizationScope activity. That's it! The workflow runtime will now serialize the execution of any activities inside your RealSynchronizationScope activity across workflow instances.