# Saturday, February 04, 2006

Roy did a great interview with Kent Beck, an author of several books about XP\Agile development and one of the most influence figures in that industry. I tried to think about the answers I would give Roy if he asked me some of those question, so here are my answers and some short feedback about the interview itself:

Push yourself to your extreme.
I'm one of the folks Roy mentioned that tries to get better by testing new methodologies\practices like Pair Programming, Unit-Test-first code-after, daily build process (etc) when I have the chance of doing so. By saying that some of the techniques such as Pair Programming just couldn't work here in Israel due to our complex nature(intolerance and straight-hard-to-your-face-comments) is somewhat rude (see - I'm a good Israeli, no problem saying "hard comments" ;-)) as the term "Pair Programming", IMHO anyway, doesn't necessarily mean working on the same code at the same time; It's about thinking and discussing about the same context and move toward the solution at the same time - something which I enjoy doing on my every day work and I'm familiar with many more programmers out there that practice this technique in their every day work.
I think that Kent gave a good answer: those methods DO work(even in Israel) - the context or definition of "success" is debatable and can go either way, but those methods serve a better all as our main goal is to be the best we can be, and XP\Agile techniques are just some more tools and ideas for us to become so. That attitude, the "extreme achiever-wannabe", is the one I'm searching of at people, and this is what I'm working hard on in order to inspire others.
 
The cold hard truth - one man can't(?) change an entire organization.
Every once in a while I hear(while someone just throws it at my face) the sentence "you're still young and naive, you can't change this\that\him\her" or "you've been lucky to work with those people; with my teammates you couldn't done it..."; I guess that I'm just one of those optimistic people which think that by doing your best and influence others by your positive nature will work (to some extent, as I mentioned earlier) in any given group of people unless this group is doomed for failure and are willingly accept it. Can one man can change the world? I guess not, but I would like keep thinking so as I know that this will give me the inspiration and motivation I need. The definition of success is bound to the "ribbon" you're attached to. As a programmer, your world is pretty small but you can definitely make it spin in the reverse direction if you push hard enough. It would be much more difficult to change the world of other team in your department, I just think that this shouldn't stop you.
 
"People want some hard answers which will inspire them to get better"
Roy - I can't agree more, and at the same breath, I can't disagree more on this phrase. You see, most of us want hard answers as we wish to believe that by applying other methodologies\actions\thoughts we're improving our-selfs and raising our bar just one inch higher in the path of becoming better; So I definitely think that hard answers for complicated question, in some of the cases(case = person&context), will create the wanted effect.
On the other hand, the more creative you are, the more "self-succeeder" you want to become - the less it will apply to you. Meaning, I don't want to get straight answers about "What is the right way to develop a 6 months project with 3 programmers and one team leader" and the reason is simple - any answer you'll give will be wrong, but at the same time it will be also right so I'm still at step one. As you get older you realize that there is no right answer, so reading a book, or asking Kent for his opinion is just another (great)source\idea\tool to add to you tool-box, nothing more. Showing your attentions and discuss about those hard questions with other co-workers can cause the required inspiration that people are so eagerly searching for.
 
General feedback:
Roy - I think that you did a great job "pinning" Kent to the corner and ask the really hard questions about XP\Agile development which can seem like empty buzzwords instead of real solutions to specific organization\projects\teams\context in the eye of the intermediate programmer. I can't say that I've learned something entirely new, but It sure made feel better about my grasp of software development and people management.
Kudos for your not-so-Israeli accent(:-)) and for your time !
   

Posted by Oren Ellenbogen 
04/02/2006 02:19, Israel time UTC-07:00,     Comments [1]  | 
# Wednesday, February 01, 2006

I'm using dasBlog "Insert Code" feature in order to insert some code to the post(strange, but true). Until now, my code was nicely highlighted but it was lacking of background color and some border to give it the proper attention it was required. After digging for couple of seconds in the dasBlog directory I found out that the page ftb.insertcode.aspx (under ftb directory) is in charge of highlighting the code. Here are the important lines (Notice the background color & border ! :-)):

