Foreach loop – eligible types

Apparently, the types are not required to implement IEnumerable to be iterated over with foreach loop – they just required to have GetEnumerator() method.

 

class EnumerableItem
{
}

class EnumerableItemsCollection // : IEnumerable<EnumerableItem>
{
    public IEnumerator<EnumerableItem> GetEnumerator()
    {
        return null;
    }
    public static void Test()
    {
        foreach (var item in new EnumerableItemsCollection())
        {
        }
    }
}

The code above compiles just fine.
My first thought was – “Reflection ?”. Can’t be, Reflection is too slow. It is, in fact, handled by compiler.

First, it checks if the type can be implicitly converted to an IEnumerable; if it can’t – it will look for a GetEnumerator method.

Also, the foreach loop calls for Dispose on enumerated object, so using using on it is redundant.

Btw, for some reason foreach loop seems to be a bit faster than for loop (not by much, and they’re both very fast.. don’t switch for loops to foreach to speed up your code :)).

 

For references, check the C# language specs document.

Better folder browser dialog in WinForms

The FolderBrowserDialog provided by .NET is just plain bad, the one that comes standard with Vista/7 is so much better..

So, download Windows API Code Pack, and then

using Microsoft.WindowsAPICodePack.Dialogs;

and

using (Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog folderDialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog())
{
 folderDialog.IsFolderPicker = true;
 if (folderDialog.ShowDialog() == CommonFileDialogResult.Ok)

 {
     string folder = folderDialog.FileName;
 }
}

This will give you a dialog like this:

“(500) Internal Server Error” when POSTing JSON

Just spent probably 2 hours on trying to figure this out.. Super-simple POST to a rest api, along those lines:

 
public static string SendToWebService(string url, CommunicationMessageBase message)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentException("Empty url");
            if (message == null)
                throw new ArgumentException("Message is null.");
 
            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/json");
                return client.UploadString(url, "POST", message.ToJSON());
            }
        }

This is a correct code, which was failing, returning server 500 error. Basically, I was passing an object of a class, inhrerited from CommunicationMessageBase.. And I forgot to define parameterless constructor on the child class! D-uh!

IoC performance – StructureMap

This is a continuation of NInject performance, in a way.

Ran same test with StructureMap, and results look much better comparing to Ninject: 309ms to create 100k objects using StructureMap vs 2ms to create same number of objects just using constructors. That’s about 7x faster than Ninject.

Again, here’s the code I used to test (though it didn’t change much).

 

class StructureMapPerfTest
    {
        public StructureMapPerfTest()
        {
            this.InitIoC();
        }
 
        private void InitIoC()
        {
            ObjectFactory.Initialize(x =>
            {
                x.For<IWorker>().Use<Worker>();
            });
        }
 
        public void Test()
        {
            int count = 100000;
 
            DateTime start = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                IWorker w = ObjectFactory.GetInstance<IWorker>();
            }
            Debug.WriteLine(DateTime.Now.Subtract(start).TotalMilliseconds + " ms with Ioc");
 
            start = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                IWorker w = new Worker();
            }
            Debug.WriteLine(DateTime.Now.Subtract(start).TotalMilliseconds + " ms with constructor");
        }
 
        interface IWorker
        {
            void DoWork();
        }
 
        class Worker : IWorker
        {
            public void DoWork()
            {
                Console.WriteLine("Working hard");
            }
        }
     }

Ninject performance

This was somewhat unexpected to me.

Just ran a test on how long it takes Ninject to instantiate 100.000 objects, and it took over a 1000x longer than making those objects using constructor (2269 ms  vs 2 ms).  If I’m asking Ninject to return a singletone, it drops down to about 1200 ms.

Yeah, it’s a lot of instances, so it’s not likely to make noticeable difference in real applications, but it’s something worth keeping in mind.  When working on a high-volume web site, this can be noticeable.

Here’s the code I used to test, just in case:

 

class NinjectPerfTest
    {
        Ninject.IKernel kernel = null;
 
        public NinjectPerfTest()
        {
            this.InitNinject();
        }
 
        private void InitNinject()
        {
            this.kernel = new Ninject.StandardKernel(new NinjectModule());
        }
 
        public void Test()
        {
            int count = 100000;
 
            DateTime start = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                IWorker w = this.kernel.Get<IWorker>();
            }
            Debug.WriteLine(DateTime.Now.Subtract(start).TotalMilliseconds + " ms with ninject");
 
            start = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                IWorker w = new Worker();
            }
            Debug.WriteLine(DateTime.Now.Subtract(start).TotalMilliseconds + " ms with constructor");
        }
 
        interface IWorker
        {
            void DoWork();
        }
 
        class Worker : IWorker
        {
            public void DoWork()
            {
                Console.WriteLine("Working hard");
            }
        }
 
        private class NinjectModule : Ninject.Modules.NinjectModule
        {
            public override void Load()
            {
                this.Bind<IWorker>().To<Worker>().InSingletonScope();
            }
        }
    }