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, May 24, 2006

We want to perform a Merge Replication between 2 databases via WebService (SSL).
The relevant Architecture for the Merge Replication is the following:

replicationviawebservice_1.jpg

Our DBA, Moran, made an attempt to configure the publisher and the subscriber according to the following links, without significant success so far:

http://msdn2.microsoft.com/en-US/library/ms345214.aspx
http://msdn2.microsoft.com/en-US/library/ms152511.aspx
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=352025&SiteID=1
http://msdn2.microsoft.com/en-US/library/ms151763.aspx
http://www.eggheadcafe.com/forumarchives/SQLServerreplication/

The error message we receive is: "The Proxy Auto-configuration URL was not found".

We think that the problem is due to local LAN proxy settings. We got the idea from this post:
http://www.eggheadcafe.com/forumarchives/sqlserverreplication/nov2005/post24306635.asp

Do you have any suggestions on the matter ?

* It's important to mention that Merge Replication over LAN works without a problem.

 

Any suggestion or reference will be most appreciated...

Posted by Oren Ellenbogen 
24/05/2006 10:42, Israel time UTC+03:00,     Comments [0]  | 
# Tuesday, May 23, 2006

Before I'll talk about a different solution, let's talk about the default solution so we could compare them.

Demonstrate the (default)missionary approach - Inheritance:

Let's view a very simple piece of code to make things a bit more tangible:

UsersDal.generated.cs file:

This file is auto-generated based on Users table from our database:

// This file is auto-generated.
// Any changes to this file can be lost in the next code generation.
// If you need to change something - check UsersDal.cs

public abstract class UsersDalBase
{
   public virtual void Add(User u)
   {
      Console.WriteLine("Doing \"base\" behavior for UsersDalBase.Add(User u)");
   }
}


You can imagine that in reality, UsersDalBase.Add method will actually open a connection against the database and insert the received user object. As you can tell, this file should be changed only by the code generator (if you change the table structure or relations for example).


Let's look at our stub class that inherit from the "Base" class.

UsersDal.cs file:

// This file is safe for edit !

public class UsersDal : UsersDalBase
{
}

This file is also generated but only as an empty stub class which can be used if we(the programmers) need to change the default behavior in UsersDalBase. Any upper layer(Business Layer, WS, whatever) in our application will use only UsersDal so any changes to UsersDal or UsersDalBase will be reflected automatically.

Now, let's say that the generated code isn't good enough. I want to check some conditions on the user object before actually adding it to our database. All I have to do is simply override the Add method in our UsersDal class.

public class UsersDal : UsersDalBase
{
   public override void Add(User u)
   {
      if (Validator.IsValid(u))
      {
         base.Add(u);
      }
      else
      {
         throw new ArgumentException("The given object is invalid.");
      }
   }
}

Now, if I want to re-generate my code due to some changes in my ERD, all I have to do is to replace the UsersDalBase.generated.cs file and my custom changes remains untouched.

The only problem with inheritance is it's limitation:

(1) You can inherit from one class only and by using inheritance I can't inherit from GenericDal (unless I'll add another layer of inheritance, not ideal).

(2) I need to give "high" access modifier(public) to my UsersDalBase. We use UsersDalBase just to allow custom changes. In a perfect world UsersDalBase should be internal (Data Access Layer project).


Let's look at a different solution - events based separation:

We want to keep our original ability to make changes in our code without losing it on the next code-generation. First, let's look at a very raw UsersEventArgs I'll use later on:

public class UserEventArgs : EventArgs
{
   private User m_user;
   private bool m_cancel;

   public UserEventArgs(User u)
   {
      m_user = u;
   }

   public User User
   {
      get { return m_user; }
      set { m_user = value; }
   }   

   public bool Cancel
   {
      get { return m_cancel; }
      set { m_cancel = value; }
   }
}

Notice the "Cancel" property, we'll use it later on.

UsersDal.generated.cs (version 2)

public partial class UsersDal
{
   protected event EventHandler<UserEventArgs> Adding;
   protected event EventHandler<UserEventArgs> Added;

   public void Add(User u)
   {
      UserEventArgs ea = new UserEventArgs(u);

      RaiseAdding(ea);

      if (!ea.Cancel)
      {
         // default logic
         AddUser(u);

         RaiseAdded(ea);
      }
   }