void parseButton_Click(object sender, EventArgs e)
{
   AylarSolutions.Highlight.Highlighter h = new AylarSolutions.Highlight.Highlighter();
   h.ConfigurationFile = Server.MapPath("CodeHighlightDefinitions.xml");
   h.OutputType = AylarSolutions.Highlight.OutputType.Html;
   string result = h.Highlight(sourceTextBox.Text, languageDropDown.SelectedValue);
   result = result.Replace("\t", "    ");
   result = result.Replace(Environment.NewLine, "<br>");
   resultLabel.Text = result;
   codeText.Text = "<p>" + result + "</p>";
}

All you have to do is replace the line:

codeText.Text = "<p>" + result + "</p>";

With this:

codeText.Text = "<p class='HighlightedCode'>" + result + "</p>";

Now add the class into your template css and that's it!

* I'm using:

.HighlightedCode
{
    border-style: dashed;
    border: 1px Silver;
    background-color: White;
    margin-left: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
    margin-top: 10px;
    padding-left: 4px;
    padding-right: 4px;
    padding-bottom: 4px;
    padding-top: 4px;
}

Sweeeeet !
   

Posted by Oren Ellenbogen 
01/02/2006 05:18, Israel time UTC-07:00,     Comments [0]  | 

I've just upgraded my CodeSmith version to 3.2; It went pretty well just until I've opened the CodeSmith Studio and tried to compile my template. I got a strange NullReferenceException in the CodeSmith.Engine.CodeTemplate constructor.
I thought about 2 reasons which can cause this behavior:

  1. Maybe the CodeSmith Studio works with an old version of one of the dlls, for some unknown reason (unlikely).
  2. I'm using a compiled dll as my CodeTemplate base class, maybe I need to recompile it again and then try to compile the template (more likely).

So I compiled my DLL (and did a quick restart to my computer, just to be safe) - now it works...

   

Posted by Oren Ellenbogen 
01/02/2006 10:25, Israel time UTC-07:00,     Comments [0]  | 
# Saturday, January 28, 2006

After a long meeting with Ken and Roee about our(SQLink R&D department) architecture, I decided to put it out on the table - maybe you can give us some better insights about some questions we brought up during our session. I'll start from the end of our session - this is the architecture design we thought about:

layers_small.jpg

   

Posted by Oren Ellenbogen 
28/01/2006 03:22, Israel time UTC-07:00,     Comments [4]  | 

I'm using the Captcha anti-comment-spamming-engine in my blog:

captcha.jpg

Some of you complained that after posting a comment you can't see it afterwards. This is caused due to a time mechanism plugged in the Captcha engine - after X seconds, the code becomes invalid and you have to insert a new one. In case that the Captcha will have code timeout - it will make you enter a new generated code simply by leaving you on the same page. So please make sure that after hitting the "Save Comment" you're on the main page and you don't have your comment at the bottom of the page, if so - enter the new code and click the "Save Comment".

Thanks.

   

Posted by Oren Ellenbogen 
28/01/2006 02:04, Israel time UTC-07:00,     Comments [1]  | 
# Friday, January 27, 2006

After elaborating on the topic on my first post (see comments), it's time to wrap the all thing up. As I've noted, the purpose was to brought up some points of interest about developing classes which wrap unmanaged code inside them. When I'm reviewing my teammates code, any usage of unmanaged code triggers me as I start thinking about all the scenarios of which the unmanaged code stays un-handled and therefore causes memory leaks in the application. One of the scenarios which can cause a memory leak was the one we've talked about(again, the code in the first post was only for teaching purpose, so this post will be more relevant), but this could be better handled by implementing "Dispose pattern" on the (wrapper)class.
   

Posted by Oren Ellenbogen 
27/01/2006 01:33, Israel time UTC-07:00,     Comments [1]  | 
# Tuesday, January 24, 2006

Consider the following code:

* Note: this code was written for teaching purpose only and is highly not recommended in "real world" implementation.

public class CustomWriter : IDisposable
{
   private StreamWriter m_sw;

   public CustomWriter(string filePath, int numberOfLinesToWrite)
   {
      m_sw = new StreamWriter(filePath);

      if (numberOfLinesToWrite < 0)
      {
         throw new ArgumentException("What's wrong with you ?!!? numberOfLinesToWrite can't be less than 0", "numberOfLinesToWrite");
      }

      // Assume that I'm using numberOfLinesToWrite here...
   }

   #region IDisposable Members

   public void Dispose()
   {
      // Time to say goodbye
      m_sw.Close();
   }

