April 2008 - Posts

I was just starting to read the very first pages of the great book "Beautiful Code" (by Andy Oram, Greg Wilson) this morning as a refreshment and as an indirect result to Scott Hanselman's list of basic must-read books (although it didn't include this book - BTW, I read parts of it before, and I don't remember why I stopped), I had to write this post.

To all of you guys thinking in DDD, TDD, MVC, ASP.NET, shiny AJAX and RIA (Flash/Silverlight) controls, GC, SharePoint, Rails, Python, ORMs (NHibernate, SubSonic, Linq2SQL,...), etc.. etc... Please get back to basics and read the PLAIN OLD C CODE I'm quoting in this post. Hopefully it's not illegal to quote such!

The code is a VERY simple RegEx (Regular Expression) matching. Some code that you send a pattern and text to match. It returns 1 if the text matches the pattern and 0 otherwise. The pattern domain is a very stripped version of RegEx than only includes:

  • c => (Any character) matches any literal character c
  • . => (Period) matches any single character
  • ^ => matches the beginning of the string (meaning there must be beginning, not empty string)
  • $ => matches the end of the string (meaning when tested, there should be no more characters in the string)
  • * => (appearing after a character) matches zero or more occurrences of the previous character in the string

The big story of this code is included in the book "Beautiful Code" (It first appeared in another great book called "The Practice Of Programming") - Do yourself a favor and get a copy of both if you can afford it! (Or search your company library, otherwise ask them to get that in the next books batch)

   1:  /* match: search for regexp anywhere in text */
   2:  int match(char *regexp, char *text)
   3:  {
   4:      if (regexp[0] == '^')
   5:          return matchhere(regexp+1, text);
   6:      do { /* must look even if string is empty */
   7:          if (matchhere(regexp, text))
   8:              return 1;
   9:      } while (*text++ != '\0');
  10:      return 0;
  11:  }
  12:  /* matchhere: search for regexp at beginning of text */
  13:  int matchhere(char *regexp, char *text)
  14:  {
  15:      if (regexp[0] == '\0')
  16:          return 1;
  17:      if (regexp[1] == '*')
  18:          return matchstar(regexp[0], regexp+2, text);
  19:      if (regexp[0] == '$' && regexp[1] == '\0')
  20:          return *text == '\0';
  21:      if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text))
  22:          return matchhere(regexp+1, text+1);
  23:      return 0;
  24:  }
  25:  /* matchstar: search for c*regexp at beginning of text */
  26:  int matchstar(int c, char *regexp, char *text)
  27:  {
  28:      do { /* a * matches zero or more instances */
  29:          if (matchhere(regexp, text))
  30:              return 1;
  31:      } while (*text != '\0' && (*text++ == c || c == '.'));
  32:      return 0;
  33:  }

Now, I am not doing to discuss the code. Not just because it's not that hard to analyze (hey, but I didn't get it from first look either), but as the discussion in the book itself is very comprehensive, and I'd advice you again to get it (and also copying as much from the book sure will not be allowed by the authors).

Instead of this, I'll give you a very simple example to trace:

match("c*xyz", "cxyz" );

Clearly this matches. The character c occurs once in the string and the part xyz as well. It should return 1, but tracing it is the most interesting part.

If you are interested in discussing your trace of this example, or your example, just drop a comment here. I'll be very excited to share in this discussion, as it'll not be quoting or repeating the book notes :).

NOTE: This exact code is not the only alternative, you can read more in the book.

So what? I've seen  ALT OF WAY BETTER CODE

It's not about this specific example, but about CODE READING

OK, if you search in the algorithm specific books with all their more interesting usage of recursion and pointers sometimes and/or advanced data structures, or even in this same book but advanced chapters, you are likely to see WAY MORE IMPRESSIVE EXAMPLES of interesting code. It's just this is the one I was reading this morning when I thought: We need so many such examples of this kind of old code, as we're kept far away from all that, and we really should get ourselves a treat by reading such codes.

I'd even go further and say read code in languages you don't even know. Of course when demonstrated in blogs with clear discussion. Reading the posts like "Doing {..the very big task..} in less than .... lines of code with {..any language..}" is really a very important practice to keep from time to time.

More Modern Code: Reading .NET Open Source Code With Discussions Provided

Scott Hanselman has a series he calls "Weekly Source Code". In this series he discusses many .NET open source projects that are used in practice, like all the managed DIGG, Facebook,etc.... API wrappers, some Visual Studio and Live Writer Plugins and many other examples. He demonstrates some of the interesting parts of the code and goes into great discussion about such. If you don't have Hanselman's feed in your feed reader list yet, you really should do!!

 

