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, June 28, 2006

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

Posted by Oren Ellenbogen 
28/06/2006 10:02, Israel time UTC+03:00,     Comments [4]  | 
# Tuesday, June 27, 2006

I've just created an interface named:

/// <summary>
/// Defines an object which support xml representation in the system.
/// </summary>
public interface ISupportXmlFormat
{
   /// <summary>
   /// Return the object representation as xml string.
   /// </summary>
   /// <returns>Xml string</returns>
   string ToXml();
}

I know, this is a silly name but it made me laugh quite a bit so I thought to share with you my geeky sense of humor ;-)

It is hard sometimes to think about a good name for an interface. I general, I follow Roy Osherove's Interface naming guidelines and name my interfaces by their purpose or "what can be done to them".

Do you have a better name to suggest ?

Posted by Oren Ellenbogen 
27/06/2006 09:27, Israel time UTC+03:00,     Comments [8]  | 
# Sunday, June 25, 2006

Restoring Smart Tags in the C# IDE after installing the C# Language Service (LINQ Preview May 2006):

After installing C# Language Service, you'll notice that Visual Studio .Net starts to misbehave. The IntelliSense and the Refactoring(Resolve, Rename, etc) engine disappears from the menu and do not work even if you try to activate them manually. It turns out that this is a known issue and there is a fix available here.

