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,640
|
Comments: 51,263
Privacy Policy · Terms
filter by tags archive
time to read 5 min | 812 words

I have several ways of categorizing code. Production quality, test, demo, and utilities. When I am talking about utilities, I am talking about little programs that I use to do all sorts of small tasks. There I rarely worry about maintainability, and today there was a gem here:

public delegate Control BuildSpecialCase(TextBox textbox);

private BuildSpecialCase GetSpecialCaseControl(string name)
{
 if (name.IndexOf("ConnectionString", StringComparison.InvariantCultureIgnoreCase) != -1)
 {
  return delegate(TextBox t)
  {
   Button change = new Button();
   change.Click += delegate { t.Text = PromptForConnectionString(t.Text); };
   change.Dock = DockStyle.Right;
   change.Text = "...";
   change.Width = 30;
   return change;
  };
 }
 if (name.IndexOf("File", StringComparison.InvariantCultureIgnoreCase) != -1)
 {
  return delegate(TextBox t)
  {
   Button change = new Button();
   change.Click += delegate
   {
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Multiselect = false;
    dialog.FileName = t.Text;
    if (dialog.ShowDialog(this) == DialogResult.OK)
    {
     t.Text = dialog.FileName;
    }
   };
   change.Dock = DockStyle.Right;
   change.Text = "...";
   change.Width = 30;
   return change;
  };
 }
 if (name.IndexOf("Folder", StringComparison.InvariantCultureIgnoreCase) != -1 ||
  name.IndexOf("Dir", StringComparison.InvariantCultureIgnoreCase) != -1)
 {
  return delegate(TextBox t)
  {
   Button change = new Button();
   change.Click += delegate
   {
    FolderBrowserDialog dialog = new FolderBrowserDialog();
    dialog.SelectedPath = t.Text;
    if (dialog.ShowDialog(this) == DialogResult.OK)
    {
     t.Text = dialog.SelectedPath;
    }
   };
   change.Dock = DockStyle.Right;
   change.Text = "...";
   change.Width = 30;
   return change;
  };
 }
 return null;
}

Can you figure out what is going on?

As long as we are talking about unmaintainable code, here an example from code meant for production that I just wrote:

IDictionary<Customer, IDictionary<string, IList<Policy>>> namedPoliciesByCustomers = new ...;

But for that I have tests :-)

For Experts Only

time to read 2 min | 349 words

There are some things that programmers really shouldn't do. I was once called to help figuring out why a batch process would run for a few hours at 100%. The previous guy has claimed that this was a natural occurance of the task at hand (loading XML file to DB), and that he had already optimized it as far as possible.

int count = 0;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filePath);

foreach(XmlNode node in xdoc.SelectNodes("data/row")) 
{
   count++;
   new Thread(delegate(object state){
        XmlNode n = (XmlNode)state;
        using(SqlConnection con = new SqlConnection("... "))
        using(SqlCommand cmd = con.CreateCommand ())
        {
            cmd.CommandText = "INSERT INTO .... ";
            cmd.ExecuteNonQuery();
        }
        Interlocked.Decrement(out count);
   }).Start(node);
}

while(count!=0); 

After de-optimizing the code, I managed to get 10,000% performance improvement, and you could actually use the server for more than a single task.

time to read 4 min | 734 words

Evaluate the following approaches:

List<Address> addresses = new List<Address>();

addresses.Add(customer.HomeAddress);

addresses.Add(customer.BusinessAddress);

addresses.Add(customer.ShippingAddress);

addresses.RemoveAll(delegate(Address a) { return a == null; });

And:

List<Address> addresses = new List<Address>();

if (customer.HomeAddress != null)

    addresses.Add(customer.HomeAddress);

if (customer.BusinessAddress != null)

    addresses.Add(customer.BusinessAddress);

if (customer.ShippingAddress != null)

    addresses.Add(customer.ShippingAddress);

Which do you think that I used? Which would you rather use?

time to read 3 min | 545 words

I am doing code reviews, and I am running into some unique ideas about how code should work. Take into account this new locking pattern:

public void ShouldOnlyAllowSingleInstance()
{
  object syncLock = new object();
  lock(syncLock)
  {
    // code that modify a thread-shared resource
   }
}

Everyone know that you can use threads to increase the reponsiveness and throughput of your application, but this approach reach a whole another level, although it didn't manage to meet quite the scalability requirements