I'm not sure if I'll keep posting such examples (from different sources of course), but it really sounds like a good idea! :D :D

Day 1: Session 1 [Arch. Track]: Introduction to Agile Software Development   (By: Ahmed Sidky)

Ahmed introduced himself as one that has a master about CMMI and 1st of those to get PhD in software related stuff i Egypt. He spoke in Agile Egypt event before and works in coaching teams implementing Agile. He's someone who knows what he's talking about.

"Agile" means flexibility. "What would you do if the customer came to you saying he can only afford a single day of work ? Hint, based on what you provide, he may find a value in investing in one more day of development". While many in the audience said that they may provide a prototype (which Ahmed interpretted as non-functional one), he wanted to remind us all what our job is. We are not software developers, as software means nothing to the customer, we are "value providers". A prototype will not benefit the customer. He'll not gain/save money out of it! What you want to provide in only a single day of work would be the smallest piece of working software, the most important single feature you can develop in a day maybe. Again, until the software is working, it has NO VALUE. You should start giving you customer true value that he only then can afford another day of development!

Agile is all about this, "value driven". In the 60s when people started to note the major problems of the very limited software at that time, "over budget", "doesn't meet schedule" and "don't meet expectations". Later, Waterfall came to solve this, but still in the 90s we face the same problems. A paradigm shift was needed. People started looking to the industrial process management to learn from. That's where all the stuff like CMMI came from.

Later, in 2001, 17 practitioners  started thinking: "What are we doing right". They didn't come with something totally new, but were looking to things that already existed in the late 90 like eXtreme Programming (XP) and Scrum. They introduced what they called "The Agile Manifesto". It didn't aim to be be a silver bullet or a solution to everything, instead, it focuses on "showing us our existing problems early enough".

A Flexible Process

To dig into Agile, Ahmed first introduced the "Process theory". There're two kinds of processes:

  • Defined Process: Where you guarantee that whenever you include the same input in the process, you always get the same output. This applies to industry, but it -by definition- does not apply to software. If you give the same requirements to different developers or even to the same developer in different years, would you get the same software ??
  • Empirical: That's just the opposite of the defined process. The output is always subject to change.

Continuing, and in many other parts, I felt we developers were sort of wrong audience for this session, as a lot of talk I believed was for project managers more than for developers, although we had a debate about that point. Ahmed went talking about how most PMs try to treat software as a defined process "Get all specs then build". Don't they try to put fixed estimate for the software? How would you get that unless it's well defined? (A quick note was that there still are ways to get fair close estimate with empirical process as well). He talked about the story of trying to create a house in 4 hours. It was planned for 4 hours but was actually even done in 3.5 hours, but hey, it took 6 months of planning!

This is what we (I think he means PMs) try to do with software. But it doesn't work. A great situations Ahmed told is that he once said to a customer "Do you want to 6 months to get you something you don't want or wait 2 weeks to give you something you don't want ??". Because we all know the very first release of the software will not be what the customer really need. Adaptation to change is by default. The key is: "Inspect and Adapt (change to fit)". Ahmed confirmed, this is just a different mind set. You could be doing Agile while still using existing process like CMMI.

The Principles

Ahmed went first on more detailed talk about the Agile Manifesto. The manifesto says:

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

A point highlighted was that the right part after the word "over" in every line is still valued, it's just values less vs. the left side. He asked, when the deadline is getting close, and you are missing features and specs for them, would you focus on documentation or working software?? The point is, we all already follow this manifesto, but we normally only follow it "IN CRISIS MODE".

Then, Ahmed moved into the key principles behind Agile (sample  details). First, the highest priority should be customer satisfaction. After all, that's the one who pays for the software :D. You achieve that by keeping a value stream, that means keeping an early continuous delivery of valued software.

Another principle is welcoming requirement (plans / expected results) change - eve if late in development! Of course it should be understood and even communicated to the customer that this does not come for free. If the customer accepts the cost of change (time/money), then they should be welcomed. To know about the change as early as possible, we get to the next principle, deliver "working software" frequently (2 weeks to month), with preference to the shorter timescale. Also, another related principle is that business people should work daily throughout the project. Of course business people does not mean the customer here, but the business analyst

The next one is interesting; Build around motivated individuals, the  motivation is expected to a result of the team's self management nature. Also, another principle almost already mentioned is that working software is the primary measure of progress. The key point here is that your progress is not where you are in  the plan (requirements, documents, design,...), if your plan says you have 2 months to finish and the actual takes 4, this means you were at 60% of progress, not 80%. Other principles are abut promoting sustainable development, and simplicity.

