Tag Archives: dotNet

Lucene.Net and Transactions

Lucene Search Engine Logo

Lucene.Net is an open source full text search engine library (a port from Java). It is stable and works like a charm – I’ve been using Lucene.Net for a couple of years now and implement a handful of solutions. Lucene is awesome.

If you want to try working with Lucene.Net, then the DimeCast.Net crew has recently made two short webcasts introducing Lucene.Net.

.Net 2.0 made it simple to use transactions with the System.Transactions namespace. Two of the great features are automatic elevation to distributed transactions (and utilize the Distributed Transaction Coordinator) and the other is the simplicity of creating your own transactional resource managers.

The .Net Framework defines a resource manager as a resource that can automatically enlist in a transaction managed by System.Transactions – which means that any object that implements any of the following interfaces can enlist in a transaction:

  • IEnlistmentNotification for the two-phase-commit protocol
  • IPromotableSinglePhaseNotification for the single-phase-commit protocol (non-distributed transactions)

To implement a resource manager for the Lucene.Net IndexWriter, and therefore make it transactional, all you have to do is the following:

public class TransactionalIndexWriter : IndexWriter, IEnlistmentNotification
    #region ctor
    public TransactionalIndexWriter(Directory d, Analyzer a, bool create, MaxFieldLength mfl)
        : base(d, a, create, mfl)
    /* More constructors */

    public void EnlistTransaction()
        // Enlist in transaction if ambient transaction exists
        Transaction tx = Transaction.Current;
        if (tx != null)
            tx.EnlistVolatile(this, EnlistmentOptions.None);

    #region IEnlistmentNotification Members
    public void Commit(Enlistment enlistment)

    public void InDoubt(Enlistment enlistment)
        // Do nothing.

    public void Prepare(PreparingEnlistment preparingEnlistment)

    public void Rollback(Enlistment enlistment)

You can use it like so:

IndexWriter indexWriter = null;
TransactionScope tx = null;

    tx = new TransactionScope();
    indexWriter = new TransactionalIndexWriter(...);

    // Perform transactional work
    indexWriter.AddDocument(new Document());
    indexWriter.AddDocument(new Document());
    indexWriter.AddDocument(new Document());

    // Connect to Database, MSMQ etc. to elevate to a distributed transaction

    // Commit transaction
    if (tx != null)

    if (indexWriter != null)

Fairly simply uh? Just remember to instantiate the TransactionalIndexWriter or call the public method EnlistTransaction within the scope of an ambient transaction.
You might consider implementing IDisposable for TransactionalIndexWriter so you can take advantage of the using statement.

I will leave it to the reader to implement a TransactionalIndexReader.

Lucene.Net is an open source full text search engine library (a port from Java). It is stable and works like a charm – I’ve been using Lucene.Net for a couple of years now and implement a handful of solutions. Lucene is awesome.

If you want to try working with Lucene.Net, then the DimeCast.Net crew has recently made two 10 short webcast introducing Lucene.Net (http://dimecasts.net/Casts/ByTag/Lucene).

ASP.NET MVC Best Practices

ASP.Net MVCI love ASP.Net MVC – It has made web development fun. It also introduced new pitfalls…

Microsoft MVP Simone Chiaretta has fathered 12 ASP.NET MVC Best Practices worth reading.

In particular I find the these items interesting:

Monitors and thread context

Running the below code will fail – why?

var syncRoot = new object();


ThreadPool.QueueUserWorkItem(x => Monitor.Exit(syncRoot));

It will throw a SynchronizationLockException with the message “Object synchronization method was called from an unsynchronized block of code.”

It is because System.Threading.Monitor requires the Enter and Exit methods must be executed on the same thread for the same synchronization object.

I did not know that :-/

How to view default values for a WCF binding

… or create a custom binding from a build-in binding.
… or create an administrative XML-based configuration from an administrative programmatic configuration.

Below codes does all that:

// Specify the source binding
// - Programmatic binding
// - Administrative XML-based binding
// - Convert to custom binding

/* Programmatic binding */
var binding = new BasicHttpBinding();
binding.TransferMode = TransferMode.Streamed;
binding.MaxReceivedMessageSize = 10000;

/* Administrative XML-based binding */
// var binding = new BasicHttpBinding("basicHttp");

/* Convert to custom binding */
// var wsBinding = new WSHttpBinding("wsHttp");
// var binding = new CustomBinding(wsBinding);

string outputConfigFile = "out.config";

Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration();

var fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = outputConfigFile;
fileMap.MachineConfigFilename = machineConfig.FilePath;

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
config.NamespaceDeclared = true;

var scg = new ServiceContractGenerator(config);

string sectionName, configName;
scg.GenerateBinding(binding, out sectionName, out configName);

The programmatic source binding will create a configuration file with all default values for the BasicHttpBinding except for TransferMode and MaxReceivedMessageSize attributes like so:

    <binding name="BasicHttpBinding" 
        <readerquotas maxDepth="32" 
                      maxNameTableCharCount="16384" />
        <security mode="None">
            <transport clientCredentialType="None" 
                       realm="" />
            <message clientCredentialType="UserName" 
                     algorithmSuite="Default" />

I found this tip by Brian McNamara on the MSDN WCF forum.

Handcrafting the WCF client

Two years ago I wrote an article Building a Windows Communication Foundation client, describing three ways of creating WCF clients. I did not mention the fourth one, as I did not know at the time. Now I am older and wiser 😉

The four ways of creating a WCF client are:

  1. Visual Studio’s “Add Service” reference
  2. Service Model Metadata Utility Tool (SvcUtil.exe) command line tool
  3. Dynamic proxy with ChannelFactory
  4. Handcrafting the WCF client

The last two options are only viable for WCF to WCF implementations where you either have control of both service and client or the service provider supplies a .Net assembly. Because both of them require the service contract aka the .Net interface marked with ServiceContractAttribute and OperationContractAttribute.

Anybody that has tried the “Add Service” reference in Visual Studio knows it is broken. First of all it generates an enormous amount of files, even for the simplest service contract.

Secondly it sometimes corrupts the state of the generated files, so you have to remove the reference and then add it again.. Just try to google it and you will find many frustrated developers. Do not use it!

The SvcUtil.exe is better and has a vast number of options. This is the preferred option for non .Net services or where the service contract interface is not available.

The dynamic proxy with ChannelFactory is useful, but be aware that the interface returned does not implement IDisposable, but the implementation does. See below:

var factory = new ChannelFactory<ihelloworldservice>("myEndPoint");

IHelloWorldService proxy = factory.CreateChannel();

using (proxy as IDisposable)

Finally the handcrafted version – the one I want to talk about. Writing the WCF client by hand is fairly easy – it requires the implementation to inherit from ClienBase and implementing the service contract interface. Below is first a simple service contract IHelloWorldService:

[ServiceContract(Namespace = "www.lybecker.com/blog/HelloWorldService")]
public interface IHelloWorldService
   string HelloWorld();

Next the handcrafted WCF client with constructors and service contract interface implementation:

public class HelloWorldClient : ClientBase<ihelloworldservice>, IHelloWorldService
   public HelloWorldClient()
   { }

   public HelloWorldClient(string configurationName) : base(configurationName)
   { }

   public HelloWorldClient(Binding binding, EndpointAddress address) : base(binding, address)
   { }

   public string HelloWorld()
      return Channel.HelloWorld();

That’s it. 🙂

Now you have full control of the WCF client implementation.

Download the sample application Hello World WCF clients including a handcrafted version