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, January 18, 2006

Do I need to call base.METHOD after overriding it, and if so - when is it the right time ?


Well, I'm glad you've asked; I had some chat with my co-worker about the subject when he did some overriding to the Form (WinForm) methods and he wasn't sure about when is it smart to call the base method and if so, should he call base.METHOD before implementing his code, or maybe after. To clarify, quick example:

public class MyForm : Form
{
   protected override void OnLoad(EventArgs e)
   {
      //OK, what here ???!!

      // Custom code here ?
      //base.OnLoad(e); // should I ?
      // Or maybe - Custom code here... ?

   }

}

After thinking for a few seconds, I came up with this explanation - sort of my "best practice" to the issue:

When do I call base.METHOD:

  1. If you don't know the implementation in the method you've just override: assume that it does some "magic" stuff which is important to the correct flow of the application; But This doesn't mean that you must call the base method.
    • If you want to stop the logic flow, it makes sense to override the appropriate method and write your code which will change the flow according to your need. In this scenario there is no need to call the base method.
    • If you don't want to change the logic flow, or you're not sure - call the base method.
  2. If you know the implementation in the method you've just override: no "magic" stuff so this is an easy call - if you need the code in the base method, call it - otherwise - leave it out.

Do I call base.METHOD after my custom code, or maybe before:

This is a tricky one and there is not straight answer - my way of thinking and tackling this question is simply by Explore, Run & Learn "process" - meaning, try to Explore about the base method original purpose and try to figure out the logic; This will give you some logical direction whether you need to call the base method or not. For example - if you override the Render method, you can tell (by MSDN or by Reflector) that its rendering the entire object graph so you probably should call it (eventually). Now that you have some feeling about whether you need to write your code before or after the base.METHOD call, Run it and exam the results:

  • Does the page behaves as you expected?
  • Can you mess it up so it won't work in some scenarios - how can you deal with it ?
  • Grab the nearest programmer available, can he think about something which will mess it up ? if so - how can you deal with it ?

According to the results and the answers about the given questions, you should now have a clear vision about your decision. Make the required adjustments, place some important remarks(to describe your thinking at the moment) and feel good about your code, you did your best to get a good result. And most important - Learn from the process so it will be more natural on the next time you'll have to face this decision.

Posted by Oren Ellenbogen 
18/01/2006 08:08, Israel time UTC+02:00,     Comments [5]  | 
# Saturday, January 14, 2006

I love the new generics in .Net 2.0; Combining it with abstract classes and I could almost throw my interfaces to the garbage collection of life (coming soon...).
There is one scenario though that I can't seem to figure out the solution with a generic type, and that's the is keyword. The problem is that you can't ask the object if it is from GenericClass<T> type, assuming you don't care about the T object. You can't even ask if it is from GenericClass<BaseClass> (where T : BaseClass) in case that T is inherits from BaseClass. The only way to get "true" from this phrase it is to ask for the specific T used in the GenericClass, which is most of the time unknown. I know, I know, this is Chinese at the first read, so here is an example and than you'll have to go Memento(the movie) on this post and roll back to the beginning of the post to understand my point:

public class EntityCollection<T> : List<T>
   where T : EntityBase
{
   public virtual string GetXml()
   {
      StringBuilder output = new StringBuilder(Count * 100);

      output.Append("<" + typeof(T).Name + "List" + ">"); 

      // Build the inner xml for every "T" object.
      this.ForEach(delegate(T t) { output.Append(t.GetXml()); });

      output.Append("</" + typeof(T).Name + "List" + ">"); 

      return output.ToString();
   }
}

public abstract class EntityBase
{
   public virtual string GetXml()
   {
      StringBuilder output = new StringBuilder(100);
      Type currentType = this.GetType();

      output.Append("<" + currentType.Name + ">");

      // --
      // Use reflection to build the properties xml on the fly.
      PropertyInfo[] props = currentType.GetProperties();
      foreach (PropertyInfo prop in props)
      {
         object propertyValue = prop.GetValue(this, null);
         string text = "";
         if (propertyValue != null)
         {
            // ****
            // DON'T WORK:
            // propertyValue will never be from EntityCollection<EntityBase> though it will contain EntityCollection<Item>
            // and Item inherits from EntityBase. This is logically right of course, BUT I still need a workaround.
            if (propertyValue is EntityCollection<EntityBase>) // <-- The problem is here!
            {
               text = ((EntityCollection<EntityBase>)propertyValue).GetXml();
            }
            else if (propertyValue is EntityBase)
            {
               text = ((EntityBase)propertyValue).GetXml();
            }
            else
            {
               text = "<![CDATA[" + propertyValue.ToString() + "]]>";
            }
            // ****
         }

         output.Append("<" + prop.Name + ">");
         output.Append(text);
         output.Append("</" + prop.Name + ">");
      }
      // --

      output.Append("</" + currentType.Name + ">");

      return output.ToString();
   }
}