Then Ahmed went on confirming, this is all best for self-organized teams. The whole team reflects what's gone wrong / right and realizes the need to change. The paradigm shift to "Value Driven" approach makes you consider delivering the highest value at the beginning. Sometimes up to 45% of the features in some projects are almost never used. In agile, the client tells what he wants to be developed for the next iteration. He knows better what makes best value to him. Of course there still should be a planning iteration.

Afterwards we saw a picture of 15 or more developers sitting on their desks in a cube-less office with dual monitors per desk (the dual monitors reminded me of the office in SilverKey!) and having a big data show monitor. On the walls so many sticky notes with different colors, one is red. That was room for Ahmed to explain the value of pair programming, code review, and the very interesting walls thing. The sticky notes on the walls were actually work items, yeah, features and bugs. A manager passing by can easily see the walls as a real-time graph of functionality vs. quality (feature progress vs. amount of bugs). This is the point here, visibility and communication vs. cubes! It's that developers are people, not resources, which even inspires the point that people have good days and bad days as well.

Of course agile promises that this can achieve customer satisfaction as well as team moral. It comes when all the developers have enough common understanding (remember, the developers altogether put the estimates) of the risks, system design, and have a common perspective about the whole project.

The last thing was promoting again practices like automated unit test (yeah, and TDD), and pair programming. and reminding that agile is all about minimum process, yet, maximum value.

I think the session was one of the good sessions in EDC, mainly a very quick skimming and introducing practices. Some areas I felt targeted PMs (who are not intended audience of this conference), but maybe I say that as I'm over concerned with "delivering process to developers" since my dotNETwork session (also on agile), "Scrum For Developers". I think in general Ahmed is a very heavy speaker. I'll love to attend a session he presents, hopefully on more advanced level topic (God Willing).

 

Introduction

Hey there. As promised, I'm covering the Egyptian Developers Conference 2008 that took place last Sunday/Monday.

WARNING: I have so many sheets of notes that I don't know when to write, so, I'll either stop writing at some point or throw a very big pile of text to you :D.

For the same reason, I'm not sure whether I'll be able to make well-sized sub titles, also, will relay on referencing to related resources when possible.

DISCLAIMER: This is still a very personal perspective thing. Of course I missed parts of the presentations, forgot some parts, and didn't care about other some, and even over and under estimated a lot of topics. This is just to open doors for you to read on, NOT MEANT TO BE REPLACEMENT TO SESSION ATTENDANCE but it should help.

When the session videos are uploaded, I'll sure blog about that as well - God Willing.

The Keynote

Hmm, I find the keynote this year very interesting, especially looking back to MDC 2007's keynote, with so much cheesy talk and kid-TV-shows-like stands!

It started with some sort of making-of videos of the guys who worked on organizing the event. That included few advices like "keep mobiles silent" and "Don't sleep :D" and such in a very friendly funny way. Then was simulating the decision to get a celebrity to the keynote, simulating failing tries with some famous sportsmen and singers :D, and then choosing Michael Koester from Silverlight team instead :).

The Silverlight Guy

Michael is a very interesting guy. You love to talk to such person. He was focusing in his keynote speech on students which was weird because neither the conference nature as we know it, nor the nature of topics this specific year target students, but that clearly Microsoft Egypt guidance. To target students in the keynote and professionals in the sessions!!

He started by telling brief of his prof. story, the companies he shared in creating - the most that survived and the few that didn't go well. He pointed out himself as a sample of the effect of technology in people's life, being from a farmer family, the only one to join univ. in his family actually, and now working for Microsoft.

Afterwards, he turned into what drives technology. That's the "experience" as he identified - referring to the user experience. He pointed it out as the fundamental multiplier of technology. A sample was how Google's new experience and "clean competition" they caused changed Microsoft's thoughts of technology, and the "Dragons" book talking about such kinds of effect. He also highlighted the importance of "connected" "global" natures of experience.

Afterwards, he went to the different mindsets in work, from "getting the task done" to "delivering experience". An example was how many needed to know mechanics when cars first appeared, and how many need to know now to drive them. Another example was demoing (With Ahmed Adel from Microsoft Egypt) the use of XBOX controllers to navigate through Virtual Earth map. It was very fun demo, the 3D features for going to streets in US was very impressive :D.

The he went into the nature of the industry. It's a mix between telecommunication and software that form the "Technology" industry. Somehow that let to the S+S (Software + Service) shine. He focused on the variety of clients existing today (Win, Web, WPF, Silverlight), and tools (VS, Expression). He was also very passionate about PopFly. He thinks it's now just a mash-up tool, but this is as it's still a new baby, that he believes will later become a development enviroment that lives on services. A sample usage of it he mentioned was connecting to concert tickets data source or so, combining that with a map, and putting all that as a mashup in facebook or myspace.

