Oren Eini

CEO of RavenDB

a NoSQL Open Source Document Database

Get in touch with me:

oren@ravendb.net +972 52-548-6969

Posts: 7,565
|
Comments: 51,184
Privacy Policy · Terms
filter by tags archive
time to read 1 min | 150 words

One of the things that I wanted to do with NH Prof is to build it in a way that would be very close to the Erlang way. That is, functional, immutable message passing. After spending some time trying to do this, I backed off, and used mutable OO with message passing.

The reason for that is quite simple. State.

Erlang can get away with being functional language with immutable state because it has a framework that manages that state around, and allow you to replace your state all the time. With C#, while I can create immutable data structures, if I want to actually create a large scale application using this manner, I have to write the state management framework, which is something that I didn't feel like doing.

Instead, I am using a more natural model for C#, and using the bus model to manage thread safety and multi threading scenarios.

time to read 2 min | 301 words

I am doing a spike in ASP.Net MVC now (and I'll talk about this at length at another time). I hit the wall when I wanted to do something that is trivially simple in MonoRail, limit a routing parameter to be a valid integer.

Luckily, just looking at the API signature told me that this is a supported scenario:

image

Unfortunately, that is all that it told me. This method accept an object. And there is no hint of documentation to explain what I am suppose to do with it. A bit of thinking suggested that I am probably supposed to pass an anonymous type with the key as the route parameter and the value is some sort of a constraint. But what sort of a constraint.

Type information is one of those things that static language actually do, and from experience in both dynamic and static languages, while it is often a PITA to specify types, it actually help for people who read the code. Not often, I'll admit, but it is helpful for the uninitiated.

I am... unused to having this type of problem in C#.

So I did what any developer would do, hit google and tried to find some information about it. Didn't work.

I pulled reflector and started to track down what is going on there. Following a maze of untyped paths that I have not seen the like since the 1.1 days, I finally figured out that the value that I need to push is an instance of IRouteConstraint.

Obvious, isn't it?

In short, and the reason of this post. I am seeing a lot of parameter signatures that look like that, and have barely defined semantics. I would file this under C#.Abuse();

Reading MEF code

time to read 3 min | 401 words

Okay, here is the deal. There is a feature in MEF that I find interesting, the ability to dynamically recompose the imports that an instance have. Well, that is not accurate. that doesn't really interest me. What does interest me is some of the implementation details. Let me explain a bit better.

As I understand the feature, MEF can load the imports from an assembly, and if I drop another file into the appropriate location, it will be able to update my imports collection. Now, what I am interested in is to know whatever MEF allow me to update file itself and update it on the fly. The reason that I am interested in that is to know how this is done without locking the file (loading an assembly usually locks the file, unless you use shadow copy assemblies, which means that you have to use a separate AppDomain).

As you can imagine, this is a very specific need, and I want to go in, figure out if this is possible, and go away.

I started by checking out the MEF code:

svn co https://mef.svn.codeplex.com/svn mef

I just love the SVN integration that CodePlex has.

Now, the only way that MEF can implement this feature is by watching the file system, and that can be done using a FileSystemWatcher. Looking for that, I can see that it appears that DirectoryPartCatalog is using it, which isn't really surprising.

But, going there and reading the code gives us this:

image

Note what isn't there. there is no registration to Changed. This is likely not something that MEF supports.

Okay, one more try. Let us see how it actually load an assembly. We start from Export<T> and GetExportedObject() which calls to GetExportedObjectCore() which shell out to a delegate. Along the way I looked at CompositionException, just to make sure that it doesn't have the same problem as TypeLoadException and the hidden information, it doesn't.

I tried to follow the reference chain, but I quickly got lost, I then tried to figure out how MEF does delayed assembly loading, to see if it is doing anything special there, but I am currently hung at ComposablePartDefinition.Create, which seems promising, but it is accepting a delegate and no one is calling this.

So this looks like it for now.

time to read 2 min | 314 words

I am going over a code base that I haven't seen in a while, and I am familiarizing myself with it by doing a code review to see that I understand what the code is doing now.

I am going to post code samples of changes that I made, along with some explanations.

image

This code can be improved by introducing a guard clause, like this:

image

This reduce nesting and make the code easier to read in the long run (no nesting).

image

I hope you recognize the issue. The code is using reflection to do an operation that is already built into the CLR.

This is much better:

image

Of course, there is another issue here, why the hell do we have those if statement on type instead of pushing this into polymorphic behavior. No answer yet, I am current just doing blind code review.

Here is another issue, using List explicitly:

image

It is generally better to rely on the most abstract type that you can use:

image

This is a matter of style more than anything else, but it drives me crazy:

image

I much rather have this:

image

Note that I added braces for both clauses, because it also bother me if one has it and the other doesn't.

Another issue is hanging ifs:

image

Which we can rewrite as:

image

I think that this is enough for now...

time to read 2 min | 265 words

Java Enums are much more powerful than the ones that exists in the CLR. There are numerous ways of handling this issue, but here is my approach.

Given this enum (defined in Java):

private static enum Layer {
    FIRST,
    SECOND;

	public boolean isRightLayer(WorkType type) {
		if (this == FIRST && type != WorkType.COLLECTION) return true;
		return this == SECOND && type == WorkType.COLLECTION;
		}
}

And the C# version is:

private class Layer
{
    public static readonly Layer First = new Layer(delegate(WorkType type)
    {
        return type != WorkType.Collection;
    });
    public static readonly Layer Second = new Layer(delegate(WorkType type)
    {
        return type == WorkType.Collection;
    });

    public delegate bool IsRightLayerDelegate(WorkType type);

    private readonly IsRightLayerDelegate isRightLayer;

    protected Layer(IsRightLayerDelegate isRightLayer)
    {
        this.isRightLayer = isRightLayer;
    }

    public bool IsRightLayer(WorkType type)
    {
        return isRightLayer(type);
    }
}
time to read 3 min | 548 words

I look at a bit of code that dealt with traversing expression an expression tree, using recursion, of course. The edge condition immediate popped to mind was unbounded expression. I decided to see if I can kill the compiler using this. Why? Because.

The first thing to do is to find out how deep a stack we usually need. I wrote this simple test:

class Program
{
	static void Main(string[] args)
	{
		Recursive(1);
	}

	static void Recursive(int i)
	{
		Console.WriteLine(i);
		Recursive(i+1);
	}
}

The last result was: 79994

Obviously this change based on how much stack space each function takes, but it is a good number to go with. I started with this code:

class Program
{
	static void Main(string[] args)
	{
		using(var fw = File.CreateText("text.txt"))
		{
			for (int i = 0; i < 80000; i++)
			{
				fw.Write(" a > "+i +" && ");
				if(i%10==0)
					fw.WriteLine();
			}
		}
	}
}

I then took the file ( slightly over 1 MB in size) and pasted the content to Visual Studio.

That was a mistake:

image

Okay, I can deal with this, let us try a different approach:

class Program
{
	static void Main(string[] args)
	{
		using(var fw = File.CreateText("text.cs"))
		{
			fw.WriteLine("public class Program {");
			fw.WriteLine("	static void Main(string[] args) {");
			fw.WriteLine("		var a = -1;");
			fw.Write    ("		var test = ");
			for (int i = 0; i < 80000; i++)
			{
				fw.Write(" a > "+i +" && ");
				if(i%10==0)
					fw.WriteLine();
			}
			fw.WriteLine(" a < 0;");
			fw.WriteLine("System.Console.WriteLine(test);");
			fw.WriteLine("	}");
			fw.WriteLine("}");

		}
	}
}

Trying to compile that produces:

fatal error CS1647: An expression is too long or complex to compile near ''

The help for CS1647 is:

There was a stack overflow in the compiler processing your code. To resolve this error, simplify your code. If your code is valid, contact Product Support.

The is valid, I guess, just not really reasonable. What is scary is that this is something that was added for 2.0, so at the 1.0 days, someone actually run into this issue.

Some experimentation showed that the C# compiler can handle expressions composed of 23,553 nodes. Now it is the time to get to the next stage, now the code is this:

class Program
{
	static void Main(string[] args)
	{
		using(var fw = File.CreateText("text.cs"))
		{
			fw.WriteLine("using System;");
			fw.WriteLine("using System.Linq.Expressions;");
			fw.WriteLine("public class Program {");
			fw.WriteLine("	static void Main(string[] args) {");
			fw.Write    ("		Expression<Predicate<int>> test = (a) => ");
			for (int i = 0; i < 11700; i++)
			{
				fw.Write(" a > "+i +" && ");
				if(i%10==0)
					fw.WriteLine();
			}
			fw.WriteLine(" a < 0;");
			fw.WriteLine("System.Console.WriteLine(test);");
			fw.WriteLine("	}");
			fw.WriteLine("}");

		}
	}
}

Note that I had to dramatically simplify the expression. Before it handled 23 thousands and change, but now it chokes on merely 12 thousands.

What is really surprising is that after compiling the code, it is running and seems to do the expected thing. Amazing.

Anyway, here is a completely useless post, but now I know that the C# compiler has well defined behavior for stack overflows. :-)

time to read 1 min | 126 words

I found something extremely surprising while profiling a project. Take a look at this piece of code:

Stopwatch stop = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
	new WeakReference(null);
}
stop.Stop();
Console.WriteLine("WeakRef: " + stop.ElapsedMilliseconds);

stop = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
	new string('a', 5);
}
stop.Stop();
Console.WriteLine("'aaaaa': " + stop.ElapsedMilliseconds);

On my machine, this has the following output:

WeakRef: 980
'aaaaa': 35

Creating a WeakReference is much more costly than creating a normal object. Not surprising, when you think of it, WeakReference has deep ties to the CLR, but I couldn't really believe it when I saw it the first time.

FUTURE POSTS

No future posts left, oh my!

RECENT SERIES

  1. Production Postmortem (52):
    07 Apr 2025 - The race condition in the interlock
  2. RavenDB (13):
    02 Apr 2025 - .NET Aspire integration
  3. RavenDB 7.1 (6):
    18 Mar 2025 - One IO Ring to rule them all
  4. RavenDB 7.0 Released (4):
    07 Mar 2025 - Moving to NLog
  5. Challenge (77):
    03 Feb 2025 - Giving file system developer ulcer
View all series

RECENT COMMENTS

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats
}