public class Order : EntityBase
{
   private int m_orderID;
   private EntityCollection<Item> m_orderItems;

   public Order(int orderID)
   {
      m_orderID = orderID;
      m_orderItems = new EntityCollection<Item>();
   }

   public EntityCollection<Item> OrderItems
   {
      get { return m_orderItems; }
      set { m_orderItems = value; }
   }
}

public class Item : EntityBase
{
   private int m_id;
   private string m_name;

   public int ID
   { 
      get { return m_id; }
      set { m_id = value; }
   }

   public string Name
   {
      get { return m_name; }
      set { m_name = value; }
   }

   public Item(int id, string name)
   {
      m_id = id;
      m_name = name;
   }    
}

And here is a simple tester:

static void Main(string[] args)
{
   Order o = new Order(1);
   o.OrderItems.Add(new Item(1, ".Net 2.0 book"));
   o.OrderItems.Add(new Item(2, "yet another .Net 2.0 book"));

   string oXml = o.GetXml();
}


The only solution I found to this problem is to implement an interface and inherit from it in my generic class and than use the is keyword on my interface instead of on the GenericClass<T>, i.e:

  1. Create IXml interface which hold the GetXml method signature.
  2. The EntityBase & EntityCollection class implement the IXml interface.
  3. The EntityBase.Getxml() method check if propertyValue is IXml and if so - call ((IXml)propertyValue).GetXml();
Posted by Oren Ellenbogen 
14/01/2006 03:15, Israel time UTC+02:00,     Comments [0]  | 

After talking with some folks about it, I did some refactoring to the structure.

Just to remind you my purpose:

  1. I want to validate the data before sending it to the DB(performance stuff), or at least at some level:
    • For "string" fields - check for their length (by DB definition).
    • For not nullable fields - check that they aren't null, depending on the required action (Insert, Update, Delete)
I don't want to go all the way to my DB just to get the errors "ID column can't be null" nor "Name field must be less or equal to 50 chars".

The actions I took:

In the ideal world, the entity would know how to validate it self, from A to Z, but the problem is that the validations change according to the required action(Insert, Delete, Update) and I don't want to couple my entity with my DAL.
I decided to split the "validation" checking in two - some of it in my Entities layer and the other some, in my Data-Access layer.

  1. Entities layer:
    • In every set of the property(if the property is from string type, of course) -> validate the length of the property.
  2. Data-Access layer:
    • Insert action:
      • Check that all the not nullable fields aren't nullable, unless the column is an Identity(auto-increment) field.
    • Update action:
      • If the field has to be updated (its status is "dirty", meaning, the programmer wants to update it) -> check for his "null condition" (all rights for this phrase are reserved for me, Oren Ellenbogen Inc.).
      • Check that all the primary key columns are not null.
    • Delete action:
      • Check that all the primary key columns are not null.
Any thoughts ?
Posted by Oren Ellenbogen 
14/01/2006 01:52, Israel time UTC+02:00,     Comments [4]  | 
# Friday, January 13, 2006

I like to handle my .cst(CodeSmith templates files) files with my VS.NET for it's integration with Visual Source Safe.
Well, no need for VSTweaks in this version of Visual Studio, The trick is quite simple:

  1. Open you Visual Studio .Net 2005.
  2. Tools -> Options -> Text Editor -> File Extension
  3. In the "Extension" text-box write ".cst" and in the "Editor" drop-down-list select "Html Editor".
This will put some color to your .cst files.
Sweet.
Posted by Oren Ellenbogen 
13/01/2006 12:27, Israel time UTC+02:00,     Comments [0]  | 
# Friday, January 06, 2006

I'm doing some major refactoring to our code and I'm still wondering about the "right" way to do some of the things. This post will reflect my thoughts about implementing our "Entities" layer. Just to be clear, in my world, "Entity" is an object that represents a single row in a given table or some sort of logic being.
My entities looks something like:
 
 
1). I have entity "base" class:

public abstract class EntityBase
{
   protected StringBuilder m_validationErrors;

   public string ValidationErrors
   {
      get
      {
         return m_validationErrors.ToString();
      }
   }

   public bool IsValid(Enum field)
   {
      Validate(field);
      return (m_validationErrors.Length == 0);
   }

   protected abstract void Validate(Enum field);

   // Some other code...
}

This class will hold the "basic" behaviors for my entities.
 
2). I've cut aside some of my code from my real Area class, just to think about the implementation later:
 