   protected virtual void AddUser(User u)
   {
      // generated code
      Console.WriteLine("Doing \"base\" behavior for UsersDal.Add");
   }

   protected void RaiseAdding(UserEventArgs e)
   {
      EventHandler<UserEventArgs> handler = Adding;
      if (handler != null)
         handler(this, e);
   }

   protected void RaiseAdded(UserEventArgs e)
   {
      EventHandler<UserEventArgs> handler = Added;
      if (handler != null)
         handler(this, e);
   }
}

(1) As you can see, I'm raising an event just before adding the user and another event just after adding the user.
(2) We are using partial class (UsersDal).

UsersDal.cs (version 2):

public partial class UsersDal
{
   public UsersDal()
   {
      // Register to (self) events:
      this.Adding += new EventHandler<UserEventArgs>(UsersDal_OnAdding);
      this.Added += new EventHandler<UserEventArgs>(UsersDal_Added);
   }

   protected void UsersDal_OnAdding(object sender, UserEventArgs e)
   {
      if (!Validator.IsValid(e.User))
      {
         e.Cancel = true;
         // I can also throw a new exception, that will work as well.
      }

      // If e.Cancel remains false (default) the basic (generated)behavior will be executed.
   }

   void UsersDal_Added(object sender, UserEventArgs e)
   {
      // Console.WriteLine("Doing custom UsersDal.Add - on added");
   }
}

Calling e.Cancel = true will actually stop the flow in the generated file. You can obviously add more code - according to your needs.

This separation will able you to do just about everything you could via inheritance and then some:

(1) The ability to add another partial class in order to separate class by "topics".
(2) The ability to add more listeners(event handlers).
(3) The ability to inherit from other classes, if you need to.
(4) No need for extra class in our namespace which means less confusion to the programmer - "Should I use UsersDalBase ? Oh.. wait... I remember something about it... Ya! I need to use UsersDal...".

Hope it helps.

.NET | Design
Posted by Oren Ellenbogen 
23/05/2006 11:53, Israel time UTC+03:00,     Comments [1]  | 

Nikhil Kothari, one of the coolest programmers on the planet (and one of the folks behind Atlas) came up with a brand new compiler which will basically allow you to write JavaScript via C#.
He named it Script# (pronounced: ScriptSharp).

This means you can now write JavaScript equivalent code with full IntelliSense, compile time error checking and full debugging enabled framework !!

