What's hot ? (and I mean really ...) - scroll down for more
1).  Code Templating - advanced usage of delegates & generics: my slides & demos are available for download! CodeProject article is also available.

2).  My series "TDD in the eyes of a simpleminded" is in progress(including code!): preface, part1, part2, Q&A 1, Manual Stub .vs. Mock Stub

3).  TDD Workshop: SeeCompass v0.1 and v0.2 are out.
# Wednesday, October 04, 2006

A few days ago a teammate asked to me to help him with a little some-some. This some-some was an event delegation problem (some-some sounds better) that she wanted to implement and wasn't really sure how. The scenario is quite simple, we have a few classes and one of the classes is a little “deep” (deep object graph), meaning:

object of type A 
object of type B 
object of type C 
   inner member of type class D 
     inner member of type class E
      inner member of type class F – known as f1

Now, the value f1 can change, and while it does so, we need to notify the rest of the instances (a1,b1,c1,d1,e1) of that change and provide them some extra details about the change itself. One solution is to add an event to all the classes, register from each one to the inner member event and then f1 can trigger the change to E which will trigger the event to D and then to C->B->A. In short - delegate the call all the way up and around. It seems like a hard job to me - too many places to change, too many events to declare which are not really necessary. I came up with a static Events Notifier solution. Think of it as a repository for registering and triggering events. Here it goes:

public static class EventsNotifier
{
   public static event EventHandler<Status> StatusChanged = delegate {};

   public static TriggerChangeStatus(object sender, Status s)
   {
      StatusChanged(sender, s);
   }
}

Now each class, in its constructor, can register to EventsNotifier.ChangeStatus event and my f1 can call EventsNotifier.TriggerChangeStatus(this, new Status(...)); which will notify the rest of the objects. I know, it's not a perfect solution, but It has its pros. What would you do ?

Posted by Oren Ellenbogen 
04/10/2006 09:42, Israel time UTC+02:00,     Comments [3]  | 
# Monday, October 02, 2006

Let's say we have an entity named "Blog" that has many "Post"s in it:

[ActiveRecord("Blogs")]
public class Blog : ActiveRecordValidationBase<Blog>
{
   private IList _posts;
   // ... snipped ... 

   [HasMany(typeof (Post), 
      Table = "Posts"
      Lazy = true,
      ColumnKey = "BlogId")]
   public IList Posts
   {
      get { return _posts; }
      set { _posts = value; }
   }
   
   // ... snipped ...
}

Configure your web application to support lazy loading:

  1. Use the isWeb="true" attribute in your web.config file - look here for "how to".
  2. Open a SessionScope at the beginning of each request - look here for "how to".


Now, How do you know if lazy loading is (really)enabled:

Blog b = Blog.Find(1);
bool isInit = NHibernateUtil.IsInitialized(b.Posts);

If isInit shows true, then lazy loading wasn't enabled and you need to make sure you didn't miss anything. if it shows false - lazy loading is on!

Thanks for Ayende Rahien for pointing on NHibernateUtill, this can be quite handy.

Posted by Oren Ellenbogen 
02/10/2006 08:01, Israel time UTC+02:00,     Comments [6]  | 

Myself and Pasha are now starting to build a little thing we came up with and we thought that it will be a good idea to use this little baby to learn about the new technologies out there. But you can't learn everything at once right? so we decided to start with Atlas. In addition, we want to take advantage of some sort of infrastructure to perform the common tasks we are all familiar with while developing an application like (1) Data persistence (2) Lazy Loading (3) Caching (4) Data Validation (5) Nullable fields (6) Transaction support and their partners (7) Authorization&Authentication (8) Logging and such. Looking around the net, it seems that ActiveRecord (I see it as an abstract shape of NHibernate, one that makes you smile while mapping your entities and querying them instead of pulling your hair in anger) which is part of Castle Project, support tasks 1-6 pretty damn good so it will be a huge part of my POC. I'm planning to share my insights with you, including the "How To", "Why To" and the complete source code of the POC which will include the skeleton of our infrastructure.

You can download the Castle version(Includes ActiveRecord) I use from here (It is from August 27th, 2006).

Posted by Oren Ellenbogen 
02/10/2006 07:44, Israel time UTC+02:00,     Comments [0]  | 
# Wednesday, September 27, 2006

