November 15, 2009
@ 12:07 PM

Jesse Ezell  left the following comment on my previous WCF rant (Windows Trick-or-treat Foundation)

You wouldn't expect WCF to take care every TCP/IP registry setting as well would you? At some point, the things WCF exposes have to stop so transport specific settings come into play. What would really suck is if WCF completely abstracted every detail of every transport and came up with new names for things like cookies and specific http request and response headers in the name of creating a "unified" experience across every transport.
The point of WCF is to give you a unified communication API. You don't have to change your code to switch from HTTP, to MSMQ, to TCP, etc. However, the point of WCF is not to hide all the specifics of each transport from you. There are a lot of transport specific options in WCF that you won't find in a WSDL file. However... none of these settings actually require you to change any code to take advantage of them. IMO, WCF does a really good job of providing a uniform communication API and limiting transport specific details to configuration settings. Even in this case, you were able to resolve the issue by configuration settings rather than code changes.
If you had used http request manually, this is one of very few settings you would actually have control over via configuration. What about other popular competing APIs? Look at something like NServiceBus. NServiceBus has a transport model that abstracts communication to some degree... but what happens when you want to change the format of the messages on the wire? For example, maybe you want to switch from raw XML messages to messages with SOAP envelopes on an endpoint or limit the depth of XML node hierarchies to protect against XML attacks. Maybe you want to switch to a completely new transport that was provided by a vendor that has never seen your product. Maybe you want to add compression, or chunking, or certificate based security. Can you do that all via configuration files without ever touching code in any other .NET API? Maybe this is my own ignorance... but I don't know of any .NET communication API that offers even half of the flexibility of WCF.

Well, I would actually expect WCF to do one of two things either provide a complete API of all the communications need (next version of .NET communication , unified communication model and all that..) and retire the other .NET communication libraries or on the other hand provide a thin layer of abstraction that will make it clear you need to move to the specific underlying protocols.

What we’ve got now is something that isn’t quite there on the first and way away from the second – which means that when you try to do serious stuff with WCF you hit these unexpected (ok now they are) snags where you don’t know where to go – until you realize that this is a specific thing regarding TCP this or HTTP that which is not readily apparent and is not well documented or even worse you need to set it outside of WCF altogether.

In my experience , you can’t in fact, “just change the binding” and expect everything to work unless you are doing very simple stuff. For instance when  if you move from HTTP binding to TCP you’d find that the channels are suddenly getting closed after periods of inactivity and you need to “keep them alive” or if you move in the other direction from TCP to HTTP you’d find that the size of messages gets larger by an order of magnitude  etc.

Not to mention the  “training wheels” approach to setting defaults (at least some of it is fixed for .NET 4) which I talked about a few times in the past. Also there cryptic error messages that make you scratch your head looking for the configuration item you need to set. for instance if your send a large message (>8K) you won’t see any problem in the sending side but you’d get the following

“An exception of type 'System.ServiceModel.Dispatcher.NetDispatcherFaultException' occurred in mscorlib.dll but was not handled in user code

Additional information: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:ClientPrintResult. The InnerException message was 'There was an error deserializing the object of type System.String. The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 2, position 40523.'.  Please see InnerException for more details.”

I am sure all of you immediately understood you need to set  ReaderQuotas, MaximumReceiveMessageSize and MaxBuferSize on the binding e.g.:

var binding = new WebHttpBinding()
        {
            ReaderQuotas = { MaxArrayLength = 20 * 8192},
            MaxReceivedMessageSize = 20 * 8192,
            MaxBufferSize = 20 * 8192

        };

Don’t get me wrong, WCF isn’t all bad or anything like that but it does get annoying like hell at times.

As for the reference to other frameworks - I can’t speak for NServiceBus  because I didn’t write it (though I think the answer would be the same) - but if I consider the communication framework I did write for xsights (which builds on WCF by the way) it is not as presumptuous as WCF. It does not pretend to be an all-encompassing communication layer for .NET and  It is build to provide a specific architectural approach – which is why it shouldn’t be judged by the same standards.


 
Tags: .NET | Software Architecture | WCF

October 30, 2009
@ 10:58 PM

Yes, this is another WCF rant…

We were getting ready to launch an open-for-all version of our service, we were also adding more cores to the system, to make sure our computation engine will be able to handle higher request loads (We’re basically implementing the Gridable Service pattern -  if it is interesting, I can expand on that in another post). We tried a few load tests, which on first look, seemed OK. However we then noticed that we get WCF timeouts on some of the calls.

WCF timeouts!? what gives? we already took care of all the annoying throttling defaults. After busting my head (and Google) for a few hours, I found that apparently, when using http bindings in WCF you only get 2 outgoing channels for each server (IP) you are connecting to. yep WCF thinks your services are novice users using a  browser. So if you have a service that tries to access a remote server with more than two requests simultaneously (say, under load…) you may find, like us, that you’d get occasional timeouts.

Yes, there’s also a solution, which also took time to find – it is called ConnectionManagment element in the network configuration (I am yet to find a programmable way to do this). So now the services app.config (see below) sets the value to 16 instead of 2 and everything is well again, at least until the next default hits us..

<system.net>
   <connectionManagement>
     <add address = "*" maxconnection = "16" />
   </connectionManagement>
 </system.net>

 

From trying to work with WCF in the last few years, it seems its abstractions are very leaky.They are almost leaky  to the point  of rendering it useless as a “unified” framework. So, in the spirit of the times, and as the title suggest – maybe they should just rename WCF to Windows Trick-or-treat Foundation – Alas, we are getting more and more of the “trick’ part rather that the “treat”, but at least the acronym fits well.


 
Tags: .NET | SOA Patterns | WCF

Yesterday I gave a talk on SOA pattern on the European Virtual Alt.Net user group. You can find the recording of that talk here as well as download a pdf of the slides.

Before I’ll talk a little about the substance I want to say a few words about office-live meeting (the platform used for the presentation). To sum this in one word the experience was horrid. It took me more than 35 minutes just to upload my presentation. Then I had to switch to windows XP (VM in parallels) to speak since it has problem with Windows 7 (low sound volume). However, the worst thing is that throughout the presentation I constantly lost control of the slides progress (i.e. couldn’t move the slides forward), which was very distracting. 

Anyway, if ignoring all that, I think overall the presentation is still beneficial and  addresses a  few interesting issues that are challenging like flexibility, reporting and management of SOA. If I am to sum the presentation I’d say that  when you build a system on SOA you get a system built of (relatively) a lot of components of questionable reliability. You can reap a lot of benefits in the flexibility department, but you have to address several challenges in the performance, availability, management (etc.) departments. Additionally you  need to look at the overall solution from an holistic viewpoint since different parts of the solution can push in different direction or  only cover part of the picture.

Lastly thanks to Jan and Colin for organizing the event and for all the attendees for giving me an hour and half of their time


 
Tags: .NET | SOA | SOA Patterns | Software Architecture

I begun writing SOA patterns a long time ago. I was making nice progress when suddenly  xsights happened and my free time evaporated. Now,  2 years or so later, we’re finally in production. Since the progress on the book has, hmm how shall I put it, been hampered by xsights,   I thought it would, at least, be appropriate to share a some details on how the ideas presented in the book (written, half-written and yet-to-be-written) are being put to use. As it happens, this also coincided with  Jan Van Ryswyck & Colin Jack  asking me if I’d be interested to in presenting something to the European Virtual Alt.Net group (E-VAN).

So here we are. Next week, I am going to be talking about SOA patterns. I am going to present a few common SOA challenges (availability, flexibility, Reporting, multi-tenancy.) and discuss the patterns and implementation we are using to meet them.  I am still finalizing the presentation so if you have any questions you’d like me to answer, feel free to send them to me (either my email or a comment here) and I’ll do my best to address as many of the questions as possible

Hope to see you there.

Start Time: Monday, October 05, 2009 07:00 PM GMT*

End Time: Monday, October 05, 2009 08:30 PM GMT

Attendee URL: http://snipr.com/virtualaltnet (Live Meeting)

VAN Calendar: http://www.virtualaltnet.com/Home/Calendar

(*) 08:00 PM UK, 09:00 PM Brussels/Israel, 02:00 PM EST and 11:00 AM PST


 
Tags: .NET | SOA | SOA Patterns | xsights

September 17, 2009
@ 11:07 AM

One of the options for interacting with the xsights platform is via web-services for use with mobile clients.  Since the iPhone is all-the-rage these days* we also  wanted an app for this platform. We outsourced the first version (time-to-market…) but we’d like to take ownership on the next versions… Which made me meet objective-C. Now I’ve picked up a lot of programming languages over the years, some where easy to grasp, some where complex, some had a flowing syntax etc. None of them, except maybe Erlang, is as ugly as objective-C is (this is just my opinion, so pardon for any of the cocoa-enthusiastics out there)

Anyway, I’ve been looking around for alternatives and I found few compelling options, most notable of these was Rhodes – a ruby based, cross platform solution. The main problem I’ve had with Rhodes, is that it uses an interpreter. The fact that they feel the need to explain why they comply with the App store rules coupled with the troubles a similar approach using Javascript gets from the app store approval process, I decided to postpone using it (and review it again in a few months).

Then I found MonoTouch (via Miguel de lcase’s blog). MonoTouch, as the post’s title says, brings .NET to iPhone developments. It includes everything you need to write C# code for the iPhone, it integrates well with the Apple tools (e.g. you can use the Interface Builder the same way you’d use xcode while developing objective-C). C#’s friendlier syntax is reason enough for me to use this platform but  it also has a nice side effect of having to write less code to get what you want (e.g. no need to for an .h file if you don’t need really need an interface, no need to release/allocate etc.)

Kudos to Novell on the effort – 


* And rightfully so! – I’ve personally switched to an iPhone 3GS after years of using windows mobile (and its ancestors – I’ve owned different window devices ever since the philips nino was out…). This is not to say that the iPhone is perfect (it is not) but I think that today it offers the best overall experience…ButI guess, that’s a subject for another post.


 
Tags: .NET | iPhone | Mobile | Mono

I noticed that the images and code samples are a little off on the blog (I have to admit I just pasted it from word, and we all know the great HTML that produces…). To help remedy this I am also making this pattern available in PDF from.

The next pattern I am going to publish is actually an anti-pattern called “NanoServices”, which as the name implies is about making services too small. I hope to have that ready early next week. Next after that would be the “Aggregated Reporting” pattern. Aggregated Reporting is aimed at solving the dispersed data problem that autonomy and a lot of services creates.

Any thoughts (on the pattern or otherwise) are welcomed


 
Tags: .NET | Java | SOA | SOA Patterns | Software Architecture

September 8, 2009
@ 06:53 PM

1.1 Reservation

When you use transactions in “traditional” n-tier systems life is relatively simple. For instance, when you run a transaction and an error or fault occurs you abort the transaction and easily rollback any changes – getting back your system-wide consistency and peace of mind. The reasons this is possible is that a transaction isolates changes made within it from the rest of the world. One of the base assumptions behind Transactions is that the time that elapses from the beginning of the transaction until it ends is short. Under that assumption we can afford the luxury of letting the transaction hold locks on our resources (such as databases) and mask changes from others while the transaction is in progress. Transactions provide four basic guarantees – Atomicity, Consistency, Isolation and Durability, usually remembered by their acronym - ACID.

Unfortunately, in a distributed world, SOA or otherwise, it is rarely a good idea to use atomic short lived transactions (see the Cross-Service Transactions anti-pattern in chapter 10 for more details). Indeed, the fact that cross service transactions are discourages is one of the main reasons we would to consider using the Saga pattern in the first place.

One of the obvious shortcomings of Sagas is that you cannot perform rollbacks. The two conditions mentioned above, locking and isolation do not hold anymore so you cannot provide the needed guarantee. Still, since interactions, and especially long running ones, can fail or be canceled Sagas offer the notion of Compensations. Compensations are cool; we can’t have rollbacks so instead we will reverse the interaction’s operation and have a pseudo rollback. If we added one hundred (dollars/units/whatnot) during the original activity we’ll just subtract the same 100 in the compensation. Easy, right?

1.1.1 The Problem

Wrong – as you probably know, it isn’t easy. Unfortunately, there are a number of problems with compensations. These problems come from the fact that, unlike ACID transactions, the changes made by the Saga activities are not isolated. The lack of isolation means that other interactions with the service may operate on the data that was modified by an activity of other sagas, and render the compensation impossible. To give an extreme example, if a request to one service changes the readiness status of the space shuttle to “all-set” and another service caused the shuttle to launch based on that status, it would be a little too late for the first service to try to reverse the “all-set” status now that the “bird has left the coop”. A more down to earth (pardon the pun) business scenario is any interaction where you work with limited resources e.g. ordering from a, usually limited, stock.

Consider, for instance, the scenario in figure 6.1 below. A customer orders an item. The ordering service requests the item from the warehouse as it wants to ship the item to the customer (probably by notifying another service). Meanwhile on the warehouse service the item ordered causes a restocking threshold to be hit which triggers a restocking order from a supplier. Then the customer decides to cancel the order – now what?

6.1

Figure 6.1 Chapter 6 focus is about connecting Services with Service consumers in the levels and layers beyond the basic message exchange patterns.

Should the restocking order be cancelled as well? Can it be cancelled under the ordering terms of the supplier? Also a customer requesting the item between the ordering and cancellation might get an out of stock notice which will cause him to go to our competitors. This can be especially problematic for orders which are prone for cancellations like hotel bookings, vacations etc.

Another limitation of compensations and the Saga pattern itself, for that matter, is that it requires a coordinator. A coordinator means placing trust in an external entity, i.e., outside (most) of the services involved in the saga, to set things straight. This is a challenge for some of the SOA goals as it compromises autonomy and introduces unwanted coupling to the external coordinator.

The question then is

How can we efficiently provide a level of guarantee in a loosely coupled manner while maintaining services’ autonomy and consistency?

We already discussed the limitations of compensations, which of course is one of the options to solve this challenge. Again, one problem is that we can’t afford to make mini changes since we will then be dependent on an external party to set the record straight. The other problem with compensations is that we expose these “semi-states” – which are essentially, the internal details of the services, to the out-side world. Increasing the footprint of the services’ contract, esp. with internal detail, makes the services less flexible and more coupled to their environment (See also the white box services anti-pattern in chapter 10)

We’ve also mentioned that distributed transactions is not the answer since they both lock internal resources for too long (a Saga might go on for days..?) as well as put excess trust on external services which may be external to the organization.

This seems like a quagmire of sorts, fortunately, real life already found a way to deal with a similar need for fuzzy, half guarantees – reservations!

1.1.2The Solution

Implement the Reservation pattern and have the services provide a level of guarantee on internal resources for a limited time

6.2

Figure 6.2 The Reservation pattern. A service that implement reservation consider some messages as “Reserving” in which it tries to secure an internal resource and sends confirmation if it succeeds. When a message considered as “confirming” the service validate the reservation still holds. In between the service can choose to expire reservation based on internal criteria

The Reservation pattern means there will be an internal component in the service that will handle the reservations. Its responsibilities include

§ Reservation - making the reservation when a message that is deemed “reserving” arrives. For instance when an order arrives, in addition to updating some durable storage (e.g. database) on the order it needs to set a timer or an expiration time for the order confirmation alternatively it can set some marker that the order is not final.

§ Validation – making sure that a reservation is still valid before finalizing the process. In the ordering scenario mentioned before that would be making sure the items designated for the order were not given to someone else.

§ Expiration – marking invalid reservation when the conditions changed. E.g. if a VIP customer wants the item I reserved, the system can provision it for her. It should also invalidate my reservation so when I finally try to claim it the system will know it’s gone. Expiration can also be timed, as in, |we’re keeping the book for you until noon tomorrow”

Reservations can be explicit i.e. the contract would have a ReserveBook action or implicit. In case of an implicit order the service decides internally what will be considered as Reserving message and what will be considered as confirming message e.g. an action like Order, will trigger the internal reservation and an action like closing the saga will serve as the confirming message. When the reservation is implicit the service consumer implementation will probably be simpler as the consumer designers are likely to treat reservation expiration as “simple” failures whereas when it is explicit they are likely to treat the reservation state.

Reservations happen in business transactions world-wide every day. The most obvious example is making a ordering a flight. You send in a request for a room (initiate a saga) saying you’d arrive on a certain date, say for a conference, and check out on another (complete the saga). The hotel says ok, we have a room for you (reservation) – provided you confirm your arrival by a set-date (limited time). Even if everything went well, you may still arrive at the hotel, only to find out your room has been given to another person (limited guarantee). The idea of the reservation pattern is to copy this behavior to the interaction of services so that services that support reservations offer a sort of “limited lock” for a limited time and with a limited level of guarantee. Limited level of guarantee, means that like real life, services can overbook and then resolve that overbooking by various strategies such as fist come, first served; VIP first served etc

It is easy to see Reservation applied to services that handle “real-life” reservations as part of their business logic, such as a ordering service for hotels (used in the example above) or an airline etc., However reservations are suitable for a lot of other scenarios where services are called to provide guarantees on internal resources. For instance, in one system I built we used reservations as part of the saga initiation process. The system uses the Service Instance pattern (see chapter 3) where some services are stateful (the reasons are beyond the scope of this discussion). Naturally, services have limited capacity to handle consumers (i.e. an instance can handle n-number of concurrent sagas/events).

This means that when a saga initialized all the participants of the saga needs to know the instances that are part of the saga. As long as a single service instance initiates sagas everything is fine. However, as illustrated in figure 6.3 below, when two or more services (or instances) initiate sagas concurrently they may (and given enough load/time they will) both try to allocate the same service instance to their relative sagas. In the illustration we see that both Initiator A and Initiator B want to use Participant A and Participant B. Participant A has a capacity of 2 so everything is fine for both Initiators. Service B, however, has limited capacity so at least one of the Sagas will have to fail the allocation, i.e. not start.

6.3

Figure 6.3 : Sample for a situation that can benefit from the reservation pattern

The reservation pattern enabled us to manage this resource allocation process in an orderly manner by implementing a two pass protocol (somewhat similar to a two phase commit). The initiator asks each potential participant to reserve itself for the saga. Each participant tries to reserve itself and notify back if it is successful – so in the above scenario, A would say yes to both and B would say yes to one of them. If the initiator gets an OK from all the involved services (within a timeout) it will tell all the participants the specific instances within the saga (i.e. initiate it).

The participants only reserve themselves for a short period of time. Once an internally set timeout elapse the participants remove the commitment independently. As a side note, I’ll just say that the initiator and other saga members can’t assume that the participant will be there just because they are “officially” part of the saga and the system still needs to handle the various failure scenarios. The Reservation pattern is used here only to help prevent over allocation and it does not provide any transactional guarantees.

A reservation is somewhat like a lock and thus it “somewhat” introduce some of the risks distributed locks presents. These risks aren’t inherent in the pattern but can easily surface if you don’t pay attention during implementation (e.g. using database locks for implementation).

The first risk worth discussing is deadlock. Whenever you start reserving anything, esp. in a distributed environment you introduce the potential for deadlocks. For instance if both participants had a capacity for single saga, initiator A contacts participant A first and participant B next and initiator B used the reverse order – we would have had a deadlock potential. In this case there are several mechanisms that prevent that deadlock. The first is inherent to the Reservation pattern, where the participants release the “lock” themselves. However, for example, if there is a retry mechanism to initiate the sagas (as both would fail after the timeout) and the same resources will be allocated over and over there may be a deadlock after all

Another risk to watch out from when implementing Reservations is Denial of Service (whether maliciously or as an byproduct of misuse). DoS can happen from similar reasons discussed in the deadlock (i.e. if you incur a deadlock you also have a DoS). Another way is via exploiting the reservations by constantly re-reserving. Depending on the reservation time-out, regular firewalls might fail detecting the DoS so you may want to consider using a Service Firewall (chapter 4) to help mitigate this thread.

Besides the risks discussed above, another thing to pay attention to is that when you introduce Reservation, you are likely to add additional network calls. The system discussed above mention that when it introduce another call tell the Saga members which instances are involved in the saga.

In addition to the Service Firewall pattern, mentioned above, another pattern related to Reservations can be the Active Service pattern (see chapter 2). The Active Service pattern can be used to handle reservation expiration when implemented by timed. Note however, that sometimes better, resource-wise, to handle expiration passively and not actively as we’ll see looking at s implementation options in the next section.

1.1.3Technology Mapping

Unlike a lot of the patterns in this book, the Reservation pattern is more a business pattern than a technological one. This means there isn’t a straight one-to-one technology mapping to make it happen. On the other hand, code-wise, the pattern is relatively easy to implement.

One thing you have to do is to keep a live thread at the service to make sure that when the lease or reservation expires someone will be there to clean up. One option is the Active Service pattern mentioned above. You can use technologies that support timed events provide the “wakeup service” for you. For instance if you are running in an EJB 3.0 server you can use single action timers i.e. timers that only raise their event once to accomplish this. Code listing 6.1 below shows a simple code excerpt to set a timer to go off based on time received in the message. Other technologies provide similar mechanism to accomplish the same effect.

Code Listing 6.1 setting a timer event for a timer based on a message to set the timer (using JBOSS )