public void CopyData(IDbCommand cmd)
{
    cmd.CommandText = "SELECT * FROM TableWith_700_Rows;"
    IDataReader reader = cmd.ExecuteReader();
   while(reader.Read())
   {
     CustomerCopier customer = CustomerCopier.FromReader(reader);
    new Thread(customer.DoCopy).Start();
   }
}

// In CustomerCopier

public void DoCopy()
{
   using(SqlConnection connection = CreateConnectionToSourceDb())
  {
    using(ITransaction tx = connection.BeginTransaction(SeperationLevel.Serializable))
    {
      // execute insert
    }
  }
}

Oh, and here is a general comment, while green is a soothing color, I do not need to see so much of it on the screen.

Update: In case is wasn't clear, the above samples are really bad code.

time to read 2 min | 360 words

It is not often that I am arriving to work and the first application that I open is Visual Studio, and I can't get it to open fast enough. Today was such a day, mostly because I got an Eureka moment. It is not often that I get those, so I really want to try it out.

Check out the following code:

public class Aggregator<T> : Aggregator<T, List<T>>

{}

 

public class Aggregator<T, TCollection>

     where TCollection : ICollection<T>, new()

{

     private ICollection<T> collection = new TCollection();

}

Can you tell why I am excited? Because this means that I have static generic specialization (I already have dynamic generic specialization, thanks to Windsor) back!

Notice that for all intents and purposes, I can either use Aggerator<T>, or use the more generic version of Aggerator<T, TCollection>, which allows me to pass my own ICollection<T> implementation.

This is actually compiler supported Inversion Of Control!

Now, of course that I can do this using ctor parameter, but this puts the burden on the client code, and couples the base implementation to the defaults. This approach keeps the base implementation frees from any default whatsoever.

I intend to make use of this soon, so I'll post about the results.

time to read 2 min | 211 words

Related to the previous post, I present you a simple SP that is highly vulnerable to SQL injections, and is directly related to my statement about evil sadistics bastards.

ALTER

PROCEDURE GetDataForDate
   @date
DATETIME
AS
  
DECLARE @sql nvarchar(max)
  
SET @sql = 'select * from data_' + convert(nvarchar(30),getdate(),112)
   
EXEC sp_executesql @sql

I think you can deduct what the rest of the system looked like, and what fun it was optimizing the reports that run over data gathered for years.

time to read 5 min | 889 words

I found that I need to group a collection by a certain attribute of its member quite often. Usually because I'm trying to do some crazy things with deeply nested and timed to put some data on the screen.

Anyway, here is the code:

public static IDictionary<T, ICollection<K>> GroupBy<K, T>(ICollection<K> collection, Converter<K, T> converter)

{

       Dictionary<T, ICollection<K>> dic = new Dictionary<T, ICollection<K>>();

       foreach (K k in collection)

       {

              T key = converter(k);

              if (dic.ContainsKey(key) == false)

              {

                     dic[key] = new List<K>();

              }

              dic[key].Add(k);

       }

       return dic;

}

It is not earth shattering or anything like it, but it is going to make a lot of tasks a lot easier now.

(BTW, this is now a part of Rhino Commons).

time to read 2 min | 387 words

Take a guess, what is going to be the result of the following code?

Enum one = DayOfWeek.Sunday;

Enum two = DayOfWeek.Sunday;

Assert.IsTrue(one == two);

Update: Tomas Restrepo, hit the nail on the head in the comments.

System.Enum is a reference type. The first line actually translates to:

L_0001: ldc.i4.0
L_0002: box [mscorlib]System.DayOfWeek
L_0007: stloc.0

There is boxing done here, and then the == is doing reference equality. I actually learned about this from Tomas, a while ago, when discussing about wierd-ass questions.

This is a freakish issue because Enum inherits from ValueType, so you would expect it to keep value types semantics. Check the comments for Tomas' for explanation

FUTURE POSTS

No future posts left, oh my!

RECENT SERIES

  1. API Design (10):
    29 Jan 2026 - Don't try to guess
  2. Recording (20):
    05 Dec 2025 - Build AI that understands your business
  3. Webinar (8):
    16 Sep 2025 - Building AI Agents in RavenDB
  4. RavenDB 7.1 (7):
    11 Jul 2025 - The Gen AI release
  5. Production postmorterm (2):
    11 Jun 2025 - The rookie server's untimely promotion
View all series

Syndication

Main feed ... ...
Comments feed   ... ...