Jun 18 2009

Using Memcached with NHibernate

Category: Uncategorizedzvolkov @ 1:35 pm

Memcached is a data caching system used by such giants as YouTube, Facebook, Digg, Twitter, Wikipedia, SourceForge and others. Since it’s free and open source you can use it for many purposes, either directly from C#, or as a SQL-backed distributed ASP.NET session provider, but in this post, I’ll focus on how to configure Memcached as a 2nd level cache provider for NHibernate.

If you don’t know what 2nd level caching is, read this post on Hibernating Rhinos blog, plus check out related section in NHibernate documentation. You may also want to check this post on Pragmatic Developer’s Blog to see how to unit-test that your queries and entities actually use 2nd level cache. Assuming you’re beyond that, and have your cache working with SysCache provider, let’s move on!

First of all you’ll need Memcached provider for NHibernate. If you worked with SysCache provider, you already received all available providers, including Memcached, as a part of NHibernate.Caches package from NHContrib project on SourceForge. And of course, you’ll need the Memcached itself. Besides getting it from its native web site where it’s only available in its Linux form, you can also get a windows version here (version 1.2.6) or here (version 1.4.4) and configure it like so.

However, a much better option is to get it as a part of MemCacheD Manager, a free app that automates installation and configuration of Memcached on Windows servers. The good part about MemCacheD Manager (MM), you don’t need to manually install the Memcached. Instead, MM can remotely connect to a Windows server, install Memcached as a windows service, and configure it to listen on a port! It even works on 64-bit platform, at least on my Windows Server 2008 development machine.

The MM includes same 1.2.6 version of Memcached, but if you choose to get a newer version from here, you can easily upgrade it remotely by copying the new memcached.exe over to MM folder. Then, simply right click on each server and select “Redeploy / Update MemCacheD” and your specified version will be copied to the remote machine, and the Memcached service will be restarted!

Once you have Memcached up and running, it’s time to configure NHibernate to use it. I use NHibernate version 2.0.1.GA and NHibernate Caches version 2.0.0.GA, so all the config details below are specific to those versions. As this thread illustrates, different versions of NHibernate Caches may use different configuration settings.

If you worked with SysCache you know that the first thing to do is to specify provider class in your NHibernate config. Depending on how exactly you configure your application (using Spring Framework’s NH extensions, using App.Config, or programmatically) the exact syntaxis may vary, but essentially all you need to do is to set property cache.provider_class to NHibernate.Caches.MemCache.MemCacheProvider, NHibernate.Caches.MemCache. This requires that at run-time, your application is able to find the DLLs, and indeed, you’ll need to add ICSharpCode.SharpZipLib.dll, Memcached.ClientLibrary.dll and NHibernate.Caches.MemCache.dll to your build script or add them as references to your project (the last option is not recommended as you may want to change the cache provider w/o having to recompile the app). Don’t forget to unblock the downloaded DLLs, otherwise Visual Studio will freak out and refuse to load them:

Next step is to add memcache section to your App.Config. That will tell Memcache NH Provider which server/port to connect to. Please note that in the current version this must be done in App.Config, not in Spring config, nor programmatically. Here’s what you need to add to your App.Config:

<configuration>
      <configSections>
            <section name="memcache" type="NHibernate.Caches.MemCache.MemCacheSectionHandler, NHibernate.Caches.MemCache"/>
      </configSections>
      <memcache>
            <memcached host="127.0.0.1" port="11211" weight="1" />
            <memcached host="X.Y.Z.Q" port="11211" weight="3" />
      </memcache>
</configuration>

As this post indicates, the optional weight attribute should be set proportionaly to load handling ability of the Memcached server. In the above example server X.Y.Z.Q can handle 3 times more requests than our localhost, so Memcached client will distribute its requests accordingly. If you didn’t get it still, Memcached does not replicate data between the instances (unlike its twin brother repcached), nor does it have any keyspace partitioning mechanism (unlike a real DHT) that would decide which item goes to which instance. Both put and get requests are distributed randomly accross all servers, with distribution controlled on each client with the weight parameter. Correction: it turns out Memcached does implement a key partitioning algorithm as explained in this 2004 article; it is responsibility of the client library to ensure that for a given key, the same Memcached node will be consistently picked to handle that key. In the example above, entire space of all possible item keys is split into 4 “buckets” with 3 of them going to X.Y.Z.Q and only 1 to localhost.

If everything is configured correctly, you should be able to hit the cache with your app and see the stats getting updated on MM status tab:

Two important settings that you set in NHibernate properties are “expiration” (in seconds) and “failover” — a boolean value that tells the client whether to try another server if this one fails to respond (true by default). Finally, if you’re crazy enough to share the same cache farm between the applications (e.g. multi-tenant scenarios), remember to set “cache.region_prefix” to a unique value for each application.

One convenient way to troubleshoot your caching, is to use Memcached telnet interface. Simply telnet to the port the Memcached runs on, and use memcached protocol to access stats, get/set cached values etc.