public class TimerMessage implements MessageListener {

@Resource

private MessageDrivenContext mdc;

.

.

.

public void onMessage(Message message) {

ObjectMessage msg = null;

try { #1

if (message instanceof ObjectMessage) {

msg = (ObjectMessage) message;

TimerDetailsEntity e = (TimerDetailsEntity) msg.getObject();

TimerService timerService = messageDrivenCtx.getTimerService();

// Timer createTimer(Date expiration, Serializable info) #2

Timer timer = timerService.createTimer(e.Date, e);

}

} catch (JMSException e) {

e.printStackTrace();

mdc.setRollbackOnly();

} catch (Throwable te) {

te.printStackTrace();

}

}

.

.

.

(Annotation) <#1 some vanilla code to process a message and get the interesting entity out of it >

(Annotation) <#2 Here is where we set the single action timer based on the info in the message we’ve just got>

Timer based cancellation, as described above, might be an overkill if the reservation implementation is simple. For instance the Reservation in listing 6.2 below (implemented in C#) is used by the participants discussed in the Saga and reservation sample discussed in the previous section.

Code Listing 6.2 Simple in-memory, non-persistent reservation

public Guid Reserve(Guid sagaId)

        {

            try

            {

                Rwl.TryWLock();

                var isReserverd = Allocator.TryPinResource(localUri, sagaId);

                if (!isReserverd) #1

                    return Guid.Empty;

//Some code to set the expiration #2

                return sagaId; #3

            }

            finally

            {

               Rwl.ExitWLock();

            }

        }

(Annotation) <#1 The allocator is a resource allocation control, which manages, among other things, the capacity of the service. If we didn’t succeed in marking the service as belonging to the Saga, we can’t allocate the service to the specific Saga>

(Annotation) <#2 Here is where we need to add code to mark when the reservation expired, the previous example (6.1) used timers , we’ll try to do something different here>

(Annotation) <#3 successful reservation returns the SagaId this assures the caller that the reply it got is related to the request it sent – a simple Boolean might be confusing >

Since the Reservation in listing 6.2 does not involve heavy service resources (like, say, a database etc.), we can implement a passive handling of reservation expiration, which will be more efficient than a timer based one. Listing 6.3 below shows both a revised reservation implementation which removes timeout reservation before it commits. Note that an expired reservation can still be committed if no other reservation occurred in between or the capacity of the service is not exceeded.

Code Listing 6.3 passive reservation expiration handling (added on top of the code from listing 6.2)

public Guid Reserve(Guid sagaId)

        {

            try

            {

                Rwl.TryWLock();

                RemoveExpiredReservations(); #1

                var isReserverd = Allocator.TryPinResource(localUri, sagaId);

                if (!isReserverd)

                    return Guid.Empty;

                OpenReservations[sagaId] = DateTimeOffset.Now + MAX_RESERVERVATION; #2

                return sagaId;

            }

            finally

            {

               Rwl.ExitWLock();

            }

        }

private void RemoveExpiredReservations()

        {

            var reftime = DateTimeOffset.Now;

            var ids = from item in OpenReservations where item.Value < reftime select item.Key;

            if (ids.Count() == 0) return;

            var keys=ids.ToArray();

            foreach (var id in keys)

            {

                OpenReservations.Remove(id);

                Allocator.FreePinnedResources(id);

            }

        }

(Annotation) <#1 Added a small method (RemoveExpiredReservations which also appears in the listing) to clean expired reservations. This method is ran everytime the service needs to handle a new reservation request and it cleans up expired reservations. Note that there is no timer involved, reservation are only cleaned if there is a new reservation to process>

(Annotation) <#2 Instead of a timer the reservation is done by marking down when the reservation will expire>

The code samples above show that implementing Reservation can be simple. This doesn’t mean that other implementations can’t be more complex. For example if you want/need to persist the reservation or distribute a reservation between multiple service instances etc., but at its core it shouldn’t be a heavy or complex process.

Another implementation aspect is whether reservations are explicit or implicit. Explicit reservation means there will be a distinct “Reserve” message. This usually means there will also be a “Commit” type message and that the service or workflow engine that request the Reservation might find itself implementing a 2-phase commit type protocol, which isn’t very pleasant, to say the least.

The other alternative is implicit where the service decides internally when to reserve and what conditions to commit the reservation and when to reject it. As usual the tradeoff is between simple implementation to the service and simple implementation for the service consumer

1.1.4Quality Attributes

As usual, we wrap up pattern by taking a brief look at some business drives (or scenarios) that can drive us to use the reservation pattern.

In essence, the main drive to reservation is the need for commitment from resources and since it is a complementary pattern to Sagas it also has similar quality attributes. As mentioned above Reservation helps provide partial guarantees in long running interactions thus the quality attribute that point us toward it is Integrity.

Quality Attribute (level1)

Quality Attribute (level2)

Sample Scenario

Integrity

Correctness

Under all conditions, failure receive payment within 5 business days will cancel the order and shipping

Integrity

Predictability

Under normal conditions, the chances of a customer getting billed for a cancelled order shall be less than 5%

Table 6.2 Reservation pattern quality attributes scenarios. These are the architectural scenarios that can make us think about using the Decoupled Invocation pattern.

Reservations is a protocol level pattern which that involves Reservation involves exchange of messages between service consumers and services. The next pattern is one of the enablers of such message exchange , it is also a one of the confusing pattern since a lot of commercial offerings which include it include gazillion other capabilities - yes I am talking about the ServiceBus


 
Tags: .NET | Java | SOA | SOA Patterns | Software Architecture

I am currently implementing Reservation (a pattern for  “partial temporary commitment” when using Sagas).The  implementation calls for calling a few of the saga members asking them to reserve an asset. Since network calls can take some time I wanted to make each call on its own thread, collect any errors (failures to reserve or communication exceptions) and then have all the threads reconverge to the initiating thread  where any problems will be sorted out (e.g. by retrying the reservation). It basically looks something like the figure below:

image

As you can probably guess this type of synchronization is called Rendezvous (as the threads “meet”). It is also actually fairly easy to implement in .NET I usually do something along the lines of the code snippet below and things like Parallel.For in C# 4.0  will give a similar effect

  1.       private void DispatchThreads(List<Thread> threads, List<SharedContext> sharedContexts, ParameterizedThreadStart threadFunction)
  2.         {
  3.             //initiate threads
  4.             foreach (var context in sharedContexts)
  5.             {
  6.                 var dispatchThread = new Thread(threadFunction);
  7.                 threads.Add(dispatchThread);
  8.                 dispatchThread.Start(context);
  9.             }
  10.             //Rendezvous
  11.             foreach (var dispatchThread in threads)
  12.                 dispatchThread.Join();
  13.         \

However, that’s not why I am writing this post. It turns out I have a more complicated situation. In my setup the code of “Main Thread” (in the figure above) can be run by multiple different threads which are initiated by external events (i.e. I don’t control when they run) – What I needed to to is to make sure that if there are several threads that run in parallel they need to wait for the last of them to finish one section of the code before they can all move on. To explain this better consider the figure below:imageThread 1 starts, sometime after that Thread 2 starts and then Thread 3 starts as well – Thread 1 and Thread 2 have to hold and wait until Thread 3 finished. Thread 4 starts beyond the Rendezvous so none of the other threads care about it. Had it started just before Thread 3 finished all the threads would have had to wait for it as well. Basically I need a similar effect to chords in polyphonic C#

I couldn’t find anything that .NET 3.5 for this - It is kind of what ManualResetEvent – however, it not quite that, since we need to wait for the event only when we’re done. Also we need to let other threads “know” we are running so that they’d wait for us. So indeed I wrapped a ManualResetEvent with a few methods to do just that and ended up with the following.

  1. public class Rendezvous
  2.     {
  3.         private readonly ManualResetEvent Synch = new ManualResetEvent(true);
  4.         private readonly object Locker = new object();
  5.         private int Counter = 0;
  6.         /// <summary>
  7.         /// Join the Rendezvous - Mark that a thread is active and it should finish before the others can continue
  8.         /// </summary>
  9.         public void MarkStart()
  10.         {
  11.             lock (Locker)
  12.             {
  13.                 if (Counter < 0) Counter = 0;
  14.                 Counter++;
  15.                 Synch.Reset();
  16.             }
  17.         }
  18.         /// <summary>
  19.         /// Allows a thread to wait for others without having the others wait for it
  20.         /// </summary>
  21.         public void Wait()
  22.         {
  23.             Synch.WaitOne();
  24.         }
  25.         /// <summary>
  26.         ///
  27.         /// </summary>
  28.         public void MarkFinishAndWait()
  29.         {
  30.             lock (Locker)
  31.             {
  32.                 if (--Counter <= 0) Synch.Set();
  33.             }
  34.             //it is ok if we context switch and lock since we want to synchronize the end times
  35.             Wait();
  36.         }
  37.     \

As long as all the threads have access to the same instance of the Rendezvous class they can synchronize their end times.

Rendezvous is a common pattern for workflow systems (also known as Join-And). It is the first time I had to do that in C# with uncontrolled/uncoordinated thread starts so I don’t know how useful it would be to you. However I thought it is also interesting reading so I published it anyway :)


 
Tags: .NET | Design

This is another post (<Rant>) about WCF default behavior and how it can make the life of developers miserable ( you can also check out “WCF defaults limit scalability”  and “Another WCF gotcha - calling another service/resource within a call”)

Anyway, the trigger for this is a post by Ayende called “WCF works in mysterious ways”.  Ayende posted some code he wrote which was throwing a serialization exception. You can see his post for the full code, but in a nut shell he was defining a large object graph (8192 objects that contain other objects) and was trying to send that over the wire. Here’s a short excerpt from the service definition:

   1: [ServiceBehavior(
   2:        InstanceContextMode = InstanceContextMode.Single,
   3:        ConcurrencyMode = ConcurrencyMode.Single,
   4:        MaxItemsInObjectGraph = Int32.MaxValue
   5:        )]
   6:    public class DistributedHashTableMaster : IDistributedHashTableMaster
   7:    {
   8:        private readonly Segment[] segments;
   9:  
  10:        public DistributedHashTableMaster(NodeEndpoint endpoint)
  11:        {
  12:            segments = Enumerable.Range(0, 8192).Select(i =>
  13:                                                        new Segment
  14:                                                        {
  15:                                                            AssignedEndpoint = endpoint,
  16:                                                            Index = i
  17:                                                        }).ToArray();
  18:        }
  19:  
  20:        public Segment[] Join()
  21:        {
  22:            return segments;
  23:        }
  24:    }
  25:  
  26:    [ServiceContract]
  27:    public interface IDistributedHashTableMaster
  28:    {
  29:        [OperationContract]
  30:        Segment[] Join();
  31:    }
  32:  
  33:    public class NodeEndpoint
  34:    {
  35:        public string Sync { get; set; }
  36:        public string Async { get; set; }
  37:    }
  38:  
  39:    public class Segment
  40:    {
  41:        public Guid Version { get; set; }
  42:  
  43:        public int Index { get; set; }
  44:        public NodeEndpoint AssignedEndpoint { get; set; }
  45:        public NodeEndpoint InProcessOfMovingToEndpoint { get; set; }
  46:  
  47:        public int WcfHatesMeAndMakeMeSad { get; set; }
  48:    }

As you can see in line 4 – the service is properly decorated with an attribute to enlarge the number of objects in graph. so looking at the code I initially suggested he add a few ServiceKnowType and DataContract/DataMember attributes on the data classes (as the serialization sometimes needs some guidance. After that didn’t help I actually ran the code and then I noticed that the code was missing setting that same attribute – on the client side. So to fix the problem, the client side code below

   1: var channel =
   2:     new ChannelFactory<IDistributedHashTableMaster>(binding, new EndpointAddress(uri))
   3:         .CreateChannel();
   4: channel.Join();
Need to change to something like
   1: var channelFactory =
   2: new ChannelFactory(binding, new EndpointAddress(uri));
   3:  
   4: foreach (var operationDescription in channelFactory.Endpoint.Contract.Operations)
   5: {
   6:  
   7: var dataContractBehavior =
   8:  
   9: operationDescription.Behaviors[typeof(DataContractSerializerOperationBehavior)]
  10:  
  11: as DataContractSerializerOperationBehavior;
  12:  
  13: if (dataContractBehavior != null)
  14: {
  15:  
  16: dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
  17:  
  18: }
  19:  
  20: }
  21: var channel=channelFactory.CreateChannel();
  22: channel.Join();

The main problem I find with this piece of code is the fact that it is needed at all. As the post’s title suggest I find this behavior greatly affects the loose coupling of anything that uses WCF (services or other components).

WCF requires that any change you make to the channel on the server side would be reflected in the channel on each and every client (e.g. we have a similar setting where we enlarge message sizes for webHttpBinding and there are many other such examples).

Sure, you say, that is just like adding a new field in the contract isn’t it? – Well no it isn’t since unlike anything else which appears in the (verbose as it is) SOAP contract these changes in default values, which are purely a WCF design choice, are not documented. Again, the changes in default values are not part of the contract. These are things you need to remember to pass on to you service consumer. So not only do I pay the overhead of having an explicit contract (e.g. vs. REST) – it really doesn’t work.  It means that two components who use the same contract may not  be interchangeable if one returns more data (in this case). It means that the two sides are coupled by the need to change these defaults and for what? WCF is smart enough to know how long is the message; WCF is smart enough to handle the message (if I encourage it by setting a behavior) why can’t it add 2 and 2 by itself?

Sometimes I just wish WCF had a TrainingWheels or DemosOnly attribute I could just set to false and make all this crap go away…

</Rant>


 
Tags: .NET | SOA | WCF

May 8, 2009
@ 10:59 PM

Apropos the Blogjecting  Watchdog pattern,  In addition to blogging I recently added to our system the ability to twitter. I am using Tweet# from DimeBrain (thanks Mark Nijhof for the tip via twitter).

Tweet# makes using tweeter really simple (I included the code below in case you find it useful).

The tweeter sender is part of a PostOffice service (I thought that it would be problematic to present it as SpamServer which was its original name :) ).

image Update 11/05 Here it is working on our staging environment :)

A few points about our design in general that are interesting in this regards are

  • The PostOffice is a “Server” type service – we have 3 types of services: server which has one instance per node, channel which has multiple instances per node and algorithmic which has one instance per core
  • The PostOffice implements a pattern I call “Legacy Bridge” – which is basically an SOA version of an adapter+facade in OO terms. The post office supports the events (over WCF) mechanism we have in our system from one side  and connects to external systems (SMS, coupons and twitter) on the other. The PostOffice, basically contains an Edge Component which accepts the requests and funnels them to *Sender classes that interact with the external systems.
  • from contract design perspective – The events I added into the system are StatusEvent and AdminStatusEvent (and not TwitterEvent and DirectMessageEvent). this is better, in my opinion, as it carries the intent of what I want to achieve. It also means that if I choose to change technology or use multiple destinations the events will stay meaningful. For instance, the AdminStatusEvent will be used by our monitoring system to send a notification if the system crashes. I’ll probably want that as an SMS, maybe even a phone call as well as a twit (so the AdminStatusEvent will have a severity to designate how it should be handled)
   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using Dimebrain.TweetSharp.Fluent;
   6:  
   7: namespace xsights.Apps.PostOffice.Server.Twitter
   8: {
   9:     class TwitterSender
  10:     {
  11:         private string account;
  12:         private string password;
  13:         private string admin;
  14:  
  15:         public TwitterSender(string tweetAccount, string twitterPassword,string adminAccount)
  16:         {
  17:             account = tweetAccount;
  18:             password = twitterPassword;
  19:             admin = adminAccount;
  20:         }
  21:         public void Update(string msg)
  22:         {
  23:              foreach (var tweet in BreakToTwitts(msg))
  24:             {
  25:                 var update =
  26:                     FluentTwitter.CreateRequest().AuthenticateAs(account, password).Statuses().Update(tweet).AsJson();
  27:  
  28:                 update.Request();
  29:             }
  30:         }
  31:  
  32:         public void SendAdminMessage(string msg)
  33:         {
  34:             foreach (var twit  in BreakToTwitts(msg))
  35:             {
  36:                 var dm =
  37:                 FluentTwitter.CreateRequest().AuthenticateAs(account, password).DirectMessages().Send(admin, twit).AsJson();
  38:  
  39:                 Retry(2,dm.Request,false);
  40:             }   
  41:             
  42:         }
  43:  
  44:         private IList<string> BreakToTwitts(string originalString)
  45:         {
  46:             var list = new List<string>();
  47:             for (int i = 0; i < originalString.Length; i += 140)
  48:             {
  49:                 var len = 140;
  50:                 if (originalString.Length - i < 140) len = originalString.Length - i;
  51:                 list.Add(originalString.Substring(i, len));
  52:             }
  53:             return list;
  54:         }
  55:  
  56:         private void Retry(int retries, Func<string> call,bool shouldThrow)
  57:         {
  58:            
  59:             try
  60:             {
  61:                 call();
  62:             }
  63:             catch (Exception ex)
  64:             {
  65:  
  66:                 if (retries > 0)
  67:                     Retry(--retries, call,shouldThrow);
  68:                 else
  69:                 {
  70:                     if (shouldThrow)
  71:                         throw;
  72:                 }
  73:             }
  74:           }
  75:           
  76:         }
  77:     }
  78:  
  79: }

 
Tags: .NET | OO | SOA | SOA Patterns

the previous installment provided some context as to why I want to implement this pattern. This
installment will look at some of the implementation options.

As I noted before, WCF provides quite a lot of extension points on the route the message pass from arriving on the service to the point WCF
calls the actual method in the service instance. Several of those extension points are possible candidates for the Service Firewall for instance

  • Contract Filter-The contract filter is responsible to route messages to the appropriate contract. It needs to be a subclass of a MessageFilter. It looks that the contract filter is a good option since it intercepts the call rather early so it means it would probably be the fastest option. Also its name (filter..) implies it is a good option
  • Message Inspector - The Message inspector is responsible for looking at or modifying messages when they enter a service and looks like a natural candidate for the job. There are two kinds of Message Inspectors: Those who look at messages on the client side (implement the IClientMessageInspector interface) and those that look at the server side (implement the IDispatchMessageInspector). It seems that the latter is the type of inspector we need here.
  • Service Authorization Manager - responsible for evaluating policies, claims etc. of the client to make sure that a call is valid from the security perspective. This looks like it would be a good class to use for a real service firewall. It seems it won't be a good fit for the purpose of what we need here.

When I need to choose  between several technical options that seem to be similar I usually do a POC - proof of concept.  A piece of throwaway code to get a feel of the different options and better understand their strengths and weaknesses (in the context of the solution I seek).

What I did was to take a class I prepared for some of the integration tests of the EventBroker and build a few extensions that interact with them. Here is some of the setup code of the environment:

testServer = new Tester();
 service1 = new ServiceHost(testServer, new Uri(string.Format("http://localhost:{0}", TestServerPort)));
 var binding = new WebHttpBinding
 {
     ReaderQuotas = { MaxArrayLength = 600000 },
     MaxReceivedMessageSize = 800000,
     MaxBufferSize = 800000

 };

 var ep = service1.AddServiceEndpoint(typeof(TestingContract), binding, string.Format("http://localhost:{0}/S1", TestServerPort));
 ep.Behaviors.Add(new WebHttpBehavior());
 ep.Behaviors.Add(new InspectorBehavior());
 service1.Authorization.ServiceAuthorizationManager = new TestAuthorizer();
 var cp = service1.AddServiceEndpoint(typeof(ImContract), binding, string.Format("http://localhost:{0}/Control", TestServerPort));
 cp.Behaviors.Add(new WebHttpBehavior());

The two redlines above are the ones responsible for injecting the POCs the InspectorBehavior is reponsible for inserting the ContractFilter and the MessageInspector and the TestAuthorizer is the Authorization Manager test implementation.

We also need some code to raise an event:

public void SendMessage()
 {
     var evnt = new TestingEvent { sagaId = Guid.NewGuid() };

     moqRA.Expect(x => x.GetChannel<TestingContract>(evnt.sagaId, true)).Returns(channel1);
     moqRA.Expect(x => x.GetChannel<TestingContract2>(evnt.sagaId, true)).Returns(channel3);

     eb.BeginNewSagaEvent(evnt.sagaId, evnt);
     eb.CloseSaga(evnt.sagaId);

 }

And now we can look at the different options. The InspectorBehavior is just a helper class to wite the filter and/or inspector to the endpont. (The Authorization Manager is setup at the service level (i.e. for all endpoints))

public class InspectorBehavior : IEndpointBehavior
 {
     
     public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
     {
     }

     public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
     {
         throw new NotImplementedException();
     }

     public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
     {
      var inspector = new TestInspector();
      endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
      endpointDispatcher.ContractFilter = new TestFilter(endpointDispatcher.ContractFilter);
         
     }

     public void Validate(ServiceEndpoint endpoint)
     {
     }

The first thing I tried was the "ContractFilter". It is actually very simple to use. You inherit from MessageFilter and there are two "Match" method you need to override. One that accepts a buffer and one that accepts a (WCF) Message. WCF calls the Match method which accepts a Message.

WCF's Message class is interesting in the sense that it has a one-time touch feature. i.e. only one piece of code can read/copy it and the next piece of code which will try to do the same will fail

So the match method you can do something like the following:

public override bool Match(Message message)
 {
     var buffer = message.CreateBufferedCopy(Int32.MaxValue);
     message = buffer.CreateMessage();
     var r = buffer.CreateMessage().GetReaderAtBodyContents();
     .
     .
     .
 }

Which basically means get a buffer of the message, create one copy to preserve and the get another copy for internal use and work with that to parse and verify the actual message. Unfortunetly, this doesn't really work - the message parameter is not passed as ref so the original message is lost on the first line of the method and that's it. Note that you can access the header part of the message without problem, however that's not a good fit for what I am trying to do.

The next thing I looked at the MessageInspector. Again implementing it is rather simple, you just need to implement the IDispatchMessageInspector interface. This interface has two methods BeforeSendReply and AfterReceiveRequest. We'll look at the AfterReceiveRequest method. Again we try the message copy trick:

public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     var buffer = request.CreateBufferedCopy(Int32.MaxValue);
     request = buffer.CreateMessage();
     var temp = buffer.CreateMessage().GetReaderAtBodyContents();
     .
     .
     .
 }

This time it works since we get the request parameter as ref. At first it seemed to me that while you can inspect and alter the message as your heart wishes there is no way to say that the message is bad. One option is to alter the message to a faulty message and let the application handle it - but that means too much coupling between infrastructure and application. Another, better, option is to throw an exception.

So using the MessageInspector is a usable option. It is very good if you want to alter the incoming message but throwing an exception when the message is bad is not very clean

Which brings us to our third option Authorization Manager which, surprisingly  turned out to be the best option

public class TestAuthorizer :ServiceAuthorizationManager
 {
     public override bool CheckAccess(OperationContext operationContext, ref Message message)
     {
         var autorized= base.CheckAccess(operationContext, ref message);
         var buffer = message.CreateBufferedCopy(Int32.MaxValue);
         message = buffer.CreateMessage();
         var testMessage = buffer.CreateMessage();
         .
         .
         .
         return autorized;
     }
     
 }

Like the message inspector it receives the message as ref and like the filter it allows a single yes/no answer to decide if a message should continue or be discarded. Additionally it notifies the client that the message was rejected if that is what you choose to do (in the WebHttpBinding I used that means a 400 bad request return code)

Ok, so we've seen some of the options for implementing the Service Firewall and briefly went over thier different behaviors. The next part in this series will take a look at some of the actual implementation I did



 
Tags: .NET | SOA | SOA Patterns | WCF

One of the SOA patterns I already described is the Service Firewall. The idea behind the service firewall is to have an intermidiator between the actual service and callers and inspect in an applicative level incoming and outgoing messages.


Anyway, while I documented the pattern as a security one, I am actually going to implement it for another purpose - a saga filter.
In our implementation of EventBroker I made the design decision to have services expose regular WCF contract. i.e. services can communicate with each other directly and not just via eventing. This design decision is there to allow both interaction with non WCF services and to allow flexibility for multiple message exchange pattern (where events are not the best choice).
Another design decision we have is that we have two types of services. Servers and Channels. Servers handle multiple sessions and are (relatively) heavy to write. Channels on the other hand are light-weight services that  are stateful and dedicated for a specific session. Naturally there are a lot of instances of channels to allow supporting multiple sessions (and there are infrastructure bits to allow allocations and propagate liveliness etc. but that's another story). Channels have several benefits like increasing the systems capabilities to cope with failure (if a channel is down only the session it supported fails). One of the benefits of Channels is simple coding model. The Channel is dedicated to a session (typically a saga) and thus it doesn't have to handle all the routing of messages to sagas etc. that Servers have to cope with. This is where the Service Firewall comes to play.
In order to keep channels' code simple "someone" has to make sure the channel doesn't get messages that are not related to the saga it is part of. Otherwise the Channel will have to know about its current active saga and filter messages by itself - which kind of misses the point.
Making sure other services will not send messages while not in saga etc. will only take us so far (you know - latencies and stuff). A service firewall will let us intercept the messages before they reach the service and only allow the messages related to an active saga to pass through (while maintaining the benefits of direct contracts)

WCF has a rich extensibility model (see figure from MSDN below). This series will show how you can use some of these extension points to implement a service firewall and achieve the goal depicted above.  I hope you'd find it interesting




 
Tags: .NET | SOA | SOA Patterns | WCF

 A couple of days ago, one of our team members saw in the log that we are getting index out of bound exceptions in some of the code of the a piece of code I wrote (part of the EventBroker). Taking a look he saw the following:
       private void EventSender(object state)
{
var id = (Guid) state;
try
{
sagas[id].Dispatch();
}
catch (Exception e)
{

            Logger.DebugFormat("EventSender: Exeption Details={0}",e);
rwl.TryRLock();
var isClosed = true;
if (sagas.ContainsKey(id))
isClosed = sagas[id].IsClosed;
rwl.ExitReadLock();

if (!isClosed)
HandleSagaFault(id);

}
}

It is well known that one of the guidelines for exception throwing is "Do not use exceptions for normal or expected errors, or for normal flow of control".So,naturally, he raised an eyebrow and asked me why don't I check that the id exist before I try to call the Dispatch method.
e.g. something like:
            try
{

rwl.TryRLock();
var isClosed = true;
if (sagas.ContainsKey(id))

sagas[id].Dispatch();
rwl.ExitReadLock();
}

Well, as it happens the EventSender method runs on a thread pool thread (something you could have guessed from the object State parameter). It's role is to get the saga to dissipate the event. i.e. the Dispatch method on the Saga object handles actually sending   events to event's subscribers.And while it does its work in parallel it also waits for all the events to arrive before returning (collecting any communications exceptions etc.) What this means is that the Dispatch method takes awhile to return.

Ahh, there's the rub - Contrary to the guideline mentioned above, it is actually more worthwhile to pay the performance penalty of throwing an exception rather than pay the more severe penalty of holding a lock for a long time. The lock affects all the threads running whereas the exception only affects the isolated thread.

Indeed - on another MSDN page there a better version of the guideline "Do not use exceptions for normal flow of control, if possible. Except for system failures and operations with potential race conditions"

The lesson here is (again) is that we need to think before blindly following guidelines.Guidelines are, well er, guidelines not commandments

PS
if you release the lock before calling Dispatch you don't gain anything, since it is multi-threaded code and the id can still be collected between the check and the call itself.

PPS
in case you are wondering TryRLock() is an extension method which try to obtain a lock with a given (short) timeout and throw (instead of deadlock) if the timeout is reached.


 
Tags: .NET | Design | OO

January 5, 2009
@ 08:02 PM
We are going to use some of our test code in production. Yes you read it right test code in production. Here are the details
In our system, among other things, we support visual search in video calls. i.e. an end user calls the system, points the camera at something she is interested, and (hopefully :) ) gets relevant information. Basically the system is made of several resources (image extraction, identification etc.) that collaborate via an event broker. We have a blogjecting watchdog that makes sure everything is up and running and we have applicative recovery service to handle failures.
The watchdog makes sure resources/services are up, resources report their liveliness and wellness so we know more about the resources than the fact that they are up. However, we still need a way to make sure that resource instances  can collaborate to provide the service.

Enter our automated acceptance tests. Part of our development effort included building a test runner for automated tests scenarios, e.g. load tests, verifying algorithms correctness etc. One of these tests is the smoke test (run after each successful build) which includes a sunny-day scenario of a video call- as described above. What we're going to do now is build on the test runner and the sunny day scenario a "keep-alive" tester that will periodically make test calls to the system (depending on the current load etc.) and make sure that everything is still working correctly.


So there you have it, an unexpected benefit of automated acceptance tests, who would have thunk it :)



 
Tags: .NET | SOA | Software Architecture | TDD | WCF

November 29, 2008
@ 08:41 PM
I don't usually blog about promotions and vendor programs - but this is something we joined and if you are a startup using/considering Microsoft's technologies you ought to hear about.

The program is called Microsft Bizspark and essentially it gives you free licenses for all the development team for the porpuse of designing, developing, testing and demoing the application - that's a huge save in development costs (we're using tools like Mingle and subversion but the program even includes a license for team foundation server if you fancy that)

