Posts Tagged ‘dotNet’

Lucene.Net and Transactions

Thursday, December 3rd, 2009

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)
    {
        EnlistTransaction();
    }
    /* More constructors */
    #endregion

    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)
    {
        base.Commit();
        enlistment.Done();
    }

    public void InDoubt(Enlistment enlistment)
    {
        // Do nothing.
        enlistment.Done();
    }

    public void Prepare(PreparingEnlistment preparingEnlistment)
    {
        base.PrepareCommit();
        preparingEnlistment.Prepared();
    }

    public void Rollback(Enlistment enlistment)
    {
        base.Rollback();
        enlistment.Done();
    }
    #endregion
}

You can use it like so:

IndexWriter indexWriter = null;
TransactionScope tx = null;

try
{
    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
    tx.Complete();
}
finally
{
    if (tx != null)
        tx.Dispose();

    if (indexWriter != null)
        indexWriter.Close();
}

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

Thursday, October 29th, 2009

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

Thursday, October 15th, 2009

Running the below code will fail – why?


var syncRoot = new object();

Monitor.Enter(syncRoot);

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

Thursday, April 23rd, 2009

… 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);
config.Save();

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

<basichttpbinding>
    <binding name="BasicHttpBinding"
             closeTimeout="00:01:00"
             openTimeout="00:01:00"
             receiveTimeout="00:10:00"
             sendTimeout="00:01:00"
             allowCookies="false"
             bypassProxyOnLocal="false"
             hostNameComparisonMode="StrongWildcard"
             maxBufferSize="65536"
             maxBufferPoolSize="524288"
             maxReceivedMessageSize="10000"
             messageEncoding="Text"
             textEncoding="utf-8"
             transferMode="Streamed"
             useDefaultWebProxy="true">
        <readerquotas maxDepth="32"
                      maxStringContentLength="8192"
                      maxArrayLength="16384"
                      maxBytesPerRead="4096"
                      maxNameTableCharCount="16384" />
        <security mode="None">
            <transport clientCredentialType="None"
                       proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="UserName"
                     algorithmSuite="Default" />
        </security>
    </binding>
</basichttpbinding>

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

Handcrafting the WCF client

Thursday, March 5th, 2009

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)
{
   MessageBox.Show(proxy.HelloWorld());
}

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
{
   [OperationContract]
   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

Visiting Microsoft in Johannesburg, South Africa

Wednesday, February 11th, 2009

I live and work in the suburbs of Copenhagen in Denmark, but I’m currently in South Africa on business. While I’m here I might as well visit Microsoft South Africa – I did that today. I attended a presentation of the .Net services by Juval Löwy.

Microsoft South Africa is situated in a nice and fairly new building, as you can see on the picture above.

I was amazed about the level of security – first I had to cleared by the security guards before entering the parking lot. This is not uncommon in South Africa, but very uncommon in Denmark.

Inside in the reception the security check barriers prevent unauthorized people to enter.

When I finally was granted access to the presentation, Microsoft served sodas, pizza and beer!

.Net 3.5 installation WTF

Thursday, November 27th, 2008

Installing .Net 3.5 SP1 can be difficult, especially when below screen appears :-)

A colleague of mine stumbled upon this today. You cannot install SP1 because the SP1 install setup process is running :-D

I just had to share it with you.

Serialization in .Net 3.5 SP1

Saturday, November 22nd, 2008

In .Net 3.5 SP1 it is now possible to serialize any object that has a default constructor without decorating it with [DataContract] or [Serializable].

Developers have these choices now when serializing objects:

  • Implicit serialization – requires public default constructor and only serialize public read/write fields
  • Use the [Serializable] attribute
  • Use [DataContract] and [DataMember] attributes
  • Implement the ISerializable interface

I must say, that I’m not keen on this new feature. I prefer explicit serialization to implicit serialization. I predict that implicit serialization of entire object graphs will cause performance problems for many .Net developers in the years to come. This could also be a good thing as I am a consultant  ;-)

Aaron Skonnard has a more detailed blog post about the new serialization features in .Net 3.5 SP1.

.Net debugger visualizers

Sunday, October 12th, 2008

The .Net framework 2.0 gave some great tools for debugging – they are a great help when writing code.

Some of these features are the DebuggerDisplay and DebuggerStepThrough attributes. I seldom use any of them, as I prefer to just overriding the ToString method instead of using the DebuggerDisplay attribute. This makes it easy to instrument the code too, as I can reuse the ToString method implementation for tracing.

Another feature is the ability to develop custom debugger visualizers. They enable smart developers to build their own. I find some really useful, especially the WCF visualizer. But there a many – check out this list of custom .Net debugger visualizers.

These small enhancements make it so easy to get an overview of the current state, instead of inspecting properties.

Microsoft releasing the .Net framework source code

Thursday, October 4th, 2007

But only for sneak peaking.

Read more on Scott Guthrie’s blog.