Deterministic disposal of your COM objects in .Net

In our migration process, we encounter a few(~6) VB6 classes with heavy logic in their destructors. In the old world of VB6, the destructor was called after setting the object to Nothing (deterministic destructor) which is quite the opposite than the new world of .Net where the Garbage Collector is in charge of disposing the objects and you can’t never know when the destructor will be called. This means that wrapping an old VB6 dll with an Interop and using one of it’s classes in our .Net classes, will now make its destructors non-deterministic(The proxy is also managed in the CLR, so it behaves by the same rules every .Net class follow) which is very bad for our application – performance-wise, memory leaks etc. Our solution was to force the disposal of the object by calling Marshal.ReleaseComObject in a “Interop Wrapper”, and here is the concept:


Let’s say that we have a VB6 dll named Class1.dll (COM dll) which contains MyService class with some logic in its destructor.
We create an Interop for it which will be called Interop.Class1.dll (this is .Net assembly).
And here is our “Interop Wrapper” (named ComObjectScope) and our consumer(MyClass).


/// <summary>
/// Wrap a COM object in order to control its life cycle (deterministic disposal).
///
/// Usage:
/// MyComObject obj = new MyComObject();
/// using (new ComObjectScope(obj))
/// {
/// // Use obj here.
/// } // here obj will be disposed. Don’t use it outside of the using block.
/// </summary>
/// <example>
/// MyComObject obj = new MyComObject();
/// using (new ComObjectScope(obj))
/// {
/// // Use obj here.
/// } // here obj will be disposed. Don’t use it outside of the using block.
/// </example>
public class ComObjectScope : IDisposable
{
   private bool _isDisposed = false;
   private object _comObject;

   public ComObjectScope(object comObject)
   {
      if (!comObject.GetType().IsCOMObject)
         throw new ArgumentException(“The provided object must be of COM object type.”);

      _comObject = comObject;
   }

   protected virtual void Dispose(bool disposing)
   {
      if (_isDisposed)
         return;

      if (!_isDisposed)
      {
         if (disposing)
         {
            Marshal.ReleaseComObject(_comObject); // This baby release the COM object for good.
            _comObject = null;
         }
      }

      this._isDisposed = true;
   }

   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);
   }

   ~ComObjectScope()
   {
      Dispose(false);
   }
}


public class MyClass
{
    public void DoSomethingWithComObject()
    {
        Interop.Class1.MyService service = new Interop.Class1.MyService();
        using (new ComObjectScope(service))
        {
            // …
            // use service here as needed.
            //….
        
        } // here service will die and its destructor will be called

        // don’t use service here! you’ll get NullReferenceException
    }    
}

 

VB.NET to C# convertor

This post is mainly self referral, but hack – it might be useful for the random reader as well.


We are converting a few (very small)projects of us from VB.NET 2.0 into C# 2.0. We thought that converting everything manually will take something like 2 hours, but we managed to find an on-line convertor that will cut our work into ~10 minutes. The 10 minutes will be spent on building a new Project as this on-line tool can’t migrate our *.vbproj files into *.csproj files. There are tools on the market that actually support it, but they cost money and therefore recommended only if you migrate big chunks of code\projects\solution.


Our migration process:


1. Create a new C# Project for each VB.NET Project.
2. Create classes files in C# for each VB.NET files.
3. Migrate each VB.NET code via the automatic tool and put the result in the related C# file.
4. Run our Unit Tests.
5. Delete our VB.NET projects (bye bye VB.NET)
6. Smile… :-)


You can find the automatic convertor tool here.

 

TDD in the eyes of a simpleminded: Manual Stub .vs. Mock Stub

Source Code:


RhinoMocksExample.zip (94.18 KB)


You will need to download and install Nunit 2.2.8 and RhinoMocks(for .Net 2.0) in order to run the tests.


Background:


Not as usual, we’ll start with the code and continue with it’s UnitTests.
We have a single, simple class named MailService. This class contains one method named MailText(string textToMail, params MailInfo[] mailList) that looks like this:


public class MailService
{
   private IMailValidator m_mailValidator;
   public IMailValidator MailValidator // setter, getter