Let me repeat (I'm hooked, sorry ;-)):

(1) No more need for alert("...") or debugger;
(2) You can compile the code and get typos errors before running the explorer and be spammed with yellow message boxes.
(3) IntelliSense people. IntelliSense. no need to open MSDN to find window or document members.
(4) I hate prototyping in JavaScript - The syntax is quite confusing and I'm lacking 2 must-have IDE features: "Go To Definition" and "Go To Reference". Now you can do it all via C#.

The idea is pretty simple. You, the developer, write C# code and compile it. Behind the scene, the Script# compiler transforms your C# code into equivalent JavaScript and create a *.js file automatically for you. This (js)file will be download to the client (you can even use the new WebResource Attribute in ASP.NET 2.0) and that's it.

You can find a set of demos, examples and of course -the binaries at Nikhil's Blog.

Fantastic !

Posted by Oren Ellenbogen 
23/05/2006 09:43, Israel time UTC+03:00,     Comments [0]  | 
# Monday, May 22, 2006

I want to elaborate on my main ideas from my presentation about Code Templating - abstracting your code via delegates & anonymous methods. During the presentation, I talked about solutions to repetitive, every-day tasks. One of the examples I presented was something *we are all familiar with and that is querying our database. Lets take a look shall we?

public static List<User> GetUsersList()
{
   using (SqlConnection conn = new SqlConnection(ConnectionString))
   {
      SqlCommand cmd = new SqlCommand("Select Id, Name From Users", conn);

      conn.Open();

      List<User> users = new List<User>();

      SqlDataReader r = cmd.ExecuteReader();
      while (r.Read())
      {
         User u = new User();
         u.Id = Convert.ToInt32(r["Id"]);
         u.Name = Convert.ToString(r["Name"]);

         users.Add(u);
      }

      return users;
   }
}

Now let's imagine that we also have Get*List for Products, Orders, Items and Sales. That's 5 Get*List methods already. Let's look at the code that is common among those potential methods (in red):

public static List<User> GetUsersList()
{
   using (SqlConnection conn = new SqlConnection(ConnectionString))
   {

      SqlCommand cmd = new SqlCommand("Select Id, Name From Users", conn);

      conn.Open();

      List<User> users = new List<User>();

      SqlDataReader r = cmd.ExecuteReader();
      while (r.Read())
      {
         User u = new User();
         u.Id = Convert.ToInt32(r["Id"]);
         u.Name = Convert.ToString(r["Name"]);

         users.Add(u);
      }

      return users;
   }
}


So the first solution to refactor those lines of (repetitive)code out will be, obviously, via OOP.
Here is a quick solution I came up with just to make the point clear:

interface IDataReaderParser<TRet>
{
   TRet Parse(IDataReader liveReader);
}

static class DbServices
{
   public static TRet ExecuteReader<TRet>(
      IDbCommand cmd, 
      IDataReaderParser<TRet> parser)
   {
      using (SqlConnection conn = new SqlConnection(ConnectionString))
      {
         cmd.Connection = conn;

         conn.Open();

         IDataReader reader = cmd.ExecuteReader();

         return parser.Parse(reader);
      }
   }
}

So far we have some "parser" interface which will get a liveReader and return some generic type based on the required parsing. I don't know if you've noticed but DbServices.ExecuteReader holds all the lines I marked with red just before. 

Let's look at our GetUsers parser:

class GetUserListParser : IDataReaderParser<List<User>>
{
   public List<User> Parse(IDataReader liveReader)
   {
      List<User> users = new List<User>();

      while (liveReader.Read())
      {
         User u = new User();
         u.Id = Convert.ToInt32(r["Id"]);
         u.Name = Convert.ToString(r["Name"]);

         users.Add(u);
      }

      return users;
   }
}

Our parser get the live IDataReader and returns a list of users. Simple.
GetUsersListParser.Parse method contains the rest of the code (all code minus code in red) from our original GetUsersList method.

Finally, our GetUsersList method looks like this:

public static List<User> GetUsersList()
{
   SqlCommand cmd = new SqlCommand("Select Id, Name From Users");

   GetUserListParser parser = new GetUserListParser();

   return DbServices.ExecuteReader<List<User>>(cmd, parser);
}

That's nice, but is it good enough ?? 
For every Get*List method we will have to build a separate class which will implement IDataReaderParser<TRet>. Let's pause here.

* breath.... good .... *


Let's rewind. When I started writing the original GetUsersList method, my main goal were those lines:

// (1) Create command
SqlCommand cmd = new SqlCommand("Select Id, Name From Users");

// (2) In some magical way, execute the command and return a live reader so I can parse it into objects.
List<User> users = new List<User>();

while (liveReader.Read())
{
   User u = new User();
   u.Id = Convert.ToInt32(r["Id"]);
   u.Name = Convert.ToString(r["Name"]);

   users.Add(u);
}

return users;


Open a connection against the database, executing the command as reader and disposing the connection were irrelevant at the time, I knew that I will have to write those lines down but they were just means to get to my real goal(=my real code). So I refactored my code via some sort of OOP solution.

Now I have pieces of code all over the place and even worse - in 1-2 months from now I will have to "Go To Definition" just to remember what the hack is GetUsersListParser class.


My main code was refactored out of my method.


Life shouldn't be so hard. Like a very wise(and old, they are always old) programmer once said: "If you code it, it will come;".
Let's look at a different solution - let's abstract our code via delegates & anonymous methods.

So our DbServices.ExecuteReader<TRet> will look like:

public delegate TRet ReaderHandler<TRet>(IDataReader liveReader);


static class DbServices
{
   public static TRet ExecuteReader<TRet>(
      IDbCommand cmd, 
      ReaderHandler<TRet> handler)
   {
      using (SqlConnection conn = new SqlConnection(ConnectionString))
      {
         cmd.Connection = conn;

         conn.Open();

         IDataReader reader = cmd.ExecuteReader();

         return handler(reader);
      }
   }
}

DbServices.ExecuteReader receive a (Sql)command to execute and an "handler" - a method with the same signature as ReaderHandler<TRet> delegate. ExecuteReader method will execute the command as a reader and send it(the reader) to the method handler. So who is this "handler" I talk about so much ?! The anonymous method !!

Let's look at the new version of GetUsersList:

public static List<User> GetUsersList()
{
   SqlCommand cmd = new SqlCommand("Select Id, Name From Users");

   return DbServices.ExecuteReader<List<User>>(cmd,
      delegate(IDataReader liveReader) <-- our handler, inline
      {
         List<User> users = new List<User>();

         while (liveReader.Read())
         {
            User u = new User();
            u.Id = Convert.ToInt32(liveReader["Id"]);
            u.Name = Convert.ToString(liveReader["Name"]);

            users.Add(u);
         }

         return users;
   });
}


The entire logic is just in front of me now, no need to start smelling around it !

Just like in the first OOP solution, I don't need to handle the connection, call the ADO.NETs' ExecuteReader, nothing.

To sum up:

Delegates & anonymous methods       1 : 0       OOP



Think about solutions you've implemented via OOP and start thinking about delegates as an alternative abstraction technique. For many straight forward architectural problems, delegates will be by far a better solution than traditional OOP.

My next post on this matter will cover the expected question - when delegates solution is too complex??

* Well, most of us anyway. For the rest of you - be cool and play along.

.NET | Design
Posted by Oren Ellenbogen 
22/05/2006 07:21, Israel time UTC+03:00,     Comments [1]  | 
# Friday, May 19, 2006

In the new asp.net 2.0 web application model, every web page (.aspx) and it's code behind (the class that this page "Inherits" from, actually it's partial with it, but that's the property name) compiles into a single assembly. At least as a default behavior.

aspnet2_Compile_flow.gif

 

That means that the following relationship is completely valid in this compilation model:

Default.aspx (CodeFile=Default.aspx.cs, Inherits=MyNamesapce.MyDefaultPage)
   Default.aspx.cs (class name MyNamespace.MyDefaultPage)

Default2.aspx (CodeFile=Default2.aspx.cs, Inherits=MyNamesapce.MyDefaultPage) // Inherits: same as above
   Default2.aspx.cs (class name MyNamespace.MyDefaultPage// class name: same as above


This can be quite confusing though. While you're developing everything will work as expected as every .aspx & aspx.cs will compile to a different assembly so no collision will occur; So you think you're good to go...

The problems start to show up when you're trying to compile everything to a single assembly (production env.). Now you'll get an "aspnet_merge.exe" error which tells you that you can't combine (1) Default.aspx with (2) Default2.aspx and (3) MyNamespace.MyDefaultPage class. It makes sense, after all, those three are partial classes.

When can this happen ?

if you Copy-Paste an existing page & forget to change the name of the class in the CodeBehind and in the Inherits property.

Solution - How to check if you're really good to go:

I've written a small utility with Mario, my teammate, which will find this duplication and give you a little report telling ya if you have more than 1 aspx file which inherit from the same class. Running it on the example above will produce the following report:

aspnet2_inspector_util.gif

Now all I have to do is change the Default.aspx.cs class name and change the Inherits property name in Default.aspx.

How to use the "Duplication Inspector" utility ?

(1) Extract the zip file (down below).
(2) Open app.config and change the "WebDirectoryToInspect" as needed.
(3) Run the InheritsDuplicationInspector.exe and voila !

You can find the source files here:

InheritsDuplicationInspector.zip - 47 KB

Have fun.

Posted by Oren Ellenbogen 
19/05/2006 09:55, Israel time UTC+03:00,     Comments [1]  | 
# Thursday, May 18, 2006

I had so much fun lecturing yesterday before the C++/C# User Group about abstracting your code via delegates & anonymous methods. The number of people that showed up was really astonishing, at least to my expectations, as about 70 people gave me the honor to talk about something I really like so thank you guys !

I got some really good feedbacks(update: Royo, Ken and Shani dedicated a post on the matter) from the audience, one of them even told me at the end that my lecture was much better than one of the lectures at TechEd 2006 about Generics so I'm really happy that my words and demos made an *impact*. Still, I feel that I can do a lot better so I hope I'll have the pleasure to give more lectures on the near future.

Finally, I got to say a BIG thanks to a bunch of folks: Justin Angel helped me to put my lecture on video so all of you (Hebrew speakers) can hear & see the live presentation(Justin - you rock!), Roy Osherove helped me think about the context of my lecture and connected me to the C++\C# User Group Leaders - Shai & Moshe. I owe a big thanks for Shai Bar Lev & Moshe Raab for giving me the opportunity and making it all possible. And finally, I want to say thanks to my teammates at SQLink that really pushed me through.

You can download the presentation & demos from this links:

Code Templating presentation (ppt) - 1.8 MB

Code Templating Demos (zip) - 500 KB

Code Templating Database (zip) - 139 KB

    * You need to restore this database on Sql Server 2005 Express which comes free 
       with VS.NET 2005. Without the database the ISPARefactoring demos wouldn't work.


The video will be available in a few days so stay tuned.

btw - Barca won the Champions League cup! What a great evening!

Barca.gif

Posted by Oren Ellenbogen 
18/05/2006 12:50, Israel time UTC+03:00,     Comments [3]  | 
# Monday, May 15, 2006

I'm presenting before the C# group on the following Wednesday (17/05/2006, 17:30) and I thought to give you a heads-up. You can click here for more details about the "Agenda", including how to get there & where to park your keyboard.

I'll elaborate on a new way (aka "Code Templating") to refactor your existing code for better re-usage and present some cool tricks via delegates and anonymous methods so get ready for some * cool * code. For the finale, I'm planning some live refactoring on existing code so you really don't want to miss this one !

btw - if you aren't familiar with the terms delegate, event, anonymous method or Generics - this presentation is for you as well; I'll try to cover as much as I can in this session.

It will be great to see you all there.

Posted by Oren Ellenbogen 
15/05/2006 05:07, Israel time UTC+03:00,     Comments [0]  | 
# Sunday, May 14, 2006

Preface:

Let's say that you have Button control named myBtn and you want to handle its Click event:

myBtn.Click += new EventHandler(myBtn_Click);

static void myBtn_Click(object sender, EventArgs e) {
   // do something
}


Now, raise your hand if you ever attached the event handler to the event manually, meaning you wrote "new EventHandler(myBtn_Click);" or even specified the method signature "void myBtn_Click(object sender, EventArgs e)".
I don't know about you, but the way I work is by simply writing "myBtn.Click +=" and this magic yellow thingi appears:

autoCompleteEvent.gif

TAB-ing again will generate the method stub and I'm good to go.

Doing this yellow magic on delegates parameters:

We all(?) worked with List<T>. This nice class has some nice methods like ForEach, FindAll, Find etc which get delegate(Action<T>\Predicate<T>) as parameter. for example: 

List<int> numbers = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });

// Print the numbers via ForEach method
numbers.ForEach(
delegate(int i) {
   
Console.Write(i);
});

Would it be great if you can write something like:

numbers.ForEach(

And the yellow thingi will popup and by clicking TAB this code will be generated:

numbers.ForEach(delegate(int i) {
   //TODO
});

This means that this IDE feature should check the type of the delegate - the number and type (even generic type!) of parameters and the return type. This will prevent us from looking at MSDN or "Go To Definition" while working with delegates which are sent as parameters.

Time for you to make a difference:

what say you ? can this save you some time ? If so - leave a comment, I'll do my best to implement it or to forward this request to MS folks (as ladybug).

Posted by Oren Ellenbogen 
14/05/2006 12:27, Israel time UTC+03:00,     Comments [5]  | 
# Saturday, May 13, 2006

We got up at 07:05. It was hard as hell, but we had to put the effort for the team. After all, we came to hear some great lectures. No way in hell I'm gonna miss it... Oh, and there are many pictures to see, come on, I know you want to see this one !
Posted by Oren Ellenbogen 
13/05/2006 07:37, Israel time UTC+03:00,     Comments [3]  | 
# Friday, May 12, 2006

So it all began on Tuesday, Moty (CEO), Roee(CTO), Ken (Team Leader and a major guffy) and myself drove about 5 hours to Eilat...
Posted by Oren Ellenbogen 
12/05/2006 09:30, Israel time UTC+03:00,     Comments [0]  |