Furthermore, if you, like us, develop a software as a service (SaaS) solution you are also eligible for free production license

To be eligible you have to
  1. be a startup that develops software
  2. privately held
  3. be in the business for less than 3 years
  4. and have less than 1 million USD revenues
check out the program guide for more details

Powered by ScribeFire.


 
Tags: .NET | General

November 5, 2008
@ 07:30 PM
Reshef Mann, one of the members of our devdiv released a nifty little utility for reading configuration files into easy to work-with type-safe interface.
Instead of trying to explain it - Here is the example from his Getting Started :

When you have .config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 
<appSettings>
   
<add key="MailNotificationSettings.SmtpServerAddress" value="http://localhost"/>
   
<add key="MailNotificationSettings.Username" value="user123"/>
   
<add key="MailNotificationSettings.Password" value="passwd123"/>
 
</appSettings>
</configuration>

Define the following interface:

public interface IMailNotificationSettings
{
   
Uri SmtpServerAddress { get; }
   
string Username { get; }
   
string Password { get; }
}

And from your program use this code:

public static void Main()
{
       
ConfigurationReader configReader = new ConfigurationReader().SetupConfigOf<IMailNotificationSettings>();
       
IMailNotificationSettings mailNotificationSettings = configReader.ConfigBrowser.Get<IMailNotificationSettings>();
       
       
var mailNotificationService = new MailNotificationService(mailNotificationSettings);
       
       
//
       
//      Do the work..
       
//
}


The project is open sourced under the Apache 2.0 license- so feel free to use it


 
Tags: .NET | new

October 18, 2008
@ 10:58 PM
As I mentioned in a couple of previous posts (like "Using REST along with other architectural ), I've been spending the last few weeks writing an Event system over WCF (probably also explains posts on  WCF gotchas like this;) ). Being a communication infrastructure it is still a long way from being completed, but it seems to be stabilizing and I think it turned out nicely so I thought I'd share a few details.

Let's start with the simple part - the usage.
The eventing is built on the idea of a bus (i.e. no centralized components) and the resources/services that want to use eventing have to use a library which I call EventBroker.  There are two modes for using the EventBroker. one is "regular" events which are contexless. This means that consecutive events can reach different services, and there is no context that flows from event to event:

bool raisedEvent = eb.RaiseEvent<SampleEvent>(new SampleEvent());
The second type of events are Sagas, which represent long running interactions. Sagas does have a "best effort" guarantee to reach the same recipients over consecutive calls. Also you can also End sagas (sucessful termination), Force End Saga (successful termination by a service that didn't initiate the saga) and Abot Saga (unsuccessful termination): Here is how you raise a saga event.
var evnt = new SampleEvent { data = somevalue};
var SagaId = Guid.NewGuid();
eb.RaiseSagaEvent<SampleEvent>(SagaId, evnt);
if you use the same Saga Id, the events are handled as part of the same saga, if you use a Saga Id that wasn't previously defined it will initialize a new saga.
The eventbroker translates events to the relevant contract and dispatches the events over to the different subscribers. Which brings us to to the next part which I  guess,   is also a little more interesting. How subscriptions are defined.

The first thing to do is to define the event itself.
    public class SampleClassEvent :ImEvent
{
public string DataMember1 {set;get;}
public int DataMember2 { set; get;}
}
There aren't any real constraints on the event, except that it has to "implement" the ImEvent interface. Which is really an empty interface but it marks the event as one for the event broker.
Then you have to define an interface for handling the event. The event broker, builds on the idea of convention rather than configuration (an idea popularized by the rails framework) so it is easier to generate the interface (something I do with a resharper template)
    [ServiceContract]
public interface IHandleSampleClass
{
[OperationContract]
int SampleClass(SampleClassEvent eventOccured);

}
The convention is that the interface will have a IHandle prefix followed by the name of the event. It will hold a single operation named like the event (without the Event suffix) and will recieve a single parameter which is the event data. Currently  events do return a value (int) but I am thinking about changing it to void and have everything marked as OneWay for added performance

Now, when we create a service which needs to handle events it will do that by specifing which events it handles. E.g.
    [ServiceContract]
public interface ImSampelResource : ImContract, IHandleSampleClass, IHandleSomeOtherThing
 {
}
So each contract declares all its subscriptions (by a list of IHandleXXX). It should also include the ImContract interface which holds all the service operation used by the eventbroker (e.g. ending sagas etc.).
Services that want to raise events should inherit from a ControlEdge class (base class Edge component that delegates control events to the event broker)

There's still the question of how does the event broker knows where to find other services. There are several ways this can be done (e.g. a service repository) but since we have  blogjecting watchdogs in place anyway, we use them to propagate liveliness (and location ) of services.

This sums up this post. It is basically just a little context for several planned posts where I hope to talk about some of the challenges, alternatives and design decisions that led me to the current design. Meanwhile, I'd also be happy to hear any comments, ideas or reactions you may have
 
Tags: .NET | Design | OO | SOA | SOA Patterns | Software Architecture | WCF | xsights

October 12, 2008
@ 11:25 PM
In xsights we are doing a lot of work with mobile video, streaming and the like. We are also doing most of our development in C#. Up until recently we've had to resort to C++ (e.g. GStreamer) and sometimes Java (JMF) to handle RTP related tasks.

I've been searching for RTP stack on .NET for a long while and never found anything worthwhile. There's one implementation from Microsoft Reaseach (as part of ConferenceXP ) however the licensing for this is problematic for commercial applications.
Well, a few days ago I finally managed to locate a solution from a small company that goes by the name streamcoders. Not only do those guys offer an RTP.NET implementation it is even free to use and distribute (you can get the source code for a fee). They also have a few other components dealing with related technologies (streaming,coding, encoding).

Sure saved us a lot of trouble :)

Powered by ScribeFire.


 
Tags: .NET | Mobile

I wrote in the past how WCF defaults limit scalability but this thing (which had cost me two days of head scratching) is even worse.
Consider the following scenario:
 You have a WCF service/resource. when you get a message/request your codes needs to send another message to another service.
Sounds common enough now doesn't it? and it is - unless you happen to use a service with   WebHttpBinding (e.g. if you try to develop a RESTful WCF service or want to use POX services).  When you use WebHttpBinding and try to make a call within a call you are likely to find yourself starring at a ProtocolException with a 405 error - Method not allowed. Turns out WCF finds itself confused by the Operation Context (OperationalContextScope) of the incoming request so if you want things to work properly you need to create a new one for the request
var webBinding = new WebHttpBinding();
var channel = new ChannelFactory(webBinding, controlUri);
channel.Endpoint.Behaviors.Add(new WebHttpBehavior());
var proxy = channel.CreateChannel();
using( new OperationContextScope((IContextChannel) proxy))
{
proxy.Dostuff()
}

I already spent the time figuring this bugger out- I hope this post will save you the trouble


 
Tags: .NET | REST | WCF

September 21, 2008
@ 11:50 PM
Back in may Andrew Binstock wondered "is the popularity of unit tests waning?" Andrew lists 5 indications he observed to support his conclusion:
  1. Commercial tools are waning
  2. Few OSS products
  3. Unit testing is not taught by major Java instructors
  4. Few books get published on unit testing
  5. xUnit alternatives are completely invisible.
I am not sure I agree with all these observations, nevertheless,in a followup article in Java World Andrew continued to ask "Is unit testing doomed?".
Andrew says that two issues with unit testing are that they seem to offer little value and that the evangelism of unit testing in general and TDD in particular also causes antagonism (I can say from personal experience with introducing unit testing to long time C and C++ developers that, indeed, the initial responses are rather cold)

Andrew also quotes former CEO of Agitar (Jerry Rudisin) saying that "unit testing hasn't taken off as mainstream practice". A survey ran by Scott Ambler for Dr. Dobb's also found that "The more difficult practices, such as TDD and executable specifications, have lower adoption rates than easier practices such as daily scrum meetings." (although another survey by VisionOne found that within companies where agile practices are used 77% use unit testing and about 49% use TDD)

I recently read another interesting post on the subject, this time by Dan North about the "end of endotesting" explaining why the record-reply idium of most mocking framework is not intuitive and more easy to use mocking frameworks like mockito (his example) or Moq and Mocha (my examples) are better.

Now, yesterday I read Roy Osherov's post "Goodbye mocks, Farewall stubs". Roy makes similar observation on the adoption (or lack therof ) of unit testing practices. Roy believes the number one reason holding back unit testing is the learning curve associated with it and suggests we simplify the tools and terminology (and gives a example similar to Dan's mentioned above)

What we see is that both in the Java and the .NET worlds unit tests adoption hit a few snags. The way I see it there are event  additional barriers to wide adoption of unit test and TDD but I'll talk about that in part II where I'll also try to talk a little about what can/should  be done

Powered by ScribeFire.


 
Tags: .NET | Java | TDD | Trends

I was demonstrating a POC I wrote to one of my colleagues and I showed him one of the integration demo where I have a two console application - a producer and a consumer who communicate by WCF. He was surprised to see&nbsp; I get two separate console windows running from within Visual Studio.

So just in case you don't know that as well, all you need to do is to go to the solution properties (Right click on the solution-&gt;Properties) and under "Startup project" select "Multiple Startup project".
You can even decide which projects will run with a debugger and which won't :)


 
Tags: .NET | General

Microsoft recently released SP1 for .NET. While the SP brings some nice stuff it seems it also has some bugs and a few less than inspiring components
Another example for a less than stellar idea is the "ADO.NET data services" component. Before I go on to explain why I think that. I should probably mention that this isn't just a Microsoft thing as IBM also mentions similar ideas as part of their (broader and sometimes even worse) view of "Information as a Service"

So why is exposing the database through a web-service (RESTful or otherwise) is wrong? let me count the ways
  1. It circumvents the whole idea about "Services" - there's no business logic
  2. It makes for CRUD resources/services
  3. It is exposing internal database structure or data rather than a thought-out contract
  4. It encourages bypassing real services and going straight to their data
  5. It creates a blob service (the data source)
  6. It encourages minuscule demi-serices (the multiple "interfaces" of said blob) that disregard few of the fallacies of distributed computing
  7. It is just client-server in sheep's clothing
When it comes for ADO.NET data services you can add a few other problems like
  1. it isn't really RESTful - you can also "enhance" the services with operations like example 18 in "Using ADO.NET data services" : http://host/vdir/northwind.svc/CustomersByCity?city=London (though it does support caching and hypermedia )
  2. Also it doesn't really externalize a state machine it externalizes a relational model
  3. It is built on Entity Services.

 
Tags: .NET | data | REST | SOA

The .NET community is generally criticized (and rightfully in many cases) that it lacks innovation, with a lot of developers relying either on Microsoft or porting Java stuff* (Junit - > Nunit, log4j -> log4net, Hibernate -> NHibernate, Spring -> Spring.net and the list goes on).
Amidst all this, it is nice to see, that a lot of .NET original ideas are generated here in Israel**.

Few examples that come to mind are
The reason for this post is a new open source project coming from here. This one is from Sasha Goldshtein and Alon Fliess and it is a Non Paged CLR host which offers
"This custom CLR host ensures that all memory given out to the CLR is locked into physical memory if possible, thus eliminating paging completely."
Which can be very useful in performance intensive applications. Cool :)


* This is not to say that sometimes, the port is better than the original (NUnit 2.0 is a prime example for that in my opinion)
**Naturally there's also original stuff happening outside of israel :) e.g. Ninject by Nate Kohari or StoryTeller by Jeremy D. Miller
 
Tags: .NET | new

July 2, 2008
@ 01:07 PM
As I was going through my RSS list (which I publish as a linkblog) I noticed Reginald Braithwaite's post on the metaobject protocol. Reginald says

The bottom line: Languages like Java give you an object protocol: There is one way to do things with objects and classes and interfaces, period. Anything else, like adding generics or annotations, must be done outside of the language, it must be done by the creators of the language.

Languages like Common Lisp and Smalltalk give you a meta object protocol: You can decide for yourself how to do things with objects, classes, interfaces, generic functions, whatever you want. You don’t need to wait for a committee to try something different.

What's nice is that a couple of posts later I noticed a link by Harry Pierson to an attempt by Jeff Moser to port OMeta to the .NET world and to enable the very "meta object protocol" Reginald mentios. Here are the opening bits from Jeff's post (go read the rest):

What if programming language implementations were object-oriented? What if you wanted to change one itty-bitty part of your favorite language? Say you wanted to add an exponentiation operator (^^). How hard would it be?

Wouldn't it be nice if you could "subclass" a language like C# and then add 5 lines of code to make it work and then use it? What if you could add Ruby-like method_missing support in 20 lines?

What if you could conceive of a new language and start experimenting with it in production code in an hour? What if it leveraged your knowledge of existing frameworks like .NET?

Also check out the code Jeff posted so far (on CodePlex)


 
Tags: .NET | Design | OO | Trends

Technical documentation of the code/project  seem like a worthy goal. After all if we aren't living in a vacuum someone will need to understand our code/design and maintain it, use it to develop new stuff etc.
On the other hand writing documentation can get tedious, boring, hard to maintain and whatnot - so you get all sorts of ways to deal with it. Consider, for example, the following:
  • On a recent article in IBM's DeveloperWorks Paul Duvall suggests you use automation to generate various documentation artifacts like UML diagrams based on the source code (using ANT tasks and UMLGraph), ERDs (with SchemaSpy) etc.
  • Another example, is a .Net tool called GhostDoc. This tool automagically generates C# XML documentation comments ("///") e.g. (all comments below are ghostdoc work):
/// <summary>
/// Appends the HTML text.
/// </summary>
/// <param name="htmlProvider">The HTML provider.</param>
public void AppendHtmlText( IHtmlProvider htmlProvider )
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item.</param>
public void Add( string item )
/// <summary>
/// Determines the size of the page buffer.
/// </summary>
/// <param name="initialPageBufferSize">Initial size of the page buffer.</param>
/// <returns></returns>
public int DeterminePageBufferSize( int initialPageBufferSize )