   public void MailText(string textToMail, params MailInfo[] mailList)
   {
      foreach (MailInfo mail in mailList) { //I know I can collect addresses…
         ValidationResult validationResult = this.MailValidator.Validate(mail);

         if (!validationResult.IsValid)
            throw new ArgumentException(“Invalid mail: “ + validationResult.ValidationMessage, “mail”);

         // Send the email somehow…
      }
   }
}


And here is the IMailValidator, MailInfo and ValidationResult:


public class MailInfo {
   public string Address; //not best practice
   public MailInfo(string address) { this.Address = address; }
}

public class ValidationResult {
   public bool IsValid; //not best practice
   public string ValidationMessage; //not best practice

   public ValidationResult() { IsValid = true; ValidationMessage = string.Empty; }

   public ValidationResult(bool isValid, string message) {
      IsValid = isValid;
      ValidationMessage = message;
   }
}

public interface IMailValidator {
   ValidationResult Validate(MailInfo mail);
}


That is pretty straightforward I hope.


Testing inner behavior:


MailService.MailText has one dependency to IMailValidator. One way of testing our MailService.MailText method is via manual stub implementation of IMailValidator. Let’s examine the tests and then look at the manual stub I’ve created.


1). Manual stub based testing:

[TestFixture]
public class MailServiceTests
{
   [Test]
   public void MailText_OneValidEmail_MethodWorks()
   {
      MailService service = new MailService();
      MailInfo mail1 = new MailInfo(“valid@mercury.com”);

      service.MailValidator = new StubMailValidator();

      service.MailText(“Enlarge your ‘memory stick'”, mail1);
   }

   [Test]
   [ExpectedException(typeof(ArgumentException))]
   public void MailText_OneValidEmailAndOneInvalidEmail_ThrowException()
   {
      MailService service = new MailService();
      MailInfo validMail = new MailInfo(“valid@mercury.com”);
      MailInfo invalidMail = new MailInfo(“invalid.com”);

      service.MailValidator = new StubMailValidator();

      service.MailText(“Enlarge your ‘memory stick'”, validMail, invalidMail);
   }
}


And here is the simple StubMailValidator in one of it’s versions: (This stub was developed after the first test(MailText_OneValidEmail_MethodWorks) was written)


public class StubMailValidator : IMailValidator
{
   public ValidationResult Validate(MailInfo mail)
   {
      ValidationResult res = new ValidationResult(); //default: valid.
      if (mail.Address.IndexOf(“.com”) == -1) {
         res.IsValid = false;
         res.ValidationMessage = “The email address must end with .com”;
      }

      return res;
   }
}


NOTICE: Manual stubs with inner logic can be devastating !


As you may or may not notice, this stub has a bug in it. Just look at the second test on the “invalid.com” MailInfo. This is an invalid email address and yet, our stub will say that it’s valid and fail our second test. This is extremely dangerous! It is one of the things that makes people afraid from Unit Testing. When your stub need to switch his response according to a given parameter(s) based on some logic, you better switch your manual stub with dynamic\generated stub. You don’t want any test-related logic outside of your test method. Let’s look at mocked stub testing.


2). Mock stub based testing:


I’m using Oren Eini’s (aka Ayende) RhinoMocks for simulating “controlled” implementation of IMailValidator. That means that you are creating some dynamic implementation of IMailValidtor and you are telling it how to act when the tested method calls it.


Let’s look at our first test:


[Test]
public void MailText_OneValidEmail_MethodWorks()
{
   MailInfo validMail = new MailInfo(“valid@mercury.com”);
   ValidationResult validValidationResult = ValidationResult(true, string.Empty);

   // —— (1) ——-
   MockRepository mocks = new MockRepository();
   IMailValidator validator = (IMailValidator)mocks.CreateMock<IMailValidator>();
   Expect.Call(validator.Validate(validMail)).Return(validValidationResult);
   // ——————

   service.MailValidator = validator;

   mocks.ReplayAll(); // Make sure the mock object is ready to “respond”

   service.MailText(“Enlarge your ‘memory stick'”, validMail);

   mocks.VerifyAll(); // Make sure everything was called correctly.
}


(1) – This is the important stuff. I’m asking the MockRepository to create a new Mock from IMailValidtor type that our MailService expect. The line in bold tells this story: “listen dear mocked validator, if someone calls your Validate method with the parameter validMail – please send him back validValidationResult object”. If we know that our validator will be called twice – we’ll have two lines with Expect.Call as needed.


One of our main purpose in UnitTesting is to test one method (and one method only) and see if it behaves correctly if it receive a certain data. We also want to check the stomach of the method, what happen if our tested method calls another method(dependency) that return “1” – will it still behave as expected? Via Mock object I can control the dependency object’s result easily inside the test. This make it very easy to detect bugs in contrast to our manual stub that sits somewhere else, outside of our test.


Recap:


If you have a dependency to some other object and your manual stub start to contain logic, you should mock that dependency and control the returned values in the same place you write your tests via mock object.


Bonus (delegates style Interaction Based Testing):


[Test]
public void MailText_OneValidEmail_MethodWorks2()
{
   MailInfo validMail = new MailInfo(“valid@mercury.com”);
   ValidationResult validValidationResult = ValidationResult(true, string.Empty);

   RunMock<IMailValidator>(
      delegate(IMailValidator validator, MockRepository repository) {
         Expect.Call(validator.Validate(validMail)).Return(validValidationResult);

         service.MailValidator = validator;
         repository.ReplayAll();

         service.MailText(“Enlarge your ‘memory stick'”, validMail);
      }
   );
}

private void RunMock<TObjectToMock>(MockedProc<TObjectToMock> func)
{
   MockRepository mocks = new MockRepository();
   TObjectToMock obj = (TObjectToMock)mocks.CreateMock<TObjectToMock>();

   func(obj, mocks);

   mocks.VerifyAll();
}

private delegate void MockedProc<TObjectToMock>(TObjectToMock mockedObject, MockRepository repository);


Enjoy!

 

Code Templating lecture – any buyers ?

A few months ago, I lectured before Microsoft C#/C++ User Group about advance usage of delegates, generics and anonymous methods. The audience was great and I got really nice feedback. I was talking with my good friend Pavel a few days ago about lecturing in general and he made an excellent point: I should have done more “rounds” with this lecture. This could have been good experience for me to learn from the feedback I got and use it into practice before different audience. So, would you like to hear me present for ~1.5 hours about those topics (after “work hours”, say 17:30+) in your “home”(=working place)? All I need is a projector and a working air conditioner(I don’t have 3 built-in fan as my computer have, unfortunately). You can look at the lecture syllabus here and there are code samples and presentation(ppt) file of the entire thing right here. Of course, there should be a minimum number of people attending as I don’t want to drive for an hour just to talk with 2 people (actually, I do, but this won’t be very productive and bad usage of my time, so I’m sorry folks).


Minimum knowledge required to participate: good understanding of .Net 1.1 is a must; .Net 2.0 – bonus.
Lecture (“MS”)Level: 400. (technical hardcore stuff, no SOA will be presented, I promise).



Drop a comment or send me an email (oren dot ellenbogen at gmail dot com) and we’ll set a date.

 

TDD Workshop: SeeCompass v0.2 is available

This (very)little beauty is getting along quite nicely. I’m going to work quite a bit on it in the following days so keep tracking…


source:


Lnbogen.SeeCompass_v0.2.zip (205.34 KB)

 

TDD Workshop: SeeCompass v0.1 is available

After sitting with Roy during our last meeting, we managed to write some neat tests and code and the SEE(Simple Expression Engine) infrastructure started to crystallized. Roy even managed to refactor the name of my infrastructure and brought a brilliant suffix – SeeCompass. SEE is like a compass that helps you navigate in the ocean of data; man, I think that the web-bully will not be happy with this phrase.


If you don’t remember what is SeeCompass all about read this post.


Source:


Lnbogen.SeeCompass.zip (156.39 KB)


How to start:


1. Open the solution (I know, revolutionary).
2. Open Lnbogen.SeeCompass.Framework.Tests project.
3. Open the file FilterExpressionTests.cs under FilterExpression directory.
4. Jump to the test Build_EmptyFilter_EmptyString (remember the method name structure: MethodToTest_MethodState_ExpectedResult).
5. Move on to the next test, one at a time.



I know, it can be a little hard to grasp the “entire picture” at the moment, but the tests should give you a good pick at the future.
As always, I left one failing test which will lead to a very drastic refactoring (BetweenExpression should have more than one parameter) – this will give me an entry point to continue.

 

Safe events with .Net

This is another brilliant idea from Juval Lowy. I got to see him speak about unify ASP.NET and WinForms security models last week and during the session (which was really great by the way, but that’s for another day), I’ve notice this genius row:


public event EventHandler<EventArgs> Click = delegate {};


Isn’t it a beauty ?!


I know, it doesn’t ring a bell yet, so I’ll make the picture a bit clearer. But before we move forward, let’s take a few steps backward.


Starting from scratch, a reminder:


We want to raise our Click event.
I’m sure you are familiar with these lines:


private void OnClick(EventArgs e)
{
   if (this.Click != null) // check if the invocation list is empty
      this.Click(this, e);
}


The reason we do it is we we don’t want to raise an event with an empty invocation list; This will raise an exception, which is a big no-no if we can avoid it. simple ah ?


This implementation is problematic as between the check (if statement) and the activation the listener can be removed. A quick fix will look like this:


private void OnClick(EventArgs e)
{
   EventHandler<EventArgs> handler = this.Click;
   if (handler != null) // check if the invocation list is empty
      handler(this, e);
}



Ok, so it’s a little safer invocation now (I remember a version with locking, but the above will do for now).


Rewind:


Now let’s get back to Juval’s genius line I’ve showed before:


public event EventHandler<EventArgs> Click = delegate {};


attaching delegate{} to the invocation list will create (behind the scene) a class, with a random name, with an empty method (matching EventHandler<EventArgs> signature), with a random name.


Why is this so brilliant ? Because now we verified that the the event invocation list is
always filled with *at least* one (empty)listener.


We can’t clear the empty listener as we don’t have it’s instance (it was generated for us) nor it’s name.


The checks for not-empty invocation list can be thrown to the garbage. We now have a safe event, guaranteed.


This is certainly a best practice for working with events (following Framework Design Guidelines structure):


   Do   Consider attaching an empty delegate to your event.



Recap


public class MyClass
{
    public event EventHandler Click = delegate {};
    
    private void OnClick(EventArgs e)
    {
        // no need to check if (this.Click!=null)
        this.Click(this, e);
    }
}


nice and easy.



Extra: one more step for safe events:


If we’re talking about safe events, there is an advanced scenario in which you want the “eat” exception raised by one of the listeners, so the the other listeners will still be triggered. In the above, any exception in one of our listeners will stop the triggering of our invocation list.


The solution is quite simple also:


private void OnClick(EventArgs e)
{
   EventHandler<EventArgs> handler = this.Click;
   if(handler != null)
   {
      Delegate[] list = handler.GetInvocationList();

      foreach (Delegate del in list)
      {
         try
         {
            EventHandler<EventArgs> listener = (EventHandler<EventArgs>)del;

            listener(this, e);
         }
         catch { }
      }
   }
}


Juval even wrote a cool generic utility class named EventsHelper which you can get here.


Brilliant.

 

ORM, Microsoft and in between – The dilemmas

ORM conversations flood the web during the last months.


Microsoft new players (DLinq, ADO.NET entity framework) cause a lot of drama and “oh-ha” statements in our industry. Microsoft is playing around; They are throwing names all over the place (DLinq, LINQ for Sql, LINQ for simple scenarios, ADO.NET vNext, ADO.NET Entities, ADO.NET 3.0). I guess that the picture will become clearer in a few months as the minds behind this infrastructures will assemble and a new, solid infrastructure will take place. Just look at Remoting, WebSercies, Enterprise Services which assembled together into WCF.


This causes some old, damn good, questions to arise as well:


“Should I use Business Entities (Entity Info+ BL + DAL in the same class) or should I create a separate classes ?”


“Should I write my queries or ORM is good enough? I heard it’s somewhat slow, but I’m not sure…”


“Should I use ORM and map my entities with attributes or with xml? What is better ?”


“Which infrastructure to use? Is DLinq or ADO.Net solid ? Should I use NHibernate? “


etc…


I’m not going to answer these questions at the moment, but I’m certainly going to address them in the following months as my BL->DAL agenda started to shift from separate classes to Business Entities. I’m still doing a lot of prototypes to see the pros & cons.


In case you are interested to know the difference between DLinq and ADO.NET Entities (or ADO.NET vNext, you name it), here is a nice post to set your mind.



Oh, before I forget – It is time to make some good names to Microsoft products !
Why not calling ADO.NET vNext something like DARVIN (Data Access Revolutionary INfrastructure) ?
That’s cool !



Any thoughts ? names ?

 

Conflict between instance and class properties with the same name

I don’t know, maybe I’m missing something or maybe I’m just stupid (you can pick, just let me know):


class User
{
   public static readonly int ID; // class property

   public int ID; // instance property
}



Compiling this little cutie returns the error:
The type ‘ConsoleApplication1.User’ already contains a definition for ‘ID’


What’s going on here ? This properties are completely different, one is *instance* property and the other is *class* property. What is the conflict here? Am I missing some Microsoft spec on this one? Am I missing some OOP lesson? Is it C# restriction? Is it CLI restriction ?


I’m confused…

 

Generics Constraints: Use Interfaces over Base Class

Prologue:


I’m a big fan of Interface with a Base Class which implement that interface with base behavior. Providing this two together allows the programmer to decide if he wants to inherit from the Base Class and override only the things he really wants or to implement the Interface from scratch.


Here is an example from our code:


1). The Interface:


public interface IPersistentEntity
{
   string ToXml();
   string GetKey();
   // … snippet …
}


2). The Base Class that implements the interface:


/// <summary>
/// Base class for a Business Entity.
/// </summary>
public abstract class EntityBase : IPersistentEntity
{
   public string GetKey()
   {
      return GetKeyCore();   
   }