The message he wanted to deliver although he knows sounds little cheesy is to "Never underestimate the power of technology. It changes lives, and nations. "And it starts with you", he added, "Students".

The Egyptian Catalyst

After Sherif El Touny (Microsoft Egypt) introduced the sponsors, he gave the talk to Hanan A. Mageed from LINK.NET. I recall Hanan from the developers conference last year when she talked about developer communities. Although I believed she was underestimating any community effort by any non-profit group or any corporation that doesn't have her company's name in it, she was very convincing and impressive even to a guy like me who would argue all the relations she mentioned in her talk. This time I totally agreed with her in everything she mentioned, so, she was even more impressive.

Hanan went to the local side.She started her presentation with pessimistic phrases about local situations in Egypt that started to appear lately in online communities. Her point was to go against such, as she titled her presentation "iHOPE" (where "i" stands for IT :D). She spoke in numbers first, showing how IT revenue of 40 to 50% increase in hope to reach 1 Billion (starting from 250 Million), It was interesting to see her mention companies that last year have either came to or expanded their work in or recruited from Egypt, like many Indian companies, Microsoft, and Google.

Continuing the talk in number, she mentioned that we have 300K graduates, 17K of which are engineers, including 2400 IT ones - Not all are ready to be hired. Skills are what brings investments. She highlighted communication skills and team collaboration, and professionalism and avoiding dealing in personal way, respecting differences whether in opinions or whole culture (like traditions that might sound very weird to us), adaptation, and willingness to learn new things.

Finally, she spotted, "It 'sounds' very simple, very basic to handle", and ended her presentation with a statement contradicting the main negative statement of the ones she started showing. Very inspiring, Hanan :).

The EDC Logo, "Fodoooly"!

The last part in keynote before demonstrating the day agenda was announcing a new way to win prizes. You tell in the EDC website what sessions had the EDC logo in one of the slides. There's one or more in each track. This reminded me of similar thing in old children magazine called "Maged" where you would look for the face of a cartoon character called "Fodooly" in the drawings of every issue :D :D.

Side Talk: The Registration Process

Before the keynote, I met Mohamed Wahby, one of the guys who carried out the work that made the event possible. We talked about the new registration process they had for the event this year.

The process is as follows:

  1. You go to the EDC site, get the mobile phone of a contact in a delivery/shipping company you call to get an "invitation". You can use it during normal business days/hours only of course.
  2. You wait for 3 to 4 days to get the "invitation". Actually the name is very ambiguous. It's like a "ticket". You pay the conference fees to get the "invitation".
  3. You go back to the EDC site to register for the event using the registration code. without this, you have done nothing (although you paid already).
  4. The dead line for the process was a week before the event date. The process stared about 10 working days or before the deadline.
  5. Once you teach the conference, you look for the desk that has the first letter of your first name to get your fancy name tag :).

I told Wahby that so many people thought that it was a weird process, very manual process for the biggest software company in the world!

The reason for this that not many noticed - Wahby said, is that the regular registration process used to require very large lines/queues that were very annoying and remain the same size for hours. This is because the on-site payment, and having to "print" the nametag on-site as well. Both billing and printing took so long, and Microsoft Egypt wanted to take the hassle of those hours to be split over two weeks instead.

Actually, when you think about it, it really makes sense. There were very small waiting lines this year :). Wahby agrees that the big mistake about that is starting the process to last for only two weeks, and that it should take longer than that. I've suffered from this myself as I and my fiancee paid the fees very soon and few days after registration got FREE invitation code that was totally useless by then :D (well, not exactly, I gave it away to a friend who was about to miss the the deadline for registration).

 

A Promise

The day before Microsoft EDC 2008 (Egyptian Developer Conference), I promised to blog about the conference minutes as I see them through my eyes, as I used to do with the MDC (Middleeast Developers Conference, I was the first blogger to write about its minutes and main reference, although I started writing the 3rd year!!!) and any conference I get into as an attendee not a speaker.

Usually, I blog about the conference day at the night of the same day. Once it took me a day after the conference was over. In EDC, although I have explicitly promised to blog about it, I have written none!! Actually, this is because I had so many notes this year (more about that below), I've got buried under so many mid-term exams and quizes at universities, had to write another document about Enterprise Service Bus (ESB) Messaging for work purpose, and yeah, I had other reasons as well. Still,  I was lazy.

The Notes

One of the reasons for not writing is that in EDC 2008 I had so many notes. More than I had in any conference ever. I have around ONE HUNDRED small sheets of notes. Most notes are very small reminder bulletins, some of them consist of one word, because those are meant to be the "compressed" version of the notes. Typically I read a word or more in my notes, and this turns into a statement to a a paragraph in the blog post.