public class Area : EntityBase
{
   [Flags]
   public enum Fields
   {
      ID = 0x01,
      Description = 0x02
   }

   public int? ID = null; // In the real class, it's not like this...
   public string Description = null; // In the real class, it's not like this...

   public bool IsValid(Fields field)
   {
      return base.IsValid(field);
   }
 
   //OREN NOTE: "problematic" code number (1) - I'm doing the type check on run-time.
   protected override void Validate(Enum field)
   {
      if (!(field is Fields))
         throw new ArgumentException(this.GetType().Name + ".Validate method must get Area.Fields as parameter");

      Fields f = (Fields)field;

      m_validationErrors = new StringBuilder(50);

      if (((f & Fields.ID) != 0) &&
         ID == null)
      {
         m_validationErrors.Append("ID property must be set." + Environment.NewLine);
      }

      if (((f & Fields.Description) != 0) &&
         Description == null)
      {
         m_validationErrors.Append("Description property must be set." + Environment.NewLine);
      }
   }
 
   // Some other code...
}
 
Here is a dirty usage of this Area class:

Area a = new Area();
//a.ID = 1;
//a.Description = "oren";
if (!a.IsValid(Area.Fields.ID | Area.Fields.Description))
   Console.WriteLine("Errors: " + a.ValidationErrors);
else
   Console.WriteLine("a is valid");

a.IsValid method is a "strongly typed" method which will get Area.Fields as parameter so I'm quite(not entirely, see problem (1)) happy. The catch is when I'm starting to work with multiple Area entities.

3). Declaring my generic EntityCollection class:

public class EntityCollection<ENT> : List<ENT>
   where ENT : EntityBase
{
   protected StringBuilder m_validationErrors;

   //OREN NOTE: "problematic" code number (2) - I want to get Area.Fields as parameter if I'm declaring EntityCollection<Area>
   public bool IsValid(Enum field)
   {
      m_validationErrors = new StringBuilder(Count * 50);

      int counter = 0;
      this.ForEach(delegate(ENT e)
      {
         if (!e.IsValid(field))
         {
            m_validationErrors.AppendFormat("Index in list: {0}.{2}Errors: {1}{2}",
               counter,
               e.ValidationErrors,
               Environment.NewLine);
         }

         counter++;
      });

      return (m_validationErrors.Length == 0);
   }

   public string ValidationErrors
   {
      get { return m_validationErrors.ToString(); }
   }
}

Here is a quick usage for this EntityCollection class:

EntityCollection<Area> areas = new EntityCollection<Area>();
Area a1 = new Area();
a1.ID = 5;
Area a2 = new Area();
a2.Description = "orennnnn";
Area a3 = new Area();
a3.ID = 1;
areas.Add(a1);
areas.Add(a2);
areas.Add(a3);

if (!areas.IsValid(Area.Fields.Description))
   Console.WriteLine("areas Errors: " + areas.ValidationErrors);
else
   Console.WriteLine("areas is valid");

areas.IsValid accept Enum as parameters, this is quite shitty because in my ideal world it would accept only Area.Fields as parameter.

The solution I found at the moment is to inherit from EntityCollection and add the check there, something like:

public class Areas : EntityCollection<Area>
{
   public bool IsValid(Area.Fields field)
   {
      m_validationErrors = new StringBuilder(Count * 50);

      int counter = 0;
      this.ForEach(delegate(Area a)
      {
         if (!a.IsValid(field))
         {
            m_validationErrors.AppendFormat("Index in list: {0}.{2}Errors: {1}{2}",
               counter,
               a.ValidationErrors,
               Environment.NewLine);
         }
   
         counter++;
      });

      return (m_validationErrors.Length == 0);
   }
}

I can always check the integrity of the collection via outside delegate & ForEach method, but I want the collection to verify its inner entities without my help. This is why I need your advice - what do YOU suggest in order to handle this more nicely ? Am I doing something totally wrong ?

Posted by Oren Ellenbogen 
06/01/2006 06:34, Israel time UTC+02:00,     Comments [0]  | 
# Saturday, December 31, 2005