   protected abstract string GetKeyCore();

   public virtual string ToXml()
   {
      // Build the xml via Reflection over the current type.
   }

   // … snippet …
}



I constraint my EntityCollection object to EntityBase:


/// <summary>
/// Represents a strongly typed list of Business Entities.
/// </summary>
/// <typeparam name=”ENT”>Entity type which inherits from EntityBase class.</typeparam>
[Serializable]
public class EntityCollection<ENT> : List<ENT>, ISerializable
   where ENT : EntityBase
{
   // … snippet …
}


As you can tell, I’m constraining the ENT generic type to be any object that inherit from EntityBase.


The Story:


My teammate, Moran (Yes, him again, goshh… he really challenges me to think deeply about our infrastructure), wanted to create a new EntityCollection of ISpecificEntity (i.e: EntityCollection<ISpecificEntity>). That means that he wanted to extend the IPersistantEntity I showed above.

The problem was that my EntityCollection made a constraint on the generic type to inherit from EntityBase.

That means that the interface should inherit from EntityBase class which is obviously not possible. so his interface should have been some sort of another SpecificEntity class that inherit from EntityBase. Well, that’s no good as some of our existing entities already inherit from the EntityBase and Moran wanted to use them in the collection. That means that Moran should have change the signature of this class (among others):


public class Zone : SpecificEntity //EntityBase
{
   // … snippet …
}


The problem was that Zone was inherited also by another class and we couldn’t change that. To make a long story short, our  headaches were a result of one simple fact:
One of the biggest drawback of inheriting from a Base Class is [your answer here].
You right, the biggest drawback is that you can do it only *once*.


Using abstract classes with interfaces behind is a very good practice, in my book anyway, but using it(abstract class) as a constraint in a Generic Type can cause you some problems later on. The only thing we did was to change the signature of EntityCollection to:


public class EntityCollection<ENT> : List<ENT>, ISerializable
   where ENT : IPersistentEntity
{
   // …
}


That made our life easier as we can always implement additional interface(s) in our class.


Epilogue:


The drawback of single inheritance from class is a dangerous pitfall you should avoid while working with Generics constraints, so my tip for you is:

Constraint your generic type(s) by Interface and not by Base Class.