I believe this is enough information to get you started.

Rephrasing the classic, in near future there’s gonna be no theater, nor television, just one eternal cache! Enjoy it while you can!


Jun 12 2009

Parallels Extensions for .NET Framework 3.5

Category: Uncategorizedzvolkov @ 1:06 pm

Today I had very pleasant experience with new library that Microsoft will ship as part of .NET 4.0. If you want to start playing with it now, it’s available as Parallels Extensions for .NET Framework 3.5 and you can easily get it from Microsoft web site. Note that as any other .NET assembly, it does _not_ have to be installed, you can simply drop it alongside your application binaries.

The piece that got me so excited today is called “CountdownEvent” — this is a synchronization primitive that helps your write elegant multithreaded code.

Consider following example. In order to reproduce a race condition, I need to start two threads at exactly the same time, wait until they’re done, and then see if the error happened in one of them. Having two threads wait for an event is trivial with ManualResetEvent. However, traditionally, waiting until both threads are done was a more challenging task, requiring multiple ManualResetEvents, and WaitAll, or, even worse, Monitor and pulsing. This was error prone and required careful testing. 

Now, thanks to the CountdownEvent, you simply start at a number, make your worker threads do .Decrement(), and just do a Wait in your main thread. Bravissimo!

using System;
using System.Threading;
using FileHelpers;
using NUnit.Framework;

namespace FileHelpersTests.Tests.Common
{
    [TestFixture]
    public class Multithreading
    {
        private ManualResetEvent flagStart;
        private CountdownEvent flagFinish;
        private Exception initializationException;

        [Test]
        public void AsyncEngineInitialization()
        {
            flagStart = new ManualResetEvent(false);
            flagFinish = new CountdownEvent(2);

            new Thread(InitializeAsyncEngineWhenFlagIsRaised).Start();
            new Thread(InitializeAsyncEngineWhenFlagIsRaised).Start();

            flagStart.Set();
            flagFinish.Wait();

            if (initializationException != null) throw new ApplicationException("Failure during AsyncEngine initialization", initializationException);
        }

        private void InitializeAsyncEngineWhenFlagIsRaised()
        {
            flagStart.WaitOne();
            try
            {
                new FileHelperAsyncEngine<SampleType>();
            }
            catch (Exception e)
            {
                initializationException = e;
            }
            flagFinish.Decrement();
        }

    }
}


Jun 11 2009

.NET Framework sources, Reflector, Resharper and Visual Studio

Category: Uncategorizedzvolkov @ 2:28 pm

You use .NET Reflector regularly. You know what Resharper is, and with any luck you’ve talked your boss into buying you the license (if he won’t, I highly recommend you to pay for it by yourself, it’s WELL worth the money). You may even know that Microsoft has released the source code for .NET Framework, complete with variable names and comments. What you probably do NOT know is that you can bring this all together for a seamless experience. Imagine: you Ctrl+Left-Mouse-Click on a class name, be it third-party or Microsoft, and it shows you the source code, complete with comments, or, if source code is not available, brings up the Reflector. Getting Reflector to work is pretty easy, but getting the .NET sources download to work is a little trickier.

Here’s how to set it up:

  • Get Visual Studio 2008 (regular or SP1) or 2005
  • Install Resharper 4.1 or 4.5
  • Install Reflector
  • Install Scout plug-in for Resharper
  • Make sure you have .NET Framework 2.0 SP1/SP2 and 3.5 SP1
  • If you run Visual Studio 2008 pre-SP1 you may need to install this hot-fix for VS 2008 that “updates a DLL that’s part of the Visual Studio debugger that fetches the source” but don’t do this until you run into issues after doing all the steps below
  • If you run Visual Studio 2005, you will have to manually install Microsoft Debugging Tools and copy srcsrv.dll & symsrv.dll into your Program Files\VisualStudio\Common7\IDE folder
  • Configure Visual Studio as per Microsoft’s instructions, most importantly
    • Uncheck “Enable Just My Code (Managed only)”
    • Check “Enable source server support”
    • Uncheck “Require source files to exactly match the original version”
    • Check “Enable .NET Framework source stepping” – VS 2008 only
    • Add http://referencesource.microsoft.com/symbols as the first location of symbol files (or, in my case, the only location)
    • Set the symbols cache folder and make sure the folder exists
    • Clear “Search the above location only when symbols are loaded manually”
    • In VS 2008, the two buttons at the bottom of Options -> Debugging -> Symbols dialog will stay disabled, that’s Ok!
  • Go to Resharper -> Options -> Search and Navigation -> Scout
    • specify path to .NET Reflector
    • make sure both “Recover source locations from program debug database (pdb) files” and “Use Red Gate .NET Reflector” are enabled.
    • Select “use debugger settings” for the .NET source location
  • You may need to restart Visual Studio and/or reload the solution.

Now, with any luck you should be able to “Go To Declaration” of any symbol and see its source code, either natively, or in Reflector, or, like I say you can just Ctrl+Left-Mouse-Click! Of course you can also step-by-step debug .NET sources, even w/o Resharper or the Scout plugin.