I don't really know how come I got with this huge amount of compressed notes that I found it'll take me ages to extract in this blog. Maybe because my beloved fiancee was there this year. Sure this made me more enthusiast about the event, and gave me more power. BTW, she's a very clever/smart fun developer too.

Late Better Than Never, Or, Now What?!

So, I have decided to keep my promise. I know it's over 10 days since the EDC is over and maybe nobody is interested in the topic any longer, but I'll bet on it. Please if you are interested, encourage me to extract more notes by sending an email or writing a comment out here.

The EDC videos are not released yet. Microsoft Egypt has kept the promise to publish the videos only once of 5 MDC rounds, and it was a weird story. The notes are not meant to replace the videos though. Those are VERY PERSONAL TAKES on the conference minutes the ways I saw them. The target of posting them is sharing different personal opinions with you friends and the rest of the community, and to provide "keywords" for those interested in the session topics to use when googling the topics online.

This is how the game will be:

Instead of the usual style of one post per conference day day, it'll be one post per session of group of few sessions. I'll add a new tag "EDC 2008" to the blog tags besides ("Local Events" and "EDC") so that you can find them easily in one place. I'll make a post every day or so - God Willing.

Hope this may have use to anyone around :).

 

Technorati Tags: ,,,

I have been working lately with a big group of fellow developers here in SilverKey on the architecture and design of a relatively big project that required much services and messaging work. We thought that we should implement our public services the REST way using WCF for .NET 3.5, with so many customizations, and that we'll use a library called nServiceBus for internal messaging. Mohammed Nour wrote a little about thinking in REST.

nServiceBus is a framework for handling publisher/subscriber (pub/sub) model of messaging. It provides reliable messaging via the Enterprise Service Bus (ESB) pattern, and uses MSMQ as the physical bus.

It's an interesting piece of work to look at actually; of course free, open source. I have been involved in evaluating it for our project, and wrote a document about it as part of my work, so that it's easier for the rest of the team to use it later. As the documentation for nServiceBus is very limited at this stage of the project, I and my boss Dody decided to share the document with the community.

Another very important reason for this is enabling the nServiceBus group to correct and enhance the document as much as possible. That's why the document is published under the Creative Commons Attribution-Share Alike 3.0 Unported License.

Download the document

WARNING: This IS going to change, see the nServiceBus Yahoo group for updates to this document.

If you are lazy to download check this out:


Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

Revision History

Author: Mohammad Meligy

Revision Number: 1.1

Project:

Status: Public Draft

Last Updated:

Feature ID:

Related Document(s):

 

 

Revision History    2

Overview    4

Context    4

Glossary    4

Requirements    5

Goals    5

Non Goals    5

Major Features    5

Dependencies    5

Usage    6

How it works    6

Defining the message contracts    6

Writing the code to handle the messages    6

Setting up messaging communication    7

Logging (Optional)    12

Security Consideration    12

Security Constraints    12

FAQ    13

 

 

Overview

This document shows the use of nServiceBus library (www.nservicebus.com) for managing enterprise messaging using the service bus pattern. The model explained is an advancement of a publisher / subscriber model.

Context

The document is written to be guidance for developers involved in intercommunication between components in enterprise project, however, it is written with no specific relevance to the project components, and can be used for any project that implements this kind of messaging.

Glossary

There're some common terms used in this document:

  • Message

    A message is the object that groups the data you want to pass from a module to another module or system for processing outside your module.

  • Publisher

    This is the code that creates the message and puts it publicly to be available for later processing.

    Note: It's very common when dealing with nServiceBus to call the publisher as a "Client"

  • Subscriber

    This is the code that checks for published messages and passes is responsible for performing any desired operations on them.

    Note that the subscriber that subscribes to a certain request message for example may want to send a response message in return, hence, it then acts as a publisher, and so. It's normal that the module that acts as a publisher acts also as a subscriber and vice-versa.

    Note: It's very common when dealing with nServiceBus to call the subscriber as a "Server"

  • Service Bus

    This is the shared message store where all the messages are be written to by the publishers requesting processing, and then later read by the subscribers for processing. Once the messages are delivered to subscribers, they're typically removed from the message store.

 

Requirements

Goals

  1. Enable asynchronous messaging across multiple servers.
  2. Ensure reliability for the asynchronous messaging.
  3. Enable a publisher / subscriber model for the messaging.
  4. Enable multiple subscribers to each published message.
  5. Enable a publisher to receive response messages from subscribers.