[from Introduction to GhostDoc]
 What I think is that while both of these efforts can help satisfy a customer specific requirement for "comprehansive documentation"* they have very little value in making anyone understand anything about your code. UML diagrams can only help if they are created at a higher level of abstraction than the code (which means they'd be hand-crafted) and if GhostDoc can understand your code enough to create anything useful it means that your method and parameter names are self-descriptive anyway.

In a previous post I mentioned that I prefer to rely on tests, short methods and meaningful names for readability. I'll talk about tests in another post, for this installment lets look at the other two. I think it would be better demonstrated by an example.
Consider the following horror of a method:
       public void HandleWithFrame(FrameProp Frame)
        {

         int FreeProcessNum = 0;
         int FreeProcessId = 0;

         if (Frame != null)
         {
             rwl.EnterWriteLock();

             if (m_WaitingFrame.ContainsKey(Frame.m_SessionId))
                 m_WaitingFrame[Frame.m_SessionId].m_Frame = Frame;
             else
                 m_WaitingFrame.Add(Frame.m_SessionId, new WaitingFrame(Frame));

             IncrementPriority();

             rwl.ExitWriteLock();
         }

           rwl.EnterUpgradeableReadLock();
           foreach (var keyValuePair in m_ProcessMap)
          {
            if (keyValuePair.Value.m_Busy == false)
            {
               FreeProcessId = keyValuePair.Key;
               ++FreeProcessNum;

               if (FreeProcessNum > 1)
                     break;
            }

          }

           if (FreeProcessNum == 0)
           {
               rwl.ExitUpgradeableReadLock();
               return;
           }
       

           if (FreeProcessNum >= 2  )
           {

               rwl.EnterWriteLock();
            
                m_ProcessMap[FreeProcessId].SendFrame2CV(Frame);
              
                m_WaitingFrame[Frame.m_SessionId].m_NumProcess += 1;
                m_WaitingFrame[Frame.m_SessionId].m_Priority = 0;
                m_WaitingFrame[Frame.m_SessionId].m_Frame = null;

                m_ProcessMap[FreeProcessId].m_Busy = true;
              
 
              rwl.ExitWriteLock();
              rwl.ExitUpgradeableReadLock();
              return ;
          }


        


          WaitingFrame MaxPriority = new WaitingFrame();
          MaxPriority.m_NumProcess = 1000;
          MaxPriority.m_Priority = -1;

       
            foreach (var Item in m_WaitingFrame)
            {
                 if (Item.Value.m_NumProcess < MaxPriority.m_NumProcess)
                      if (Item.Value.m_Priority > MaxPriority.m_Priority)
                          MaxPriority.m_Frame = Item.Value.m_Frame;
            }
       
         rwl.EnterWriteLock();

       //  Console.WriteLine("ProcessId={0} Assign", FreeProcessId);
          m_ProcessMap[FreeProcessId].SendFrame2CV(MaxPriority.m_Frame);
          m_ProcessMap[FreeProcessId].m_Busy = true;

        
          m_WaitingFrame[MaxPriority.m_Frame.m_SessionId].m_NumProcess += 1;
          m_WaitingFrame[MaxPriority.m_Frame.m_SessionId].m_Priority = 0;
          m_WaitingFrame[MaxPriority.m_Frame.m_SessionId].m_Frame = null;
        
        
        rwl.ExitWriteLock();
        rwl.ExitUpgradeableReadLock();
        return ;

       }
This class needs a lot of explanations if you want to understand what exactly going on here. So you can set your self up to writing a lot of comments and trying to figure things our - or assuming this class was fully tested (which it wasn't, but that's another story)  try to refactor it until we get something meaningful (I will omit the added tests though for brevity)

Step1 - First If

It seems that when we have a first frame we want to keep it aside, so let's extract method all the if code to EnqueueFrame

           if (Frame != null)
               EnqueueFrame(Frame);

Ok so now we look at EnqueueFrame, The code we see here talks with the  m_WaitingFrame private member (which is a Dictionary of <Guid, WaitingFrame>();. The first thing we'll do is to rename it to FramesQueue. Now the more interesting thing is that the code here has to do with managing this FramesQueue and isn't directly related to the containing class.
We can either subclass the Dictionary class or we can add an extnention method to Dictionary<Guid,WaitingFrame> to handle this for us.
Do we'll do that and then refactor the If again:

           if (Frame != null)
           {
               rwl.EnterWriteLock();
               FramesQueue.Enqueue(Frame);
               rwl.ExitWriteLock();
           }

and Enqueue looks like (in a separate interanal static class)

        public static void Enqueue(this Dictionary<Guid, WaitingFrame> queue, FrameProp Frame)
        {

            if (queue.ContainsKey(Frame.m_SessionId))
                queue[Frame.m_SessionId].m_Frame = Frame;
            else
                queue.Add(Frame.m_SessionId, new WaitingFrame(Frame));

            queue.Prioritize();

        }
The advantage of what we've achieved thus far is both better OO design (separation of concerns) and enhanced readability by using intention revealing names and notation.

Step 2 - The foreach loop
Again we'll start with Extract Method, we can now remove the definition of FreeProcessNum from the beginging and we get
var FreeProcessNum = GetFreeProcessNum(ref FreeProcessId);

but this code is not really clear, for one we have to rename FreeProcessNum to FreeProcessesCount to make it more legible. and we have an ugly and hard to follow ref variable. It is probably better to apply the Single Responsibility principle and  seperate this into two distinct methods,  so we'd get
var FreeProcessesCount = ProcessesList.CountFree();
var FreeProcessId = ProcessesList.GetNextFreeId(); // we don't really need/want the ID but we'll fix that later

(as in the previous example we add extension methods to ProcessesList to make the code more intention revealing and for better seperation of concerns)
All we want to do in CountFree is count how many proccesses are not marked as busy so we can rewrite

var FreeProcessNum = 0;
foreach (var keyValuePair in ProcessesList)
{
        if (keyValuePair.Value.m_Busy == false)
        {
               FreeProcessId = keyValuePair.Key;
               ++FreeProcessNum;

               if (FreeProcessNum > 1)
                       break;
         }

 }
  return FreeProcessNum;
into
        public static int CountFree(this Dictionary<int, ProcessStatus> processesList)
        {
            return processesList.Count(item => item.Value.m_Busy == false);
        }

Thank you MS for adding Linq and Lambda expressions :). The same can be done for GetNextFreeId
 

Step 3 the two Ifs and the rest
Taking a deep look at the code we can see that the rest of the method tries to find a free processor and if there are enough processors send the frame, otherwise it should send the top prioritized. We can also spot a bug here that two different threads can get the same Processor and then try to send a message to it one after the other. Another potential bug comes from the way the maximal priority is found. There's an assumption there that the max priority would be 1000. While it isn't likely to happen it is still a hard coded assumption.
Anyway, if we continue and apply the same principles that got us here (Single Responsibility Principle, Don't Repeat Yourself, Intention revealing methods, coherence and opening classes to add specific functionaliy) we get the original method to look like the following:

       public void ProcessFrame(FrameProp nextFrame) //was HandleWithFrame
        {
           rwl.EnterWriteLock();
           try
           {
               if (nextFrame != null)
                   FramesQueue.Enqueue(nextFrame);

               TryDispatchTopFrame();
           }
           finally
           {
               rwl.ExitWriteLock();
           }

       }
Compare this with the original method....
Also note that it isn't that the functionality disappeared - it is just neatly distributed and grouped in short related methods in related classes e.g.

    internal static class FramesQueueExtnesions
    {
        public static void Enqueue(this Dictionary<Guid, WaitingFrame> queue, FrameProp Frame)
        {

            if (queue.ContainsKey(Frame.m_SessionId))
                queue[Frame.m_SessionId].m_Frame = Frame;
            else
                queue.Add(Frame.m_SessionId, new WaitingFrame(Frame));

            queue.UpdatePriorities();

        }

        public static void ResetSlot(this Dictionary<Guid, WaitingFrame> queue,Guid slotId)
        {
            queue[slotId].m_NumProcess += 1;
            queue[slotId].m_Priority = 0;
            queue[slotId].m_Frame = null;
        }


        public static void UpdatePriorities(this Dictionary<Guid, WaitingFrame> queue)
        {

            foreach (var Item in queue)
            {
                if (Item.Value.m_Frame != null)
                    Item.Value.m_Priority += 1;
            }


        }
        public static FrameProp FindTopPrioritized(this Dictionary<Guid,WaitingFrame> queue)
        {
            var maxPriority=  queue.Max(item => item.Value.m_Priority);
            return queue.First(item => item.Value.m_Priority == maxPriority).Value.m_Frame;
        }
    }

You should note that this is not the end of the refactoring (e.g. we should still handle the WaitingFrame, FrameQueue and the ProcessesList which we are called here) we just took a look at a single method.

While there might still be a need for an occasional explanatory remark , I think this little exercise demonstrate that we can gain a lot in the way of clarity by refacroting code and keeping up a few simple principles. Oh yea, and what we got at the end of the process is not just readable code, but also a more maintainable, better designed code that can move forward and evolve further as the system changes.



* I don't underestimate the value of generating full documentation when there's such a requirement from a customer. I would prefer to convince a customer that having such a Write-Only document is a complete waste of time  and trees but sometimes you can't help it. Generating documents in these situations can be a life-saver.


 
Tags: .NET | Agile | refactoring

I guess the designers of WCF really want to discourage some of the uses of the framework - I can't really understand some of their choices, if that was not the case.

For instance, when you create a stateful service (InstanceContextMode = InstanceContextMode.Single) the default concurrency behavior is single threaded. In this mode, WCF will serialize all the calls to the service and messages will wait/time-out. While it is easier to program, this has no real-life use except maybe for demo applications in Teched presentations.
Luckily you can override that and set ConcurrencyMode = ConcurrencyMode.Multiple and get a multithreaded service but the default is useless at best. By the way beware of the ConcurrencyMode.Reentrant  since in this setting you still have a single threaded service and WCF can accept calls when you call other services so you need to take care of multithreading but don't get the benefits.

Another example which is even worse, is the default for maximum number of connections for self hosted services. This is limited to 10, yes, 10 concurrent connections. We found that out when we set up a service that had, lo and behold, 11 different services that interact with it. These services would call the service something like 10 times a second and occationally we got timeout exceptions. At first we figured we got something wrong with the multi-threading implementation. So we spent a couple of days going over the locks and releases, and what-not. Then we thought the problem was with the transport (net.tcp) so we changed that to http and still saw the same problems. Only then we figured out that, as I mentioned above, the default is 10 concurrent sessions.
To solve this problem you need to configure the Throtteling behavior of the service by using ServiceThrottlingBehavior. This class has three useful settings

The MaxConcurrentCalls property limits the number of messages that currently process across a ServiceHost.

The MaxConcurrentInstances property limits the number of InstanceContext objects that execute at one time across a ServiceHost.

The MaxConcurrentSessions property limits the number of sessions a ServiceHost object can accept.


The default for MaxConcurrentCalls is 16, MaxConcurrentInstances int32.MaxValue and MaxConcurrentSessions is 10.
If you're using a self hosted service bump these up or you might DOS yourself like we did :)

Anyway, these defaults are a real barrier to scale and performance. Sure, you can change them easily, but you first have to know about them, and that's the probelm. Hopefully, my wasted time will help you avoid these problems :)


 
Tags: .NET | SOA

Dare Obasanjo complains about Resharper 4.0's recommendation to use implicitly typed locals (i.e. var someVariable = SomeMethod(); rather than SomeType someVariable = SomeMethod();)
It is a small issue and I would probably wouldn't comment about it except I hear some of the same complaints from members in our team. The main grievance Dare has is that using var impedes the readability of the code. He also says that that people using var will be more inclined to use long "hungarian style" variable names.
Dare also mentions MS recomendation on the use of var which recomends

As for me, I am just happy with anything that get me nearer to true duck typing and the extreme-late-binding it offers.
Dr. Alan Kay (inventor of Smalltalk and one of the fathers of OOP) even says that that extreme late-binding is one of the essential attributes of an Object oriented language:
"(I'm not against types, but I don't know of any type systems that aren't a complete pain, so I still like dynamic typing.)
OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. It can be done in Smalltalk and in LISP. There are possibly other systems in which this is possible, but I'm not aware of them."
Yes, the var keyword is still a far cry from duck typing as it doesn't provide the true late binding to the interface needed you get in languages like Python or Ruby. It does however takes one worry from you and helps reduce the overall accidental complexity. var, extension methods and lambda expressions all help make C# more "dynamic" and easier to work with.

I think Ola Bini summed the issue best:
"A statically typed language with type inference will give you some of the same benefits as a good dynamic language, but definitely not all of them. In particular, you get different benefits and a larger degree of flexibility from a dynamic language that can't be achieved in a static language. Neal Ford and others have been talking about the distinction between dynamic and static typing as being incorrect. The real question is between essence and ceremony. Java is a ceremonious language because it needs you to do several dances to the rain gods to declare even the simplest form of method. In an essential language you will say what you need to say, but nothing else. This is one of the reasons dynamic languages and type-inferenced static languages sometimes look quite alike - it's the absence of ceremony that people react to."
Edit As for the code readability claim. I prefer to focus on stronger methods like keeping methods short, meaningful method and variable names and supporting tests (which can actually help you understand how the code behaves...). Not to mention that, if you really really need that, resharper will tell you the type if you put the mouse over the "var" keyword ;) 
 
Tags: .NET | OO


Among the reactions I got for my previous post on the Singleton pattern in .NET were a couple that talked about the design rationale behind the solution I posted:

Adi Avnit posted on the risk of using a "generic singleton":
"However, there is one possible pitfall to this approach, as it makes this code possible:
Singleton obj = Singleton.Instance;
MyClass obj2 = new MyClass();

While I personally like the idea of having the freedom to use the same class in two different ways throughout the application, I know some people like their Singletons - well, single.
On the other hand, if you write a class from the start as a Singleton this is not an issue.

There is an inherit risk in decoupling a class from it's expected behavior, so take this into consideration before using this pattern."

And Cade Roux wrote in a comment:
"don't believe discoverability was a motivation for Singleton. The purpose was to ensure only one instance existed (a print spooler, a file system). You can get discoverability through the technique you explain but the primary purpose of singleton was a pattern of prohibition - to stop a programmer doing something they shouldn't do by accident by enforcing the primary goals of single point of access.

It is more than a global, and the OP, while comparing them to globals, does not acknowledge that this solves many of the problems which made "global" a 4-letter word. Knee-jerk reaction against globals is not healthy once you've mitigated their drawbacks.

It is true that usage of singleton can be misguided and cause coupling - which is why you need to ensure that the usage of the pattern matches the motivation in the first place.

This is a key point of design patterns which Alexander should have made clear in http://en.wikipedia.org/wiki/N...is_of_Form - the pattern is a result of a resolution of system of forces. It only satisfies that system - moving it to another different system will result in poor fitness. "
I guess that's a good opportunity  to talk about design issues regarding Design Patterns in general and the GoF ones in particular.

Aristotle Pagaltzis
noted (in a comment on Cedric's blog) that
"design patterns are a sign of a deficiency of a language for the purpose that the design pattern addresses. In other words, the Visitor pattern used in Java points to the fact that Java is deficient in terms of list processing: the `map` and `filter` constructs need to be emulated with lengthy OO incantations."
In other words Concrete patterns* (like GoF's) are tied to implementation which means that the implementation language is  part of their "context". Thus when you come to apply a pattern in a different language you need to consider the language in use and make sure that
  1. The pattern is needed
  2. The solution in the pattern is the best one for the language.
Let's look at a few examples.
If we take the Visitor pattern mentioned above - The intent of the visitor pattern is to "represent an operation to be performed on the elements of an object structure without changing the classes of the elements". In .NET 3.5 you can do that with the use of LINQ (to find relevant items) and extension methods (to add external functionality) - same intent, completely different implementation.

In the case of the Singleton pattern (mentioned in the previous post). The intent is to "Ensure a class only has one instance, and provide a global point of access to it". An implementation using templates (or generics) is superior since it provides the same intent but also adds better compliance with the Single Responsibility Principle. While it is possible to create the class as a non-singleton on the one hand it solves the multi-threading issue in one place preventing both duplication of code and mistakes (again this can be especially important in non-forgiving environments like C++). It also lets you (not in the implementation I provided) add flexibility and e.g. let singletons die and (if needed) resurrect themselves etc. Note that even if you are not convinced that using generics is better, there's no doubt that using .NET's thread-safe static readonly variable (public static readonly MySingleton = new MySingleton();)  is a much simpler solution than the GoF one and again, answers the original intent with a different solution.

Another example would be the Template method pattern. The idea behind the template method is to support the Open closed principle (classes should be open for extension but closed for modification) or as the GoF defines the intent:
"Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm strucuture"
.NET 3.5 supports the notion of Generic Delegates so you can define functions as parameters and pass them along. This is a better implementation than the template method as now you don't have to subclass when you want to extend an algorithm you can just pass a function that matches the signature
e.g.
    class Program
    {
        static void Main(string[] args)
        {
            var alg = new Algorithm();
            alg.DoSomething(Funky);
        }

        static bool Funky(string value)
        {
            return value == "somevalue";
        }
    }


    class Algorithm
    {
        public void DoSomething(Func<string,bool>CanGoForward)
        {
            string someVariable = "somevalue";

            if (null!=CanGoForward && CanGoForward(someVariable))
            {
                //do one step
            }
            // whatever
        }
    }


You should note that this "refactoring to fit the language" phenomena isn't limited to GoF patterns (or .NET :)) , for instance you can consider the use (or lack thereof) of Dependency Injection in languages such as Ruby which I wrote about a few months ago.

To sum up - when you talk about design patterns you need to consider the implementation language, design pattern deal with deficiencies in the language and different languages have different deficiencies and may have better solutions to the problems solved by the patterns



* As opposed to architectural patterns which are more abstract and thus more reusable (e.g. Hohpe & Wolf Enterprise integration patterns, or Martin fowler Enterprise Architecture patterns)


 
Tags: .NET | Design | OO

March 31, 2008
@ 10:00 AM
While I personally don't like the Singleton pattern too much (it is essentially an OO mask for Global Variables, it makes it harder to unit test etc.), I still need to use them now and then. Anyway, I saw a post by Jack Altiere about "Using the Singleton Pattern" in .NET and since it presents an implementation that leaves a lot to be desired I decided to comment on that

For one, he presents a solution which locks every time the singleton is accessed (see below). The reason this is flawed is that singletons are instantiated once, but they are accessed a lot of times and with this implementation you pay every time you try to access the singleton

//bad implementation - don't use
//also note some initialization etc. is omitted for brevity
public static Foo Instance
{
get
{
// This lock allows thread safety.
lock (_mutex)
{
if (_instance == null)
_instance = new Foo();
return _instance;
}
}
}

There's a better "standard" way to do that which basically means you check if the the instance is null, lock, check again (in case more than one thread got past the first check ) and only then instantiate (you'd also need to mark the instance volatile in this case)
.NET has a better way to create thread safe singletons by merely using a static readonly declaration as in:
public  sealed class singleton
{
public static readonly MySigleton Instance = new MySingleton()
}



This implementation is not as lazy as the implementations above - but it is thread safe an efficient (you can get more laziness if you use a nested class as described here)

But that's not all- see, one of the problems of the Singleton pattern (besides the ones mentioned above) is that it is also a violation of the Single Responsibility Principle (SRP see OO primer). You can solve this problem if you use Generics and create something like C++'s template based Singleton class:
namespace ConsoleApplication5
{
class Singleton<T> where T : new()
{
private static readonly T inst = new T();

public static T Instance
{
get { return inst; }
}
}
}


and then use that simply by doing something like Singleton<MyClass>.Instance
[update]
Eran points out that Jack's code is not only inefficient but also not thread safe (see Eran's post on the subject) - basically you need to make the instance variable volatile just like in the double check scenario

Reshef points to the "Static Gateway Pattern" as an alternate  way to get the singleton effect. While we are talking about other possibilities, I should have probably mentioned that the usual way I handle situation where I need a single instance is instantiating one instance on the main/loader thread and then just using dependency injection... :)


 
Tags: .NET | Design

If you recall what I currently work on is a type of a visual search engine. In a nutshell when we get a request (image) we allocate a bunch of algorithmic engines in a grid like manner to process the image  (e.g. try to perform OCR or whatever). As it happens, we are developing the different components using several different environments(*) - e.g. the control bits run on windows (.NET) and most algorithms run on Linux (mostly C++).
The need for easy cross-platform communications and extensibility, the resource nature of the solution and a few other tidbits led us to design our solution in a RESTful manner.

If you are a .NET developer/architect and wanted you may know that to implement a RESTful application in Windows Communication Foundation (WCF) you really have to jump through hoops.For instance  you have to go back to basics and use the HttpRequest and HttpResponse, handle the breakdown and parsing of URI hierarchies yourself not to mention  fight  with the  bindings .

Fortunetly this all changed with WCF 3.5. True, .Net doesn't have (to my knowledge anyway) something like RESTlets, but at least building REST on http is pretty straightforward.

Consider for example the following excerpt:

    [ServiceContract(Namespace = "http://paperlnx.Contracts/2007/12", Name = "ISessions")]
public interface ISessions
{
[OperationContract]
[WebGet(UriTemplate = "/Sessions/{sessionId}")]
[ServiceKnownType(typeof(Atom10FeedFormatter))]
SyndicationFeedFormatter ListSessionStatus(string sessionId);
.
.
.

With these 6 lines of code you see the essence of  the .NET 3.5 REST goodies
  1. Integrated support for HTTP verbs  - The sample above shows the support for GET. You can get the other verbs almost as easy with the WebInvoke Attribute. To do that simply specify the verb you want e.g.   [WebInvoke(Method = "PUT")] , [WebInvoke(Method="DELETE")] etc.

  2. Support for URI templates -  In a way not too far from Joe Gregorio's IETF draft , WCF supports the notion of providing a way to describe families of URIs. This is done using the UriTemplate class. The WebGet and WebInvoke attributes also accept URI templates as variables and map the variable values (the curly brackets ones {}) to parameters of methods.
  3. Support for standard  formats - you can use plain XML or you can choose to use RSS and ATOM syndication formats. In its most basic form you just create a syndicationfeed and format it to atom feed. Which is what we do for error messages:

    public static SyndicationFeedFormatter GenerateAtomError(string errormessage, string description,Uri location)
    {
    SyndicationFeed feed = new SyndicationFeed(errormessage, description, location);
    return new Atom10FeedFormatter(feed);
    }
    Naturally you can also add items and element extensions to all elements (e.g. the feed or items)

All in all, I am a happy camper :) After all, when you make an architectural decision, you always need to review it once you opted for an underlying technology. Even when a decision is right. The friction caused by a  technology which doesn't accommodate it well can both make your life miserable and make a good decision bad. .NET 3.5 with its newly added support for REST increases the architectural freedom and that's always a good thing




* Among other things, it helps us avoid the "Network is homogeneous" fallacy - but that's another story :)


 
Tags: .NET | Design | REST

Great news. Two of my friends and fellow DDJ bloggers, Eric Bruno and Udi Dahan have agreed to join my (now ours) SOA Patterns book which will be published by Manning.