TIP: Take a good, long, coffee break(or use the time to read C# 3.0 Specification) after running the command devenv /setup /resetuserdata /resetsettings . You'll have a second break when you'll try to run the Visual Studio .Net 2005 again (for the first time). I guess that Microsoft are kind enough to decide when I should(== I must) take a break from code.

[ via Ken Egozi ]

Posted by Oren Ellenbogen 
25/06/2006 01:57, Israel time UTC+03:00,     Comments [0]  | 
# Thursday, June 22, 2006

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.

.NET | Design
Posted by Oren Ellenbogen 
22/06/2006 10:57, Israel time UTC+03:00,     Comments [3]  | 
# Wednesday, June 21, 2006

I'm reading one of our client's characterization in order to determine the amount of time it will be required from us to develop the project. While reading the paper I've encountered this hilarious sentence:

"Architecture: Smart-Client application in DNA methodology(3 tiers) with .Net"

(global) Tip: If you don't understand the meaning of a (buzz)word, don't use it. It is that simple.

btw - I think that this phrase will win the "How-Many-Buzzwords-Can-You-Put-In-A-Sentence-Without-Knocking-Yourself-Out" contest. I'll vote for it anyway.

Posted by Oren Ellenbogen 
21/06/2006 05:21, Israel time UTC+03:00,     Comments [3]  | 

I'm reading a fantastic management book: "First, Break All The Rules" by Marcus Buckingham and Curt Coffman. There were few paragraphs which really made me think about the way I'm interviewing people when our company look for candidates.

" Managers look at "lower-level" roles like housekeeping or out-bound telemarketing and wonder, "How could anyone want to do that job ? That job must be so demoralizing." "

" Let's take hotel housekeepers as an example. Most of us haven't spent much time mulling over the details of house-keeping. But consider, for a moment, what hotel housekeepers do and how often they have to do it. Put yourself in their shoes. Okay. Two things might have occurred to you: first, that this is an easy job anyone with a modicum of responsibility can do; and second, that this is a terrible job that everyone, including housekeepers, must hate to do. If this thought crossed your mind, then you would be wrong on both counts.We shouldn't devalue housekeepers. Anyone can probable clean a hotel room once in a while, but great housekeepers are special. "

" "How do you know if a room is clean?" we asked them (the housekeepers). They said that the last thing they did before leaving a room was to lie on the guest's bed and turn on the ceiling fan.
"Why?"
"Because", they explained, "that is the first thing that a guest will do after a long day out. They will walk into the room, flop down on the bed, and turn on the fan. If dust comes off the top of the fan, then no matter how sparkling clean the rest of the room was, the guest might think it was as dirty as the top of the fan. "


Does it ring a bell? how many times we think that maintaining code is a job that any mediocre programmer can do but developing infrastructures requires a superstar programmer. I guess that we all do in some point of our lives. The truth is that those tasks will be performed in a productive manner according to the person's talents. If the person is passionate about understanding how current things work just so he could fix a leaking class in the system he'll probably be very good in maintaining applications (this is the same talent that will make a superstar plummer). If the person passion is to know how the entire framework works, he love to read about the small details and he loves to develop everything from scratch (at least at first), he'll probably be a great infrastructures developer but poor at maintenance.

As an interviewer, how many times are you interviewing people just to see if they're good programmers in general. Let's assume that you're looking for a programmer for your existing team. "On the one hand, her analytic thinking is excellent, she's familiar with the technology, she can handle problems by herself and she can find her path in a pile of documents. On the other hand, she looks kind of a "cold" person, which can be problematic in our very bound-together team; But hack, I can teach her how to be "wormer" so she could fit it. what are we waiting for?! she's an excellent programmer, let's hire her !!"

Do you really think you can change a person that much ? would she be able to express her full potential in your team ? I guess it's possible, but not likely. What about your other teammates ? Will they be more productive with her in the team ? I guess that probably not.

My point is that you should consider the talents the candidate should posses before considering the skills and experience you're looking for. Skills can be taught and upgraded, knowledge can be transfered, experience is only a matter of time. Talent is what we born with and what makes us unique. You can't teach someone to be a positive guy or a code-passionate person (or any other talent, for that matter), but you can certainly place him in the right spot so he could make the most of his *existing* talents.

Posted by Oren Ellenbogen 
21/06/2006 10:14, Israel time UTC+03:00,     Comments [0]  | 
# Monday, June 19, 2006

Today I sat with Moran after he "paged" me. He reviewed some code of one of our applications and he saw some things he thought he could make better. It was one of those classic "Hey! it should be a single service which every one of our applications will use!". Step after step he made the required refactoring and some elegant API took shape. The improvement was in magnitude but I still thought that the API should be quite different before making it "public" and placing it in our infrastructure. But, and that's a big but, the guys that develop the specific application needed the class and Moran was required to help in another project.

Should Moran take the opportunity to invest some time in this API? Should I help him through? We can talk about services, about providers, about extendability. We can play with code just to see how the API will look like. We can play with ideas, learn from each other, share our experience. We can share with others, we can send some quick "API tests" to get some feedbacks.

The process of developing the basics for our applications should be *long*. It should allow space for errors. The margins should be wide enough to let us experience, to learn from our mistakes, to discuss, to make Design Reviews, To Prototyping and throwing it all to the garbage 2 days later. It's all OK.

But maybe this is not the right time for games. Maybe Moran should make it work somehow and carry on to the next project ? After all, the next project's deadline is near(like always) and we need to join forces just to keep it up. Hey! we get paid to reach deadlines, to make it happen while keeping the quality at high level. The deadline is sacred. I truly believe that a good team will deliver on time even on the expense of features or well-known but low prioritized bugs.

On the one hand, I know that developing small to medium applications (0.5-2 human years) almost never allow you to invest the required amount of time in the basics. On the other hand, I also know that developing applications at work and infrastructures at home is not the answer for long terms. The process is short. No errors are allowed. There is almost no Design Reviews. Does it mean that the results of "home infrastructures" will be poor ? of course not, but the experience, the ability to break our requirements to programmer stories, to exchange ideas, to grow - is lost. The funniest part is that developing small application without a solid infrastructure turns into medium-large application. I guess it's the egg-chicken paradox.

The best I can do is to tell the reality from my perspective. My reality is that there is never time(well, that depends on the urgency and the magnitude of the application), and keeping with my expectations makes me perform the global thinking and implementation at home. This is the only time that I actually "have the time". Investing my time in developing some required infrastructure can save my guys at work a significant amount of work. Still, putting the effort on developing infrastructure during work hours will come on the expense of developing user stories, mentoring, guiding, consulting, talking with our customers. I guess that I still don't know my place. I'm a good developer, I would like to think, and coding some really interesting delegates-based infrastructure or some neat OOP solution are those treats I can't live without. Still, leading projects, make sure everything ticks and the quality is high is a challenge I love to face in my every-day work; Above all - seeing my guys getting to the next step and helping them in this journey is the main reason I'm doing what I'm doing. I want to be the best I can be for my team and yet make an influence in the way we work via developing some solid infrastructures. My gut feeling is that I need to get better. I feel that I can and should be a lot better as a manager and a programmer but It is still very hard for me to decide how and where to invest my time.

This issue keeps me awake at nights "lately"(last 6 months or so).


Where do you put the line ? How do you decide to invest your time in programming on the expense of managing and vice versa ? When do you think it'ss appropriate to invest additional hour\day\month to something you believe in ? Do you have some rules of thumb ?

Posted by Oren Ellenbogen 
19/06/2006 10:53, Israel time UTC+03:00,     Comments [4]  | 
# Thursday, June 15, 2006

linq.png

:-)