Non Goals

  1. Enable canceling of already published messages.
  2. Specify the sequence of message subscribers handling via configuration (still available from inside the subscriber code).

Major Features

  1. Setting a server to act as service bus for multiple publishers/subscribers.
  2. Setting the publishers to send messaging to a service bus asynchronously.
  3. Setting multiple subscribers inside a service bus.
  4. Limiting the handling of messages based on their type.

Dependencies

  1. MSMQ – Acts as store for published messages
  2. Spring.NET Library (On all the publisher and subscriber application – included with nServiceBus assemblies) – For initializing the messaging infrastructure
  3. Log4net Library (http://logging.apache.org/log4net) - For logging purposes
  4. Serialization (On all the code classes that are included in published / returned messages)

 

Usage

 

How it works

You create the message type, create a type that holds the processing of the message (called message handler), configure the publisher and create the message instance itself that it publishes to the bus, and, configure the subscriber to subscribe to the bus and map the message instance to new message handler instance.

You'll notice that the difference between the client and the server is really small. A client publishes a message to one or more primary buses. The server subscribes to the messages it has handlers for that come on the primary bus. But, for the server to be able to send back "response" messages to the client, the client also has its own bus (queue) that it subscribes to for handling response messages.

 

Defining the message contracts

You define the message type (class) normally in any VS project with certain considerations:

  1. It should implements an interface "NServiceBus.IMessage".

    This interface does not require you to implement any methods / properties.

  2. It should be attributed as "Serializable".
  3. It's highly recommended that your message have an identity field of type GUID.

 

This message acts as data contract between the publisher and subscriber, and it should be available to both. This is the actual data that's being passed between them.

Example:

 

Writing the code to handle the messages

A handler is the business logic that does the actual processing of a message. When the subscriber receives a message, it checks which handler(s) it should call to process this message. A handler is independent from the subscriber and can be used with multiple subscribers though.

When creating the handler type (class), you should either

  • implement the interface "NServiceBus.IMessageHandler<MESSAGE_TYPE>"
  • Inherit from class "NServiceBus.BaseMessageHandler<MESSAGE_TYPE>"

MESSAGE_TYPE is the type of the message to handle.

The two options are equal in effect. You write a method "public void Handle(MESSAGE_TYPE)" where you write the code that actually processes the message.

Note: You can implement the interface multiple times for MESSAGE_TYPE_1, MESSAGE_TYPE_2, etc, and then you have to implement the methods "public void Handle(MESSAGE_TYPE_1)" and "public void Handle(MESSAGE_TYPE_2)", etc.

Example:

In this example, the handler just creates a message of a different type (which it does not have to do or have to define) and sends it to the service buss.

The last line has the method "Reply" which accepts "paramas" of message(s) that act as response to the original message and sends the response message(s) back to the queue of the client (who sent the original request message).

Error Codes

To indicate that there was an error processing the message. NServiceBus promotes error codes and creating custom messages that represent the error against throwing an exception.

Here's a sample code or creating "enum" for wrapping error codes and returning it:

 

Setting up messaging communication

Now, you have a message type, and a message handler. What's remaining is writing the publisher that sends this message to the service bus, and the subscriber that asks the service bus to subscribe to any message of the type(s) you want, and before all that, creating the service bus itself.

 

Preparing the service bus

The first thing you need to do is to create the MSMQ queue that acts as a service bus. The name of the queue will later be available to publishers and subscribers to write messages to / read messages from.

 

Creating the publisher

The publisher is the code that sends the messages to the service bus through configurations. Before writing anything, you need to add references to the following assemblies:

  1. NServiceBus
  2. NServiceBus.UniCast
  3. NServiceBus.UniCast.Subscriptions
  4. NServiceBus.UniCast.Subscriptions.Msmq
  5. NServiceBus.UniCast.Transport
  6. NServiceBus.UniCast.Transport.Msmq
  7. utils

The way nServiceBus highly promotes is setting the publisher configuration in the app.config/web.config of the Visual Studio project that contains publishing code using Spring.Net configuration.

A typical configuration looks like this:

  1. A configuration section that registers the Spring.Net configurations

    The "Common" and "log4net" parts are optional and are only used in case you want to use logging.

  2. Create the standard sections for Spring.NET

  3. Replace the part "<!-- All the required configuration for nServiceBus comes here -->" with the actual configuration to use. A typical configuration looks like:

    The properties that matter in this context are:

  • "Transport"
    • "InputQueue"

      Sets the path to the queue where the messages will be read from. This is essential as the publisher might also subscribe to messages (typically responses to published requests).

      Note: For MSMQ v3 (Windows XP, 2003), this must be a local queue.

  • "Message Owners"

    This connects the message - based on the message type (class, the one that implements "IMessage" interface) – to the MSMQ address where it will be published.

    As shown above, this is written as a dictionary, where:

    • "key": is either the name of the message type (class) – or – the name of an assembly, so that nServiceBus looks inside this assembly and locate all the classes that implement the "IMessage" interface.
    • "value": is name of the MSMQ queue to publish the "key" messages to
  1. Write the actual code that sends the message to the service bus

    In this sample, "RequestDataMessage" is just the message type (class).

    The code is pretty simple, you:

  • Use Spring.NET to create the service buss
  • Create the message itself normally and fill its members
  • Send the message to be published to the bus (This has some alternatives discussed later)
  1. As the message is published asynchronously, you can optionally create a callback method that handles the message. A code for something like that would look like:

    You send the message and sending returns an "ICallback" object. This object has single method "Register" which you use to register "AsyncCallback" delegate to a method that will be called asynchronously when the sever returns a reply, which is "RequestDataComplete" in our example. A sample implementation of this method would look like:

    Clearly, you can see that result returned is a "NServiceBus.CompletionResult" which has both "state" which has the original sent message, and "messages" which has the response messages.

     

Creating the subscriber

The subscriber is the code that reads the messages published to the service bus, and pass the messages to the messages handler(s) set for it.

The configuration for the subscriber is very similar to the publisher:

  1. Steps 1 to 3 in the publisher are the same for the subscriber
  2. The final nServiceBus specific configurations would look like:

    Note the following sections as well:

  • "Transport"
    • "InputQueue"

      This is the MSMQ queue that the subscriber will listen to.

  • "SubscriptionStorage"
    • "Queue"

      This is the MSMQ queue where the subscription messages will be stored (The mapping between the subscriber and publishers)

      Note: For MSMQ v3 (Windows XP, 2003), this must be a local queue.

  • "MessageHandlerAssemblies"

    This is a list of assemblies to look in for message handler types (classes, ones that implement "NServiceBus.IMessageHandler<MESSAGE_TYPE>"), so that it maps the handlers to the messages it receives

  1. Writing the actual code that subscribes to the bus. This is very simple piece of code

    You can see it's very simple. You create the "Bus" object from the information in the config file using the "Spring" library, and just start the bus. It loads all the necessary information like which messages to subscribe to and the mapping between message types and message handlers, etc, from the config.

  2. Now you need to deploy the code that runs the server. Note that the bus should be living forever! You'll want to treat it as you treat a Windows Workflow Foundation Workflow Runtime for example. Either make it an independent Windows Service, or write it in some Application even of the global.asax of a web application.

 

Logging (Optional)

For the error logging and such, nServiceBus library has dependency on another library called Log4net. You can use that for any kind of logging. Sample logging code looks like:

For Log4net library specific documentation check

 

Security Consideration

Seeing how nServiceBus works, you notice you have typically two queues, one for the server and another for the client. You also notice that you have two operations for each, read and write.

Security Constraints

To setup MSMQ, you can use public queues, but those are hard to create and are very insecure. Typically you use the default private queues. This causes few constraints on the queue operations.

  • For reading from the queue (AKA subscribing to the bus), the queue has to be on the same machine as the subscriber. You cannot subscribe to a queue that is on a different machine if you are using MSMQ version 3 (like using Windows 2003).
  • To write to the queue (AKA, publish to the bus), the OS process running client/publisher has to be running with a use account that has sufficient privileges on the machine that has the queue you want to write to. This means you'll typically be running the client and server on two machines in the same LAN with Active directory and sufficient user access, which is a common scenario anyway.

FAQ

  1. Where to find a copy of the examples in this document or get a working example for nServiceBus in general?

    The code snippets in this document are mostly coming from the "FullDuplex" example that comes with the library source code.

    The source code can be found at: http://sourceforge.net/projects/nservicebus

    For more examples, check the library Yahoo group at: http://tech.groups.yahoo.com/group/nservicebus

  2. When I downloaded the nServiceBus source from the library SVN repository I found the configuration much different than described in this document. Any Idea?

    The next version of nServiceBus will have different configuration. It's not documented here because it's NOT a complete release yet so is still subject to change before the next release.

    For differences between the configuration of the current release and the upcoming release, check nServiceBus wiki page at: http://nservicebus.wiki.sourceforge.net/Configuration

    There's also incomplete documentation of the examples on nServiceBus wiki at http://nservicebus.wiki.sourceforge.net/Samples

  3. Is there any documentation for nServiceBus?

    There are few resources:

However, most of those are either very limited or incomplete.

  1. How do I write the name of a MSMQ queue that exists on a different computer?

    You write the name of the queue in a format like "QUEUE_NAME @MACHINE_NAME"

    MACHINE_NAME is the computer name of the machine that has the queue.
    QUEUE_NAME is the name of the queue itself

 

Hey everybody. You sure remember that tomorrow is the first of the two-days Microsoft Egyptian Developer Conference EDC 2008. I'll be there since the early hour of registration (8:30 or 9:00 AM)  - God Willing.

So, it'll be great to see all the guys from different gangs around. ArabTeam2000, dotNETwork, DemoDay and so. It'll be great to see you all coming saying "hi". I'll try to hunt as much as possible of you anyway! :D

You too catch me whenever we are in circles discussing any of those long discussions about a company called Microsoft (or something?) and all the talks about the weird .COM .NET tools, and all the other patterns and architecture talks. ;-)