Both Udi and Eric are competent and experienced architects who have experience designing SOAs . On the technology side -  Udi (“The software simplest”) specializes in .NET development e.g. his nServiceBus framework – which is a very good example for an endpoint-ware ServiceBus (vs. middleware ServiceBuses which is what most ESBs do).And  Eric, on the other hand, is a Java and C++ expert . Eric is the author of Java Messaging (one of the best books on JMS and web services ) and has also has a lot of experience in Financial systems. Together, the three of us bring a lot of real-life experience of building large and complicated system into this project.

The current game plan is for Eric to focus on the SOA pitfalls (“anti-patterns”) part of the book, Udi to provide a “putting-it-all-together” chapter , and for me to cover what’s left. I am sure however, that their experience and insight will also help make the other parts of the book (even? ) better.

If you are not familiar with the book - you may want to take a look at the first chapter and/or some of the published patterns like Saga, Service Firewall, Gridable Service, Edge Component and (a very early draft of) Aggregated Reporting pattern . Also you can take a look at the slides from my "SOA Patterns" presentation at Dr. Dobb's Architecture & Design world last year, which illustrates some additional patterns


 
Tags: .NET | Java | new | SOA Patterns | Software Architecture

PaperLnx develops an advanced visual search solution for mobile handsets based on computer vision and image understanding technologies developed by Rafael. PaperLnx solves the cumbersome web surfing experience on mobile handsets by enabling end users to send captured images from their mobiles to retrieve relevant information for the object photographed.

We now have few open positions (in Israel) for the following profiles:

 Senior Developer

We are looking for a highly motivated, resourceful and intelligent developer. Good interpersonal and communication skills will be very appreciated. A Team player. Broad thinking and problem solving capabilities are also desired.
  • At least 5 years of server side development with thorough understanding of Object Oriented principled and  understanding of architectural styles and design patterns.
  • Experience in multithreading and in distributed systems.
  • .NET/Ruby experience
  • Integration with C++ components
  • Experience with O/R Mappers such as nHibernate/ActiveRecord etc.
  • Video processing experience/ familiarity with video related protocols (H.324m, H.323 etc.)  a plus
  • Web experience (AJAX, CSS, ASP.NET) a plus
  • Mobile Internet backend development a big advantage
  • Understanding of architectural constraints (security, availability, scalability etc.) for internet scale platforms a big advantage
  • Team leading skills – an advantage.

 Algorithms Developer