   #endregion
}

And now, here is a simple runner:

using (CustomWriter cw = new CustomWriter(@"c:\oren.txt", 15))
{
   // some code here...
}

This one works as expected and the StreamWriter is being cleaned as using calls the Dispose method.

But what happens if the path is invalid like "c:oren.txt" or maybe "c:\windows\system32\cdosys.dll" ??
Nothing much to tell the truth as the resource(StreamWriter) will die and fail to initalize - we're OK.

But what about this scenario:

using (CustomWriter cw = new CustomWriter(@"c:\oren.txt", -5)) // <-- Remember? "-5" is invalid argument
{
   // some code here...
}

Now we're in trouble: The Dispose method is NOT called at all and the resource is running free on the memory street with no GC(garbage collector) police to hold him back (a little metaphor, why not?). Need I to say how BAD this case is ?!

 

To sum it all up: constructors should NEVER throw any kind of exception. If you have a case which you need to do some extra initialization that could throw an exception in certain cases - do it in a method inside the class (Initialize() sounds right).

* I'd like to give the deserved credit for Amir Engel(His blog is on its way, hold tight) for elaborating on the subject with me ;-)

   

Posted by Oren Ellenbogen 
24/01/2006 05:14, Israel time UTC-07:00,     Comments [8]  | 
# Monday, January 23, 2006

A dear friend of mine, Shani, wrote a great post about the subject which I highly recommand; Pay him a visit.

   

Posted by Oren Ellenbogen 
23/01/2006 10:17, Israel time UTC-07:00,     Comments [0]  | 

I've written a method which will format any given string into a more readable phrase. This method can be quite useful if you're generating your code or building your API based on an outer settings like a config file, DB, Reflection etc. Here is the code...
   

Posted by Oren Ellenbogen 
23/01/2006 06:49, Israel time UTC-07:00,     Comments [0]  | 
# Sunday, January 22, 2006

must read, IMO, article about xml parsing:

http://support.softartisans.com/kbview.aspx?ID=673

This will give you some insights about the options available for you via .Net framework for parsing\manipulating xml data.

   

Posted by Oren Ellenbogen 
22/01/2006 07:46, Israel time UTC-07:00,     Comments [1]  | 

This post is mostly a self reminder but it may come useful if you're using CodeSmith as well.
It is possible to check if a (schema)column is an identity field via ExtendedProperties property of the SchemaObjectBase class:

// Only for Sql Server
private bool IsIdentityColumn(ColumnSchema column)
{
   return (bool)column.ExtendedProperties["CS_IsIdentity"].Value;
}

There is one exception though and that's if you're sending the column object through the TableSchema.ForeignKey[index].ForeignKeyMemberColumns or TableSchema.ForeignKeys[index].PrimaryKeyMemberColumns, meaning:

for(int i=0; i<MySourceTable.ForeignKeys.Count; i++)
{
   // Same thing about MySourceTable.ForeignKeys[i].PrimaryKeyMemberColumns...
   for (int j=0; j<MySourceTable.ForeignKeys[i].ForeignKeyMemberColumns.Count; j++)
   {
      if (IsIdentityColumn(MySourceTable.ForeignKeys[i].ForeignKeyMemberColumns[j])) // <-- Exception Here.
      {
         //do some code
         
      }
   }   
}

The extended properties will NOT hold the key "CS_IsIdentity" and IsIdentityColumn will throw an exception (null reference). I'm still not sure if this is by design or not, so I'll try to fish it out on from the net and update the post later on. 

The solution is simply working a little harder via TableSchema.Keys and than verify the type of the key (by PrimaryKeyTable and ForeignKeyTable properties).

update:
This is quite a dirty hack, but it works and I'm loving it (I don't have to change a lot of code in a lot of different places) !  
I refactor the mehotd IsIdentityColumn so it will do the trick:

private bool IsIdentityColumn(ColumnSchema column)
{
   if (column.ExtendedProperties["CS_IsIdentity"] == null)
      column = column.Table.Columns[column.Name];

   return (bool)column.ExtendedProperties["CS_IsIdentity"].Value;
}

Back to code...

   

Posted by Oren Ellenbogen 
22/01/2006 10:31, Israel time UTC-07:00,     Comments [0]  | 
# 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-07: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-07: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-07: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-07:00,     Comments [0]  |