Think Before Coding

To content | To menu | To search

.Net Framework

Entries feed - Comments feed

Friday, December 2, 2011

I love SQL Server and cultures... NOT !

When developing a large system, all is not unicorns and rainbows.

For now, everybody was working on a single SQL dev server and friction is high.


That’s why I’m working on SQL scripts management with mercurial and powershell to the rescue, so that any developer can trash his own SQLExpress instance, and rebuild everything needed in a single command. (I’ll maybe blog about all that later).


We have loads of stored procs.. I know people don’t like it, but it acts as a strong sanity layer when the database schema is so ugly your eyes bleed when you look at it.


Yesterday, I run a stored proc, and I get the following error :

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.


Why the f**k.


The procedures is using a scalar function :

ALTER FUNCTION [dbo].[DateMaxValue]()
RETURNS datetime
RETURN '9999-12-31 23:59:59.998'


It’s working on other servers.. why doesn’t it work here.

After several tries, I try with the date ‘9999-12-01’ and I get the following date:

Year: 9999

Month: 01

Day: 12


Yes.. the date is interpreted as YYYY-dd-MM on a French server.


Even when you use the YYYY-??-?? format, SQL Server still try to mess with culture month/day ordering !


You can use the SET DATEFORMAT dmy or SET DATEFORMAT mdy to change this, but it will apply only in current session, and you cannot use it in a stored proc.


You can change the server culture, but it wont change anything. The dmy/mdy setting is ultimately in the Login culture.


You read it right :

  • For an English Login the function above works.
  • For a French Login the function above fails miserably.

There is no way to my knowledge to specify a strict date parsing in a stored proc or function.


So generates your logins with scripts, and enforce the same culture for all logins.


It’s just profoundly broken.

Friday, January 21, 2011


I’ve been posting a sample SmtpListener on my repository a few days ago.

It’s infrastructure stuff.. what does it have to do with what I’m usually talking about here ?


It’s about Reactive Programming.


Sometimes you have to integrate with legacy systems that’ll send you things through email.

Ok, I know, it kind of sucks as an integration mechanism, but still… you have to do this way.


The usual way to receive email in an application is to set a mailbox on a mail server (think Exchange), and pull mailboxes periodically to see if there’s something new there.


There are two bad things here :

  • People tend to use their enterprise mail server for this. The mail sever is often vital for your business and screwing it up with a bug can have a big impact on your organization.
  • Email are pushed to you.. why would you pull it. You can push it directly on your service bus !

So, I prototyped a small smtp listener that could easily be integrated with whatever you want.


You need to add a MX entry in your dns zone configuration so that other servers find it, and get a valid certificate if you want to use secured TLS connections (I’ve disabled certificated verification for demo purpose).


But as you can see, the code is very simple since the .Net framework has already what’s needed.


The TcpListener is used to receive connections that’ll provide a TcpClient with underlying streams.

The SslStream class is used to encapsulate tcp streams to add Ssl encryption.

I’m using the reactive framework to convert the Begin/EndAcceptTcpClient methods to an Observable to avoid writing the accept loop myself.


Then implementation of the protocol is very easy, you can find an overview and sample on wikipedia.

The RFCs can easily be found :

RFC 5321: Simple Mail Transfer Protocol

RFC 3207: SMTP Service Extension for Secure SMTP over Transport Layer Security


Of course you can use it freely, and propose changes to make it better since it’s not attack proof.

This code is not resistant to known potential SMTP attacks, including dangling connections, long lines etc..

Thursday, January 20, 2011

Code code code