Remember "Lnbogen test for Google's rating, the target: Oren Cohen"?
Well, I thought it will take about 2 weeks, but google managed to surprise me. Looking for "Oren Cohen" in google.com will give you my post as the 18th result. Oren is now thinking about publish his pictures\sites in my blog. I guess I should start thinking about a pricing model ;-), I need to provide some food to my kids, support 15 wifes, etc. It can get quite expensive you know...

The proof (you are welcome to search for "Oren Cohen" at google.com yourself, of course):

OrenCohenBetSmall.gif

Posted by Oren Ellenbogen 
27/09/2006 04:13, Israel time UTC+03:00,     Comments [0]  | 
# Thursday, September 21, 2006

COM object think that they understand .Net assemblies (via Proxy(tlb file)) but in matter of fact, this proxy is a mediator(girlfriend\gay-friend) to the real assembly that actually make the connection work while .Net assemblies think that they understand COM object, again, via proxy(Interop file) but in matter of fact, this proxy is only a mediator(friend, lesbian-friend) that make the connection work.

The hard migrating process my team encounters this days(and will keep dealing with for the next few iterations) makes you(well, me, but a sorrow shared is a fool's comfort) appreciate one-platform systems. Integration between different platforms can be a female dog (translation: bitch!) if you are not familiar with the tips&tricks on the subject. Working with the registry is a complete disaster. I don't think that the initial idea of MS was to abuse the registry so much and literally write every reference as a long GUID that points to some class\interface\dll. Hack, register a simple dll (via RegSvr32.exe) and unregister it can leave you garbage on the registry, not mentioning migrating VB6 code into VB.NET\C# code which requires RegAsm.exe for "old" clients. So much garbage to cleanup. And you think that throwing the garbage at your home, once every your-wife-is-nagging-again is hard. Think again.

Yes, they(COM, .Net) know how to communicate and live together, but just like Men and Women - you can't really understand how it actually works.

I wonder if I should start writing a book on the topic...

p.s - don't get me wrong, women are hard to understand but it's only making the game more fun. So does the migration challange.

.NET | @ff Topic | COM
Posted by Oren Ellenbogen 
21/09/2006 08:26, Israel time UTC+03:00,     Comments [4]  | 

I was just laughing with my teammate Oren Cohen (Yes, we have 2 "Oren" in the team. We solve it via alias(=namespace) so my name is "Boogi" but this is a story for another day). I made a point that I managed to "publish" a few friends of mine here by mentioning their name (Amir Markowitz, Dror Engel, Ken Egozi, Moran Benisty) and during that conversation I searched for "Oren Cohen" at Google.com which returned about ~627,000 results, non of them are related to the "subject"(Oren Cohen, my teammate). I wondered how much time it will take from the second I'll publish this post until he will be rated from my site.

But let's make it interesting OK?
Let's make a "virtual bet" (one beer for the winner on my expense): my bet is that in 2 weeks - he will be on the first 50 results for "Oren Cohen" in google.com.

All bets are on!

Posted by Oren Ellenbogen 
21/09/2006 12:03, Israel time UTC+03:00,     Comments [1]  | 
# Wednesday, September 20, 2006

<rational thinking>

Let's assume we have a WebSite(the same issue applied to WebService btw) named WebApplication1. Now, we want to put its(the website's) output files into some other directory (!= "bin" directory) for development reasons (working as part of a team with some sophisticated Source Safe). What's the first thing you (and me) do? we use our "rational" programmer nature and Right-Click on the project->Properties->Build Tab->and changing the Output path to whatever we need.

OutputPath.gif