P.S. If source files for a given class can’t be downloaded, Scout automatically launches Reflector. Since loading source for a particular class takes a while, first few times you Ctrl+Click on it it may bring up the Navigate menu I shown above. This does not mean the feature does not work but most probably you’ll have to cancel the menu and try again a few times until it loads the source. Depending on your OS version and platform some classes will never work no matter how many times you try. For me, IDictionary<TKey, TValue> does not work while Object and String do.


Jun 11 2009

Notepad++

Category: Uncategorizedzvolkov @ 10:32 am

For some time now I’ve been a big fan of Notepad++, a free open source text editor. I use it for all kinds of ad-hoc text editing — looking at log files, configs, xml, some random C# sources etc. Some people still use notepad for those kinds of things and I just can’t stress enough how much time and frustration you’ll save if you switch to Notepad++.

Think about this: how much time you spend clicking Start and typing notepad.exe in the Run window? Or clicking through Programs menu to find notepad? Guess what, notepad++ adds a context menu item to windows, so you just right click on any file -> Edit In Notepad++

Not just it feels snappy, supports multi-tabs and syntax highlighting, you can even get a dark color theme for it: Vibrant Ink. Here’s how it looks:

You can download notepad++ here. The Vibrant Ink theme is available here, copy it to C:\Users\[your user name]\AppData\[Local or Roaming]\Notepad++ on Vista. UPDATE: Vibrant Ink is now built-in, you can select it at Settings / Style Configurator / Select Theme. You’ll want to change the font size in Default Style and in Brace Highlight Style to the same size (I use 8).

P.S.

Once you installed the color theme, go to Settings -> Styler Configurator and set Dina as the default font for Global Styles / Default style. If you still don’t use Dina, the best programming font ever, here it is, just download and copy to C:\Windows\Fonts folder.


Jun 09 2009

Using Regular Expressions in Visual Studio find-and-replace window

Category: Uncategorizedzvolkov @ 12:48 pm

In the best spirit of Yesterday’s news I keep posting on stuff everybody knows about. Today I finally had a task that required using RegEx in Visual Studio find-and-replace window.

I had bunch of NHibernate mappings with same string pattern repeated multiple times:

<property name="***Name1***">
  <column name="***Name1***" />
</property>
<property name="***Name2***">
  <column name="***Name2***" />
</property>
<property name="***Name3***">
  <column name="***Name3***" />
</property>

I wanted to replace each of them with the following:

    <property name="***NameX***"/>

As you see, not only this spans multiple lines, but it also requires the regular expression to find all places where the column name is the same as property name and use than name in the resulting string.

First of all I went to VS find-and-replace window (Ctrl+H) and enabled regular expressions by checking the “Use” checkbox and selecting Regular Expressions from the drop down box.

The next step was to figure out the regex. Now, if your experience with regular expressions is limited to copypasting them from the web, you may think it’s too complicated to be used for an adhoc find-and-replace operation like this, but in reality it turns out to be very simple. Here’s what you should do:

  • Escape any non-alphanumeric symbols with \ like so: \<property name\= and so on.
  • use [A-Z]+ to match 1 or more letters, it is case insensitive, like so: \<property name\=\”[A-Z]+\”\>
  • use \n to match end of line like so: \<property name\=\”[A-Z]+\”\>\n
  • use space followed by star (i.e. ” *”) to indicate any number of spaces, like so: \<property name\=\”[A-Z]+\”\>\n *
  • finally, to reference back to a part of the string matched by this expresssion, you need to use so called capture groups. For that you need to surround corresponding part of the regex with figure brackets {} and reference it in the subsequent part of the regex with \1, like so: \<property name\=\”{[A-Z]+}“\>\n *\<column name\=\”\1\” *\/\>\n *\<\/property\>
  • As for the resulting string to replace with, keep in mind it’s not a regex, but it does support some advanced features like \n for new line and \1 to reference capture group #1. Remember to escape non-alphanumeric characters. The final expression may look like so: \<property name\=\”\1″\/\>\n

As you see the {} piece was different than normal RegEx syntaxis for capture groups where you use round brackets () to indicate capture groups.

Happy replacing, and remember: it’s always better to spend more time but learn something new than to save time and stay dumb!

P.S. here’s a Coding Horror post from 2006 that covers this topic in more details: http://www.codinghorror.com/blog/archives/000633.html


Jun 09 2009

Enabling IntelliSense for XML files in Visual Studio

Category: Uncategorizedzvolkov @ 11:24 am

Some people (including the authors of NHibernate In Action book) say that in order to enable IntelliSense for XML files in Visual Studio (for example for Wix, NHibernate or Spring.NET) you need to copy corresponding XSD files to Program Files\Microsoft Visual Studio 9.0\Common7\Packages\schemas\xml

This is not accurate. Correct location is Program Files\Microsoft Visual Studio 9.0\Xml\Schemas\