I bet the more of us all in such discussions the more they'll get exciting

 

Looking at the speaker list, although depressing to miss some of the interesting names, it's still interesting to see few new names. We'll see how those will play well in the context :).At least the ones we already know are going to be there, and this should enhance the talks indeed [I'm also expecting gaining new friends with most of the new names]. :-).

 

I'll be there with my beloved fiancee - God Willing. She's so funny and such a very smart deeply technical guru, so, this will even warm the discussions!

I'll also be blogging the sessions I attend as usual. Keep an eye on this blog if interested in those posts.

I've mentioned the sessions I intend to attend. I hope blogging them will help whoever is going to miss those in favor of other sessions - God Willing.

 

See you tomorrow in EDC 2008... Counting the hours!

If yu also played with IronPython Studio that works in isolated mode, meaning an IDE that looks just like the normal VS and shares the core shell of it, but, still is a totally isolated IDE after all, you must have been waiting for the integrated one, and to be able to open your 15+ Projects VS Solution and then go to the File Menu to add a new IronPython Project to them :D.

Well,that's already there few days ago, and I only found it yesterday, so, if you missed it as well, here are the links :). Those are for the both integrated and isolated modes.

Happy Pythonning :)

One Line Statement

Microsoft's IoC container Unity, hosted on CodePlex as an Application Block for Enterprise Library is now released in ver. 1.0.