(Instead of "bin\" we can write here "..\..\infrastructure" for example)


We then build the all thing and surprise surprise, the new output path contains all the dlls as expected. Awesome!
Satisfied with the greatness of Visual Studio .Net 2005, we now want to Publish the WebSite so we(or the QA) can play with it. "Think as a developer, think as a developer" I say to myself and Right-Click the WebSite project->Publish... A few really easy "decisions" and ~10 seconds later, VS.NET tells(it speaks to me, I swear) me that my site was published successfully.

Happy as a little girl with a new puppy, I enter my site: http://localhost/webapp1/Default.aspx and Oops!

OutputPathUnableToFindClass.gif

The page can't find its "code behind"(The class that it inherits from)! What the hack is going on here!?

Well, it turns out that the Publish process is not as smart as you may think it should be. Changing our Output path to another directory (!= "bin") caused this all mess as the Publish process simply copy all the files from the bin directory into the new(Published) bin directory. No questions asked. The Publish algorithm do not check if you actually compile your dlls into another directory via Output path and taking it into account.

</rational thinking>

<effective thinking>

Fortunately for us, the solution is pretty easy: define your Output path into the original location ("bin\") and use the Build Events(post-build in this scenario) in order to copy the output files into your "infrastructure"(or whatever) directory like this:

OutputPathUsePostBuild.gif

(The command: xcopy /Y /S ${TargetDir}*.* ..\..\Infrastructure)

</effective thinking>


May it save you the 15 minutes it took me and my teammate Hagay to solve this one.

Posted by Oren Ellenbogen 
20/09/2006 04:12, Israel time UTC+03:00,     Comments [2]  | 
# Sunday, September 17, 2006

The solution is pretty simple, just add the support(in bold) for the httpPost protocol in your web.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <system.web>
       <webServices>  
        <protocols>   
            <add name="HttpPost"/>  
        </protocols> 
       </webServices>
    </system.web>
</configuration>

Publishing the WebService do not automatically add these lines so you'll have to do it manually.

Posted by Oren Ellenbogen 
17/09/2006 11:43, Israel time UTC+03:00,     Comments [0]  | 
# Tuesday, September 12, 2006

I've just opened Yediot Acharnot's(one of the largest newspaper in Israel) site - Ynet.co.il:

newspaper.gif

On the bottom-left of the picture you can see the title "The Palestinians: 13 years old was killed by the Israeli Defense Force fire". Reading a few sentences inside of the article paints a different picture: several Palestinians terrorists, and the 13 years old boy among them, throw a grenade on our soldiers and one of our officers was hit. The fire was in response to that grenade. What the hack a 13 years old boy running with terrorists? Should we not defend ourself? Would you remain motionlessly after being hit by a grenade!? I doubt it... This boy have a mother and father, where were they? The hatred made them blind? made them believe that their son's life are not worthy? Is it OK to send your son to explode and than raise his little brother to follow his path?!

The Lebanon War was exactly the same - they(Hizbala) fired missiles from civilians houses and then entered the building. Did our army react? in 99.9% of the time the answer was NO(you didn't hear about it right?); One time (Kfar Kana) we did react - the entire world was shocked by it for several days. Where are the pictures of the destroyed houses by that missile? Where are the Israelis Pictures who died from that missile? 

Did Kadafi asked himself why a terrorist entered a building after firing a missile? I bet that he did. "Well, they fight the way they fight. I don't find logic in their actions that I can relate to, but it must be there... right?".

Did you ever see on television(CNN, FOX news, whatever) a 13 years old kid throwing a grenade on a tank that kills our soldiers or the 5 minutes later that this kid was shot? Why don't you investigate where his parents were at that time? What about the terrorist that threw a grenade inside a house with civilians in attempt to kill one of our soldiers and "accidentally" killed the civilians in that house? I guess you heard something like "Israeli Defense Force killed an entire family while catching a terrorist". What about the 100->55->44->30->22 dead in Kfar Kana. The German's press(no the Israeli press, the German's!) took picture of the place and they catched(on video) that the bodies were moved around just so it will appear that more than 100 people died!

That's OK, I don't expect from the outsiders to play nice, to cover all the facts and tell the story from our side as well(I'm no journalist, but isn't it the first rule you learn - "cover the story from every angle"). That's asking too much I assume. But from Israeli media I do expect more! These reporters make us look bad. Tell the story as it was and emphasize the cause that lead to that result, you are Israeli reports for god sake!!

The funny stuff is that we(the Israelis) always think that our ambassadors are not doing it(Public Relations) right on the outside.
We are so wrong. Our problem is from the inside, if a guy like me have to read this story from the Palestinians side and in small letters - our side, in an Israeli newspaper, it's our fault.

Shame.

I really tried not to get into the core of my thoughts as it might start a World War III which is usually a bad thing(right?). Our people want peace, we want to live with our neighbors, we do hurt that their kids are dying and our people are being bumbed in buses. I sometimes wonder though, what about the other side? What about the world?...

Posted by Oren Ellenbogen 
12/09/2006 08:43, Israel time UTC+03:00,     Comments [0]  | 

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
    }    
}

.NET | COM
Posted by Oren Ellenbogen 
12/09/2006 07:30, Israel time UTC+03:00,     Comments [1]  |