There are some sample/proof-of-concept codes on (hosted by


You can have a look at it and contribute if you want.


Enjoy !

Thursday, October 22, 2009

C# Static interfaces - Take 2

As Romain was pointing in the comments, I totally missed to tell where I wanted to go with this static interface things. Need more sleep these days…

So here it is.

No I don’t want to do this

The point was not to enable something like this :

   int value = ICountable.Count;

Static interfaces have no implementation exactly like interfaces.

With interfaces, you need an instance (usually in a variable or member) to find the actual implementation and call it. With static interfaces, you need a type.

There are two ways to specify a type:

  • with its type name (Sample4.Count)
  • with a generic type parameter (T.Count)

I was also proposing a way to specify a type for extension methods.

Where it would be useful - operators

The reason why everybody is asking for static members in interfaces is ultimately to have operators in interfaces.

Imagine :

    public static interface IArithmetic<T>


        static T operator +(T x, T y);

        static T operator -(T x, T y);

        static T operator *(T x, T y);

        static T operator /(T x, T y);


Now you can write generic code like :

        public static T Power<T>(this T value, int count) where T : IArithmetic<T>


            var result = T.Identity;


            for (int i=0;i<count;i++)

                result = result*value;


            return result;


Cool !

This way, no need for the 20 overloads of Enumerable.Sum, it would work for any type presenting the expected static interface.

Wednesday, October 21, 2009

C# Static interfaces

Read the latest post on the subject:

C# Static Interfaces - Take 3

No DDD today, let’s talk a bit about our favorite language after a short night (I should really tell my neighbors that 3am is not the good time to move their furniture all around the flat).

You can find requests for static methods in interfaces all over the internet..

But there are good reasons not to.

According to Eric Lippert, the main reasons is the difference in inheritance between static methods and instance method du to the absence of shared slots between static methods.

Mixing both static methods and instance methods in interfaces would lead to a real nightmare when you try to understand what really happens.

But why does this question arise so often then ? What’s really needed ?

Static classes as type instances

Let’s take a simple class with both static and instance members :

    class Sample


        // static part

        private static int count;

        public static int Count { get { return count; } }


        // instance part


        private readonly string name;


        public Sample(string name) { = name; }


        public void Method()



            Console.WriteLine("Total count {0} incremented by {1}", count, name);



Here, Count is a static Property. Static part is different from instance part in that static part exist only once per type.

But we could see static part as being an object with reference is type name.

Why would these object not have interfaces ?

Let refactor this a bit :


    public class Sample2


        public sealed class Sample2Class


            internal int count;

            public int Count { get { return count; } }


        public static readonly Sample2Class Class = new Sample2Class();


        private readonly string name;


        public Sample2(string name)


   = name;



        public void Method()



            Console.WriteLine("Total count {0} incremented by {1}", Class.count, name);



Here, the only static member is Class, that acts as a singleton for the type. Note that I had to change the count modifier to internal. The behavior is not the same, but it’s conceptually equivalent.

We can make something less extreme :


    public class Sample3


        private static int count;

        public static int Count { get { return count; } }


        private readonly string name;


        public static readonly Sample3Class Class = new Sample3Class();


        public sealed class Sample3Class


            public int Count { get { return Sample3.Count; } }



        public Sample3(string name) { = name; }


        public void Method()



            Console.WriteLine("Total count {0} incremented by {1}", count, name);




Here, we added only a proxy of public methods and properties on the singleton class.

We could define an interface that would be implemented by Sample3Class that would provide the missing slot concept that Eric Lipperts talk about.

We can also see here that there is no point mixing static and instance method in interface since inheritance rules differs.

Static Interface

Imagination at work. Let’s define static interface as we can define static classes :

    public static interface ICountable


        static int Count { get; }


and implement it on our sample :

    public class Sample4 : ICountable


        private static int count;

        public static int Count { get { return count; } }


        private readonly string name;


        public Sample4(string name) { = name; }


        public void Method()



            Console.WriteLine("Total count {0} incremented by {1}", count, name);



The C# compiler would be responsible for creating a singleton stub in the class. Since the goal is to provide a function table, this could also be handled at a lower level by the CLI.

Now, we can have interesting language extensions.

Static member access in generics

Let see it in action :

        public static bool IsInstanciated<T>() where T: ICountable


            return T.Count != 0;


There is no ambiguity when using this method since values of parameter T are known at compilation time. The C# compiler could replace the static call with a interface call on the proxy. On a CLI version, the JIT compiler could resolve it once and for all and emit a static call. Use of a child type whose parent type implements the interface should not be allowed, the compiler could report this.

This could be combined with an extension method syntax to provide extension methods on types :

        public static bool IsInstanciated(static ICountable type)


            return type.Count != 0;


This one is a bit twisted, and I would gracefully admit changes in the syntax, but the point is that it would enable on type/classes the same kind of thing that Linq offers with interfaces : put the minimum set of methods in interface, then add lots of features around interface with extension methods.

Back to reality

Ok, I should sleep at night, but who knows, it’s perhaps useful.

If anyone sees other applications… just drop a comment.

Thursday, May 7, 2009

Decimal, what are those trailing zeros ?

Yesterday, I stumbled on something I didn’t expect at all…

An exception appeared while testing my code that I had been carefully writing following Design By Example..

Looking in my debugger my decimal two variables had value 4M.

But calling ToString on it led to different results : “4” and “4.00”…

What the heck ?! How come ?


I should have known this

Yes, the MSDN state it explicitly :

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied.

And I did not know that, did you ?


Try it yourself

you can try it yourself :

Console.WriteLine(1m);      // 1
Console.WriteLine(1.0m);    // 1.0
Console.WriteLine(1.00m);   // 1.00

Console.WriteLine(1m == 1.0m); // true
Console.WriteLine(1m.ToString() == 1.0m.ToString()); // false

The decimal.Parse function also preserve trailing zeros :

Console.WriteLine(decimal.Parse("1.0", CultureInfo.InvariantCulture)); // 1.0
Console.WriteLine(decimal.Parse("1.000", CultureInfo.InvariantCulture)); // 1.000


The explanation

The decimal type internally represents values using an 96 bit integer and a negative power of 10 (between 0 and 28).

Those values are simply internally stored like this :

1.0 –> 10 * 10^-1
1.000 –> 1000 * 10^-3

You can check it using the decimal.GetBits method.

The trailing zeros are even maintained in arithmetical operations :

Console.WriteLine(2.0m * 3.00m);  // 6.000

But are handled correctly by the equality and comparison methods :

Console.WriteLine(1m == 1.0m);  // true
Console.WriteLine(1m.GetHashCode() == 1.0m.GetHashCode()); // true


Do you know other secrets like this ?

Of course, my unit tests did not test case I didn’t expect to happen !

But, Hey ! If you knew it, you should have told me before !

What secret feature/behavior in the .Net framework or in the C# language do you know ?

Wednesday, December 24, 2008

Data Structures and Algorithms

I had a peek through Jon Skeet’s blog this morning at a free eBook called Data Structures and Algorithms by Granville Barnett and Luca Del Tongo.

The book is clear and presents the usual linked lists, trees, sets structures in a concise yet precise way.

There’s something new I had not seen in other algorithm books before. The algorithms are written in pseudo code, but there is a chapter about unit testing your implementation.

If the writers read this, I just would like to share a little tricks that make linked list algorithms easier to write..

Linked list algorithms are always bloated with tests like this :

        if (head == null)

            head = ...;


            node->Next = ...;

Actually the content of head and then content of node->Next are both pointers on next node. But the way to reference those two locations is different, ending in a lot of if statements.

If the language supports reference variables or pointer, you can use a double pointer to hold the current position :

Node** next = &head;

This way there is no more difference between the head (*next) and nodes Next pointers. The little tricky thing is to move to next location :

next = &((*next)->Next);

With this you can consider every ‘Next’ pointer including head as equivalent. No more if statement !

By the way, I was trying to find out how to do this on C#, but is it possible without going unsafe ?