We are looking for an experienced algorithm developer or an outstanding MSC graduate with image processing concentration. A team-player interested in joining a young and dynamic firm.
  • Experience developing image processing algorithms using Matlab
  • Computer vision/Image processing experience a must
  • Experience transitioning algorithms from Matlab to software (C++/C/C#/F#)  a big plus
  • Familiarity with video compression protocols a plus
  • experience with performance tuning and scaling optimizations

 
If you think you qualify and want to join a promising startup you can send your CV  or call  me at 052-3331027
 


 
Tags: .NET | General | PaperLnx | ruby

December 20, 2007
@ 12:24 AM
Wes Dyer, one of the principal people behind the Volta tier-splitting was kind enough to leave a comment on my previous post. Here is one quote from that comment

"I do want to clear up a few things about Volta that we apparently
didn't make clear enough. We do not believe that you can develop an
application as if it will run on a single tier and then just sprinkle a
few custom attributes here and there and be done with it. More than
anything else, programmers need brains. Volta does not claim that
programmer brains can be checked at the door. When the programmer wants
to divide the application across a particular boundary then things like
network latency, new failure modes, concurrency, etc. need to be
considered at that boundary. What Volta does is make expressing the
transition between boundaries easier. It reduces the accidental
complexity of writing all of the boilerplate code to express the
programmer's intention. This allows the programmer to focus on the
essential complexity of his problem domain -- figuring out how to write
effective code for that particular tier boundary."

For one, it is good to hear that the architects behind Volta have a deeper understanding of distributed computing challenges - even if the first version doesn't seem to show it. I didn't use MS Volta enough to say that indeed the problem is not with the inherent capabilities and design  (let's just take Wes words for that). I am also not against saving the boilerplate code (though I would personally favor libraries rather than code generation and try to keep the "generation" gap to a minimum (i.e. the amount of generated code or the distance between the abstraction and the next concrete level)).
Lastly I am also in favor of trusting developers have brains and that it is ok to provide developer "sharp tools". So if all is good, where's the problem?

The problem is that you have to make it "easy to do the right thing" and provide the means to do the more complicated, less safe things. When I teach my young kids (and I can objectively say they are very smart :) ) to use a knife, I don't hand them the razor sharp, butcher knife first. They start with the plastic ones. When they've mastered that they can try something more dangerous. When you allow distributing something at a flick of an attribute and put marketing blurb on the site that makes it compelling to use it you create the wrong impression to the less experienced folks.

In one project which architecture I reviewed, the (very talented) architect/developer designed his own distributed transactions system (he shouldn't have been doing that in the first place - but that's for another post). When designing this he built in a lot ways to control the transaction behavior including the option to allow transaction participants to prevent rollback without failing the transaction.  Circumventing the transaction was as easy as making it work properly. Are there edge cases where you may need to have one participant violate the ACIDness of the transaction ? I guess  so - but that is not the general rule. Most of the time when you commit a transaction you expect it to be ACID. if for some reason it didn't behave that way - you want to know about it, even if it didn't actually failed. When you don't make it easy to do the right you get unexpected behaviors, you get hard to explain bugs, you get slow performance etc..
Developers using tools, smart as they may be, don't usually go and read all the source code of the tool/framework they are using (maybe they should). If two options are just as easy to use, it seems safe to assume they are just equally right. Things which are unsafe should be clearly marked as such to prevent mis-use by unexperienced users. This is especially true for tools that are targeted for common use and to ease the life of inexperienced developers


 
Tags: .NET | Design | Software Architecture

December 11, 2007
@ 11:27 PM
I got a couple of emails with questions reagarding  my previous post on Volta. So here's another go at explaining why dynamic-tiering is not a good move - this time in technicolor.

Let's start with a simple illustration. The diagram below represents a typical local component(A) in its environment. As a component that works locally, it has access to other local components which it interacts with. These can be objects it created by itself or objects that where injected to it. The likely design for local components is to have a chatty interaction - After all objects can talk to instances of other objects quite easily.



Now enters Volta (or any other  such framework - and I've seen a few. I am  ashamed to say but I even wrote one about 15 years ago) and says we'll just mark things we want to execute on a different server and everything would be fine. What you get is something like the illustration below:



We have the same number of interactions - only now all the interactions between A and its (used to be) near environment requires serialization, network interaction, possibly encryption, authentication, authorization and what not. You can imagine that this type of interaction can have a heavy hit on performance and scalability if it wasn't pre-designed somehow.

This is a bit of hand-waving so let me also give you an example from a real project. About 3 years ago I was invited to consult in a project. This was the kind of project that interacts with real things like sensors etc. I'll use an automated irrigation system to illustrate its architectural components. One type of component is "Things", these represent real devices you can interact with like sprinklers, soil sensors etc. Things represent the logical state of the real devices and cannot talk to each other. When two Things need to interact -e.g. we want to turn on the sprinkler if the soil is dry, we introduce another architectural component, we'll call it "Interaction" which looks at the state of the Things and can then act upon it. The last major type is "Services" (not services in the SOA sense) e.g. we can have a Service that reads the weather. Services can't interact with Things directly, but they can interact between them and they can interact with "Interactions". This particular system had dozens of Things, Hundreds of "Interactions" and "Services". And the tiers/process boundaries were as follows:


Interactions have to know about changes both in Things and Services so messages keep flying around this system to keep the Interactions in sync as well as propagate decisions made by Interactions. The outcome of this "smart" design is that every status change in a Thing results in an order of magnitude more messages to react to the change is status. I was brought in to find a way to find a way to get in-order reliable messages flow fast enough between the different tiers. I did my best and left -what they didn't want to listen to, and the better solution is to give a lot of thought about related Things , Interactions and Services and bundle them together into "tierable" component. The interactions within these "chunks" would be local and would then inflict a whole less messages on the system. In our example it makes sense to bundle the four components (sprinkler etc.) into a single tier and possibly the same process and increase the overall performance significantly while also giving us  more cohesive boundaries.




(as a side note I'll just mention that I ran into someone who is part of this particular project a few days ago - They are still struggling with performance and stability problems...)

Anyway, one could argue that frameworks like Volta would allow you to move from the bad partioning to the good one more easily - but this is not really so since when you rearange the components you also have to remodel the messages that flow between the new partitions. Also

This is not to say that having the ability to run a system in local and in distributed modes does not have value - as I said in the previous post- it is the assumption that you can easily move this boundary and still get a viable solution that is wrong. Also if you are going to allow running in local and distributed mode that doesn't have to spell to "dark magic" of MSIL rewrites and compilations.
In another (SOA) project we designed services so that in a small-scale installation you would be able to instantiate services in the same process. Services were constructed as Active Services (i.e. have at least one  thread of control). If you wanted to let two services run in the same process you just had to write a new ServiceHost and a new ServiceBus The new ServiceHost has to provide each service its own thread or thread pull and the ServiceBus has to work inmemory by passing message objects around rather then serializing/deserializing and sending them over the network. On a small installation this works better than multiple processes (but not as good as a system designed specifically to run on a single tier). Note that this is the opposite of what Volta does as it takes a distributed solution and allow it to run locally rather than the other way around.

The other part of Volta is the C# to javascript cross compiler. This may have a future - but it really depends on the attention Microsoft will put into this direction. Google does something similar on its android mobile platform where it takes Java bytecode and translated it into the Dalvik VM. But for Google that's a strategic platform. With MS investments in Silverlight (Which I personally prefer), I would guess the effort in would always lag behind (though I hope they'd get it to be better than it is today)

 
Tags: .NET | Design | Everything | SOA | Software Architecture

December 6, 2007
@ 11:43 PM
Microsoft uses the "live labs" to release all sorts of test balloons. Sometimes we get really nifty stuff like Photosynth or SeaDragon. Unfortunately, sometimes we get stupid not so bright ideas like Volta.

Ok, so what is Volta? Here's what the project's homepage has to say (emphasis mine):
" The Volta technology preview is a developer toolset that enables you to build multi-tier web applications by applying familiar techniques and patterns. First, design and build your application as a .NET client application, then assign the portions of the application to run on the server and the client tiers late in the development process. The compiler creates cross-browser JavaScript for the client tier, web services for the server tier, and communication, serialization, synchronization, security, and other boilerplate code to tie the tiers together.

Developers can target either web browsers or the CLR as clients and Volta handles the complexities of tier-splitting for you.  Volta comprises tools such as end-to-end profiling to make architectural refactoring and optimization simple and quick. In effect, Volta offers a best-effort experience in multiple environments without any changes to the application."

The idea sounds very compelling - I kid you not. So what's the problem?

The first issue is that, as a platform/framework (MS would say factory), Volta tries to accomplish too much. On the one hand Volta is another go at the web/desktop convergence trend. On the other hand it is supposed to be a solution for "painless" tier-splitting. Both of these tasks are very heavy. My opinion is that the Single Responsibility Principle (while originally defined for objects) applies here. And Volta should choose one thing and try to excel in that.

What's more disturbing to me, is the automatic handling of the "complexities of tier-splitting". Here's another excerpt from the Volta site which further explains the "tier-splitting" concept:
Objective

We have an application that runs in a monolithic environment, say the browser. We want parts of this application to run in other environments, such as servers. We don’t want to litter the application with plumbing code.

Rationale

The standard techniques for distributed applications infuse our code everywhere with information about what parts run where. This makes the code hard to change. Typically, once we make these decisions we can’t change them because it is too expensive. However, environments, requirements, and performance profiles change and we’re stuck with applications that can’t adapt to new realities. We need to separate the concerns about what the application does from the concerns about where parts of the application run.

Without Volta, we are forced to decide where code runs before we know everything it is going to do, in particular before we know the communication frequencies and delays. Development methodologies force us to make irreversible decisions too early in the application lifecycle. Volta gives us the means to delay decisions until we have adequate information to base them on.

Recipe

Volta tier splitting automates the creation of the communication plumbing code, serialization, and remoting. Simply mark classes or methods with a custom attribute that tells the Volta compiler where they should run. Unmarked classes and methods continue to run on the client.

We may base our decisions about tier assignment on any criteria we like, such as performance or location of critical assets and capabilities. Because Volta automates boilerplate code and processes for dispersing code, it is easy for us to experiment with and change assignments of classes and methods to tiers.

Wow, Agile development at its best, allowing us to postpone architectural decisions,  that just sound too good to be true. Well, the problem is that it is too good to be true. Abstracting the network out, and providing location transparency without thinking about the  implications of distribution is the reason "distributed objects" failed. e.g. Here is what Harry Pierson (DevHawk) had to say about distributed objects:
"...back in 2003, mainstream platforms typically used a distributed object approach to building distributed apps. Distributed objects were widely implemented and fairly well understood. You created an object like normal, but the underlying platform would create the actual object on a remote machine. You'd call functions on your local proxy and the platform would marshal the call across the network to the real object. The network hop would still be there, but the platform abstracted away the mechanics of making it. Examples of distributed object platforms include CORBA via IOR, Java RMI, COM via DCOM and .NET Remoting.

The (now well documented and understood) problem with this approach is that distributed objects can't be designed like other objects. For performance reasons, distributed objects have to have what Martin Fowler called a "coarse-grained interface", a design which sacrifices flexibility and extensibility in return for minimizing the number of cross-network calls. Because the network overhead can't be abstracted away, distributed objects are a very leaky abstraction.


So here comes Volta and tells us just put a [RunAtOrigin] attribute on the code you want on another tier and if you don't like that you can change it to another place in your application and what not. Note that the notion that you can automate some or maybe even all of the distribution "boilerplate" code may be viable. The problem is in the premise that you can seamlessly move that boundary around. There's a fundamental  difference between tiers and layers. Tiers should be treated as a boundary .Volta designers do talk about Security but they seem to forget a few of the other fallacies of distributed computing...



 
Tags: .NET | Agile | OO | Software Architecture | Trends

November 20, 2007
@ 06:47 PM
While everybody and their sister is busy celebrating the release of VS2008. A more interesting* release happened today - The first community release of Ruby.NET (version 0.9). This is another step in the languages trend I discussed here a few weeks ago.

The release is said to have a lot of improvements however, Ruby.Net  isn't running Rails just yet. Hopefully we'd have that soon. Another thing I would love to have is to use Ruby's testing frameworks like Mocha to test .NET classes (which already works for Java and JRuby). Well I am off to test that now :) - you can do that too, if you download the bits

By the way, you may also want to read the paper discussing the design of Ruby.Net (by Wayne Kelly and John Gough who started this project)


*my blog - my opinions :)


 
Tags: .NET | ruby | Trends

October 30, 2007
@ 11:41 PM
Earlier today Microsoft announced it newest SOA initiative codenamed Oslo Here are a few observations I have on this announcement.

Let's start with "what is it?" Well it isn't an "it" per se, since Oslo is a bunch of initiatives within the Microsoft offerings.

For one, it is some of the libraries within .NET 4.0 -- specifically the next versions of WCF and WF.

Secondly, it is a bunch of designers and tools that will be part of Visual Studio (beyond VS 2008).
The most interesting component of Oslo will be a new repository to allow version management of models and services. I guess it is safe to say it will be built upon Team Foundation Server (or a subset of which which will be used by both products).

The last part of the puzzle is of course V.Next of Biztalk and something currently branded as "Biztalk Services '1'". As far as I know Biztalk sells pretty, but I think it is both too bloated (e.g., think about the hardware needed to run this in high-performance solution) and builds on the wrong architecture (hub vs. bus). I hope Microsoft makes major updates this time (Biztalk 2004 to Biztalk 2006 mostly innovated around the business activity monitoring. While that's important I think more work on the engine was/is due).

Biztalk services would offer an implementation of some of the SOA patterns I talk about -- service host, workflodize, etc. -- to provide an infrastructure for building services. The relation between "Biztalk 6" and "Biztalk services 1" is not clear from the information provided by Microsoft; hopefully this is just a branding issue and not a tight relation between the products.

On the upside, one of the key persons working on this is Don Ferguson who, before joining Microsoft, was chief architect for IBM's software group. About a year ago I had the chance to hear him talk about SOA and all I can say is that Don is someone who really knows his stuff.

PS: It's amusing to see the press release talks about "model-driven" approach rather than software factories, but I guess that's just nitpicking.
 
Tags: .NET | Everything | SOA | Software Architecture

I am currently interviewing people for developer positions for my startup (PaperLnx) and as I presented my plans to use multiple languages to one of the candidates he immediately retorted with "why on earth would you want to do that?"

Why indeed?
 
As I mentioned in the previous post about F# and Erlang it seems to me that the age of "one size fits all" is ending  in a lot of areas. I think that it is also happening for languages.

When .NET was announced, one of the messages by Microsoft was that .NET is the platform and that you can choose any language you want to develop in it. Microsoft also worked with partners to back up this statement and  release a lot of languages for the platform (e.g. Eiffel#, Fujitsu NetCobol  etc.) vs. Java which was a single language with a "write once, run everywhere" vision. Microsoft itself released 2 manages languages VB.NET C# and managed extensions for C++. The C++ managed extensions were very awkward to work with  and only people  who really had to use it. the non-MS languages seemed to be niche languages for legacy integration and not much more. VB.NET (we're talking .NET 1.0 here) seemed like something to try to distract VB heads while Microsoft was pulling the rug beneath their legs. Which basically left C# as the only viable language to develop in if you were serious about .NET (at least in my eyes). The "many languages" vision seemed like something to hide the (obvious) fact that Microsoft had to come up with an answer to Java (especially since around the same time Sun also sued Microsoft over the J++ and JVM implementations)

5-6 years later the situation is a little different. For one, we see that the JVM is not just about Java anymore. Just like the original .NET vision, the JVM has become a platform supporting many different languages Jython, JRuby, Scala, Groovy etc.
The .Net platform is also getting more interesting  languages like  Boo or   Gardens Point Ruby.Net . .NET is also being extended by Microsoft itself (with IronPython, IronRuby, F# ).

Two interesting things we can see are one, suddenly the languages are cross platform. e.g. I can program in python and deploy it natively, .NET or on a JVM - so in a way you get some platform independence.

The other and more significant issue (in my eyes) is that the languages available on each platform are different enough in meaningful ways - to a point where it is getting worthwhile to use more than one language in projects. Here are few examples from around the blogsphere that demonstrate this:
  • Neal Ford shows an example using the (excellent) Mocha mocking library (in JRuby for testing Java classes. So the dynamic properties of Ruby help make the testing simpler for the statically typed Java.
  • The BOO Build System (via Ayende) - which is about building a DSL for builds (a la rake). again we see taking advantage of the properties of a dynamic language this time to help with .Net languages.
  • (not) Dennis Byrne shows how you can call Erlang from Java - which demonstrate taking advantage of the concurrency features of Erlang from Java.
When it comes to the difference between general purpose languages (i.e. Java, C#, VB.NET) we mainly see syntactic nuances. When it comes to dynamic languages vs. static languages vs. functional languages etc. the differences are more meaningful. What has changed now is that both platforms and open standards (e.g. REST over HTTP/WS-*) enable better integration and increase the motivation to use the "best tool for the job" approach over "the everything looks like a nail" approach .

I think the time for language pluralism is ripe - In my solution this would probably translate to a mix of C/C++, F#, C# and Ruby - What about your projects?


 
Tags: .NET | Everything | Java | PaperLnx | ruby

A couple of thoughts on functional programming in general and on F# and Erlang in particular

Erlang - is it worth it?
I read Armstrong's Erlang thesis and other Erlang related material with great interest. After all Erlang claims some very compelling architectural benefits in the areas of scalability and availability.  However one thing that prevents me from digging too deep into it is the utter ugliness of the language vs. for example, ruby which is very compelling
i also tend to agree with Otaku that at least today you can achieve this tauted resilience with other languages as well.

On the other hand we start to see some really interesting things built on Erlang like RabbitMQ which is an AMQP implementation (AMQP - The Advanced Message Queue Protocol), MNesia persistence engine . Yaws web server etc. (you can see here one guy that even likes Yaws + MNesia better than Ruby + Rails)

Well, I am still on the fence  for this one, but I guess I will take a deeper look at Erlang eventually..

By the way, while other functional languages also have irritating syntax (e.g. Scheme ) - some look more intereseting (like F# or OCaml)

 which brings me to the next tidbit...

Functional Languages moving mainstream.

Functional programming is an old paradigm (see for example this paper from 1984 "Why Functional Programming Matters" explaining the advantages of functional programming over structured programming..).

For a decade or even more and even today the object oriented paradigm has ruled the software development world. In a way, and as part of the end of the "one size fits all" paradigm (I also mentioned this trend here) we also see more pluralism for languages so we get more dynamic languages vs. static typed one and we find a place for functional languages and not just object oriented ones. (I'll expand more on that in another post).

Anyway, Yesterday S. Somasegar (MS VP of DevDiv) announced on his blog that F# will be "productized" :
"We will be partnering with Don Syme and others in Microsoft Research to fully integrate the F# language into Visual Studio and continue innovating and evolving F#. In my mind, F# is another first-class programming language on the CLR. "
Microsoft is of course not the center of the universe, but when a company like Microsoft chooses to bring something closer to main stream it is a significant move which, in my opinion, shows that functional programming is getting more traction.




 
Tags: .NET | Everything | Functional Languages | OO

In the previous post on the subject I promised to expand a little more on the suggested content for "Distributed Systems Architectures Workshop" so here a short drill-down:

Even though most of the time should be spent on working, designing and evaluating architectures there's probably a little room for theory .

Module 1 The basics (probably not more than half a day)
What's software architecture
The software architect role
Activities
Scenario based architectural design
(documenting software architectures)
Agile SDLC and architects

Module 2 Distributed Systems background

Understanding the Fallacies of distributed computing

Distributed architectures styles - it is important to understand the different architectural styles that can be used to implement distributed system - whithin this topics like clustering, computation and data grids, messaging , publish subscribe etc should also be discussed

  • Client-server - The most basic distributed architectural style. It is based on the  N=1 premise and isn't fit for most of today's challenged. However it is still an option for some types of projects.
  • Pipe and Filters - not necessarily a distributed style, but it can be applied in distributed space
  • N-Tier - That's actually a moniker to anything where N>2 but usually it pertains to 3-tier architecture (front-end, server, database) or the internet 4-tier version (client, webserver, application server, database). 
  • Event Driven Architecture
  • Service Oriented Architecture
  • REST 
  • Space-based architectures - like JavaSpaces  and its implementations like Blitz (open source) and Gigaspaces (commercial)
  • Peer-to-Peer - you know that's what all those file sharing tools use

Distributed Consensus

  • 2 phase commit - used by XA and COM+ distributed transactions
  • 3 phase commit - considered a non-blocking protocol (vs. 2PC which is a bloging protocol) 
  • Paxos commits
  • Sagas
  • Eventually consitent (BASE) - Basically Available Scalable/Soft state & Eventually Consistent. An alternative to distributed transactions used by a lot of internt-scale companies (see a post I made on ebay's architecture )

Module 3 - workshop - most of the days should be focused on actually working to design architectures.
I would think that this would be handles best by working  in groups. e.g. having each group focus on one architecture style.
 
The groups would be given a scenario which covers some architectural concern (integrity, performance, scalability, availability etc.)  and would try to design strategies to handle the scenarios within the constraints of the architectural style. Present that to the other groups and then have a facilitated discussion on the pros/cons of each strategy. The  scenarios should be based on a large enough story to allow meaningful architectures to emerge (e.g. you can see the  10 scenarios in my SOA Patterns presentation )


Any comments or other ideas for what's needed for this kind of a workshop are welcomed


 
Tags: .NET | Everything | Java | Software Architecture

A side effect of my decision not to become an independent consultant at this time means that I have to shelve some of the projects I was considering. One of these projects was to create a training program for software architects which I was discussing with a couple of training centers here in Israel.
Since It seems I am not going to promote it, I thought I'd share what I think a training program for .NET/Java architects should look like in the hope that someone would find it useful and do promote it (or parts of it)

Soft Skills
The way I see it architects needs a bunch of soft skills to be able to perform their roles.
Here is the list I identified in the past (by the way, I began a series of posts on each of these skills and never got to finish it - maybe it is time that I will :) )
  • Leadership. Influencing others to accomplish tasks and following your guidance
  • System thinking. Understand decisions and constrains in the
    wide scope pertaining to whole of the solution at hand. This includes
    the ability to abstract problems.
  • Strategic thinking. Understanding decisions and constrains and their alighments to the overall business of the company.
  • Organizational politics. Understand the environment you operate in and how it influences you.
  • Communications. Making sure you get your point across.
  • Human relations. Understand the "people" aspects or human
    factors and dynamics. This includes things like negotiation, pragmatism
    etc
I am not sure if you can teach all of them, but few courses that can help (in my opinion) include:

  • Presentation Skills - While getting the architecture and technology right is what matters, if you can't explain it to the different stakeholders you're toast.
  • Strategic Planning - This has to do with the vision thing I expect architects to manifest. Note that having a vision should not be confused with future-proofing a solution. future-proof means excess work not needed. Having a vision is knowing where you want to end - it can still be perfectly valid to completely re-write your applications along the way


Project Management
While the architect is not the project manager (mostly anyway), I think understanding the constraints coming from the project management point of view is very important. Since most environments call for a mix of agile and formal disciplines (hey, you've got to be pragmatic). I would train architect both in SCRUM and RUP (or some other formal methodology)

Also while not all environments needs this I would give an 2 days overview of important standards. The first would be IEEE 1471, which defines a standard for documenting software architectures. I would also teach ISO 90003 and CMMI.

It should be noted that the ISO 90003 is much better than the previous incarnation (ISO 9003) as it basically lets you define what you want to do to cover the different areas. The standard just helps you make sure you think about the various parts of project management (requirements, environment etc.). For instance I demonstrated how key areas of 90003 can be mapped to SCRUM to get it approved on my last project.


Languages, Design  and Patterns

I would want the .Net/Java architect training program to include at least 2 of the following languages:
Ruby, Scala, Erlang, F#, Python , Groovy ,OCaml
The reason for this is that these languages have different design goals than .NET and Java so learning them gives you additional perspectives and broaden your horizons for other ways of thinking (even if you don't use them in your project directly). You might have noticed that there's no .NET or Java training here. The reason for that is that's a prerequisite as far as I am concerned. You should master at least one

Object Oriented principles - hopefully aspiring architects already know this. However, I often see people who discovered some of the principles by themselves but haven't heard about all of them.
I am talking about principles such as Liskov Substitution  Principle , Open Closed Principle, Single Responsibility Principle , IoC containers, Don't Repeat Yourself  and YAGNI (I summarized my opinion on most of them in this paper)

The next step is to cover some design issues like Domain Driven Design, UI Design, Database modeling, Database alternatives l(after all the database is dead, right? )

Advanced design patterns - When most people hear the term design patterns they think about the GoF patterns. There are however literally hundreds of design patterns. Some of them are even worth learning :) . For instance there are patterns for concurrent and parallel systems like Proactor, Reactor Half-sync/Half-Async etc; Workflow patterns like Cancelling partial Join, Recovery Action etc; SOA patterns (ok, so I am still working on that :) )



Architecture Workshops
Another important part of the training, in my opinion, is to do some workshops and actually try to apply some of the material covered.

  • Architecture Evaluation - workshop 2-3 days - It is probably worthwhile to delve a little on scenario based evaluation techniques such as LAAAM and ATAM. While I prefer evaluating architecture in code, the scenario based thinking is very valuable for eliciting architectural requirements
  • Distributed Systems Architectures workshop - I'll expand on this in the next post


Lastly, there are also a few miscellaneous subjects like architect 101, the SPAMMED architecture framework , Agile architecture, Behavior Driven Design , common frameworks (though hopefully this would  not be needed ) like Spring/Spring.Net, Hibernate/NHibernate, iBatis  etc.


PS

Note that there are a few architect training programs available out there
One is offered by the Software Engineering Institute (SEI) and includes a 6 courses. SEI program seems to be focuses on formal sides of architecture as it includes courses on documenting software architecture and ATAM (You can see an old presentation I have on ATAM here)
Dana Bredemeyer  also offer architect training. Dana offers several workshops that cover the software architecture profession.
TOGAF (which is more of an enterprise architecture framework) offers both a certification and courses
Lastly, IASA is considering creating a software architect program and has a few courses in development
If you know any others I'd be happy to hear about them


 
Tags: .NET | Agile | Design | Everything | Java | OO | Software Architecture

Another great presentation at Architecture & Design world was Neal Ford's presentation on Domain Specific Languages (DSLs) . As the title suggests Neal gave examples both in static languages (Java) and Dynamic ones (Groovy, Ruby).

One interesting observation Neal made was that humans tend to create DSLs in real life whenever they (ok, we :)) have any non-trivial interaction or behavior. Neal gave sevaral examples such as the Starbuck's order taking ("Venti Iced Decaf with whip...") , musicians and a few others.

The next important point was contrasting ("classic") APIs and DSLs. The main difference is that the context is implicit and not repeated

A key  technique for building DSLs Neal mentioned was Fluent Interfaces. Fluent Interfaces means modeling the API so that lines of code are readable English-like sentences. The fluency comes from the easier readability by the interface user.

Fluent Interfaces, now that's a novel idea - what would a fluent interface look like, hmm, wait, I have an idea. Here are 3 samples that come to mind

DIVIDE x BY z GIVING y ROUNDED

INSPECT data REPLACING ALL "foo" BY "bar

READ someFile AT END SET eof TO TRUE


If you haven't guessed  the statements above  are in ...Cobol (by the way pardon the caps that's Cobol conventions..)
So ok, it isn't a new idea, but it is interesting to see it is making a comeback
Anyway one area where we see a lot of fluent interfaces emerging is configuration (mainly as an alternative to those lengthy XML files). For instance the following is an excerpt of configuring  Restlet components  (taken from my Edge Component pattern paper):

Builders.buildContainer()
            .addServer(Protocol.HTTP, portNumeber)
            .attachLog("Log Entry")
            .attachStatus(true, "webmaster@mysite.org", "http://www.mysite.org")
            .attachHost(portNumber)
            .attachRouter("/orders/[+")
            .attach("/getAll$", getAllRestlet).owner().start();
            .attach("/getLast$", getLastOrderRestlet).owner().start();


Note that this example also uses another fluent interface/DSL technique which is method chaining.

Dynamic languages make it even easier to write DSLs since they provide a lot of extension capabilities (see my previous post on OCP in Ruby), are less strict about types, allow reopening classes etc. 
Oneexample for a Ruby DSL is RSpec which is a framework to support Behavior Driven Development (BDD) in Ruby - The example below shows an excerpt for defining specifications for an eight-ball game

require 'eight_ball'

describe Eight_ball do
    before(:each) do
        @eight_ball=Eight_ball.new
    end
    .
    .
    .
    it "should lose if 8-ball sinked in pocket other than called" do
        [1,2,3,4,5,6,7].each ( | val | @eight_ball.sink(:player =>"Player1", :Ball=> val)
        @eight_ball.call(:player => "Player1", :pocket => :upper_left)
        @eight_ball.sink(:player => "Player1", :Ball => 8, :pocket =>:middle_left)
        @eight_ball.game_status.should == :ended
        @eight_ball.player_status("Player1").should == :lost
    end
end
 
By the way Joe Ocampo built a very nice port for rbehave (another Ruby BDD framework) to .NET 3.5 by extending NUnit which has a very Ruby-like syntax
      

Anyway, the DSLs demonstrated by Neal provide a very good example of the difference between dreaming big and actually doing stuff in the small. The counter example for that are "Software Factories". As I wrote here about a year and half ago
Software Factories is not a new idea  - see for example "Software reuse: From Library to Factory" by M. L. Griss  (published in 1993(!)) which talks about "Software Factories" and "Domain Specific kits": components, frameworks, glue languages etc.  The current Microsoft  incarnation of Software Factories takes a similar approach focusing on Domain Specific Languages, Frameworks but also adding important aspects like multiple viewpoints, patterns and designers. The idea is that  building on modern technologies, as well as learning from the mistakes from sister approaches to code generation (OMG's MDA, in case you are wondering) will enable us to build something that is useable.

Microsoft seems to be taking some steps in the right direction (GAT is probably the best example). Nevertheless there is still a long way to go before we can realize the dream of "factories" for vertical applications


Unlike small code based DSLs - the modeling based approaches of software factories, MDA etc. aim too high and thus provide much less value or suffer too much from the generation gap (the code generated is too generalized or far off from the actual need of the solution). Another problem with software factories/ MDA DSLs is the modeling (i.e. diagrams) - they say a picture is worth a thousand words. This is true if you treat models as sketches you can raise the level of abstraction by as much as you want and convey ideas with less clutter. However when you need to make the model very specific so it would allow code generation - you get to a stage where it is more convenient to do it in code and rely on generated or pre-built DSL or framework

Lastly you can  download Neal's presentation (in PDF form) from his site


 
Tags: .NET | A&D2007 | Design | Everything | ruby | Software Architecture | Java

A few weeks ago I wrote about Dependency Injection and how it doesn't really matter in Ruby. On one of the comments for this post Yoni said (in regard to extending classed - both in .Net 3.5 and Ruby):

"Regarding the issue of extending classes (and partial classes) I am very sorry it was ever invented. Developers should be encouraged to divide large classes by decomposing them into decoupled sub-components using design patterns and not by simply splitting them between files. Even though a feature is called "extending" a class it is in violation of the Open Closed Principle..."

that sounds like a serious charge :) So here's another round of  "Ruby does it better" the time featuring Bertrand Meyer's "Open Closed Principle" or OCP for short.
OCP was defined in 1988 in Bertrand's book "Object Oriented Software Construction"  as follows:
Modules should be both open (for extension and adaptation) and closed (to avoid modification that affect clients)
When we work with a language like C# or Java we have several ways to do that - here's what I had to say about it :


It is easy to see the benefit of having a class that answers this principle: When you need to add a requirement, instead of breaking dependent code (and tests) you just extend it somehow and everything is nice and dandy. Furthermore, violating OCP can result in Rigidity,Fragility, and Immobility.

But how do you do that? The obvious (and naïve) answer is inheritance. Every time something needs to change just add a sub-class. The parent class is not changes and voilà. However, if you add sub-classes all the time you'd get "lazy classes" or freeloaders--sub-classes without a real reason for existence not to mention a maintenance nightmare.

Thus, sub-classing is an option but we need to consider carefully where to apply it. Other (more practical ) OCP preserving steps include:

The way I see it Ruby (and other dynamic languages for that matter) just allows us to extend this repertoire by adding a few other options such as:

Singleton methods (that's not a very good name - but the more appropriate name "instance methods" was already taken by another poor naming choice...) which are methods added to a specific instance of a class:

class Foo
  def bar
    puts "foo.bar"
  end
end
   
obj = Foo.new
obj2 = Foo.new
def obj.bar  # redefining bar just for obj
  puts "foo.newbar"
end
obj.bar   # prints foo.newbar
obj2.bar # prints foo.bar


Closures - I already mentioned closures for C# but it existed in dynamic lanaguages for a long time now. closures are sort of like injecting a procedure. Here's a quick sample:

class Foo
  def bar(myProc)   # accepts a callable object
    foobar = "foo.bar"
    myProc.call(foobar) # call the object with a parameter
  end
end
   
obj=Foo.new
printer=Proc.new {|msg| puts msg}

obj.bar(printer)

Meta programming - Ruby has a lot of ways to add and change classes. methods and whatnot. Again. here is a simple example:
class Foo
end
   
obj=Foo.new

# obj.bar - error
Foo.class_eval do           # this simplistic example can also use regular def
    define_method :bar do   # but class_eval can also evaluate strings to create
      puts "foo.bar"        # dynamic methods like setters etc.
    end
end

obj.bar
And there are a few other similar ways.

All of them  are not violating OCP!

OCP is kept since we do not alter the original class. Anyone using the original class not in our context (i.e. not in the modified context) will not be affected by the change. The interface of the class, in the sense that was originally defined is not changed either, and remains stable. Any client that uses the modified or the original class will not have to change it syntax because of the changes we've maid. This is also in-line with the "protected variation" way of looking at OCP :
"Identify points of predicted variation and create a stable interface around them."
While in C# your would maybe want to add a template method or a specialized interface in Ruby you can apply YAGNI and only change the behavior if the need arise

Lastly, we can also extend classes - but OCP lets us do that so again, we are OK.

Nevertheless, we should be careful not to violate Liskov Substitution Principle when we do all that, which I guess is relatively tempting to do if you using Ruby - but that's for another post ...


 
Tags: .NET | Design | Everything | OO | ruby

August 9, 2007
@ 12:01 AM
I've been taking a look at ruby for a few month, I am finally getting to a stage where (I think/hope) I can actually say something intelligent about it. Last time I had an "aha moment" about a language was the fist time I saw Java.  C++  was oh-so-powerful, but Java was (is)  much more elegant and nice. Now Ruby changes the rules of the game again.
When I first heard about ruby I thought it was just a fad, something that the cool kids are using but its just another language. I getting more and more convinced that it isn't so. I am trying not to get too "silvery-bulletey"  here but working in ruby seems to actually increase productivity.
Let's take Dependency Injection(DI) as an example. DI is one of the most important and powerful tool I've learned in regard to Object Oriented development. Instead of classes depending directly on other classes classes depends on interfaces. And external classes (assemblers) provide them with their dependencies. This allows for loose coupling, increase testability and a lot of other such goodies (you can read a concise explanation in a paper I wrote on OO principles or get a more thorough explanation in a paper Martin Fowler wrote on "Inversion of Control Containers and the Dependency Injection pattern".  The .NET and Java worlds are filled with a lot of frameworks to help solve this elegantly. Spring (and Spring.Net) is probably the most known one.

How do you do DI in Ruby? in two words - you don't
If I am to join the "Define DI in one sentence" challenge by Jim Weirich I would say that
"DI is a powerful and good workaround to  the collaboration coupling problem between objects which is best addressed at the language level"

Why doesn't ruby need DI?

Well, I would say that it all starts at the basics. I remember when I learned OO, I was told objects communicate using messages. I never really understood why they call "method invocation" messages - it doesn't make any sense. The point is that in ruby you really don't "call a method" you "send a message"*.  When you make a call like someVariable.SomeMessage - the ruby interpreter  doesn't really care about the type of someVairable just that the object it holds (and everything is an object) has some entry which can handle SomeMessage.
Let's start with a simple example
consider the following code:

class Foo
  def bar
    puts "Foo-bar"
  end
end

class Foosa < Foo
end

class Baruser
  def baruse(b)
    b.bar  #dependency
  end
end

bu= Baruser.new

bu.baruse(Foo.new)
bu.baruse(Foosa.new)   # sub-class

Well, nothing particularly exciting here. if you run this  you get foo-bar printed twice. That's very much like the dependency injection you see in .NET or Java
It gets a little more interesting when we consider that the following classes would all work as well

class Foz
  def bar
    puts "Foz-bar"
  end
end

class NoBar
  def method_missing(methodname, *args)
    puts "NoBar" if "bar" == methodname.to_s
  end
end

class MakeBar
   define_method(:bar) {puts "madebar"}
end

bu= Baruser.new

bu.baruse(Foz.new)     # another type altogether
bu.baruse(NoBar.new)   # a class that doesn't have bar method
bu.baruse(MakeBar.new) # a class where the bar method is created programatically
 
We can see from the examples that what ruby does is searching for a handler for the bar message. The handler can be a method (symbol) called bar or a generic handle like Missing_Method - ruby doesn't care as long as the message get handled

I think that's pretty nice, we have a lot of flexibility on the dependency side but the depending class still  essentially gets the dependency by injection (the call to baruse)
Well, ruby can help us flex the dependent side as well. The answer is in the last example which uses (an overly simple an uninteresting example of) meta-programming Consider the following code example using Mocha which is a Mock object library for ruby
 
Lets say we modify our Baruser class to the following.

class Baruser
  def initialize
    buildfoo()
  end
  def baruse
    foo = buildfoo()
    foo.bar  #dependency
  end
 
 private 
  def buildfoo
    Foo.new #dependency
  end
end

Note that buildfoo is private - if we wanted to test this in.NET we need to have Foo around. i.e. we can no longer test Baruser by itself
if we use Mocha in ruby we can do the following:
foo = mock('foo')
foo.expects(:bar).at_least_once.

bu = Baruser.new
bu.stubs(:buildfoo).returns(foo) # basically what happens here is that the instance we have is changed
bu.baruse

I can't believe they invented it  - You can get  ruby for just the price of download and if you call within the next 15 minutes we'll throw in a copy of gems free of charge :)

In any event what we see here that using meta-programming and other ruby constructs we can forgo using DI altogether - no wonder Neil Ford defined DI as :
"Dependency Injection enables a vitally important but nevertheless weak, limited, syntactically confounding, and dauntingly complex form of one of the kinds of meta-programming that should exist in the language."
 Not to mention that the resulting code is much more elegant. which is actually what I like best about ruby, the code is much cleaner (but that's for another post)

Some closing thoughts

  • .NET 3.5 bring some of the ruby goodness to C# - but as the previous post demonstrated it is just a move in the right direction but not the whole thing
  • While I am on the subject of the previous post the whole interface vs. class thing is, of course, a moot point in Ruby since there are no interfaces. Interfaces, like DI, are another thing that is very important in C# and Java and not needed in Ruby
  • I've read some complaints on Ruby's performance. performance is important but there are two things to remember. First, the fact that a solution is not the fastest doesn't mean that it isn't fast enough. Second, I can still vividly recall the performance benchmarks for our Java code before we got the first hot spot compiler installed. The point is, that if it is important to enough people it will get better.




* I know, I know, Smalltalk had it since the beginning of time. However in Smalltalk everything is an object, in ruby you can also write plain scripts and (more importantly for me) - I never really took more than a cursory look at smalltalk  so I never  saw that.

 


 
Tags: .NET | A&D2007 | Design | Everything | ruby

One of the interesting presentations I attended in Architecture & Design world was "User Interface Principles in API design" by Elliotte Rusty Harold.
Elliotte started off by mentioning that developers are people too (I guess...) and that designing an API we need to think about the people (developers) who are going to use it.  I totally agree, in fact, when it comes to API design is one place I insist developers use TDD even if they don't do it on their day-to-day development. Dogfooding their own API is probably the only way to really ensure you get a usable API. Elliotte thinks you should go further than TDD and write some sample programs first.

The challenges of API or library design come from the fact that you cannot be sure about Elliotte mentioned some of the fundamental principles of UI design that apply to API design.
  • The importance of consistency
  • Simple is better (and for god sake please keep complexity internal) which translated to YAGNI and "when in doubt, leave it out")
  • Smaller surface (API) is easier to use.
To demonstrate the point of proper API design Elliotte compared the complexity of JMidi vs. the elegance of JFugue. While in JFugue you just use a couple of lines to play a few notes:
Player player = new Player();
player.play("C D E F G A B")
JMidi required more than 20 lines of setting all sorts of things related to its internal structure.

Elliotte also had a lot of practical advice on varios aspects like maintenance, specific advice for Java, specific advice for .NET etc. - Instead of me reiterating it I suggest you just take  a look at the presentation which is available on his site.

One point Elliotte made which I don't completely agree with was that you should prefer classes over interfaces. we discussed this issue after the presentation and I said that it is true for libraries but I am not sure that it is always true for frameworks (see Frameworks vs. Libraries for more details on the difference). in IoC scenarios interfaces allows extending the framewok for use with user defined types. One real-life example I offered was a plug-in framework we developed internally a few years ago. This framework incorporated a fixed set of components based on certain 3-rd party components (grid, tree etc.) - This worked very nicely, until in one project we wanted to use other 3rd party components (let's say a ribbon or another grid) which left us with either waiting for the infrastructure guy to find the time to make the changes, fork the infrastructure code, or build something new (we went with building something new since working with end-users we found we actually  didn't need most of the capabilities the framework offers like security/roles, role tayloring capabilities etc.)

On the other hand one argument for using classes over interfaces that Elliotte is right about is that when you use interfaces and then make a change in that interface. The chage  breaks all clients. If however all the clientes used a subclass they would automatically inherit the new functionality.

I thought I could work around this limitation in .NET 3.5 (or whatever microsoft will end-up calling it) by using extension methods so I did something like the following (tests etc. are excluded for brevity)
  class Program
{
static void Main(string[] args)
{
testInterface tc = new testClass();
tc.DoSomthing();
tc.DoSomethingElse();

}
}

interface testInterface
{
void DoSomthing();
void DoSomthingElse(string test); // compilation error....
}

static class testInterfaceDefaultBehaviour
{
public static void DoSomethingElse(this testInterface ti)
{
System.Console.WriteLine("Doing something else");
}

}

class testClass : testInterface
{
public void DoSomthing()
{
System.Console.WriteLine("Doing something here...");
}
}
I was wrong....

Main does  recognized the DoSomethingElse pretty well - however adding it to the Interface definition caused a compilation error.
This is a shame since the MSDN documentation says that
 " In effect, extension methods make it possible to extend existing types and constructed types with additional methods."
If it had worked that would have let us have something like method_missing in ruby in C#. Well, .NET 3.5 is still in beta so maybe it would change (not counting on that)


 
Tags: .NET | A&D2007 | Design | Everything

August 1, 2007
@ 09:52 PM
I won't say anything about my presentations (that's for others to say :) ). The point of this post is just to let you download them. So here they are:
  • SOA Patterns (2.14mb) - Takes a look at different strategies (patterns) to solve common SOA pitfalls
  • Getting SPAMMED for architecture (4.56mb) - Takes a look at the activities architects can/should do when they think about software architectures. The presentation also covers architecture in agile projects.


 
Tags: .NET | A&D2007 | Agile | Everything | SOA | SOA Patterns | Software Architecture | SPAMMED Process

Evan H asked a question about distributed transactions and services in the MSDN architecture forum:

Are distributed transactions (ie.. WS-Transaction) a violation of the "Autonomous" tenant of service orientation?   Yes or No and Why?  Kudos if you can address concurrency and scalability (in an enterprise with multiple interacting services).

I answerd this questions back in april when I wrote a couple of posts that explained why cross-service transactions are a bad idea:cross service transactions and some more thoughts on cross service transactions.
Roger Sessions also agrees with this view (well, it seems actually, he wrote about it well before I did :) ):
When the WS-Transaction specification was first proposed, back in 2002, I wrote an article explaining why I thought the idea of allowing true transactions to span services was a bad idea. I published the article in The ObjectWatch Newsletter, #41: http://www.objectwatch.com/newsletters/issue_41.htm. Nothing since then has changed my mind. Atomic transactions require holding locks, and spanning transactions across services requires allowing a foreign, untrusted service to determine how long you will hold your very precious database locks. Bad idea. Just because IBM and Microsoft agreed on something doesn't make it good!

The reason I am bringing this issue back is that Juval Lowy (who wrote the article that triggered my first post on the subject) has recorded an Arcast with Ron Jabobs. Where he re-iterated the idea that "Transactions is categoricaly the only viable programming model" and you should strive to use it whenever you can. It seems Juval admits you sometimes need to use Sagas (which he called "long running transactions" - you can see in my link why I think that's a wrong name). He also agrees that you can also use a transactionable transport and then only do internal transactions from each service to the transport (a pattern I call "Transactional Service"). However, at the end of the day, he still thinks you should use WS-AtomicTransactions whenever you can.

I agree that transactional programming is important. I think it is the simplest programming model (from the developers side). I would probably never write an interaction with a database that is not transactional; I look very favorably at initiatives for in-memory ACI (no Durability) transactions such as the one Ralf talks about.  Until we get to Distributed Transactions...

First, we should note that transactions are not "the only viable" option.As Martin Fowler notes Ebay seems to be doing fine without distributed transactions. Not only that, they abandoned distributed transaction and went "transactionless"because they needed one simple thing... Scalable performance .

In most COM+ scenarios you have a single server or a few internal servers where the distributed transaction happen - and even there you should plan your transactions carefully if you want to get any kind of decent performance. In SOA scenarios the situation is more complicated as the distribution level is expected to be higher (even if you don't involve services from other companies). More distribution means longer times to complete transactions (especially if a participant can flow the transaction and extend it). It also means increasing the chances of failure (see Steve Jones series of posts on five nines for SOA). In my opinion, the more distributed components you have the more you want their interaction to be decoupled in time - i.e. the opposite of transactions.

Juval also said he doesn't buy the denial of service problem I mentioned (supporting a transaction means you allow locks - if an external party doesn't commit you retain the lock..). Juval said he assumes that a solutions has both authentication and authorization so this shouldn't be an issue. For one, I have seen too many projects where security was something that was neglected or quickly patched in at the latest moment - so I would hardly assume security. Even with security on - you increase your attack surface.
But that's just the half of it. Even if all your service consumers have good intentions - you still don't know anything about their code. SOA is not like the "good old days" where you owned the whole application  - this means you cannot trust their security to be ample. Also you don't know anything about their code quality. Services are likely (in the general case) to be deployed on different machines, even if they start co-located. I think that a Service boundary should be treated as a trust boundary just like a tier boundary. I strongly believe you should have reduced assumptions on what's on the other side of the service's boundary - transactions are not reduced assumptions

SOA and distributed transactions do not go hand in hand - it isn't just autonomy at stake here. It is a problem for performance and scalability and even security period.

To finish this post - I would also highly recommend looking at Pat Helland's paper "Life Beyond Distributed Transactions: an Apostate's Opinion" and a post he recently made called  "SOA and Newton's Universe", where he explains more eloquently than I ever could why SOA is not a good fit for distributed transactions.



 
Tags: .NET | Everything | SOA | SOA Patterns | Software Architecture

In addition to the drafts of selected patterns I publish on my site, you can now purchase my book via the Manning Early Access Program (MEAP).
MEAP means you can get chapter drafts as I write them and the complete book when its done (ebook or printed). Here is Manning's explanation:
"Buy now through MEAP (Manning Early Access Program) and get early access to the book, chapter by chapter, as soon as they become available. You choose the format - PDF or ThoutReader - or both. By subscribing to MEAP chapters, you get an opportunity to participate in the most sensitive, final piece of the publishing cycle by offering feedback to the author. Reader feedback to the author is welcome in the Author Online forum. As new chapters are released, announcements are made in the MEAP Announcement Forum. After all chapters are released, you will be able to download the complete edited ebook. If you order the print edition, we will ship it to you upon release, direct from the bindery, weeks before it is widely available elsewhere.
By the way, this is probably also a good time to mention that I'll be speaking about quite a few of the patterns in Architecture & Design World 2007 which will take place this July.

There is still a lot of work, but I already like to thank all the people in manning that helped me get this far. especially to Cynthia Kane my editor (hey, maybe now she'll give me more slack :) )
Ok, 'nuff blubbering, back to completing chapter 5...


 
Tags: .NET | Everything | SOA | SOA Patterns | Software Architecture

Udi Dahan writes that ".NET/Java Interop is not a reason for SOA". Udi writes that companies that  need to integrate two technologies turn to web-services and that
"The only problem is that in order for things to work right, they really must have a chatty interface, and flow transaction context between these “services”, and all the other things I describe as anti-patterns"

Udi is right that if you don't rethink and remodel your systems you will (probably) not  have an SOA as you are likely to find your self implementing  anti-patterns such as the ones he mentions.

However, using Web-services does not automatically mean that you are doing an SOA. If you don't think about moving to SOA you can still opt to use web-services as a remoting  or RPC technology to connect two systems. The advantage over the other proprietary products Udi mentions is that web-services are a standard technology. This will work well or fail is orthogonal to the technology choice. It depends on the architectures of the systems you integrate. If you need to flow transaction between the systems you'd also need that even if you cross-compile one of the applications in the other environment.

Another thing I don't agree with is the word must Udi uses. First, while it is likely that older systems has chatty interfaces it is not a must. The designers of the legacy system may have thought about the consequences of distribution without regard to SOA. Also you can still wrap an existing system with a service contract (using web-services or any other technology) and not get to chatty interfaces etc. However that means that the wrapper should have some substance or business logic inside it to mask the old system's behavior this is especially important  if you are thinking about moving to SOA and you take into consideration that the business will not just halt and wait there until you are done. You have to think about interim solutions, such interim solutions can include wrapping a legacy system with an Edge Component and a SOA facade (a pattern I call Legacy Bridge) while you move in the grader direction of a full blown SOA.


 
Tags: .NET | Everything | SOA | SOA Patterns | Software Architecture

May 23, 2007
@ 11:06 PM

I just read Shy Cohen's (via Nick Malik) article in Microsoft's Architecture Journal entitled "Ontology and Taxonomy of Services in a Service-Oriented Architecture" Shy provides a list of what he calls service types. He identifies two major types  bus services and application. He then continues to sub-divide them, the Bus Services are divided into communication and utility services and the Application services  are divided into entity, capability, activity and process services. I have to say it was quite alarming to see this coming from someone who had deep involvement in defining Windows Communication Foundation Indigo.

Where do I start?

well, for one, it seems completely fails to make the distinction between Services as in Service Oriented Architecture and Services as in capabilities or features an infrastructure provide. The "Communication services" are for the most part capabilities that a service infrastructure (such as an ESB) provides. Not Services you would define in an SOA initiative And then there's the matter of service granularity and the difference between Remote objects and SOA for instance, the example  Shy gives for  a "method" (his word) on a Customer service (entity service):

"An example of a domain-specific operation is a customers service that exposes a method called FindCustomerByLocation that can locate a customer's ID given the customer's address"
why would a service return a customer ID? This is the kind of call you would make on an object you hold a reference to not some remote "Something" that also want to authorize your call and may reside in a different company. This kind of thinking is what made remote objects fail. Gregor Hohpe explained that nicely in a paper  called Developing software in a Service Oriented World
The Transparency Illusion.  Distributed components promised to hide remote communication from the developer by making the remoteness "transparent". While the basic syntactic interaction between remote components can be wrapped inside a proxy object, it turned out that dealing with partial failures, latency, and remote exceptions could not be hidden from the developer. It turned out that 90% transparency was actually worse than no transparency because it gave developers a false sense of comfort.
As a side note, Gregor recently gave a presentation that covers this paper at JavaZone which you can watch online at InfoQ

Returning to Shy's article let's take a look at another quote:
Capability Service may flow an atomic transaction in which it is included to the Entity Services that it uses. Capability Services are also used to implement a Reservation Pattern over Entity Services that do not support that pattern, and to a much lesser extent over other Capability Services that do not support that pattern.
I already explained why cross-service transactions and especially flowing transactions is not a good idea in SOA so I won't do it again here - but you can read about it both here ("Transactions between Services? No, No, No!") and here ("Cross-Service Transactions"). Also I truly hope Shy didn't mean .NET data sets when he said "In some cases, typically for convenience reasons, Entity Service implementers choose to expose the underlying data as data sets rather than strongly-schematized XML data. Even though data sets are not entities in the strict sense, those services are still considered Entity Services for classification purposes." In any event the whole decomposition of Services into fine grained "capability", "Activity" and "process" takes no account of the fact the SOA is a distributed architecture...maybe Microsoft is not affected by the  fallacies of distributed computing ?
*ad nauseam (latin)- to the point of disgust


 
Tags: .NET | Everything | SOA | Software Architecture

May 7, 2007
@ 06:15 PM
In the article mentioned in the previous post, I talk about adding EDA to SOA and how you can use Complex Event Processing (CEP) to process the event streams and infer the trends and enhance the understanding of what happen inside your business. All the tools I knew about were Java tools I knew about were Java tools but now I've found out (via Nauman Leghari's blog) that there's also a .NET CEP engine and it is even open source - It is called NESper and like many other tools it is a port of a Java tool.
I am not sure how good it is - but at least I'll have an interesting evening today :)


 
Tags: .NET | Everything | SOA

April 30, 2007
@ 07:34 PM
An article I wrote on Business Intelligence (BI) and Service Oriented Architecture (SOA) has just been published on MSDN.
You can find it here http://msdn2.microsoft.com/en-us/library/bb419307.aspx.

The article explains the SOA & BI mismatch and how to bridge it by adding EDA to SOA. (I bloged about it here before, but the article is more ordered and complete)


 
Tags: .NET | Everything | SOA | SOA Patterns | Software Architecture

April 29, 2007
@ 03:14 PM
Back in January, I took part in an architect panel that Microsoft Israel organized. The panel was led by Ron Jacobs and it featured Udi Dahan, Assaf Jacoby, Coby Cohen, Dudu Benabou and myself. A few days ago Ron edited this recoding and turned it into a podcast in his Arcast series.

The panel's focus was on lessons learned from mistakes made in past project. Ego maniac as I may be :) -- even though you don't get to hear me much in the final edited version -- I think the podcast is worth listening to, as the panel raised some interesting points. You can download the podcast here (don't worry it is in English even though it was recorded in Israel)

PS

I am the first speaker after the introduction, in case you are wondering.


 
Tags: .NET | Everything | General | Software Architecture

April 17, 2007
@ 01:58 PM

After seeing Juval Lowy's article on WCF transaction propagation in the May issue of MSDN magazine. I posted  " Transactions Between Services? No, No, No! " in my DDJ blog. I've got a few comments which I thought warrant a post in their own-right.

The previous post was triggered by an article that promoted flowing transactions (i.e. you perform a transaction against one or two services and then one of the services calls an additional service and it joins the transaction). It is important to say that I think transactions between services should be discouraged regardless of automating extension of transactions. Transaction propaqgation just makes the matters worse.


There might still be some edge case where you have to have an atomic transaction from a service consumer to the service. I think that in the vast majority of SOA implementations you shouldn't do that and I would think real hard about the other options before allowing it in my architecture.In general  I think cross-service transactions are an antipattern (and that's the way you'd find them documented in my SOA patterns book :) )

One of the comments I received began with:

"Cross service transactions are a sure way to introduce coupling and performance problems into your SOA." I'm not sure I agree with that thought. Logically speaking, cross service transactions are a must. The question is how to implement them. There are two mechanisms we can use for implementing TXs: (1) ACID TXs; (2) Long-running TXs. The latter is preferable for the cases Arnon is talking about (large geographical distances, multiple trust authorities, and distinct execution environments). ACID TXs are more suitable for what Guy has mentioned (DeleteCustomer service invokes the DeleteCustomerOrder service internally). I agree with Arnon the a-synchronicity is preferable, but we all have encountered use-cases where ACID-ness is required from a business requirement level... [snipped]


One minor point in regard to this comment is that I don't like the term long running transaction - there is a long running interactions between services and I think the term SAGA describes them better. Sagas are made of a series of business activities that flow back and forth between services to realize a larger business process. Note that these interactions doesn't necessarily have transaction-like behavior.


which brings me to the more important point of looking at the statement "Logically speaking, cross service transactions are a must". I don't think so. For instance, if a service that manages the inventory in a warehouse receives a request for some items and later a cancelation of that request. The first request can trigger the inventory service to order some more items from a supplier. Whether or not the cancellation would cause a cancellation of the order of the supplier depends on the business rules of the inventory service for inventory levels for the items ordered. it might also depend on whether or not the items have already been received etc. The cancellation (the "abort") of the original request does not have to translate to an abort (or compensation) on the request receiver. Furthermore if the service communications model is based on the push model (e.g. using EDA with SOA) the cancellation notice would just be propagated without regard to the inventory service -. It is the inventory service's responsibility to understand the ramifications of this event and act accordingly. Even the example given in the comment 'DeleteCustomer service invokes the DeleteCustomerOrder service internally" is not a good candidate from ACID transactions (there's also a problem of service granularity here - I'll talk about it later). Since when the customer service decides to delete a comment and request the Orders service to delete orders - there's a reasonable chance that some of the orders are already paid for but not delivered. In this case the customer cannot really delete the customer until all the paid orders are resolved. Or maybe the order service is a facade to a night batch that does the actual deletion. - I know I am just fantasizing with these examples but the point is that the customer service has no knowledge on the order service or the inventory service above except the messages supported in their contract. To assume something about the internal behavior is problematic. Even if you know about the internal structure on the onset, the whole idea of SOA is that the services can evolve independently from each other...


Another thought triggered by the example in the comment originated by the granularity of the services (DeleteCustomer service vs. a Customer Service that also supports deleting customers) is that we should be really conscious to the difference between other architectures like 3-tier client/server and SOA. SOA is actually more distributed than 3-tier - we cross a distribution boundary every time we pass a message from a service to a service and not just when we move a massage from a client-tier to an application server. We add this distribution to gain advantages in flexibility and agility. However, we should note that this is a weakness of SOA (considering for example, that Martin Fowler's first law of distributed object design is" Don't distribute your objects!") means we should really pay attention to the way services interact with each other.

  • The granularity of services - having a lot of fine grained services means there will be a lot of interactions over the wire (even if you don't go out to the network you still have to serialize/deserialize, follow the security policy etc.) rather than internal interactions that much faster
  • The Granularity of messages - The same considerations should also guide us to try to create larger and fewer messages. for the example above . Instead of a DeleteCustomerOrder message maybe something like an UpdateCustomersOrders message that can hold a list of customers and orders and the status changes or . by the way this would also support off-line clients better since they can accumulate changes.
  • The assumptions we can make on the other service's availability, performance, internal structure, the trust we have for it etc. - We should try to minimize the assumptions we make and concentrate on what can be inferred from the contract. Remember that policies can change externally so the business logic within a service cannot count on them being constant. this brings us back to the issue of transaction. every cross-wire interaction increases the chances of failure - in transactions one failure invalidates all the transaction is invalidate. every cross-wire interaction within a transaction increases the length of time we lock internal resources (even if we do trust all the involved parties) - especially if that transaction can extend itself automatically. Also as I've mentioned in the previous post the transactions also open the door for denial of service attacks.

If we want to reap the benefits that are sold under the SOA moniker, like flexibility and agility, we really have to pay attention to this extra distribution and design our services differently than we would components in a 3-tier architecture - but hey, that's why they pay us the big bucks, right ? :)

I should probably also add  that building SOAs is not a goal in itself. We can build perfectly good solutions using other architectures - but if we find that we do need SOA (or any other architecture for that matter) we have to pay attention to the way we implement it to both keep its benefits and not harm other quality attributes like performance, security etc..



 
Tags: .NET | SOA | SOA Patterns | Software Architecture

Back in January I opined that  moving to web applications was not the optimal solution to the real problem we have/had with desktop applications which was  installation woes. What we got was a poor UI without installation problems so we (software industry) started to resolve problems like we had when we moved from  terminals to graphical UIs etc. - 
So now we have Rich Internet Applications (RIA) - using technologies like AJAX - but they suffer from other problems  which again we've already been through

Well that was the topic of the post in January. Now I've stumbled upon an interesting/amusing  twist - called Adobe Apollo
Apollo let's you, yes you've guessed it, take your RIA applications and deploy them as desktop applications.  you can now take your HTML, CSSs , AJAX scripts pack them up as a single file (AIR) and lo and behold deploy them on the desktop. You even get these nifty start menu and desktop shortcuts :)

The reason not to dismiss this a complete waste of time - is that what we actually see here is another example of a trend to convergence  web and desktop UI architectures  and programming models. I say "another" because coming from the desktop direction Microsoft is doing pretty much the same thing. WPF brings the web-programming model  with its markup (XAML) and "code-behind" concepts to the desktop as well as pushing the same model to the browser with WPF/E .

The difference between Microsoft's and Adobe's solutions is that, Adobe is coming from the web-side and, as I said, Microsoft is coming from the Desktop side - both companies are striding toward the same goal -  and what we are left with,  is yet another technology war





 
Tags: .NET | Everything | General | Software Architecture

August 27, 2006
@ 09:58 PM

The Microsoft Name Machine is at it again - this time's poor victim is Atlas:

[from Joshua Flanagan's blog] " The Microsoft AJAX (formerly known as DHTML) technology, codename Atlas, will be officially named... ASP.NET 7.0!"

nuff' said


 


 
Tags: .NET | Everything

August 24, 2006
@ 10:48 PM

Over the last few months I've posted a series of blogs on DDJ that cover the basic Object Oriented principles (e.g. Single Responsibility Principle, Don't Repeat Yourself, Inversion of Control etc.).

I've assembled all the posts into a single whitepaper which you can get here.

Also you can download the same (plus a little more) material as a powerpoint presentation.

 


 
Tags: .NET | Everything | General | Software Architecture

May 29, 2006
@ 07:30 PM

[Edited version of post in DDJ]

Since I have been blogging for about a year now on this blog and now also on the DDJ blog. I think  it is time to try making something with more two-way communications.

Consequently, I am going to run a little experiment for a few weeks and see how it goes.

The idea is as follows: If you have an interesting architectural or design dilemma, drop me an email at ask@rgoarchitects.com I'll pick one issue per week and post (on the DDJ blog) the dilemma (anonymously) plus voice my opinion (and/or suggested solution)--and then everyone else can chime in with their comments and insight which hopefully will shed some light on the subject.

I'd be interested to hear both your opinions on this initiative and, of course, interesting dilemmas you are facing. Again, send your dilemmas to ask@rgoarchitects.com)


 
Tags: .NET | Everything | SOA | Software Architecture | SPAMMED Process

While I still hold my view on the Current State of Software Factories - at least one company (EDS) is repoting  (in an MSDN article) that they've built a software factory for their domain entities [found via Steve Cook]. Nevertheless this is still a generic generator (i.e. not a factory for ordering system or something similar- but rather something like  a DSL for O/R Mapping).

Arnon

PS

I also wonder why do they generate unit tests fot the generated code - assuming they properly tested their templates the generated code should just work ...


 
Tags: .NET | Everything | General

April 18, 2006
@ 07:11 PM

There are 113 domain models over at eclipse.org site of all sorts of things.  I guess most models don't have any practical value (what will I do with a metamodel of COBOL) but there are several interesting ones of things like RSS, WSDL, and SDM

 

It is also interesting to note that the models are expressed in several forms including MS DSL models  , UML 

  and images . The transformation from format to format was done by code.

 

(Found via Steve Cook )


 
Tags: .NET | Everything | Software Architecture

April 9, 2006
@ 10:16 PM

One of the roles of the software architect is to act as a mentor/coach. Reviewing some of the designs in one of my projects' teams it seems the time was ripe for doing just that. Thus, last week I gave them a presentation on the basics of good OO design  - which I thought might also be of interest for other people (you can download a copy here - 312KB).

 

The presentation starts with the  7 deadly sins of software design:

  • Rigidity – make it hard to change
  • Fragility – make it easy to break
  • Immobility – make it hard to reuse
  • Viscosity – make it hard to do the right thing
  • Needless Complexity – over design
  • Needless Repetition – error prone
  • Not doing any

 

It is interesting to note that just yesterday I read an interesting piece on what makes good design (i.e. looking from the positive side) by James Shore (found via Sam Gentile

 

 

The main part of the presentation demonstrates the 5 basic design principles (drafted by people like Robert C. Martin , and Barbara Liskov ):

  • OCP open-closed principle - a class should be open for extension but closed for modifications
  • SRP single responsibility principle - a class should have a single responsibility
  • ISP interface segregation principle - there should be separate interfaces for different consumer types
  • LSP Liskov substitution principle - basically design by contract - a sub-class should fulfill the same expectations its suparclass set
  • DIP dependency inversion principle - classes should depends on abstractions, class consumers should depend on abstractions and abstractions shouldn't depend on details.

 

These principles are the basis for  some of the techniques widely used today - few examples include:

Inversion Of Control - builds on OCP

Dependency Injection - a mechanism to allow DIP

Contract First - building on LSP,DIP

 

At the end of the day following these principles helps managing classes dependencies, increase overall loose coupling and cohesion thus increasing the overall quality of design. It sometimes amazes me how using just a  few simple rules can improve maintainability, flexibility and usefulness of designs so much.


 
Tags: .NET | Everything | General | Software Architecture

March 19, 2006
@ 08:00 PM

I recently found MSF 4.0 is out  - yep, it is still in two flavors…

 

MSF Agile (or officially "MSF for Agile Software Development Process Guidance") and MSF 4 CMMI (MSF for CMMI Process Improvement Process Guidance)


I consider MSF Agile as a lightweight process, however I prefer SCRUM as an Agile project management  process.

 

I find the CMMI version more interesting - Both for  cases where Agile is not a good fit (also see  Agile vs. Plan driven development  )

and/or for organizations that need to have CMMI certifications (such as the one I currently work for). MSF 4 CMMI covers level 3 pretty well and also has some guidance moving on to the next levels.

 

Definitely worth a look :)



 
Tags: .NET | Everything | General

March 4, 2006
@ 06:25 PM

When I first learnt about WPF (it was still called Avalon back then) I thought it was strange that Microsoft is touting Smart Client development using WinForms when the WPF/XAML development model is much more closer to the code behind concept of ASP.NET.

 

Developers with ASP.NET experience will have life much  easier in the WPF era - They'll be able to utilize the same skill-set and thinking to build:

  •  Regular, run of the mill, ASP.NET application
  • AJAX application (utilizing Atlas)
  • XBAP (XAML Browser Applications) - Smart clients running in the browser
  • XAML stand-alone applications
While  the WinForm guys (and gals) will be left behind to try and learn the new  programming model.
Looking at the different CTPs of WPF it seemed all of us have a lot to learn in order put it to full use - so I guess no one will have it realy easy :).

 

Anyway, today I read Charles Petzold's "WinForms: More Vital Than Ever" blog post  - it seems that WinForms will stay with us for a while after all (ok, ok, so no real surprise there - I just wanted to make a point). By the way, it is especially interesting seeing this  coming from  Charles considering he is one of the authors currently working on WPF books 

 

ANother interesting point is that Microsoft is going into a lot of trouble unifying all the remoting and  distribution technologies into WCF on the one hand - but will leave us with 5 different technologies for UI development (ASP.NET, WinForms, DirectX, Atlas and WPF) on the other.


 
Tags: .NET | Everything

I've just found out (via  Gianpaolo's blog) that Roger Wolter (former PM of Service Broker) started blogging . He is going to focus on  Data in a Service Oriented world. I had a chance to work with Roger for a short time, which was enough to notice that if anyone knows about data, it is him.  I guess there is no surprise there, considering his past at Microsoft working on :SQL Server Service Broker, SQL Express, SQL XML Datatype, SOAP Toolkit, SQLXML and COM Plus.

His first post (after the obligatory "hello world" post) is about Service Broker positioning (vs. MSMQ, Biztalk and WCF) - Subscribed


 
Tags: .NET | Everything | SOA | Software Architecture

October 30, 2005
@ 05:32 PM

The PDC 05 videos are up @ http://microsoft.sitestream.com/PDC05/

 


 
Tags: .NET | Everything

September 15, 2005
@ 07:09 PM

It seems the PDC presentations are available here ...


 
Tags: .NET | Everything

September 14, 2005
@ 10:17 PM

(like everyone else ?) I've finished reading the C#3 Spec and the LINQ project overview.

with samples like:

public void Linq43() {
   List customers = GetCustomerList();


   var customerOrderGroups = 
         from c in customers
            select
               new {c.CompanyName, 
                  YearGroups =
                     from o in c.Orders
                        group o by o.OrderDate.Year into yg
                        select
                           new {Year = yg.Key,
                              MonthGroups = 
                                 from o in yg.Group
                                 group o by o.OrderDate.Month into mg
                                 select new {Month = mg.Key, Orders = mg.Group}
                                }
                    };

ObjectDumper.Write(customerOrderGroups, 3);
}

Hey - that's de ja vous all over again :)

Actually it is (er..will be) much stronger than SQL - for one, you can use a single LINQ query to combine data from arrays and data and XML and whatever. Also combined with lambda expressions (next gen for anonymous methods ) you'd have even more power.

While I am on the subject of what's new in C# 3.0 - I also found Extension methods very interesting - it kind of lets you have a look and feel of multiple inheritance without the associated headaches

consider the following

namespace MultipleInheritanceSimulation
{
   public static class Extensions 
   {
      public static void DoSomething<T>(this T var) 
      {
         //do whatever
      }

   }
}

And then:

using MultipleInheritanceSimulation;

namespace Tester
{
   public class Foo
   {
      public void Bar()
      {
         MyClass x;
         MyOtherClass y;
   
         x.DoSomething();
         y.DoSomething();
      }
   }
}

 

oh well,enough playing - back to work...



 
Tags: .NET | Everything

August 19, 2005
@ 10:36 AM

I've just read  Klaus Aschenbrenner's  Service Broker article on DevX. While the article provides a nice overview of the mechanics of service broker, I think there's a need to elaborate more on the essene of Service Broker (esp. vs. MSMQ) - so here's my 2 cents on the subject.

While MSMQ is a general purpose messaging engine, Service Broker is focused on (some would say limited to)  transactional messaging -And in this area it does a better job than most if not all the other messaging solutions out there. Here are two examples:

  • Message order - MSMQ transactional messages only guarantees ,message order inside the transaction - it does not guarantee order between transactions also messages from two transactions can be interleaved (see MSDN for illustrations). Service broker solves both these problems.
  • Multiple readers - If you have a large message load and want to set up multiple readers. One problem that might happen (which Service broker solves) is of  two related messages being handles by different readers at the same time - this can occur if you have a long running processes between services or if you utilize service broker for message exchange inside a service. Also in the realm of multiple readers - Service broker will do some form of load balancing the readers for you - if you are willing to let the reader be stored procedures.

Another important trait of Service Broker is that it seems it was built with service orientation in mind (and not just because of the name..). For one you have to define messages and contracts (which party can send which messages) in order to establish a conversation (even though you can trivialize it to send any message you want in any direction). Furthermore, you send messages on a conversation and not to a queue. This means that the sender doesn't really have to know who would get the message (well some layer has to know in order to set up the plumbing - but the business logic that decides to send a message is free from all this).

The other use for Service Broker is to introduce asynchronous operations into the database. It lets you create short transactions updating a single table or view and have the effects of the change ripple as a continuing transaction or transactions. for example you can update a view (that has a lot of underlying tables) and in its "instead of " triggers put the updated information in a queue. You can then read from the queue in another transaction and update the underlying tables. since everything is transactional (the send from the view's trigger, as well as the read by the updater stored procedure) you can be sure that the updates will occur (by the way, this view scenario is something that can be used for implementing insert-only databases, but that's a matter for another blog post :) ).

Arvindra Shemi posted a diagram with the main concepts of service brokers. Note that he also mentions there Monologs, which, as Pat Helland once told me (before he left Microsoft), was originally intended to be part of the product, but was dropped (postponed ?) somewhere along the way. It should be noted that you can implement the behavior of monologs using dialogs, however you need to do a some work to make that work. Another concept missing from that diagram is conversation group, which is a way to treat several conversations as if they were a single conversation.

One technical remark on the DevX article - The article shows the TSQL - it isn't too difficult to wrap these with C# code. I didn't check the latest beta of SQL  but the samples of previous versions already had such an implementation (prepared by the service broker team).

[minor updates]


 
Tags: .NET | Everything

July 24, 2005
@ 09:18 PM

Architecture Description Languages (ADLs) sound like a great idea when you look at the "spec sheet"

ADLs represent a formal way of representing architecture
ADLs are intended to be both human and machine readable
ADLs allows simulation and analysis of architectures – completeness, consistency, ambiguity, and performance
ADLs can support automatic generation of  the system (as it is represented by the architecture)

There are quite a few ADLs out there xADL , ACME/ADML,  SSEPRapide,  Wright  and the list goes on and on.

I am guessing most of you didn't hear about any of those (well ACME appears in all those Willy E Coyote vs. Road Runner cartoons but that doesn't count). I think that the culprit lies in the fact that most (if not all) these come from the academic world where the focus lies on the models (in terms of semantics, completeness, rigorness etc.) and not on the practical use and applicability to day-to-day issues. Another problem lies in the fact that main-stream tools used by the industry.

By the way, UML isn't considered an ADL for several reasons for example the weak integration between the different model that inhibits automatic analysis.

The reason I am bringing the issue of ADLs up is that looking at the new architecture designers in Visual Studio 2005  (the Application Designer , the logical data center designer ,the System Designer  and the Deployment Designer) actually form a set of DSL (Domain Specific Languages) that together can be treated as an integrated ADL. Furthermore Microsoft also provides an SDK   for the"System Definition Model" that is the underlying model behind all these DSLs which lets interested parties extend and build additional designers.

While this model is not complete in several aspects ( some designers like the logical data center designer are too limited or there aren't enough views to cover all the architectural description) it is a good starting point in bringing the ADL concept into more practical and usable form.


 


 
Tags: .NET | Everything | Software Architecture

July 14, 2005
@ 08:15 PM

The next PDC is comming to Los Angeles Sept. 13th  a (nearly complete ) list of the sessions and abstracts can be found here:

http://commnet.microsoftpdc.com/content/sessions.aspx

 


 
Tags: .NET | Everything

July 13, 2005
@ 06:07 PM

What if there was a new platform for .NET that has the following characteristics

  • lets you run .NET 2.0
  • supports web-services (something like IIS)
  • integrated message-queue (a-la MSMQ)
  • high-availability (better than clustering performance)
  • strong management tools

well there is one - it is made by Microsoft and goes by the name SQL Server 2005.

SQL Server 2005 lets you run .NET 2.0 code in process (an interesting point here is that DB2 already lets you run .NET code and Oracle will also add this capability with 10g Release 2  but both do it out-of-process).

It also  lets you expose stored procedures as web-services

It has a performant message queuing mechanism called service-broker. Service broker guarantees message ordering as well as solves the problem of multiple readers (what happens if one reader takes the order header and another takes the order line) and as I said it has good performance. by the way Roger Walter who is the group program manager for service broker is going to publish a book on the subject. Having worked with him for a short while (He was our "Redmond connection" on one of the projects I consulted) I can say without hesitation that he is the authority on service broker and a smart guy to boot :)

SQL Server 2005 also has (almost) instant fail-over capability - using Database mirroring you can have your (application?) server fail over in less than 5 seconds (compare that with clustering fail over times of 60 seconds or more). Note that each database can only fail over to one other database, but a server can be both the backup database of one server and the active server (vs. another server).

And you get all the management capabilities of SQL server (oh yeah, you also have a great DB there :) )

Taking all this into consideration there are (a limited set of) situations where you can actually use SQL Server as a hosting platform (instead of COM+ or IIS) for your application. True, this is not something I will generally recommend but I can think of one or two projects where scale-out was less of an issue where it could have been used (had it existed).

 

 


 
Tags: .NET | Everything

[thanks to Eliaz Tobias from MS Israel for the link]

The beta version of MSF 4.0 formal is available for download. This is an interactive process which is compliant with CMMI level 3.0 (see http://www.sei.cmu.edu/pub/documents/02.reports/pdf/02tr029.pdf chapter 7 - maturity levels)  and supported by the tools (i.e. Visual Studio Team System 2005). This can be great news to organizations like the one I work for these days who are certified for CMMI 3.0 and can (hopefully) stay compliant with less bureaucracy.

Looking at this process from my perspective (i.e. as an Architect) it also looks interesting. It defines several roles for architects (e.g. in domain technical level as Subject matter experts and in the solution level as an Architect).  The process suggested is tailored/aligned with VS2005 capabilities (and thus somewhat limited) however many of the steps are both viable and important. For example it has parts that do with quality of service requirements (what I call Quality Attributes in SPAMMED).  My particular favorite step is "Assess Alternatives (LAAAM)"  which I helped introduce ( :) ) in my previous job as an Architect for Microsoft Consulting Services

 


 
Tags: .NET | Everything | Software Architecture

The Composite UI Application Block (CAB) is an interesting architectural solution for smart client development. It is essentially a plug-in architecture that brings the WebParts concept to the desktop.

The CAB has the following elements:

  • WorkItems. These are the classes which represent use cases in your application and contain the business logic for those use cases.
  • SmartParts. There are the building blocks of a Windows-based application - similar in concept to WebParts.
  • Workspaces. These are helper classes that can display SmartParts with a uniform style.
  • UIElements. These are elements such as toolbars and menu bars that are shared by SmartParts within the application.
  • Support services. These include:
    • Event broker service to manage the publishing and subscribing of events between SmartParts.
    • State management service to hold shared state for areas within the application. This provides an option to encrypt the state before it is stored.

The CTP is now available on GotDotNet (needs .NET 2 beta)


 
Tags: .NET | Everything | Software Architecture

July 4, 2005
@ 08:59 PM

Don't worry  I didn't switch to blogging on Greek mythology (well, not yet anyway) this is still a  technology blog.

Ajax is an old/new web development paradigm. It is basically a combination of several existing client-side technologies to achieve responsive and "rich" web applications (a good example for that is Google maps - just pan the map and you'd see what I mean). specifically Ajax builds on XHTML, cascading style sheets (CSS),Javascript, DHTML and XMLHttpRequest (for asynchronous communication with the server). By the way the reason it was dubbed AJAX is that it is an acronym for Asynchronous Javascript and XML.

Microsoft has downplayed Ajax importance for quite sometime - claiming that basically the technologies has been available for years in Internet Explorer. Nevertheless Microsoft has recently decided to join the fray and provide structured tools to help realize Ajax development on the .NET platform  - The code name for this initiative is Atlas. Scott Guthrie from Microsoft published some of the details in his blog

Here are a few highlights of what Atlas will include:

  • Client Side Framework - an extension for Javascript with UI controls, network stack, eventing etc.
  • Server Controls - server side-controls that interact with the client side controls (based on async callbacks)
  • Web-service integration
  • Few Server-side and Client side Services - e.g. Profiles, Personalization, Authentication and Roles on the server and local browser cache on the client

It seems Microsoft will release a technology preview of Atlas at the PDC later this year.

Meanwhile, if you don't want to wait for Atlas - you can download Ajax.net  - Ajax.Net will generate client-side scripts that interact with server-side methods decorated with [Ajax.AjaxMethod] attribute - it isn't everything, but it is a very nice start (and it is available today)


 
Tags: .NET | Everything

June 23, 2005
@ 10:08 PM

Microsoft has released  the Connected Systems Toolkit. A very nice intorduction to the SOA concept (as Microsoft sees it). The toolkit (DVD) includes:

  • a connected system's course (with 4 labs)
  • an extensive sample application (with code and documentation)
  • few whitepapers
  • few presentations (ppt & video)
  • some marketing hype (well, nothing is perfect :) )

 
Tags: .NET | Everything

June 21, 2005
@ 08:11 PM

The architect doesn't talk, he acts.
When this is done,
the team says, "Amazing:
we did it, all by ourselves!"
(17) (The Tao of software architect - Philippe Kruchten)

On the surface - When it comes to agile development the role of the software architect is a little more blurred.

The most obvious aspect where architects is for the technical architecture. An experienced technical architect, can greatly enhance any project by steering the designs into the "best" directions (under the chosen platform constraints). The technical architect can also promote reuse etc.

Additionally while the requirements change a lot and not fully defined, the quality attributes of a system are more stable - if you need performance, then you need performance!. More so,  there are some qualities that are inherent to agile process - for example you want to put an emphasis on flexibility and maintainability - if your developed solution does not have these it is going to do refactorings. Thus, depending on the size of the project you may want to use an architect to help set the ground rules in the first couple of iterations.

Another area where architect involvement can be very beneficial is when you try to scale an agile project a good choice is to try to break the project to smaller loosely coupled projects (see this paper  for example)  - well, this is just  what we (architects) live for...

By the way, few agile processes, define the architect role up-front, one such process is MSF 4 Agile. Note that MSF (Microsoft Solutions Framework) version 4 comes in two "flavors" one that is aligned with CMMI  and the other a (much) more light version, the afford mentioned MSF 4.

 

How does the SPAMMED process fare with an Agile project - (surprisingly enough) I would say pretty well

First of the architect should be hands-on i.e.  part of the development team (most likely the technical lead)

  • Stakeholders, you would probably want stakeholders on-site for any architecture related  meeting (just as much as you would want the customer on site for other activities)
  • Principles would include things like TDD, Simple Implementations, Refactoring
  • Quality attributes would hold Flexibility and maintainability and a couple or so of the important project qualities (performance, availability..)
  • For the modeling you would chose very few views and would try to focus on ones that have manifestation in deliverables
    A good example for this is the Application designer  in Whidbey (see screen shot below) - the result of which is the projects structure for the solution

  • Mapping doesn't really change
  • Evaluation would be focused on proof of concepts and/or skeletal architecture.
  • Deployment - well,  being part of the team... you would notice if your decisions were wrong or circumvented

To sum up - yes Agile projects can and many times should use an architect to help it stay on track - hey, even XP has an architectural spike...

 


 
Tags: .NET | Everything | Software Architecture | SPAMMED Process

June 18, 2005
@ 08:16 PM

One of the most interesting things that MS is building these days is the set of tools around their software factories initiative.

Software Factories, is actually a methodology that builds on the concepts of Domain Specific Languages (DSLs) along with frameworks, patterns and guidance.

The idea is to bring the notion of domain modeling and DSLs from horizontal markets (e.g. the form designer in any modern IDE) to the everyday use of vertical markets (i.e. your next application) and help realize the promise of product lines. Many of the ideas in software factories are not new (see for example this article from 1993) - however, today,as the Jack Greenfield et al  state in their book, a number of needed technologies has (finally) matured enough to make it feasible. Furthermore  What's unique in this effort is that Microsoft is making the effort to back the ideas with tools  that will enable architects and developers to put them into use.

A software factory needs 3 elements a schema, a template and tool to support them (a development environment). The schema is basically the recipe containing the overall information on how things should work together. The template is the set of DSLs, samples, frameworks that are used to create the factory and lastly we need  the IDE that supports them (e.g. Visual Studio "Whidbey" - although, at least technically this can also be achieved in Eclipse etc.)

I am, personally, very interested in this initiative. We already use code generation all over the place (DAL, serializations, Data Entities etc) and employ a domain driven approach even today. I would love to have "user-friendly" tools that will let me as an architect achieve these goals more easily.

One final note - yes I am aware of MDA (Model Driven Architecture) but all the MDA tools I've encountered thus far are lacking in their usability. This, by the way, brings me to one caveat with software factories - it is not based on UML 2.0. I would rather have a DSL that is based on stereotypes, tagged values and OCL. This would allow for a specific view using the appropriate designer but also for backward compatibility (and a downgraded view) on other tools. I do agree though, that UML 2.0 has its own share of problems - but that's a matter for another discussion altogether

 


 
Tags: .NET | Everything | Software Architecture

June 13, 2005
@ 08:52 PM

Just saw an entry @ Kevin Hammond's blog that when you download the Indigo/Avalon beta you have to read through to download the SDK rather then the redistributable - I have to admit that I've made the same mistake myself...


 
Tags: .NET | Everything

I almost forgot another commercial GRID implemrntation  is Gigaspaces. Gigaspaces is interestig since it is actually based on  Java standards  JINI  and JavaSpaces but also has support for C++ and .NET


 
Tags: .NET | Everything

June 8, 2005
@ 04:01 AM
GRID computing, in the sense of distributed computing with a focus on large-scale resource sharing and high performance computing, is starting to emerge as a viable direction for several computing problems (you can also see What's the grid  )

Below are links to several  projects that lets you create Grids using the .NET platform

Happy Gridding


 
Tags: .NET | Everything