Introduction

If you do not know what IoC is, you might want to check sample articles:

I have been interested in Dependency Injection (DI) and Inversion of Control (IoC) for few months, and I brought other guys interested too such as Mohamed Nour :D. I'm not going to discuss when I believe those strategies should be used, and how they relate to each others (at least not in this post).

The usual story

If you know about IoC, you'd know that there're few big players in the field that are speaking .NET. I'll not compare them here. I'm not even talking about them with relevance to time order, but I like to see how the "vendors / characteristics" map looks like.  For comparisons, check the end of this section.

The usual story, a player coming from Java world, moving from Java's Spring to .NET's Spring.NET. As you'd expect, this is the one mostly in love with XML configurations - too much of them sometimes, but, it's the most mature one.

Then, as for everything coming from other worlds, Castle group/project was interested. They had their own player, Windsor. Windsor is of course less XML-ish, and as you may expect, it fits best in combination with other Castle stuff. As usual with Castle, the documentation is way far from complete, however, a funny joke about it is someone saying that a big feature of Windsor is that Ayende blogs a lot about it!

Also as usual, there had to be an individual player who tries to do the thing from scratch. That was StructureMap.

For a true comparison between those players, check the following articles:

Here comes Microsoft

As happened with AJAX and unit testing frameworks, when Microsoft decided to create it's own game into the scenes, Microsoft has come to this ground as well to make its standard flavor, going with the relatively recent strategy of not trying to kill the existing players (The proof is approving supporting them in ASP.NET MVC Framework).

Microsoft IoC container as usual had a unique characteristic, and as usual, the unique thing is related to integration with more MS stuff. The Unity IoC container is actually an Enterprise Library Application Block. It's meant to be part of Enterprise Library 4.0. Although Enterprise Library 4.0 is not "released" yet, The Unity Application Block itself is done 1.0, and available to download and use.

Being part of the Enterprise Library (and being an IoC container in general actually - LOL), it didn't escape the XML configuration hassle. Again, that's (unfortunately) a necessity for any IoC. For more information and examples on using Unity, check any of the following articles:

Create you own (Just for fun!!)

If you want to see how this thing from inside looks like, and you do not have time to investigate the source code of a sophisticated IoC container from any of the big players, check Ayende's Building an IoC container in 15 lines of code article. But do not expect that to make you one more player :D.

You can also check how you can try achieving very basic functionality with the existing components of the BCL - that was before Unity of course :).

More Posts