Posted by Oren Ellenbogen 
15/06/2006 03:05, Israel time UTC+03:00,     Comments [1]  | 
# Monday, June 12, 2006

I'm proud to introduce "Filter By Expressions". As I mentioned in my previous post about LINQ and IQueryable<T>, I got several ideas about implementing some sort of data(base) filter mechanism just until LINQ will be stable enough. I have  3 alternatives: (1) Implementing some sort of HQL language (like NHibernate) or query parser, (2) use an existing infrastructure and (3) Implement my own mechanism. Considering the options with my managers' hat on, options (1) and (2) are irrelevant at this stage as the learning curve and the adjustments I'll have to make is simply too much for me at the moment. In addition, LINQ will be here shortly so I don't want to invest more than 2 days of work. This leaves me with option (3).

After some good thinking(nothing more) during the weekend and 15 minutes of exchanging ideas with Moran, the [1]API took form. Here is a quick example (from one of our .aspx files):

IFilterObject filter = new Filter();
filter.PageResults = true;
filter.CurrentPage = 1;
filter.PageSize = 10;

// Here is the gold !
filter.Where(
   Expression.EqualTo(Order.Field.PurchaseDate, DateTime.Today),
   Expression.Operator(OperatorType.And),
   Expression.EqualTo(Order.Field.IsValid, true)
);

ordersGrid.DataSource = OrdersGateway.Instance.Get(filter);


Any idea what kind of "Where clause" it will generate behind the scenes ?
I bet you do so here it goes(SqlServer syntax):

WHERE Orders.PurchaseDate = @p0 AND Orders.IsValid = @p1

@p0 and @p1 will be filled with DateTime.Today and true respectively.


Here is another example, this time with "Inner condition":

filter.Where(
   Expression.Block(
      Expression.GreaterThan(User.Field.Age, 18),
      Expression.Operator(OperatorType.And),
      Expression.NotEqualTo(User.Field.Email, "")
   )

   Expression.Operator(OperatorType.Or),
   Expression.EqualTo(User.Field.IsGoldMember, true)
);

This will generate the following query(SqlServer syntax):

WHERE (Users.Age>@p0 AND Users.Email != @p1) Or Users.IsGoldMember = @p2

@p0, @p1 and @p2 will be 18, "" and true respectively.

But what about complex scenarios ? My answer is "keep it simple". With this in mind I think that we covered about 98% of every-day queries, which is good enough for me at the moment.

At the moment, our Query Generator Engine only filter the Where clause so you can't do some sort of magic like LINQ or other infrastructures out there allow you to do. Still, this infrastructure is small enough to be easily integrated with almost any existing infrastructure and yet powerful enough to be extremely useful.

Oh, by the way - at current stage, our engine support queries for SqlServer & Oracle databases.

Enough about high-level API. I'll try to explain the Architecture before I'll start showing you the way I decided to sew this engine. Our first (static)class is Expression, which is kind of Factory for expressions:

Expression.gif

Factory of expression ah ? what kind of concrete objects I've got there ?
Well, here are few samples: EqualExpression, NotEqualExpression and OperatorExpression

Expressions.gif

IDataExpression inherit from IExpression and overload GenerateQuery method with two additional parameters: DatabaseMapper and IDataParameterCollection.

IDataExpression.gif

The former one(DatabaseMapper) will simply "tell" the Query Engine how to convert User.Field.Age enum into "Users.Age" string and the latter(IDataParameterCollection) will be an empty collection of parameters which every expression can fill according to its' needs.

Eventually, we've got an Engine that receives the IExpression(s) and generates code from them:

ExpressionEngine.gif

Here is the implementation of IQueryCreatorEngine.GenerateWhereClause():

string IQueryCreatorEngine.GenerateWhereClause(IExpression[] expressions, IDataParameterCollection parameters)
{
   IDataExpression wrapper = (IDataExpression)Expression.Block(expressions);
   return wrapper.GenerateQuery(this.Mapper, parameters);
}

Pretty straight forward: wrap the expressions with DataBlockExpression and let him take care of our business. Let's look at our DataBlockExpression.GenerateQuery method:

protected override string GenerateQueryCore(DatabaseMapper mapper, System.Data.IDataParameterCollection parameters)
{
   StringBuilder whereClause = new StringBuilder(this.Expressions.Length * 150);

   whereClause.Append("( ");

   foreach (IExpression exp in this.Expressions)
   {
      IDataExpression dataExpression = exp as IDataExpression;

      if (dataExpression != null)
         whereClause.Append(dataExpression.GenerateQuery(mapper, parameters));
      else
         whereClause.Append(exp.GenerateQuery());
   }

   whereClause.Append(" )");

   return whereClause.ToString();
}


The only thing we have to do now is to supply some sort of method which implement DatabaseMapper (delegate) signature when we initialize the QueryCreatorEngine. Here is a quick example:

QueryCreatorEngine engine = new QueryCreatorEngine(
   delegate(object field)
   {
       User.Field typedObj = field as User.Field;
       if (typedObj != null)
       {
          switch(typedObj)
          {
              case User.Field.Age: return "Users.Age";
              case User.Field.IsGoldMember: return "Users.IsGoldMember";
              case User.Field.Email: return "Users.Email";
              default
               throw new ArgumentException("field not supprted"); //whatever
          }
       }
       else
           throw new 
               ArgumentException("field != User.Field type"); //whatever
   });

That's it.

Our mapper is generated by tool (our lovely Code-Agent) and our Filter By Expressions infrastructure is ready to go !

If you are still here, leave me a comment and I'll send you a T-Shirt of "Code don't make me sleepy!".

I'll upload our Data Access infrastructure in a few days so be patient and let me know if this post made you happy.


[1] We did a quick API exam in our department and the results were good.

Posted by Oren Ellenbogen 
12/06/2006 01:22, Israel time UTC+03:00,     Comments [4]  | 
# Saturday, June 10, 2006

I'm doing some thinking about our GUI, Data Access Layer, Entities and the way we should combine them. Looking a little further, LINQ is just a matter of time and effort until we'll use this great infrastructure. I've downloaded a few movies about LINQ from Channel 9, and started to glance at my future. If you're an architect, you should really take a look at Chatting about LINQ and ADO.NET Entities. This will give you a better insight about LINQ's Architecture and where you should intervene if needed.

Our department uses a product we developed in-house named Code-Agent which allows us to generate our application based on our ERD. At current stage, we have our own infrastructure for manipulating data between our tiers, but it lacks some abilities which I really want to see in the near future.

This movie made me *think*.

But before I'll carry on with my insights, let me talk about LINQ, IQueryable<T> and lamda expressions; Let's start with a little example:

var results = from order in orders
              where order.Amount > 100
              select order.Name;

results will now contain all the orders with amount > 100.
The CLR transforms this query into method calls:

var results = orders.
                  Where(delegate(Order order) { return order.Amount>100; }).
                  Select(delegate(Order order) { return order.Name; });

Or via Lamda expression (kind of version 2 to anonymous method):

var results = orders.
               Where(order => order.Amount>100).
               Select(order => order.Name);

Seeing this kind of solution immediately made me think about writing our own LINQ wrapper for the meanwhile. Still, I can't work on production code with LINQ as it really premature at current build but I can definitely build some sort of engine which implement the core principles of LINQ and in time remove my implementation, bit after bit. The next step was to look for IQueryable<T>, this baby inherit from IEnumerable<T> and let you do this magic I've demonstrated above (Where, Select, Group By, Order... you name it). I found a great post on this matter at Wayward Blog.

What's the next step you might ask ?
I guess the answer is to emulate IQueryable<T> in our current infrastructure and aim for compatibility and consistency with LINQ.

Here is a quick implementation which pops out of my head:

EntityCollection<Order> orders = 
                  EntityCollection<Order>.
                     Where(delegate(Order o) { return o.Amount > 100; }).
                     Select(delegate(Order o) { return new { o.Name, o.Id }; });

foreach (Order o in orders)
{
    Console.WriteLine("Order id: " + o.Id + " name: " + o.Name);
}

EntityCollection<T> will inherit from IQueryable<T> and implement the basics.

It's time to get into code-till-I'll-bleed mode...

.NET | Design
Posted by Oren Ellenbogen 
10/06/2006 05:09, Israel time UTC+03:00,     Comments [0]  |