Wow, it's been a long time since I've published my latest post hasn't it ?
Ok, no time for lame "I was busy" excuses so let me fill the gaps -

  1. New position:
    I got a promotion at work and now I'm a team leader at our R&D department. I've come across, in my 6 years at the business, several great people; Some of them were good because of their technical knowledge, some for their leadership capabilities, some for their good nature and some for combining all the above. I'm working my ass of to affect my teammates and the rest of the people in my company as much as the latter ones affected me in the previous six years.
  2. Interviewing candidates:
    We are hiring; Myself and Roee(our technical manager) were interviewing about 50(some of them didn't pass my "phone exam") people in the previous 2 months. It required me to think about "what developers should know" and even more important "what developers should know how to find". In addition, it gave me a great look at the people in "my world" (not a perfect one, but still...)
  3. New co-workers:
    We hired a team leader named Ken Egozi and a programmer named Tamir Kanhe – GOOD LUCK folks!
  4. New challenges:
    I'm now figuring out the "Smart Client" architecture which we want to use in our application, this includes understanding:
    1. Composite UI Application Block
    2. ClickOnce
    3. Windows Forms 2.0 best practices(data binding, Async work, web services & WSE 3.0 etc).
      The world of windows forms is new to me so I have a lot to catch up.
                  After reading a lot and making some dirty application to test things,
                  I'm now summing it all up to a clean paper –
                  "SQLink R&D methodologies in developing windows forms application".
 
 
I gathered some usefull insights in the latest month so I'll publish them in the following week.
Posted by Oren Ellenbogen 
31/12/2005 08:25, Israel time UTC+02:00,     Comments [1]  | 
# Tuesday, November 22, 2005

Reading Dror's post, I had to give it a shot so -

exe.jpg

If you want to see your extension - look here.

Posted by Oren Ellenbogen 
22/11/2005 08:41, Israel time UTC+02:00,     Comments [0]  | 

Well, Richard explains it better than me, so just read his post.

update: for some reason the link doesn't work well, so here is the full address:

http://blog.hundhausen.com/Database+Concordance+Generator+CodeSmith+Style.aspx

Just copy it and put it in the address bar, sorry for the inconvenience.

Posted by Oren Ellenbogen 
22/11/2005 05:00, Israel time UTC+02:00,     Comments [0]  | 
# Friday, November 18, 2005

I've sold my laptop(Compaq EVO N800V) today. After almost 3 years with me I had to let him go (tears are dropping on my keyboard). I'm kidding(!), I'm planing to buy a new (monster-one)laptop next week so I had to get rid of my old one somehow. Dror advised me to publish a message at Homeless and his tip was gold (worth 2000 NIS, in this case).

I really recommend this site, I got more than 10 calls today, just an hour after I've published to post there. Let me see, I've published the post around 11:00 and I've sold it at 15:00 (someone came to see it and took it away).

AMAZING!

Posted by Oren Ellenbogen 
18/11/2005 06:42, Israel time UTC+02:00,     Comments [2]  | 
# Saturday, November 12, 2005

The title got me your attention right? good, because this task - unit testing our WebService in one of our project - seemed to be a frazzled mission at first, but it's amazing how good tools and healthy thinking able you to think about new ways to "assign" the redundant work to the one(and only) dude that never complains (though it makes noises here and there) - the computer !

Let me take a step back and explain a little bit about our WebService and the unit tests it was required:
We currently finished develop another application in our department and this application was required to expose an interface for "CRUD"ing(Create,Read,Update,Delete) several "System Tables"("cities","countries","languages" etc) in the application. Eran(my teammate) was assigned for the job and he did a great job by well designing a general (XML)protocols for "talking" with the WS and by implementing the WS itself. After building the WebService and manually testing it he told me that his work was done and he's ready for his code review. I still have the image burned in my mind about how happy he was thinking about the required protocols, learning about WSE 2.0 (for WS security), implementing the WS itself to be extendable and maintainable, that it was almost tragic to see his face after I've told him that we should write an extensive unit tests for this WS due to his importance and it's extensive usage by our 3rd party softwares. The WebService had 5 methods and it handled 18 tables in our application so I thought about testing 3 different cases for each method, for each table:

  1. 1 valid xml which should return the expected valid data from the WS.
  2. invalid structure xml which should return an error from the WS.
  3. 1 invalid data xml which should return an error from the WS.

The math was simple:

3 xml files * 5 methods * 18 tables = 270 unit tests !

Eran started to plan the following 2 months for this taks but I had something else in mind - let's generate those unit test and hack, while we're in the middle of it, let's generate the XMLs as well !

I started writing the templates(while Eran was looking and learning the required basics) via CodeSmith (did I mentioned that this tool rocks? I'm sure I did, but again - Eric, great job) and after 2 hours we had all the xml files generated. Eran continued the job and written the classes (which holds the unit test methods) and checked that everything integrated properly. After a total of about 6 hours we had 270 unit tests, but more important, we managed to avoid a lot of dirty work and in case we need to support a new table, the unit tests for it will be only 2 clicks job; This is quite extendable, doesn't it ?

Posted by Oren Ellenbogen 
12/11/2005 05:35, Israel time UTC+02:00,     Comments [2]  |