<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-4923273354692358330</id><updated>2011-11-17T22:29:17.120+01:00</updated><category term='AOP'/><category term='Visual Studio'/><category term='dependency injection'/><category term='javascript'/><category term='debugging'/><category term='patterns'/><category term='security'/><category term='tutorial'/><category term='Windows Workflow Foundation'/><category term='communication'/><category term='.NET CF'/><category term='web services'/><category term='IIS'/><category term='book'/><category term='NoSQL'/><category term='ASP.NET'/><category term='C#'/><category term='EntityBag'/><category term='Boo'/><category term='WCF'/><category term='Enterprise Library'/><category term='ORM'/><category term='identity and access'/><category term='NHibernate'/><category term='team work'/><category term='testing'/><category term='Entity Framework'/><title type='text'>Marcin Budny 's blog</title><subtitle type='html'>everything Zen, I don't think so</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>48</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-7889299044371417535</id><published>2011-11-17T22:28:00.001+01:00</published><updated>2011-11-17T22:29:17.187+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='web services'/><category scheme='http://www.blogger.com/atom/ns#' term='book'/><title type='text'>Process integrity</title><content type='html'>&lt;p&gt;Recently I finished the “Enterprise SOA: Service-Oriented Architecture Best Practices” book by Dirk Krafzig, Karl Banke and Dirk Slama. A great book I must say, because it covers not only purely technical and architectural aspects, but also the business and policy environment with which you have to deal in large organizations actually using the SOA approach. One particular thing in the architecture part of the book got me really interested, namely process integrity.&lt;/p&gt;  &lt;h3&gt;Some theory…&lt;/h3&gt;  &lt;p&gt;Imagine this: you are creating a web service method (whoa!). The method is responsible for conducting some business process. The challenge is that this process involves interaction with two external systems over which you have no control. For example you might be booking a flight ticket along with hotel reservation (first external system) and car rental reservation (second external system). External systems tend to be, well… external, which means you have to assume than sooner or later communication with them is going to fail. What if you are able to make hotel reservation but then car rental reservation fails? You have to be able to a) detect when something goes wrong, b) be able to handle this situation for example by cancelling the hotel reservation and the ticket (compensation process).&lt;/p&gt;  &lt;p&gt;The most natural way to handle this would be to have some kind of ACID transaction spanning all the systems involved. While it is possible to use distributed transactions in some cases, there are a lot of problems involved. First, there are technology constraints. The external system probably won’t support a compatible transaction coordination system / standard. Then there is lack of support for long-lived processes (for example reservation confirmation from hotel system takes up to an hour). Also, distributed transactions over internet are probably bad idea.&lt;/p&gt;  &lt;p&gt;The idea to deal with that problem in SOA environment is to have so called persistent queues and transactional steps. You split the whole process into steps where each step is transactional. Then after taking each of those steps you note the fact that it either passed or failed in a persistent way. A passed step is a sign that you can perform next step in the process or finish the whole process if you have taken all the steps. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh4.ggpht.com/-rXN4mzkuajo/TsV8WeRVsSI/AAAAAAAAAWM/FH0l4htCmXs/s1600-h/image%25255B4%25255D.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/-tPm80cfjjVQ/TsV8XJAlKGI/AAAAAAAAAWQ/y1je_7NJxRs/image_thumb%25255B2%25255D.png?imgmax=800" width="644" height="292" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;(click to enlarge)&lt;/p&gt;  &lt;p&gt;What happens here? First we save a ticket information and enqueue the hotel reservation task. Then hotel reservation processor, which is periodically checking its queue, loads the task and processes it. After successful hotel reservation, car rental reservation task is enqueued. If hotel reservation task failed, the transaction would be rolled back, and the hotel reservation task would return into queue. Similar process happens for car rental reservation task.&lt;/p&gt;  &lt;p&gt;The important thing to note here is that the user who initiated the process doesn’t get the information whether it was successful or not straight away. The process is asynchronous, so the user has to check its status periodically. Also all tasks and data saved to database should be marked with a common process (or transaction) id. This way we’ll be able to identify what is the state of the process.&lt;/p&gt;  &lt;p&gt;So what can be done if one of the tasks fails? Maybe the external system is just overloaded or under maintenance. Then we can just try again later. The problem might also be with data passed to the system (for example it doesn’t pass validation). In this case trying over and over again won’t do much good. Tasks with no good chances of completing successfully should be marked as failed. Then, either automatically or manually (by a technician), the processes of which they are part should be rolled back, which usually means executing some kind of compensating logic.&lt;/p&gt;  &lt;h3&gt;…and some practice&lt;/h3&gt;  &lt;p&gt;So what is the best way to implement all that? You may don’t know it, but you’ve got all the infrastructure ready in… the Workflow Foundation. Well maybe it’s not 1:1 with what I was explaining above, but serves the purpose. Yet WF may be too heavyweight solution for you, since it requires a certain shift of thinking about building your service. &lt;/p&gt;  &lt;p&gt;Sticking to transactional steps and queues you may wonder how to implement such a queue mechanism. I think two most popular approaches would be to have either database queue or MSMQ queue. Both have their pros and cons. MSMQ is nicely suited for processing large amounts of messages, but causes some overhead in maintenance and also requires you to promote your transactions to distributed if you want them to span the queue and the database. With database the transactions are local and there’s no maintenance overhead, but it is quite challenging to create an efficient queuing mechanism due to locking problems. Then again – you might need the integrity, not the performance. &lt;/p&gt;  &lt;p&gt;Here I have a simple example how to create database queue and task processors working in background. I’m not working with a hotel or car rental system, but rather with Twitter and Facebook. Let’s pretend for a minute that it’s absolutely crucial for you to have your status updates hit both Twitter and Facebook in an integral manner :) In this example I’m using a nice scheduling library called &lt;a href="http://quartznet.sourceforge.net/"&gt;Quartz.NET&lt;/a&gt;, and also &lt;a href="http://www.twitterizer.net/"&gt;Twitterizer&lt;/a&gt; and &lt;a href="http://facebooksdk.codeplex.com/"&gt;Facebook C# SDK&lt;/a&gt;. (It is amazing how NuGet makes putting together such mashup apps quick and easy). &lt;a href="http://marcinbudny.com/files/PersistentTasks.zip"&gt;Grab the source here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh6.ggpht.com/-D8jaPq4gBWo/TsV8YMf4S3I/AAAAAAAAAWs/1PpuCM6X0Vk/image%25255B9%25255D.png?imgmax=800" width="681" height="346" /&gt;&lt;/p&gt;  &lt;p&gt;It’s a simple console app:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
{
    &lt;span style="color: green"&gt;// required to use sql ce with entity framework
    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Database&lt;/span&gt;.DefaultConnectionFactory = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SqlCeConnectionFactory&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;System.Data.SqlServerCe.4.0&amp;quot;&lt;/span&gt;);

    &lt;span style="color: green"&gt;// start scheduler
    &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;factory = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StdSchedulerFactory&lt;/span&gt;();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;scheduler = factory.GetScheduler();
    scheduler.Start();

    &lt;span style="color: green"&gt;// those are our task processors
    &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;twitterJobDetail = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;JobDetail&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;twitterJob&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;null&lt;/span&gt;, &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;PostOnTwitterJob&lt;/span&gt;));
    &lt;span style="color: blue"&gt;var &lt;/span&gt;facebookJobDetail = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;JobDetail&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;facebookJob&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;null&lt;/span&gt;, &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;PostOnFacebookJob&lt;/span&gt;));

    &lt;span style="color: green"&gt;// they check the queue every 5 seconds
    &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;twitterTrigger = &lt;span style="color: #2b91af"&gt;TriggerUtils&lt;/span&gt;.MakeSecondlyTrigger(5);
    twitterTrigger.Name = &lt;span style="color: #a31515"&gt;&amp;quot;twitter&amp;quot;&lt;/span&gt;;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;facebookTrigger = &lt;span style="color: #2b91af"&gt;TriggerUtils&lt;/span&gt;.MakeSecondlyTrigger(5);
    facebookTrigger.Name = &lt;span style="color: #a31515"&gt;&amp;quot;facebook&amp;quot;&lt;/span&gt;;

    &lt;span style="color: green"&gt;// lets start them
    &lt;/span&gt;scheduler.ScheduleJob(twitterJobDetail, twitterTrigger);
    scheduler.ScheduleJob(facebookJobDetail, facebookTrigger);

    &lt;span style="color: blue"&gt;while &lt;/span&gt;(&lt;span style="color: blue"&gt;true&lt;/span&gt;)
    {
        &lt;span style="color: green"&gt;// get post text from user
        &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;post = &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.ReadLine();
        &lt;span style="color: green"&gt;// and initiate posting
        &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskQueue&lt;/span&gt;.Enqueue(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TasksDbContext&lt;/span&gt;(), &lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;.NewGuid(), &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PostOnTwitterTaskData &lt;/span&gt;{ Text = post });
        &lt;span style="color: green"&gt;// also you could force the twitter job to run straight away so that you don't wait &amp;lt;= 5s
    &lt;/span&gt;}
}&lt;/pre&gt;

&lt;p&gt;Basically we’re taking user input and initiate posting process by storing the post on Twitter task in the database. The database representation of the task is very simple:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PersistentTask
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Guid &lt;/span&gt;Id { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    
    &lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color: green"&gt;Helps to identify the process across different tasks
    &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Guid &lt;/span&gt;TransactionId { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;IsFailed { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Type { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;SerializedData { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;The task queue:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskPair&lt;/span&gt;&amp;lt;TTaskData&amp;gt;
 {
     &lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
     /// &lt;/span&gt;&lt;span style="color: green"&gt;DB representation of the task
     &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
     &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PersistentTask &lt;/span&gt;PersistentTask { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

     &lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
     /// &lt;/span&gt;&lt;span style="color: green"&gt;Deserialized task data
     &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
     &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;TTaskData TaskData { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

     &lt;span style="color: blue"&gt;public &lt;/span&gt;TaskPair(&lt;span style="color: #2b91af"&gt;PersistentTask &lt;/span&gt;persistentTask, TTaskData taskData)
     {
         PersistentTask = persistentTask;
         TaskData = taskData;
     }
 }
 
 &lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskQueue
 &lt;/span&gt;{
     &lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
     /// &lt;/span&gt;&lt;span style="color: green"&gt;Puts a task into database queue
     &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
     &lt;/span&gt;&lt;span style="color: blue"&gt;public static void &lt;/span&gt;Enqueue(&lt;span style="color: #2b91af"&gt;TasksDbContext &lt;/span&gt;context, &lt;span style="color: #2b91af"&gt;Guid &lt;/span&gt;trasactionId, &lt;span style="color: blue"&gt;object &lt;/span&gt;taskData)
     {
         &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Enqueueing {0} with transactionId = {1}&amp;quot;&lt;/span&gt;, taskData.GetType().Name, trasactionId);
         
         &lt;span style="color: blue"&gt;var &lt;/span&gt;serializer = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;XmlSerializer&lt;/span&gt;(taskData.GetType());
         &lt;span style="color: blue"&gt;var &lt;/span&gt;writer = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StringWriter&lt;/span&gt;();
         serializer.Serialize(writer, taskData);

         &lt;span style="color: blue"&gt;var &lt;/span&gt;persistentTask = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PersistentTask
         &lt;/span&gt;{
             Id = &lt;span style="color: #2b91af"&gt;Guid&lt;/span&gt;.NewGuid(),
             TransactionId = trasactionId,
             IsFailed = &lt;span style="color: blue"&gt;false&lt;/span&gt;,
             Type = taskData.GetType().Name,
             SerializedData = writer.ToString()
         };

         context.PersistentTasks.Add(persistentTask);
         context.SaveChanges();
     }

     &lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
     /// &lt;/span&gt;&lt;span style="color: green"&gt;Dequeues a task from database queue and deserializes its data
     &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
     &lt;/span&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskPair&lt;/span&gt;&amp;lt;TTaskData&amp;gt; Dequeue&amp;lt;TTaskData&amp;gt;(&lt;span style="color: #2b91af"&gt;TasksDbContext &lt;/span&gt;context)
     {
         &lt;span style="color: blue"&gt;var &lt;/span&gt;task = context.PersistentTasks
             .Where(pt =&amp;gt; pt.Type == &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(TTaskData).Name &amp;amp;&amp;amp; !pt.IsFailed).FirstOrDefault();
         &lt;span style="color: blue"&gt;if &lt;/span&gt;(task == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
         {
             &lt;span style="color: blue"&gt;return null&lt;/span&gt;;
         }

         &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Dequeued {0} with transactionId = {1}&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(TTaskData).Name, task.TransactionId);

         context.PersistentTasks.Remove(task);
         context.SaveChanges();

         &lt;span style="color: blue"&gt;var &lt;/span&gt;serializer = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;XmlSerializer&lt;/span&gt;(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(TTaskData));
         &lt;span style="color: blue"&gt;var &lt;/span&gt;reader = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StringReader&lt;/span&gt;(task.SerializedData);

         &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskPair&lt;/span&gt;&amp;lt;TTaskData&amp;gt;(task, (TTaskData)serializer.Deserialize(reader));
     }

     &lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
     /// &lt;/span&gt;&lt;span style="color: green"&gt;Marks a certain task as failed
     &lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
     &lt;/span&gt;&lt;span style="color: blue"&gt;public static void &lt;/span&gt;MarkFailed(&lt;span style="color: #2b91af"&gt;TasksDbContext &lt;/span&gt;context, &lt;span style="color: #2b91af"&gt;Guid &lt;/span&gt;taskId)
     {
         &lt;span style="color: blue"&gt;var &lt;/span&gt;task = context.PersistentTasks.SingleOrDefault(pt =&amp;gt; pt.Id == taskId);
         &lt;span style="color: blue"&gt;if &lt;/span&gt;(task != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
         {
             task.IsFailed = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
             context.SaveChanges();
         }
     }
 }&lt;/pre&gt;

&lt;p&gt;And the jobs (or task processors):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public abstract class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskJobBase&lt;/span&gt;&amp;lt;TTaskDescription&amp;gt; : &lt;span style="color: #2b91af"&gt;IStatefulJob
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Execute(&lt;span style="color: #2b91af"&gt;JobExecutionContext &lt;/span&gt;jobContext)
    {
        &lt;span style="color: #2b91af"&gt;TaskPair&lt;/span&gt;&amp;lt;TTaskDescription&amp;gt; pair = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
        &lt;span style="color: #2b91af"&gt;ObjectContext &lt;/span&gt;objctx = &lt;span style="color: blue"&gt;null&lt;/span&gt;;

        &lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;context = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TasksDbContext&lt;/span&gt;())
        {
            &lt;span style="color: green"&gt;// unfortunately with sql ce you have to manually open/close connection or it'll not enlist in transaction
            &lt;/span&gt;objctx = ((&lt;span style="color: #2b91af"&gt;IObjectContextAdapter&lt;/span&gt;)context).ObjectContext;
            objctx.Connection.Open();

            &lt;span style="color: green"&gt;// foreach task waiting in the database
            &lt;/span&gt;&lt;span style="color: blue"&gt;do
            &lt;/span&gt;{
                &lt;span style="color: blue"&gt;try
                &lt;/span&gt;{
                    &lt;span style="color: green"&gt;// open transaction
                    &lt;/span&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;scope = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionScope&lt;/span&gt;())
                    {
                        &lt;span style="color: green"&gt;// dequeue task
                        &lt;/span&gt;pair = &lt;span style="color: #2b91af"&gt;TaskQueue&lt;/span&gt;.Dequeue&amp;lt;TTaskDescription&amp;gt;(context);
                        &lt;span style="color: blue"&gt;if &lt;/span&gt;(pair != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                        {
                            &lt;span style="color: green"&gt;// execute it
                            &lt;/span&gt;PerformTask(context, pair);
                            &lt;span style="color: green"&gt;// if ok - commit transaction
                            &lt;/span&gt;scope.Complete();
                        }
                    }
                }
                &lt;span style="color: blue"&gt;catch
                &lt;/span&gt;{
                    &lt;span style="color: green"&gt;// transaction was rolled back
                    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Task {0} with transaction id = {1} failed!&amp;quot;&lt;/span&gt;, pair.TaskData.GetType().Name,
                        pair.PersistentTask.TransactionId);

                    &lt;span style="color: green"&gt;// in this example we also mark the task as failed                        
                    &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;(pair != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                    {
                        &lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;scope = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionScope&lt;/span&gt;())
                        {
                            &lt;span style="color: #2b91af"&gt;TaskQueue&lt;/span&gt;.MarkFailed(context, pair.PersistentTask.Id);
                            scope.Complete();
                        }
                    }
                }
            } &lt;span style="color: blue"&gt;while &lt;/span&gt;(pair != &lt;span style="color: blue"&gt;null&lt;/span&gt;);

            objctx.Connection.Close();
        }
    }

    &lt;span style="color: blue"&gt;public abstract void &lt;/span&gt;PerformTask(&lt;span style="color: #2b91af"&gt;TasksDbContext &lt;/span&gt;context, &lt;span style="color: #2b91af"&gt;TaskPair&lt;/span&gt;&amp;lt;TTaskDescription&amp;gt; pair);
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PostOnTwitterJob &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TaskJobBase&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;PostOnTwitterTaskData&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;PerformTask(&lt;span style="color: #2b91af"&gt;TasksDbContext &lt;/span&gt;context, &lt;span style="color: #2b91af"&gt;TaskPair&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;PostOnTwitterTaskData&lt;/span&gt;&amp;gt; pair)
    {
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Posting \&amp;quot;{0}\&amp;quot; on Twitter&amp;quot;&lt;/span&gt;, pair.TaskData.Text);

        &lt;span style="color: #2b91af"&gt;OAuthTokens &lt;/span&gt;tokens = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OAuthTokens&lt;/span&gt;();
        tokens.AccessToken = &lt;span style="color: #a31515"&gt;&amp;quot;[your access token]&amp;quot;&lt;/span&gt;;
        tokens.AccessTokenSecret = &lt;span style="color: #a31515"&gt;&amp;quot;[your access token secret]&amp;quot;&lt;/span&gt;;
        tokens.ConsumerKey = &lt;span style="color: #a31515"&gt;&amp;quot;[your consumer key]&amp;quot;&lt;/span&gt;;
        tokens.ConsumerSecret = &lt;span style="color: #a31515"&gt;&amp;quot;[your consumer secret]&amp;quot;&lt;/span&gt;;

        &lt;span style="color: #2b91af"&gt;TwitterResponse&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;TwitterStatus&lt;/span&gt;&amp;gt; tweetResponse = &lt;span style="color: #2b91af"&gt;TwitterStatus&lt;/span&gt;.Update(tokens, pair.TaskData.Text);
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(tweetResponse.Result != &lt;span style="color: #2b91af"&gt;RequestResult&lt;/span&gt;.Success)
        {
            &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Exception&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Unable to post to twitter!&amp;quot;&lt;/span&gt;);
        }

        &lt;span style="color: green"&gt;// ok, posted! now the next step - facebook
        // it's still in the transaction!
        &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TaskQueue&lt;/span&gt;.Enqueue(context, pair.PersistentTask.TransactionId, &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PostOnFacebookTaskData &lt;/span&gt;{ Text = pair.TaskData.Text });
    }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PostOnFacebookJob &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;TaskJobBase&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;PostOnFacebookTaskData&lt;/span&gt;&amp;gt;
{
    &lt;span style="color: blue"&gt;public override void &lt;/span&gt;PerformTask(&lt;span style="color: #2b91af"&gt;TasksDbContext &lt;/span&gt;context, &lt;span style="color: #2b91af"&gt;TaskPair&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;PostOnFacebookTaskData&lt;/span&gt;&amp;gt; pair)
    {
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Posting \&amp;quot;{0}\&amp;quot; on Facebook&amp;quot;&lt;/span&gt;, pair.TaskData.Text);

        &lt;span style="color: green"&gt;// in real world app you need to refresh this token since it expires after ~2h
        &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;fb = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FacebookClient&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;[your access token]&amp;quot;&lt;/span&gt;);
 
        &lt;span style="color: blue"&gt;dynamic &lt;/span&gt;parameters = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ExpandoObject&lt;/span&gt;();
        parameters.message = pair.TaskData.Text;

        &lt;span style="color: blue"&gt;dynamic &lt;/span&gt;result = fb.Post(&lt;span style="color: #a31515"&gt;&amp;quot;me/feed&amp;quot;&lt;/span&gt;, parameters);
        &lt;span style="color: blue"&gt;var &lt;/span&gt;id = result.id;

        &lt;span style="color: green"&gt;// nothing left to do - process finished
    &lt;/span&gt;}
}&lt;/pre&gt;

&lt;p&gt;Of course the app is not something I would put into production, but it should give you an idea how things can be organized. &lt;a href="http://marcinbudny.com/files/PersistentTasks.zip"&gt;Grab the source here&lt;/a&gt;.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-7889299044371417535?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/7889299044371417535/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=7889299044371417535' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7889299044371417535'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7889299044371417535'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2011/11/recently-i-finished-enterprise-soa.html' title='Process integrity'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/-tPm80cfjjVQ/TsV8XJAlKGI/AAAAAAAAAWQ/y1je_7NJxRs/s72-c/image_thumb%25255B2%25255D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-4205701252078377153</id><published>2011-10-13T22:18:00.001+02:00</published><updated>2011-10-13T22:18:06.636+02:00</updated><title type='text'>WebSockets in .NET 4.5: a simple game</title><content type='html'>&lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/WebSocket"&gt;Websockets&lt;/a&gt; are one of the new great web standards, which applied in a right way, will enable development of completely new web applications. Microsoft introduces native support for them in .NET 4.5 and IE 10. Other browsers (Firefox 7, Chrome 14) already support the standard. To play with the new technology I created a simple game of pong&amp;#160; (&lt;a href="http://marcinbudny.com/files/Pong.zip"&gt;download code here&lt;/a&gt;):&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://lh5.ggpht.com/-WV1x5ppwQdc/TpdHfde8RPI/AAAAAAAAAVw/TbYqm1JTq18/image%25255B4%25255D.png?imgmax=800" width="644" height="322" /&gt;&lt;/p&gt;  &lt;p&gt;Basically when two players open the website, the game begins. If further players connect, new games are created for them. If one of the players in a game disconnects, the game ends. &lt;/p&gt;  &lt;p&gt;There are some interesting aspects of this sample:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;connections from players are grouped in games and the messages are broadcasted among game participants &lt;/li&gt;    &lt;li&gt;there is a thread on the server responsible for moving the ball and broadcasting its position &lt;/li&gt;    &lt;li&gt;different kinds of messages are sent &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In order to run the sample you’ll need:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Windows 8 developer preview &lt;/li&gt;    &lt;li&gt;IIS 8 &lt;u&gt;with websockets module installed&lt;/u&gt; &lt;/li&gt;    &lt;li&gt;Visual Studio 11 developer preview + NuGet &lt;/li&gt;    &lt;li&gt;ASP.NET MVC 4 for Visual Studio 11 &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In this post I’m only going to show most interesting parts related to websockets usage, if you want to see more, &lt;a href="http://marcinbudny.com/files/Pong.zip"&gt;grab the source&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;The client&lt;/h3&gt;  &lt;p&gt;The client is the browser so we’ll be coding javascript. I prefer to use OO javascript so this is the application’s structure:&lt;/p&gt;  &lt;p&gt;&lt;span style="background: white; color: teal"&gt;&lt;/span&gt;&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Pong&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;..some initialization parameters..&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
    ...&lt;/span&gt;&lt;span style="background: white; color: black"&gt;initialization code and fields here&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;...
}

&lt;/span&gt;&lt;span style="background: white; color: black"&gt;Pong&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;prototype &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= {
    ...&lt;/span&gt;&lt;span style="background: white; color: black"&gt;methods here&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;...
};&lt;/span&gt;&lt;/pre&gt;

&lt;br /&gt;

&lt;p&gt;Following code shows how to open a WebSocket on client side:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// start connecting websockets
    // Firefox 6 and 7 requires Moz prefix...
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;typeof&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;MozWebSocket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) == &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;function&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: black"&gt;MozWebSocket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;applicationUrl&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;openStateConst &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;MozWebSocket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;OPEN&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
    } &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;else &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: black"&gt;WebSocket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;applicationUrl&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;openStateConst &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;WebSocket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;OPEN&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
    }

    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// register to socket events
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;onopen &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;$&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;proxy&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;() {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;info&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;You are connected...&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
    }, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;onclose &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;$&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;proxy&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;() {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;info&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;Other player disconnected! Refresh page to restart game&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
    }, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;onerror &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;$&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;proxy&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;() {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;info&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;You have been disconnected! Sorry for that, refresh page to restart game&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
    }, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;onmessage &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;$&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;proxy&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;msg&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;processMessage&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;msg&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
    }, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Unfortunately as of Firefox 7, websocket API is still treated as a vendor extension, so you have to use Moz prefix. Otherwise it works great. Next code fragment shows how the incoming messages from server are handled:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// processes message from server basing on its type
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;processMessage&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;: &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;msg&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;data &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;JSON&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;parse&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;msg&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;data&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;switch &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;data&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;Type&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;case &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;PlayerNumberMessage&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;:
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;myPlayer &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;data&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;PlayerNumber&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;myPlayer &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;== &lt;/span&gt;&lt;span style="background: white; color: black"&gt;0&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;info&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;&amp;lt;span style='color:red'&amp;gt;You are red.&amp;lt;/span&amp;gt;&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
                } &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;else &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;{
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;info&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;&amp;lt;span style='color:blue'&amp;gt;You are blue.&amp;lt;/span&amp;gt;&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
                }
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;

            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;case &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;PlayerPositionMessage&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;:
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;otherPlayer&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;().&lt;/span&gt;&lt;span style="background: white; color: black"&gt;yPos &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;data&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;YPos&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;draw&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;();
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;

            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;case &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;BallPositionMessage&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;:
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;ball&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;xPos &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;data&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;XPos&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;ball&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;yPos &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;data&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;YPos&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;draw&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;();
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;

            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;case &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;ScoreMessage&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;:
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;score &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;data&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;Score&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;displayScore&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;();
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
        }
    }
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Data is sent in JSON, so first thing to do is to deserialize it. Messages carry a property named Type that allows to differentiate between different kinds of data being sent. Message types include other player’s position, ball’s position, score change and a message sent when player is assigned his side (red or blue). I think this is quite self-explanatory. &lt;/p&gt;

&lt;p&gt;One more thing on client’s side to mention is sending the player’s position to server:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// register on mousemove over canvas
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;$&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;canvasSelector&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;).&lt;/span&gt;&lt;span style="background: white; color: black"&gt;mousemove&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;$&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;proxy&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;e&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// has player been initialized?
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;myPlayer &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;== -&lt;/span&gt;&lt;span style="background: white; color: black"&gt;1&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;)
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;

        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// calulate mouse vertical position relative to canvas
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;offset &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;$&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;canvas&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;).&lt;/span&gt;&lt;span style="background: white; color: black"&gt;offset&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;();
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;mouseY &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;e&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;pageY &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;- &lt;/span&gt;&lt;span style="background: white; color: black"&gt;offset&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;top&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;

        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// constraint movement
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;mouseY &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;&amp;lt; &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;playerHeight &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;/ &lt;/span&gt;&lt;span style="background: white; color: black"&gt;2&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;)
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;mouseY &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;playerHeight &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;/ &lt;/span&gt;&lt;span style="background: white; color: black"&gt;2&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;mouseY &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;&amp;gt; &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;canvas&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;height &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;- &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;playerHeight &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;/ &lt;/span&gt;&lt;span style="background: white; color: black"&gt;2&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;)
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;mouseY &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;canvas&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;height &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;- &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;playerHeight &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;/ &lt;/span&gt;&lt;span style="background: white; color: black"&gt;2&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;players&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;[&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;myPlayer&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;].&lt;/span&gt;&lt;span style="background: white; color: black"&gt;yPos &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;mouseY&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;;

        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// send message to server with new position
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;sendMessage&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;({ &lt;/span&gt;&lt;span style="background: white; color: black"&gt;YPos&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;: &lt;/span&gt;&lt;span style="background: white; color: black"&gt;mouseY &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;});

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;draw&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;();
    }, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;));&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;In reaction to mousemove over the canvas, a message with new player position is sent to the server. Sending the message:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// serializes and sends message to server
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;sendMessage&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;: &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;function &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;msg&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;!= &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;undefined&amp;quot; &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;&amp;amp;&amp;amp; &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;readyState &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;== &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;openStateConst&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;) {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;msgText &lt;/span&gt;&lt;span style="background: white; color: teal"&gt;= &lt;/span&gt;&lt;span style="background: white; color: black"&gt;JSON&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;stringify&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;msg&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;.&lt;/span&gt;&lt;span style="background: white; color: black"&gt;send&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;(&lt;/span&gt;&lt;span style="background: white; color: black"&gt;msgText&lt;/span&gt;&lt;span style="background: white; color: teal"&gt;);
        }
    },&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Quite easy and strightforward.&lt;/p&gt;

&lt;h3&gt;The server &lt;/h3&gt;

&lt;p&gt;Entry point for server code is an implementation of IHttpHandler that accepts websocket connections:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Http handler accepting web socket requests
    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongHttpHandler &lt;/span&gt;&lt;span style="background: white; color: black"&gt;: &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IHttpHandler
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public bool &lt;/span&gt;&lt;span style="background: white; color: black"&gt;IsReusable
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;get &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{ &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return false&lt;/span&gt;&lt;span style="background: white; color: black"&gt;; }
        }

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;ProcessRequest(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;HttpContext &lt;/span&gt;&lt;span style="background: white; color: black"&gt;context)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(context.IsWebSocketRequest)
            {
                &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// create a player
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;player = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();
                &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongApp&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.JoinPlayer(player);

                &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// start receiving from socket
                &lt;/span&gt;&lt;span style="background: white; color: black"&gt;context.AcceptWebSocketRequest(player.Receiver);
            }
        }
    }&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;HttpContext.IsWebSocketRequest is a new property returning true if incoming connection is a websocket request. Note, that as of now, you have to be using IIS 8 with websockets module installed. Otherwise this property always returns false. &lt;/p&gt;

&lt;p&gt;In this case we accept the connection using AcceptWebSocketRequest by providing it with a delegate, that will asynchronously take care of receiving messages. This a little confusing, because there are two different ways of doing this that you can find by browsing different blogs. The other way is to provide an instance of WebSocketHandler class. The thing is that MSDN knows nothing about such class, and neither does it know about WebSocketCollection. Strange. &lt;/p&gt;

&lt;p&gt;Anyway, the PongPlayer class representing a connection to a player looks like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Represents a player and wraps his websocket operations
    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongGame &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_game;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private object &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_syncRoot = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new object&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;AspNetWebSocketContext &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_context;

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public event &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Action&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PlayerPositionMessage&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; PlayerMoved;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public event &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Action&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; PlayerDisconnected;

        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// player vertical positon
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public int &lt;/span&gt;&lt;span style="background: white; color: black"&gt;YPos { &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;get&lt;/span&gt;&lt;span style="background: white; color: black"&gt;; &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private set&lt;/span&gt;&lt;span style="background: white; color: black"&gt;; }

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;SetGame(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongGame &lt;/span&gt;&lt;span style="background: white; color: black"&gt;game)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_game != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;throw new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();
            _game = game;
        }

        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;This method is used as delegate to accept WebSocket connection
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public async &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Task &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Receiver(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;AspNetWebSocketContext &lt;/span&gt;&lt;span style="background: white; color: black"&gt;context)
        {
            _context = context;
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket = _context.WebSocket &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;as &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;AspNetWebSocket&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
            &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// prepare buffer for reading messages
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;inputBuffer = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ArraySegment&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;byte&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new byte&lt;/span&gt;&lt;span style="background: white; color: black"&gt;[1024]);

            &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// send player number to player
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;SendMessage(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PlayerNumberMessage &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{ PlayerNumber = _game.GetPlayerIndex(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;) });

            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;try
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;while &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;true&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                {
                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// read from socket
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;result = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;await &lt;/span&gt;&lt;span style="background: white; color: black"&gt;socket.ReceiveAsync(inputBuffer, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CancellationToken&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.None);
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(socket.State != &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebSocketState&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Open)
                    {
                        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(PlayerDisconnected != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                            PlayerDisconnected(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);
                        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
                    }

                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// convert bytes to text
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;messageString = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Encoding&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.UTF8.GetString(inputBuffer.Array, 0, result.Count);
                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// only PlayerPositionMessage is expected, deserialize
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;positionMessage = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;JsonConvert&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.DeserializeObject&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PlayerPositionMessage&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(messageString);

                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// save new position and notify game
                    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;YPos = positionMessage.YPos;
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(PlayerMoved != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                        PlayerMoved(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, positionMessage);

                }
            }
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;catch &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Exception &lt;/span&gt;&lt;span style="background: white; color: black"&gt;ex)
            {
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(PlayerDisconnected != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                    PlayerDisconnected(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);
            }
        }

        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Sends message through web socket to player's rowser
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public async &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Task &lt;/span&gt;&lt;span style="background: white; color: black"&gt;SendMessage(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;object &lt;/span&gt;&lt;span style="background: white; color: black"&gt;message)
        {
            &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// serialize and send
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;messageString = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;JsonConvert&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.SerializeObject(message);
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_context != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null &lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;amp;&amp;amp; _context.WebSocket.State == &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebSocketState&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Open)
            {
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;outputBuffer = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ArraySegment&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;byte&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Encoding&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.UTF8.GetBytes(messageString));
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;await &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_context.WebSocket.SendAsync(outputBuffer, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebSocketMessageType&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Text, 
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;true&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CancellationToken&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.None);
            }
        }

        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Closes player's web socket
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Close()
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_context != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null &lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;amp;&amp;amp; _context.WebSocket.State == &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebSocketState&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Open)
            {
                _context.WebSocket.CloseOutputAsync(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebSocketCloseStatus&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.NormalClosure, 
                    &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;&amp;quot;Closing...&amp;quot;&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CancellationToken&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.None).Wait();
            }
        }
    }&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Basically we’re waiting here in asynchronous manner for messages from a player in a infinite loop. When message arrives, it is deserialized and processed on the same thread. Sending messages is initiated externally by PongGame class and is performed on different thread. &lt;/p&gt;

&lt;p&gt;The PongGame represents a game between two players and groups connections:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public enum &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;GameState
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        NotInitiated,
        WaitingForPlayer,
        InProgress
    }

    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Represents pong game between two players
    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongGame
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public const int &lt;/span&gt;&lt;span style="background: white; color: black"&gt;LeftPlayer = 0;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public const int &lt;/span&gt;&lt;span style="background: white; color: black"&gt;RightPlayer = 1;

        ... more boring constants here ...

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private object &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_syncRoot = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new object&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer&lt;/span&gt;&lt;span style="background: white; color: black"&gt;[] _players = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer&lt;/span&gt;&lt;span style="background: white; color: black"&gt;[2];
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Vector &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_ballPosition = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Vector&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(FieldWidth / 2, FieldHeight / 2);
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Vector &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_ballDirection = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Vector&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.SW;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private double &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_ballSpeed = BallStartingSpeedPixPerSecond;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private int&lt;/span&gt;&lt;span style="background: white; color: black"&gt;[] _score = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new int&lt;/span&gt;&lt;span style="background: white; color: black"&gt;[2];

        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Token used to cances ball moving task
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CancellationTokenSource &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_ballCancellationTokenSource;

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;GameState &lt;/span&gt;&lt;span style="background: white; color: black"&gt;State { &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;get&lt;/span&gt;&lt;span style="background: white; color: black"&gt;; &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private set&lt;/span&gt;&lt;span style="background: white; color: black"&gt;; }
        
        ... code here...
    }&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;When new player joins the game, JoinPlayer is called:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Joins new player to this game
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;player&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;JoinPlayer(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer &lt;/span&gt;&lt;span style="background: white; color: black"&gt;player)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;lock &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_syncRoot)
            {
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_players[LeftPlayer] != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null &lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;amp;&amp;amp; _players[RightPlayer] != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;throw new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();

                player.SetGame(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);
                player.PlayerDisconnected += OnPlayerDisconnected;
                player.PlayerMoved += OnPlayerMoved;

                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_players[LeftPlayer] == &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                {
                    _players[LeftPlayer] = player;
                    State = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;GameState&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.WaitingForPlayer;
                }
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;else
                &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                    _players[RightPlayer] = player;
                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// we have two players, so start the game
                    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;State = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;GameState&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.InProgress; 
                    StartBall();
                }
            }
        }
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;We just store players in private field. When two players join, the game starts. There is a thread that is responsible for moving the ball and broadcasting ball’s position to both players:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;StartBall()
        {
            &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// this delegete is responsible for ball moving, bouncing and counting score
            &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Action&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CancellationToken&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; ballMover = (cancellationToken) =&amp;gt;
            {
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;lastTime = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;DateTime&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Now;

                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;while &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;true&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                {
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;thisTime = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;DateTime&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Now;
                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// how many seconds elapsed since last pass
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;secondsElapsed = (thisTime - lastTime).TotalMilliseconds / 1000.0;

                    MoveBall(secondsElapsed);
                    lastTime = thisTime;

                    &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Thread&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Sleep(50);

                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// finish task if cancel requested
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(cancellationToken.IsCancellationRequested)
                        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
                }
            };

            &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// prepare cancellation token and run the task
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_ballCancellationTokenSource = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CancellationTokenSource&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();
            &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Task&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Factory.StartNew(() =&amp;gt; ballMover(_ballCancellationTokenSource.Token), 
                _ballCancellationTokenSource.Token, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;TaskCreationOptions&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.LongRunning, 
                &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;TaskScheduler&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Default);
        }

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;MoveBall(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;double &lt;/span&gt;&lt;span style="background: white; color: black"&gt;secondsElapsed)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;lock &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_syncRoot)
            {
                &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// calculate new position
                &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_ballPosition += _ballDirection * (_ballSpeed * secondsElapsed);

                ...checking &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;for &lt;/span&gt;&lt;span style="background: white; color: black"&gt;collision and bouncing the ball..

                &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// check for scores
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_ballPosition.X &amp;lt; 0 || _ballPosition.X &amp;gt; FieldWidth)
                {
                    _score[_ballPosition.X &amp;lt; 0 ? RightPlayer : LeftPlayer]++;
                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// broadcast score message
                    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;BroadcastMessage(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ScoreMessage &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{ Score = _score });

                    ...reseting ball position...
                }

                &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// broadcast ball position message
                &lt;/span&gt;&lt;span style="background: white; color: black"&gt;BroadcastMessage(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;BallPositionMessage &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{ XPos = (&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;int&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)_ballPosition.X, 
                    YPos = (&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;int&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)_ballPosition.Y });
            }
        }

        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Sends a message to both players
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;message&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;BroadcastMessage(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;object &lt;/span&gt;&lt;span style="background: white; color: black"&gt;message)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;foreach &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;player &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;in &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_players)
            {
                player.SendMessage(message);
            }
        }&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;One more interesing thing about PongGame is the way it reacts to player events:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;OnPlayerMoved(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer &lt;/span&gt;&lt;span style="background: white; color: black"&gt;player, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PlayerPositionMessage &lt;/span&gt;&lt;span style="background: white; color: black"&gt;position)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;otherPlayer = OtherPlayer(player);

            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(otherPlayer != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
            {
                &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// send new player position to the other player
                &lt;/span&gt;&lt;span style="background: white; color: black"&gt;otherPlayer.SendMessage(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PlayerPositionMessage &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{ YPos = player.YPos });
            }
        }

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;OnPlayerDisconnected(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer &lt;/span&gt;&lt;span style="background: white; color: black"&gt;player)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;lock &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_syncRoot)
            {
                &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// stop the ball moving task
                &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_ballCancellationTokenSource.Cancel();
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;otherPlayer = OtherPlayer(player);

                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(otherPlayer != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                {
                    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// close connection to other player, which means game is over
                    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;otherPlayer.Close();
                }
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(GameOver != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                    GameOver(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);
            }
        }&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The last bit here is the PongApp class which basically is a collection of ongoing games.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Aggregates all games
    &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public static class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongApp
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private static object &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_syncRoot = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new object&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private static &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;List&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongGame&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; _games;

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;static &lt;/span&gt;&lt;span style="background: white; color: black"&gt;PongApp()
        {
            _games = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;List&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongGame&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;();
        }
        
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="background: white; color: green"&gt;Joins new player to existing game or creates new one 
        &lt;/span&gt;&lt;span style="background: white; color: gray"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;player&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public static void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;JoinPlayer(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongPlayer &lt;/span&gt;&lt;span style="background: white; color: black"&gt;player)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;lock &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_syncRoot)
            {
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;game = _games.Where(g =&amp;gt; g.State == &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;GameState&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.WaitingForPlayer)
                    .FirstOrDefault();
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(game == &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                {
                    game = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongGame&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();
                    _games.Add(game);
                    game.GameOver += OnGameOver;
                }
                game.JoinPlayer(player);
            }
        }

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private static void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;OnGameOver(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;PongGame &lt;/span&gt;&lt;span style="background: white; color: black"&gt;game)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;lock &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(_syncRoot)
            {
                _games.Remove(game);
            }
        }
    }&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;And that would be pretty much it. Again, the code is &lt;a href="http://marcinbudny.com/files/Pong.zip"&gt;here&lt;/a&gt;. &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-4205701252078377153?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/4205701252078377153/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=4205701252078377153' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4205701252078377153'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4205701252078377153'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2011/10/websockets-in-net-45-simple-game.html' title='WebSockets in .NET 4.5: a simple game'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh5.ggpht.com/-WV1x5ppwQdc/TpdHfde8RPI/AAAAAAAAAVw/TbYqm1JTq18/s72-c/image%25255B4%25255D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-9063007614323606776</id><published>2011-10-02T19:28:00.001+02:00</published><updated>2011-10-02T19:28:12.370+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='NoSQL'/><category scheme='http://www.blogger.com/atom/ns#' term='tutorial'/><title type='text'>Your first app with CouchDB and relax-net</title><content type='html'>&lt;p&gt;This is a tutorial that will show you how to create a simple tagged gallery ASP.NET MVC web app using CouchDB as a data store and relax-net as data access layer. It requires that you understand basic concepts behind CouchDB and have knowledge of ASP.NET MVC.&amp;#160; I’ll be focusing mainly on CouchDB related code in the post, but you can download &lt;a href="http://marcinbudny.com/files/TaggedGallery.zip"&gt;full source here&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;Preparation&lt;/h3&gt;  &lt;p&gt;In order to start, you first have to have a CouchDB up and running. I suggest you grab the community edition of &lt;a href="http://www.couchbase.com/products-and-services/couchbase-single-server"&gt;Couchbase Single Server&lt;/a&gt; for Windows. After installing and making sure that CouchbaseServer service is started, you can visit &lt;a href="http://localhost:5984/_utils/index.html"&gt;http://localhost:5984/_utils/index.html&lt;/a&gt; address to run the Futon – CouchDB management interface. Create new database named tagged_gallery. &lt;/p&gt;  &lt;p&gt;Create new ASP.NET MVC 3 project and call it TaggedGallery. Download and reference &lt;a href="http://code.google.com/p/relax-net/"&gt;relax-net&lt;/a&gt;. Unfortunately it’s not available as NuGet package, so either grab the zipped release or just build it from source.&lt;/p&gt;  &lt;h3&gt;What do we build?&lt;/h3&gt;  &lt;p&gt;A simple gallery that allows registered users to upload pictures that all visitors can browse. Each picture can have multiple tags associated with it. All tags related to currently visible pictures display on the side along with count of pictures with given tag. If you click a tag, you can browse all pictures with that tag.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh5.ggpht.com/-v8QnwXX1Eew/ToifKNZEIgI/AAAAAAAAAVk/qoH1rcZpWww/s1600-h/image%25255B10%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://lh6.ggpht.com/-D7kV95FybTw/ToifK5V6L1I/AAAAAAAAAVo/VZfUlK_gEVY/image_thumb%25255B4%25255D.png?imgmax=800" width="484" height="398" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;h3&gt;Infrastructure&lt;/h3&gt;  &lt;p&gt;relax-net takes some design patterns after NHibernate and one of them is a concept of session. Session is something that caches your entities during its lifetime and takes care that when you get a certain entity twice, you’ll get the same object reference. As with NHibernate, the best usage in web application is session per request pattern, which means you open session on BeginRequest and close it (or “return” in relax-net) on EndRequest. We have to have some means of managing the session and accessing it. The SessionManager component ‘s purpose is just that.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ISessionManager
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;void &lt;/span&gt;SetConnection(&lt;span style="color: #2b91af"&gt;Connection &lt;/span&gt;connection);
    
    &lt;span style="color: blue"&gt;void &lt;/span&gt;OpenSession(&lt;span style="color: blue"&gt;string &lt;/span&gt;database);
    &lt;span style="color: blue"&gt;void &lt;/span&gt;ReturnSession();
    &lt;span style="color: #2b91af"&gt;Session &lt;/span&gt;GetCurrentSession();

    &lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;&amp;lt;TEntity&amp;gt; GetRepositoryFor&amp;lt;TEntity&amp;gt;() &lt;span style="color: blue"&gt;where &lt;/span&gt;TEntity : &lt;span style="color: blue"&gt;class&lt;/span&gt;;
    &lt;span style="color: #2b91af"&gt;Query&lt;/span&gt;&amp;lt;TEntity&amp;gt; GetQueryFor&amp;lt;TEntity&amp;gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;design, &lt;span style="color: blue"&gt;string &lt;/span&gt;view, &lt;span style="color: blue"&gt;bool &lt;/span&gt;reduce) &lt;span style="color: blue"&gt;where &lt;/span&gt;TEntity : &lt;span style="color: blue"&gt;class&lt;/span&gt;;
}&lt;/pre&gt;

&lt;p&gt;SetConnection initializes the SessionManager by providing Connection which basically points to CouchDB server. OpenSession and ReturnSession are self explanatory. In terms of relax-net you don’t “close” the session, but rather return it to the pool. GetCurrentSession allows you to get an open session for current request from any point in your app having access to SessionManager. There are also helper methods GetRepositoryFor&amp;lt;TEntity&amp;gt; (which creates and initializes a relax-net repository for given entity type) and GetQueryFor&amp;lt;TEntity&amp;gt; (which creates and initializes a query – query is a wrapper over CouchDB view). Now for the implementation:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SessionManager &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ISessionManager
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IUnityContainer &lt;/span&gt;_container;
    
    &lt;span style="color: blue"&gt;public &lt;/span&gt;SessionManager(&lt;span style="color: #2b91af"&gt;IUnityContainer &lt;/span&gt;container)
    {
        _container = container;
    }
    
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;SetConnection(&lt;span style="color: #2b91af"&gt;Connection &lt;/span&gt;connection)
    {
        &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.Requires(connection != &lt;span style="color: blue"&gt;null&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Connection cannot be null&amp;quot;&lt;/span&gt;);

        connection.Observers.Add(c =&amp;gt; _container.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;AuditObserver&lt;/span&gt;&amp;gt;());
        connection.Observers.Add(c =&amp;gt; _container.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;TypeAssigningObserver&lt;/span&gt;&amp;gt;());
        &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Application[&lt;span style="color: #a31515"&gt;&amp;quot;DbConnection&amp;quot;&lt;/span&gt;] = connection;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Session &lt;/span&gt;GetCurrentSession()
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;DoGetSession();
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;OpenSession(&lt;span style="color: blue"&gt;string &lt;/span&gt;database)
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;connection = &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Application[&lt;span style="color: #a31515"&gt;&amp;quot;DbConnection&amp;quot;&lt;/span&gt;] &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Connection&lt;/span&gt;;
        &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.Assert(connection != &lt;span style="color: blue"&gt;null&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Connection was not set&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue"&gt;var &lt;/span&gt;session = connection.CreateSession(database);
        &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Items[&lt;span style="color: #a31515"&gt;&amp;quot;DbSession&amp;quot;&lt;/span&gt;] = session;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;ReturnSession()
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;session = DoGetSession();
        session.Connection.ReturnSession(session);
    }

    &lt;span style="color: blue"&gt;private static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Session &lt;/span&gt;DoGetSession()
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;session = &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Items[&lt;span style="color: #a31515"&gt;&amp;quot;DbSession&amp;quot;&lt;/span&gt;] &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Session&lt;/span&gt;;
        &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.Assert(session != &lt;span style="color: blue"&gt;null&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Session was not opened&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue"&gt;return &lt;/span&gt;session;
    }


    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;&amp;lt;TEntity&amp;gt; GetRepositoryFor&amp;lt;TEntity&amp;gt;() &lt;span style="color: blue"&gt;where &lt;/span&gt;TEntity : &lt;span style="color: blue"&gt;class
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;var &lt;/span&gt;resolverOverride = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ParameterOverride&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;sx&amp;quot;&lt;/span&gt;, DoGetSession());
        &lt;span style="color: blue"&gt;return &lt;/span&gt;_container.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;&amp;lt;TEntity&amp;gt;&amp;gt;(resolverOverride);
    }


    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Query&lt;/span&gt;&amp;lt;TEntity&amp;gt; GetQueryFor&amp;lt;TEntity&amp;gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;design, &lt;span style="color: blue"&gt;string &lt;/span&gt;view, &lt;span style="color: blue"&gt;bool &lt;/span&gt;reduce) &lt;span style="color: blue"&gt;where &lt;/span&gt;TEntity : &lt;span style="color: blue"&gt;class
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Query&lt;/span&gt;&amp;lt;TEntity&amp;gt;(DoGetSession(), design, view, reduce);
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see the connection is stored in HttpApplication (as it is shared for all requests) and session is stored in HttpContext (as it is private to a request). As might also noticed I’m using Unity as dependency injection framework. You can grab it by NuGet.&lt;/p&gt;

&lt;p&gt;All relax-net entities have to inherit from Document base class, which has some basic properties like Id and Revision. By default Id for new document is created in form of [lowercase type name]-[guid]. We will introduce one more layer over the Document class in order to additionally store easily accessible type name in all entities. It will also allow us to add some common behavior for all our entities if we need that later. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BaseEntity &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;Document
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Type { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;There’s also the IAuditable interface which will allow us to track who and when created or modified the entity.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IAuditable
&lt;/span&gt;{
    &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;? CreatedDate { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;? LastModifiedDate { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: #2b91af"&gt;Reference&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;User&lt;/span&gt;&amp;gt; CreatedBy { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: #2b91af"&gt;Reference&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;User&lt;/span&gt;&amp;gt; LastModifiedBy { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;Reference&amp;lt;TEntity&amp;gt; is relax-net way to associate different entities. Using reference in this case you can traverse from one entity to another dotting your way through. The references are lazily loaded, which means first time when you access the reference, relax-net will request appropriate entity it from CouchDB.&lt;/p&gt;

&lt;p&gt;We don’t want to worry about having to fill fields from IAuditable or BaseEntity by hand every time an entity is created. Fortunately we can create observers that will react to different entity lifetime events. In SessionManager the connection is initialized with two observers: AuditObserver and TypeAssigningObserver.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeAssigningObserver &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IObserver
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AfterDelete(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AfterLoad(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AfterSave(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition &lt;/span&gt;BeforeDelete(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition&lt;/span&gt;.Continue;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition &lt;/span&gt;BeforeSave(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;baseEntity = entity &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BaseEntity&lt;/span&gt;;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(baseEntity != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        {
            baseEntity.Type = baseEntity.GetType().Name.ToLowerInvariant();
        }
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition&lt;/span&gt;.Continue;
    }
}&lt;/pre&gt;

&lt;br /&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;AuditObserver &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IObserver
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ISessionManager &lt;/span&gt;_sessionManager;
    
    &lt;span style="color: blue"&gt;public &lt;/span&gt;AuditObserver(&lt;span style="color: #2b91af"&gt;ISessionManager &lt;/span&gt;sessionManager)
    {
        _sessionManager = sessionManager;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AfterDelete(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AfterLoad(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;AfterSave(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition &lt;/span&gt;BeforeDelete(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition&lt;/span&gt;.Continue;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition &lt;/span&gt;BeforeSave(&lt;span style="color: blue"&gt;object &lt;/span&gt;entity, &lt;span style="color: #2b91af"&gt;Document &lt;/span&gt;document)
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;auditable = entity &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IAuditable&lt;/span&gt;;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(auditable != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        {
            &lt;span style="color: green"&gt;// create lazy references instead of weak references to overcome problems while running under debbuger
            // no perf penalty
            
            // if revision is empty, this document is being created
            &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;string&lt;/span&gt;.IsNullOrEmpty(document.Revision))
            {
                auditable.CreatedDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Now;
                auditable.CreatedBy = &lt;span style="color: #2b91af"&gt;Reference&lt;/span&gt;.To&amp;lt;&lt;span style="color: #2b91af"&gt;User&lt;/span&gt;&amp;gt;(_sessionManager.GetCurrentSession(), 
                    &lt;span style="color: #a31515"&gt;&amp;quot;user-&amp;quot; &lt;/span&gt;+ &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.User.Identity.Name);
            }
            auditable.LastModifiedDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Now;
            auditable.LastModifiedBy = &lt;span style="color: #2b91af"&gt;Reference&lt;/span&gt;.To&amp;lt;&lt;span style="color: #2b91af"&gt;User&lt;/span&gt;&amp;gt;(_sessionManager.GetCurrentSession(),
                &lt;span style="color: #a31515"&gt;&amp;quot;user-&amp;quot; &lt;/span&gt;+ &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.User.Identity.Name);
        }
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Disposition&lt;/span&gt;.Continue;
    }
}&lt;/pre&gt;

&lt;p&gt;As you might already guessed we won’t be using a standard Id format for users, but rather something like user-[login].&lt;/p&gt;

&lt;h3&gt;Model and views&lt;/h3&gt;

&lt;p&gt;Our model will consist of two entities: Picture and User.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Picture &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;BaseEntity&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IAuditable&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IHasAttachments
&lt;/span&gt;{        
    [&lt;span style="color: #2b91af"&gt;Required&lt;/span&gt;(ErrorMessage = &lt;span style="color: #a31515"&gt;&amp;quot;Title is required&amp;quot;&lt;/span&gt;)]
    [&lt;span style="color: #2b91af"&gt;StringLength&lt;/span&gt;(50, ErrorMessage = &lt;span style="color: #a31515"&gt;&amp;quot;Cannot be longer than 50 chars&amp;quot;&lt;/span&gt;)]
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Title { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;ContentType { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; Tags { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;? CreatedDate { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;? LastModifiedDate { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Reference&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;User&lt;/span&gt;&amp;gt; CreatedBy { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Reference&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;User&lt;/span&gt;&amp;gt; LastModifiedBy { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Attachments &lt;/span&gt;Attachments { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;User &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;BaseEntity
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Login { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Email { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;PasswordHash { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;As you can see, Picture has a collection of tags, but tag is not a separate entity as it would be in normalized relational model. Tag collection will be stored within picture document. The IHasAttachements is mandatory for relax-net entities, that have binary attachments associated with them (this scenario is supported by CouchDB).&lt;/p&gt;

&lt;p&gt;There are also additional classes used to provide a strongly typed model for the views.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TagWithCount
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public string &lt;/span&gt;Tag { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;Count { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SinglePictureModel
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Picture &lt;/span&gt;Picture { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TagWithCount&lt;/span&gt;[] Tags { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PictureListModel
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Picture&lt;/span&gt;[] Pictures { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TagWithCount&lt;/span&gt;[] Tags { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;To query our database efficiently and get required data we have to implement some views. Views will be stored in _design/picture design document, which will help relax-net to load them basing on entity type name. You can edit the views using Futon. First of them named by-date will allow us to list all pictures in database ordered by creation date:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #006400"&gt;// by-date

// map
&lt;/span&gt;&lt;span style="color: blue"&gt;function &lt;/span&gt;(doc) {
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(doc.Type == &lt;span style="color: maroon"&gt;'picture'&lt;/span&gt;)
        emit(doc.CreatedDate, doc._id);
}&lt;/pre&gt;

&lt;p&gt;This view returns CreatedDate picture property as a key, which means that returned values (ids) will be sorted by this property. Second view named by-tag-date will allow us to list pictures with given tag ordered by creation date.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #006400"&gt;// by-tag-date

//map
&lt;/span&gt;&lt;span style="color: blue"&gt;function &lt;/span&gt;(doc) {
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(doc.Type == &lt;span style="color: maroon"&gt;'picture'&lt;/span&gt;)
        &lt;span style="color: blue"&gt;for &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;doc.Tags)
            emit([doc.Tags[i], doc.CreatedDate], doc._id);
}&lt;/pre&gt;

&lt;p&gt;This view emits composite key (an array of values) where first element is the tag, and second is the creation date. This means CouchDB will sort returned values first by tag, then by creation date. By putting constraints on returned key range we’ll be able to select only pictures with given tag. The last view named tags-with-count will allow us to get information of number of pictures assigned a given tag.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #006400"&gt;// tags-with-count

// map
&lt;/span&gt;&lt;span style="color: blue"&gt;function &lt;/span&gt;(doc) {
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(doc.Type == &lt;span style="color: maroon"&gt;'picture'&lt;/span&gt;)
        &lt;span style="color: blue"&gt;for &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;doc.Tags)
            emit(doc.Tags[i], 1);
}

&lt;span style="color: #006400"&gt;// reduce
&lt;/span&gt;&lt;span style="color: blue"&gt;function &lt;/span&gt;(keys, values, rereduce) {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;sum(values);
}&lt;/pre&gt;

&lt;p&gt;The map part emits tag as a key and 1 as value. The reduce part takes all the “1s” returned for given tag and sums them. As a result we get picture count for that tag. You can try out those views in Futon.&lt;/p&gt;

&lt;h3&gt;The PictureController&lt;/h3&gt;

&lt;p&gt;Last really interesting bit is the PictureController which will cover all of the picture related actions. Its general structure is as follows:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PictureController &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;Controller
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public const int &lt;/span&gt;PageSize = 6;

    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SessionManager &lt;/span&gt;_sessionManager;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;PictureController(&lt;span style="color: #2b91af"&gt;SessionManager &lt;/span&gt;sessionManager)
    {
        _sessionManager = sessionManager;
    }

    ...
}&lt;/pre&gt;

&lt;p&gt;First, actions for adding a new picture.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Displays picture adding form
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;Add()
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;View();
} 

&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Saves new picture to db
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;picture&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;The picture desciption&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;fileUpload&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;The file upload&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;[&lt;span style="color: #2b91af"&gt;HttpPost&lt;/span&gt;]
[&lt;span style="color: #2b91af"&gt;ValidateAntiForgeryToken&lt;/span&gt;]
&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;Add(&lt;span style="color: #2b91af"&gt;Picture &lt;/span&gt;picture, &lt;span style="color: blue"&gt;string &lt;/span&gt;commaTagList, &lt;span style="color: #2b91af"&gt;HttpPostedFileBase &lt;/span&gt;fileUpload)
{
    &lt;span style="color: blue"&gt;try
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(fileUpload == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        {
            ModelState.AddModelError(&lt;span style="color: #a31515"&gt;&amp;quot;fileUpload&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Choose a file to upload&amp;quot;&lt;/span&gt;);
            &lt;span style="color: blue"&gt;return &lt;/span&gt;View();
        }
        
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(!fileUpload.ContentType.StartsWith(&lt;span style="color: #a31515"&gt;&amp;quot;image/&amp;quot;&lt;/span&gt;))
        {
            ModelState.AddModelError(&lt;span style="color: #a31515"&gt;&amp;quot;fileUpload&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;File has to be an image&amp;quot;&lt;/span&gt;);
            &lt;span style="color: blue"&gt;return &lt;/span&gt;View();
        }

        &lt;span style="color: blue"&gt;if &lt;/span&gt;(!&lt;span style="color: blue"&gt;string&lt;/span&gt;.IsNullOrWhiteSpace(commaTagList))
        {
            picture.Tags = commaTagList.Split(&lt;span style="color: #a31515"&gt;','&lt;/span&gt;)
                .Select(tag =&amp;gt; tag.Trim())
                .Where(tag =&amp;gt; !&lt;span style="color: blue"&gt;string&lt;/span&gt;.IsNullOrWhiteSpace(tag))
                .ToList();
        }

        &lt;span style="color: blue"&gt;var &lt;/span&gt;repo = _sessionManager.GetRepositoryFor&amp;lt;&lt;span style="color: #2b91af"&gt;Picture&lt;/span&gt;&amp;gt;();
        repo.Save(picture);
        repo.Attach(picture, fileUpload);

        &lt;span style="color: blue"&gt;return &lt;/span&gt;RedirectToAction(&lt;span style="color: #a31515"&gt;&amp;quot;Single&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;new &lt;/span&gt;{ id = picture.Id });
    }
    &lt;span style="color: blue"&gt;catch&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Exception &lt;/span&gt;e)
    {
        ModelState.AddModelError(&lt;span style="color: #a31515"&gt;&amp;quot;&amp;quot;&lt;/span&gt;, e);
        &lt;span style="color: blue"&gt;return &lt;/span&gt;View();
    }
}&lt;/pre&gt;

&lt;p&gt;User provides picture title, comma separated tag list and selects a file to upload. By using appropriate repository we save the document to the database and then attach a binary file with the picture. Note that saving a document and creating an attachment are two separate operations and they are not included in any transaction. Lack of transactions is a problem with CouchDB as &lt;a href="http://marcinbudny.blogspot.com/2011/10/few-thoughts-on-couchdb.html"&gt;I wrote earlier&lt;/a&gt;. In real world application you’d probably want some compensation code, that will remove picture document if creating attachment fails.&lt;/p&gt;

&lt;p&gt;Now the action that displays a single picture with a tag list on its side.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;Single(&lt;span style="color: blue"&gt;string &lt;/span&gt;id)
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;repo = _sessionManager.GetRepositoryFor&amp;lt;&lt;span style="color: #2b91af"&gt;Picture&lt;/span&gt;&amp;gt;();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;picture = repo.TryGet(id);
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(picture == &lt;span style="color: blue"&gt;null &lt;/span&gt;|| picture.Attachments.Count == 0)
    {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HttpNotFoundResult&lt;/span&gt;();
    }

    &lt;span style="color: blue"&gt;var &lt;/span&gt;model = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SinglePictureModel
    &lt;/span&gt;{
        Picture = picture,
        Tags = picture.Tags != &lt;span style="color: blue"&gt;null &lt;/span&gt;? LoadTagCounts(picture.Tags.ToArray()) : &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TagWithCount&lt;/span&gt;[] { }
    };

    &lt;span style="color: blue"&gt;return &lt;/span&gt;View(model);
}

&lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TagWithCount&lt;/span&gt;[] LoadTagCounts(&lt;span style="color: blue"&gt;params string&lt;/span&gt;[] tags)
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;tagsWithCount = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;TagWithCount&lt;/span&gt;&amp;gt;();
    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;tag &lt;span style="color: blue"&gt;in &lt;/span&gt;tags)
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;query = _sessionManager.GetQueryFor&amp;lt;&lt;span style="color: #2b91af"&gt;TagWithCount&lt;/span&gt;&amp;gt;(&lt;span style="color: #a31515"&gt;&amp;quot;picture&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;tags-with-count&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;true&lt;/span&gt;)
            .All().Exactly(tag);
        &lt;span style="color: blue"&gt;var &lt;/span&gt;result = query.Execute();

        &lt;span style="color: blue"&gt;if&lt;/span&gt;(result != &lt;span style="color: blue"&gt;null &lt;/span&gt;&amp;amp;&amp;amp; result.Rows.Length &amp;gt; 0)
            tagsWithCount.Add(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TagWithCount &lt;/span&gt;{ Tag = tag, Count = &lt;span style="color: blue"&gt;int&lt;/span&gt;.Parse(result.Rows[0].Value.ToString()) });
    }

    &lt;span style="color: blue"&gt;return &lt;/span&gt;tagsWithCount.ToArray();
}&lt;/pre&gt;

&lt;p&gt;We load the picture document using TryGet(id) method od picture repository. Getting a document by its id doesn’t require creating any additional view. Then for all tags associated with this picture we want to load number of pictures under given tag. To do this we query previously created tags-with-count view and constrain returned key range to one tag. We query CouchDB as many times as there are tags, which is not very efficient. There is a feature in CouchDB that allows to load multiple keys with one go to the database. Unfortunately realx-net doesn’t currently support this feature. I sent the library’s author a patch for that, but as of now I didn’t receive any answer.&lt;/p&gt;

&lt;p&gt;Next action sends the actual picture file to user’s browser.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Sends picture file to browser
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;id&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;Id of the picture&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;Show(&lt;span style="color: blue"&gt;string &lt;/span&gt;id)
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;repo = _sessionManager.GetRepositoryFor&amp;lt;&lt;span style="color: #2b91af"&gt;Picture&lt;/span&gt;&amp;gt;();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;picture = repo.TryGet(id);
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(picture == &lt;span style="color: blue"&gt;null &lt;/span&gt;|| picture.Attachments.Count == 0)
    {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HttpNotFoundResult&lt;/span&gt;();
    }

    &lt;span style="color: blue"&gt;var &lt;/span&gt;att = picture.Attachments.First().Value;
    &lt;span style="color: blue"&gt;return &lt;/span&gt;File(att.LoadBytes(), att.ContentType);
}&lt;/pre&gt;

&lt;p&gt;In this action we download the image file to the memory and then stream it to the user. There is another way to do this. You could have user’s browser download the file directly from CouchDB by providing it with appropriate URL. But a lot of security issues arise with this approach, so here I decided to download the file to web application’s memory first.&lt;/p&gt;

&lt;p&gt;Next action lists all pictures in our gallery.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Lists all pictures
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;page&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;Page number&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;Index(&lt;span style="color: blue"&gt;int&lt;/span&gt;? page)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(page == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        page = 1;
    ViewBag.Page = page.Value;

    &lt;span style="color: blue"&gt;var &lt;/span&gt;pictureQuery = _sessionManager.GetQueryFor&amp;lt;&lt;span style="color: #2b91af"&gt;Picture&lt;/span&gt;&amp;gt;(&lt;span style="color: #a31515"&gt;&amp;quot;picture&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;by-date&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;false&lt;/span&gt;)
        .Skip((page.Value - 1) * PageSize)
        .Limit(PageSize)
        .Descending()
        .WithDocuments();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;result = pictureQuery.Execute();

    ViewBag.HasMore = result.Total &amp;gt; (page.Value * PageSize);

    &lt;span style="color: blue"&gt;var &lt;/span&gt;pictures = result.Rows.Select(r =&amp;gt; r.Entity).ToArray();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;tags = pictures.Where(p =&amp;gt; p.Tags != &lt;span style="color: blue"&gt;null&lt;/span&gt;).SelectMany(p =&amp;gt; p.Tags)
        .Distinct().OrderBy(tag =&amp;gt; tag).ToArray();

    &lt;span style="color: blue"&gt;var &lt;/span&gt;model = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PictureListModel
    &lt;/span&gt;{
        Pictures = pictures,
        Tags = LoadTagCounts(tags)

    };

    &lt;span style="color: blue"&gt;return &lt;/span&gt;View(model);
}&lt;/pre&gt;


&lt;p&gt;The by-date vie is used and there is paging using Skip() and Limit(). The Total property of query result stores number of all rows in queried view. The value of the view is merely a document id, so we also need to download rest of the document. We could query for each picture separately, which isn’t very efficient. Fortunately there is also option to download whole document related to view entry along with that entry by using WithDocuments().&lt;/p&gt;

&lt;p&gt;Next action lists pictures under given tag.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Lists pictures uder given tag
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;tag&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;The tag&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;page&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;Page number&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;Tag(&lt;span style="color: blue"&gt;string &lt;/span&gt;tag, &lt;span style="color: blue"&gt;int&lt;/span&gt;? page)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: blue"&gt;string&lt;/span&gt;.IsNullOrWhiteSpace(tag))
        &lt;span style="color: blue"&gt;return &lt;/span&gt;RedirectToAction(&lt;span style="color: #a31515"&gt;&amp;quot;Index&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;new &lt;/span&gt;{ page = 1 });
    
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(page == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        page = 1;
    ViewBag.Page = page.Value;

    &lt;span style="color: blue"&gt;var &lt;/span&gt;pictureQuery = _sessionManager.GetQueryFor&amp;lt;&lt;span style="color: #2b91af"&gt;Picture&lt;/span&gt;&amp;gt;(&lt;span style="color: #a31515"&gt;&amp;quot;picture&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;by-tag-date&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;false&lt;/span&gt;)
        .Skip((page.Value - 1) * PageSize)
        .Limit(PageSize)
        .Descending()
        .From(&lt;span style="color: blue"&gt;new string&lt;/span&gt;[] { tag, &lt;span style="color: #a31515"&gt;&amp;quot;Z&amp;quot; &lt;/span&gt;}).To(&lt;span style="color: blue"&gt;new string&lt;/span&gt;[] { tag })
        .WithDocuments();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;result = pictureQuery.Execute();

    &lt;span style="color: blue"&gt;var &lt;/span&gt;total = LoadTagCounts(tag)[0].Count;

    ViewBag.HasMore = total &amp;gt; (page.Value * PageSize);

    &lt;span style="color: blue"&gt;var &lt;/span&gt;pictures = result.Rows.Select(r =&amp;gt; r.Entity).ToArray();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;tags = pictures.Where(p =&amp;gt; p.Tags != &lt;span style="color: blue"&gt;null&lt;/span&gt;).SelectMany(p =&amp;gt; p.Tags).Distinct().OrderBy(t =&amp;gt; t).ToArray();

    &lt;span style="color: blue"&gt;var &lt;/span&gt;model = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PictureListModel
    &lt;/span&gt;{
        Pictures = pictures,
        Tags = LoadTagCounts(tags)

    };

    &lt;span style="color: blue"&gt;return &lt;/span&gt;View(&lt;span style="color: #a31515"&gt;&amp;quot;Index&amp;quot;&lt;/span&gt;, model);
}&lt;/pre&gt;

&lt;p&gt;Two interesting things here. First, we can’t use result.Total in order to employ paging since we don’t want number of all entries in the view, but rather the number of pictures with given tag. For this we use LoadTagCounts() helper method. Second thing is the way we constraint the key range loaded from by-tag-date view. Suppose we have tags like “kittens”, “puppies” and “zebras”. Suppose we load all keys from [“puppies”] to [“puppies”, “Z”].&amp;#160; [“puppies”] is after all keys like [“kittens”, date] and before all keys like [“puppies”, date]. [“puppies”, “Z”] is after all keys like [“puppies”, date] (because no date starts with letter “Z”) and just before entries like [“zebras”, “date”]. This may be hard to grasp at first…&lt;/p&gt;

&lt;p&gt;Finally, the action to delete a picture. Only the uploader can delete the picture.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: gray"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color: green"&gt;Deletes the picture
&lt;/span&gt;&lt;span style="color: gray"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;id&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green"&gt;Picture id&lt;/span&gt;&lt;span style="color: gray"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;[&lt;span style="color: #2b91af"&gt;HttpPost&lt;/span&gt;]
[&lt;span style="color: #2b91af"&gt;ValidateAntiForgeryToken&lt;/span&gt;]
&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;Delete(&lt;span style="color: blue"&gt;string &lt;/span&gt;id)
{
    &lt;span style="color: blue"&gt;try
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;var &lt;/span&gt;repo = _sessionManager.GetRepositoryFor&amp;lt;&lt;span style="color: #2b91af"&gt;Picture&lt;/span&gt;&amp;gt;();
        &lt;span style="color: blue"&gt;var &lt;/span&gt;picture = repo.TryGet(id);
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(picture == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
        {
            &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HttpNotFoundResult&lt;/span&gt;();
        }

        &lt;span style="color: blue"&gt;if &lt;/span&gt;(!picture.CreatedBy.Value.Login.Equals(HttpContext.User.Identity.Name, &lt;span style="color: #2b91af"&gt;StringComparison&lt;/span&gt;.InvariantCultureIgnoreCase))
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;RedirectToAction(&lt;span style="color: #a31515"&gt;&amp;quot;Single&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;new &lt;/span&gt;{ id = id });
        }

        repo.Delete(picture);
 
        &lt;span style="color: blue"&gt;return &lt;/span&gt;RedirectToAction(&lt;span style="color: #a31515"&gt;&amp;quot;Index&amp;quot;&lt;/span&gt;);
    }
    &lt;span style="color: blue"&gt;catch
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;return &lt;/span&gt;RedirectToAction(&lt;span style="color: #a31515"&gt;&amp;quot;Single&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;new &lt;/span&gt;{ id = id });
    }
}&lt;/pre&gt;

&lt;h3&gt;&amp;#160;&lt;/h3&gt;

&lt;h3&gt;Wrapping it up&lt;/h3&gt;

&lt;p&gt;There things like views, authentication, routes and setup in Global.asax that I won’t be covering here in the post, but if you’re interested, &lt;a href="http://marcinbudny.com/files/TaggedGallery.zip"&gt;grab the source&lt;/a&gt;. 

  &lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-9063007614323606776?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/9063007614323606776/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=9063007614323606776' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/9063007614323606776'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/9063007614323606776'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2011/10/your-first-app-with-couchdb-and-relax.html' title='Your first app with CouchDB and relax-net'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh6.ggpht.com/-D7kV95FybTw/ToifK5V6L1I/AAAAAAAAAVo/VZfUlK_gEVY/s72-c/image_thumb%25255B4%25255D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-3622233753868927901</id><published>2011-10-01T15:50:00.001+02:00</published><updated>2011-10-11T23:34:25.255+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='NoSQL'/><title type='text'>Few thoughts on CouchDB</title><content type='html'>&lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;// EDIT: See &lt;a href="http://marcinbudny.blogspot.com/2011/10/your-first-app-with-couchdb-and-relax.html"&gt;my post&lt;/a&gt; with tutorial of CouchDB + relax-net usage to build simple tagged gallery in ASP.NET MVC&lt;/p&gt;  &lt;p&gt;Apache CouchDB is one of the most popular NoSQL document database engines out there. In this post I would like to make a quick comparison to &lt;a href="http://marcinbudny.blogspot.com/2011/03/few-thoughts-on-ravendb.html"&gt;RavenDb&lt;/a&gt; as seen with .NET developer eyes.&lt;/p&gt;  &lt;h3&gt;Architecture&lt;/h3&gt;  &lt;p&gt;Again, we’re talking about document database, which means, that structure of data stored is very elastic and there is no referential integrity. If you want to keep your data pieces in some particular relation to each other, it’s up to your code to enforce this relations. Yet the data you store is not a blob understandable only to your application, but rather has document semantics, which means you can access particular properties of a document at database level. As with RavenDb, database can’t tell your entities apart, it’s up to client to store entity metadata in some understandable form.&lt;/p&gt;  &lt;p&gt;CouchDB exposes REST API and is heavily javascript based. Documents are transferred as JSON objects. All map-reduce queries, validation functions and show functions are written in javascript. Javascript is not my favourite language, but I must say, in case of CouchDB it serves its purpose well. Still, using javascript in your database is something a DBA has to get used to :)&lt;/p&gt;  &lt;p&gt;CouchDB doesn’t support transactions. It uses optimistic concurrency model which allows to avoid some cases when your database might enter inconsistent state, but if your code has a lot of places where multiple db operations have to either pass or fail as a group, then working with CouchDB will require a lot of extra work (for example implementing compensation code). This is a sacrifice CouchDB makes to gain performance and scalability.&lt;/p&gt;  &lt;p&gt;What’s quite interesting, CouchDB allows you to write so called validation functions (validate data before data operations) and show functions (format a return data in user readable form – ex. HTML). Thanks to that, you could implement whole application using nothing more than a CouchDB itself. I guess that would rarely be the case if you are implementing something more than a simple blog, because you’d want to use a solid framework like ASP.NET MVC or Rails to make things easier.&lt;/p&gt;  &lt;p&gt;The database implements some basic authentication mechanisms and you can extend it by implementing more. As for authorization, you can grant a user read-only or full access to your database. If you want something more sophisticated, I guess you have to use validation functions. &lt;/p&gt;  &lt;h3&gt;Performance&lt;/h3&gt;  &lt;p&gt;A NoSQL solution like CouchDB is built with performance in mind. Builtin replication mechanism allows to scale the application. What’s more you can create hierarchies of database instances which will operate on subtrees of a indexed structure of your documents and by that you gain extra scalability possibilities. Unfortunately there is no builtin sharding support, but there are external frameworks to support just that (see &lt;a href="http://en.wikipedia.org/wiki/Gizzard_(Scala_framework)"&gt;Gizzard&lt;/a&gt;).&lt;/p&gt;  &lt;h3&gt;Ease of use&lt;/h3&gt;  &lt;p&gt;Usage of CouchDB is made easier by some tools and projects that make up the Couch's ecosystem. This is a big advantage over RavenDb, even for .NET developers. Couchbase is a free bundle of CouchDB and it’s management interface Futon, that is easy to install and use on a Windows machine. As for .NET clients you have a choice, but in my opinion, &lt;a href="http://code.google.com/p/relax-net/"&gt;relax-net&lt;/a&gt;&amp;#160; seems to have best design and is easies to use. You won’t get Linq support as with RaveDb, but it’s still bearable.&lt;/p&gt;  &lt;h3&gt;Documentation&lt;/h3&gt;  &lt;p&gt;There is documentation on project’s page available, but if you’re new to this, I suggest you start with this &lt;a href="http://guide.couchdb.org/"&gt;free online ebook&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;Final thoughts&lt;/h3&gt;  &lt;p&gt;CouchDB seems to be a solid piece of software used by really big players and what’s more – it’s free. It’s well developed community guarantees that you will get the support and tools you need to build your great apps. Yet, lack of transaction support will make your life harder.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-3622233753868927901?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/3622233753868927901/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=3622233753868927901' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3622233753868927901'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3622233753868927901'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2011/10/few-thoughts-on-couchdb.html' title='Few thoughts on CouchDB'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-2847078501073090450</id><published>2011-03-24T20:49:00.001+01:00</published><updated>2011-03-24T20:49:01.641+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='NoSQL'/><title type='text'>Few thoughts on RavenDb</title><content type='html'>&lt;p&gt;Now, that the NoSQL hype in the blogosphere has gone down from ecstatic adoration to constructive criticism, is a good time to get a little more interested in the topic. I decided to look on most popular solutions to know what do they offer. Actually I just peeked at one until now: RavenDb. I started there not because it’s the most popular NoSQL solution. Rather because it’s implemented in and designed for use in .NET and this technology is most familiar to me. And I have some thoughts I’d like to share.&lt;/p&gt;  &lt;h3&gt;Architecture&lt;/h3&gt;  &lt;p&gt;RavenDb is a document database. Its underlying data model is plain simple: you have a big bag into which you throw whatever Json documents you like. It’s up to you to differentiate various types of entities you might have. The client library supports different types of entities in a transparent way, but if you would like to directly use REST API, the problem is yours. Is it good or bad? Hard to say, probably depends on usage scenario. Each document is identified by id and Raven is good at quickly retrieving documents by this id. The database supports transactions. It also supports so called attachments which basically are binary pieces of data stored in the database.&lt;/p&gt;  &lt;p&gt;RavenDb queries use indexes, which are calculated in the background and not during data modification. More on that later.&lt;/p&gt;  &lt;p&gt;RavenDb can be extended by bundles. Some of the bundles shipped with Raven include support for document versioning, authorization, replication, etc. You can also extend it by writing triggers (in .NET) and custom responders.&lt;/p&gt;  &lt;p&gt;I can’t find any authentication mechanisms in RaveDb by default. There is authorization bundle, however it relies on trust relationship with application server, that has to be placed between db and the client. So no data consumption from javascript code unless you want to expose everything you have to the internet. Perhaps IIS deployment of the db (which is an optional scenario) resolves this matter by standard IIS authorization mechanisms like basic authentication + SSL. Still, there would be no way to directly associate users with document level permissions.&lt;/p&gt;  &lt;h3&gt;Performance&lt;/h3&gt;  &lt;p&gt;There is a great promise of performance and scalability behind NoSQL databases. I didn’t perform any benchmark myself, but it really looks like this promise can be fulfilled by RavenDb. The queries are based on indexes, that do not slow down writing to the db, but rather are calculated in background. Queries allow for stale data so you can you can decide what is more important for you: up to date results or getting results fast. RESTful API allows for employing caching at HTTP protocol level (proxies?). Built-in sharding and replication support deliver scalability. Really impressive.&lt;/p&gt;  &lt;h3&gt;Ease of use &lt;/h3&gt;  &lt;p&gt;It’s easy to start using RavenDb. Just add references to client, point it to server instance and you’re good to go. Running the server itself is also as easy as it takes care of creating required data files and configuration automatically. As for the client itself, you’ll find some solutions similar to NHibernate. There’s a session (unit of work) and Linq provider. It seems there’s everything a jolly .NET developer needs… &lt;/p&gt;  &lt;p&gt;Yet, the fact that you have to set up indexes upfront to cover all your document searching criteria is not very encouraging. You can define ad-hoc queries, but they are &lt;a href="http://ravendb.net/documentation/http-indexes-dynamic"&gt;said to be not very effective&lt;/a&gt;. As for queries, if you want to construct them dynamically (for example set order by basing on user input), you have two options: either to use Linq and write a switch that will grow with each subsequent ordering criteria, or use Lucene syntax to express the query. Lucene doesn’t look too friendly, but I guess you can learn anything. You can also use something like &lt;a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx"&gt;dynamic Linq&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;Reliability and disaster recovery&lt;/h3&gt;  &lt;p&gt;You can’t really tell how reliable the database is. All I know is that it’s a young project and surely there are bugs to be found in RaveDb. As for disaster recovery, Raven supports replication schemes so that you can perform failover to another node, when on of the nodes is down. There is standard backup / restore mechanism, but I can’t find any information about incremental backups. This aspect is important when you think about data volumes that NoSQL solutions are designed to support. Perhaps in VSS mode there is support for incremental backups.&lt;/p&gt;  &lt;h3&gt;Documentation&lt;/h3&gt;  &lt;p&gt;It’s definitely the worst aspect of RavenDb as documentation is chaotic and incomplete. It’s not what you’d expect from commercial solution. I wasn’t even able to run official samples for the db. This is normal for OSS, but in this case – come on!&lt;/p&gt;  &lt;h3&gt;Final thoughts&lt;/h3&gt;  &lt;p&gt;I guess RavenDb will be a slick NoSQL solution in the future, but its authors really need to put some work into developer friendliness and documentation.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-2847078501073090450?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/2847078501073090450/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=2847078501073090450' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/2847078501073090450'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/2847078501073090450'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2011/03/few-thoughts-on-ravendb.html' title='Few thoughts on RavenDb'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-7686274281386000649</id><published>2011-03-05T21:01:00.001+01:00</published><updated>2011-03-05T21:01:20.056+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><title type='text'>Event driven javascript components</title><content type='html'>&lt;p&gt;Somehow javascript code usually tends to be very messy and mangled. This is especially true when web page is complicated and contains a lot of dependencies between components. I can see a lot of developers forgetting principles of fine software design when switching from C# to javascript. In order to keep js code clean and clear, I always enclose code in objects. A piece of code together with HTML markup make up a control that is maintainable and can be reused. The problem occurs when different components have to interact with each other. Direct method calling between components creates a lot of coupling and reduces ability to reuse code. Next natural thing you would think about is events. Javascript doesn’t support custom events out of the box, but you can &lt;a href="http://www.geekdaily.net/2008/04/02/javascript-defining-and-using-custom-events/"&gt;simulate them&lt;/a&gt;. Still, you have to wire the events together with handlers somehow. What I’m suggesting instead is a centralized event broker which provides complete decoupling of event publishers and event subscribers. The idea is a lot like the event broker in Patterns and Practices’ Composite Application Block. Events are identified by a unique string (topic) and you can attach additional data to the event, which will be passed from publisher to subscriber. This way components are completely decoupled and you can even substitute any side of the event contract as long as event identifier and data format matches.&lt;/p&gt;  &lt;p&gt;I’ll be using an example here in which an objects list (a component) is filtered by drop down list of object categories (another component). Let’s see the EventBroker code first:&lt;/p&gt;  &lt;pre class="code"&gt;EventBroker = &lt;span style="color: blue"&gt;function&lt;/span&gt;() { 
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._handlers = [];
};

EventBroker.prototype = {
    subscribe : &lt;span style="color: blue"&gt;function&lt;/span&gt;(eventTopic, handler) {
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(!&lt;span style="color: blue"&gt;this&lt;/span&gt;._handlers[eventTopic])
            &lt;span style="color: blue"&gt;this&lt;/span&gt;._handlers[eventTopic] = [];
        &lt;span style="color: blue"&gt;this&lt;/span&gt;._handlers[eventTopic].push(handler);
    },
    
    publish : &lt;span style="color: blue"&gt;function&lt;/span&gt;(eventTopic, eventArgs) {
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;._handlers[eventTopic]) {
            $.each(&lt;span style="color: blue"&gt;this&lt;/span&gt;._handlers[eventTopic], &lt;span style="color: blue"&gt;function&lt;/span&gt;(idx, handler) {
                &lt;span style="color: blue"&gt;if&lt;/span&gt;(eventArgs)
                    handler(eventArgs);
                &lt;span style="color: blue"&gt;else
                    &lt;/span&gt;handler();
            });
        }
    }
};

document.eventBroker = &lt;span style="color: blue"&gt;new &lt;/span&gt;EventBroker();&lt;/pre&gt;

&lt;p&gt;The EventBroker instance is registered globally by adding a property to document. Let’s take a look at main HTML file:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;html&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;body&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;script &lt;/span&gt;&lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;text/javascript&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;src&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;script&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;script &lt;/span&gt;&lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;text/javascript&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;src&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;eventBroker.js&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;script&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;script &lt;/span&gt;&lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;text/javascript&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;src&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;foodList.js&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;script&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;script &lt;/span&gt;&lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;text/javascript&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;src&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;foodFilter.js&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;script&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;script &lt;/span&gt;&lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;text/javascript&amp;quot;&amp;gt;
    &lt;/span&gt;$(document).ready(&lt;span style="color: blue"&gt;function&lt;/span&gt;() {

        &lt;span style="color: blue"&gt;var &lt;/span&gt;foodData = [
            [&lt;span style="color: maroon"&gt;&amp;quot;Fruit&amp;quot;&lt;/span&gt;, &lt;span style="color: maroon"&gt;&amp;quot;Orange&amp;quot;&lt;/span&gt;],
            [&lt;span style="color: maroon"&gt;&amp;quot;Fruit&amp;quot;&lt;/span&gt;, &lt;span style="color: maroon"&gt;&amp;quot;Apple&amp;quot;&lt;/span&gt;],
            [&lt;span style="color: maroon"&gt;&amp;quot;Fruit&amp;quot;&lt;/span&gt;, &lt;span style="color: maroon"&gt;&amp;quot;Banana&amp;quot;&lt;/span&gt;],
            [&lt;span style="color: maroon"&gt;&amp;quot;Vegetables&amp;quot;&lt;/span&gt;, &lt;span style="color: maroon"&gt;&amp;quot;Carrot&amp;quot;&lt;/span&gt;],
            [&lt;span style="color: maroon"&gt;&amp;quot;Vegetables&amp;quot;&lt;/span&gt;, &lt;span style="color: maroon"&gt;&amp;quot;Potatoes&amp;quot;&lt;/span&gt;]
        ];

        &lt;span style="color: blue"&gt;var &lt;/span&gt;foodList = &lt;span style="color: blue"&gt;new &lt;/span&gt;FoodList(foodData, &lt;span style="color: maroon"&gt;&amp;quot;#foodList&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue"&gt;var &lt;/span&gt;foodList2 = &lt;span style="color: blue"&gt;new &lt;/span&gt;FoodList(foodData, &lt;span style="color: maroon"&gt;&amp;quot;#foodList2&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue"&gt;var &lt;/span&gt;foodFilter = &lt;span style="color: blue"&gt;new &lt;/span&gt;FoodFilter(&lt;span style="color: maroon"&gt;&amp;quot;#foodFilter&amp;quot;&lt;/span&gt;);
    });
&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;script&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;select &lt;/span&gt;&lt;span style="color: red"&gt;id&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;foodFilter&amp;quot;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;option&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;Fruit&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;option&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;option&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;Vegetables&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;option&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;select&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;ul &lt;/span&gt;&lt;span style="color: red"&gt;id&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;foodList&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;ul&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: maroon"&gt;ul &lt;/span&gt;&lt;span style="color: red"&gt;id&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;foodList2&amp;quot;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;ul&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;body&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: maroon"&gt;html&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;I created two object lists in order to show how event publishing is independent from its consumption. Next let’s look at the FoodFilter class:&lt;/p&gt;

&lt;pre class="code"&gt;FoodFilter = &lt;span style="color: blue"&gt;function&lt;/span&gt;(filterSelector) {
    $(filterSelector).change(&lt;span style="color: blue"&gt;this&lt;/span&gt;.onFilterChange);
};

FoodFilter.prototype = {
    onFilterChange : &lt;span style="color: blue"&gt;function&lt;/span&gt;(e) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;filterValue = $(e.target).val();
        document.eventBroker.publish(&lt;span style="color: maroon"&gt;&amp;quot;event://filterFood&amp;quot;&lt;/span&gt;, filterValue);
    }
};&lt;/pre&gt;

&lt;p&gt;When dropdown selection changes, the “event://filterFood” event is published. Selected category is passed along with the event. And last but not least – the consumer:&lt;/p&gt;

&lt;pre class="code"&gt;FoodList = &lt;span style="color: blue"&gt;function&lt;/span&gt;(foodData, listSelector) {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._foodData = foodData;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._listSelector = listSelector;
    document.eventBroker.subscribe(&lt;span style="color: maroon"&gt;&amp;quot;event://filterFood&amp;quot;&lt;/span&gt;, $.proxy(&lt;span style="color: blue"&gt;this&lt;/span&gt;.onFilter, &lt;span style="color: blue"&gt;this&lt;/span&gt;));
};

FoodList.prototype = {
    onFilter : &lt;span style="color: blue"&gt;function&lt;/span&gt;(filter) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = $(&lt;span style="color: blue"&gt;this&lt;/span&gt;._listSelector);
        list.empty();
        jQuery.each(&lt;span style="color: blue"&gt;this&lt;/span&gt;._foodData, &lt;span style="color: blue"&gt;function&lt;/span&gt;(idx, entry) {
            &lt;span style="color: blue"&gt;if&lt;/span&gt;(filter == entry[0])
                $(&lt;span style="color: maroon"&gt;&amp;quot;&amp;lt;li /&amp;gt;&amp;quot;&lt;/span&gt;).text(entry[1]).appendTo(list);
        });
    }
};&lt;/pre&gt;

&lt;p&gt;During the subscription, a proxy is used to change call context to the instance of FoodList class. Filter value is passed as onFilter handler parameter. &lt;/p&gt;

&lt;p&gt;This code works fine, but if you’re a challenger, you would be interested in a different approach using a feature of HTML 5. There’s a way to pass a message to javascript code originating from different domain and residing within an iframe (for example facebook widgets) using the window.postMessage() method. The main use of this mechanism is cross domain communication. But we can used use it as well to substitute the EventBroker class. Event publishing looks like this:&lt;/p&gt;

&lt;pre class="code"&gt;window.postMessage(&lt;span style="color: maroon"&gt;'{ &amp;quot;topic&amp;quot; : &amp;quot;event://filterFood&amp;quot;, &amp;quot;args&amp;quot; : &amp;quot;' &lt;/span&gt;+ filterValue + &lt;span style="color: maroon"&gt;'&amp;quot; }'&lt;/span&gt;, &lt;span style="color: maroon"&gt;&amp;quot;*&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;p&gt;Unfortunately postMessage only accepts messages to pass in form of string. In order to pass a complex type, you have to create it’s a JSON representation and then parse it at subscriber. The message contains both event topic and event argument. And now the FoodList class adapted to the new approach:&lt;/p&gt;

&lt;pre class="code"&gt;FoodList = &lt;span style="color: blue"&gt;function&lt;/span&gt;(foodData, listSelector) {
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._self = &lt;span style="color: blue"&gt;this&lt;/span&gt;;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._foodData = foodData;
    &lt;span style="color: blue"&gt;this&lt;/span&gt;._listSelector = listSelector;
    window.addEventListener(&lt;span style="color: maroon"&gt;&amp;quot;message&amp;quot;&lt;/span&gt;, $.proxy(&lt;span style="color: blue"&gt;this&lt;/span&gt;.onFilter, &lt;span style="color: blue"&gt;this&lt;/span&gt;), &lt;span style="color: blue"&gt;false&lt;/span&gt;);
};

FoodList.prototype = {
    onFilter : &lt;span style="color: blue"&gt;function&lt;/span&gt;(e) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;parsedData = $.parseJSON(e.data)
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(parsedData.topic != &lt;span style="color: maroon"&gt;&amp;quot;event://filterFood&amp;quot;&lt;/span&gt;)
            &lt;span style="color: blue"&gt;return&lt;/span&gt;;
        
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = $(&lt;span style="color: blue"&gt;this&lt;/span&gt;._listSelector);
        list.empty();
        jQuery.each(&lt;span style="color: blue"&gt;this&lt;/span&gt;._foodData, &lt;span style="color: blue"&gt;function&lt;/span&gt;(idx, entry) {
            &lt;span style="color: blue"&gt;if&lt;/span&gt;(parsedData.args == entry[0])
                $(&lt;span style="color: maroon"&gt;&amp;quot;&amp;lt;li /&amp;gt;&amp;quot;&lt;/span&gt;).text(entry[1]).appendTo(list);
        });
    }
};&lt;/pre&gt;

&lt;p&gt;Of course the approach choice is up to you. You can download the code &lt;a href="http://marcinbudny.com/files/eventBroker.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-7686274281386000649?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/7686274281386000649/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=7686274281386000649' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7686274281386000649'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7686274281386000649'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2011/03/event-driven-javascript-components.html' title='Event driven javascript components'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8840773947751745298</id><published>2010-04-04T18:05:00.002+02:00</published><updated>2010-07-12T08:34:40.456+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><title type='text'>Open/closed principle</title><content type='html'>&lt;p&gt;It’s one of object-oriented design pillars. According to wikipedia definition, class following this principle is open to extension, but closed to modifications. I think it might be a little vague for beginning developers, so I present a little example. Let’s say we have a small application for processing wine orders. Here you can see a fragment of code that might be part of this application:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DateTime &lt;/span&gt;EstimatedArrivalDate { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public decimal &lt;/span&gt;ShipmentCost { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WineOrder
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;NumberOfBottles { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public decimal &lt;/span&gt;BottlePrice { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public decimal &lt;/span&gt;OrderValue
    {
        &lt;span style="color: blue"&gt;get
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return &lt;/span&gt;NumberOfBottles*BottlePrice;
        }
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo &lt;/span&gt;GetShipmentInfo()
    {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo&lt;/span&gt;()
                   {
                       EstimatedArrivalDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Today.AddDays(3),
                       ShipmentCost = (NumberOfBottles/10 + 1)*16.0M
                   };
    }
}&lt;/pre&gt;&lt;p&gt;I try to keep things really simple: this class can calculate order’s value and generate shipment info. The application is used on local market. In first version of the application we only use one way of generating shipment info: our transport service provider charges 16 ZŁ (Polish currency) per each 10 bottles of wine being transported. &lt;/p&gt;&lt;p&gt;Everything’s fine until there’s need to expand to international market. Transport to foreign countries is charged differently. We will now try to add a functionality to our application, that will handle this situation. Seemingly the easiest way to do this is to put both ways of generating shipment info to our WineOrder class:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WineOrder
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;NumberOfBottles { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public decimal &lt;/span&gt;BottlePrice { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;ShipmentCountry { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public decimal &lt;/span&gt;OrderValue
    {
        &lt;span style="color: blue"&gt;get
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return &lt;/span&gt;NumberOfBottles * BottlePrice;
        }
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo &lt;/span&gt;GetShipmentInfo()
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(ShipmentCountry == &lt;span style="color: #a31515"&gt;&amp;quot;Poland&amp;quot;&lt;/span&gt;)
        {
            &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo&lt;/span&gt;()
                       {
                           EstimatedArrivalDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Today.AddDays(3),
                           ShipmentCost = (NumberOfBottles/10 + 1)*16.0M
                       };
        }
        &lt;span style="color: blue"&gt;else
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo&lt;/span&gt;()
                       {
                           EstimatedArrivalDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Today.AddDays(7),
                           ShipmentCost = (NumberOfBottles/5 + 1)*12.0M
                       };
        }
    }
}&lt;/pre&gt;&lt;p&gt;As you can see I added destination country to WineOrder class and then put a conditional logic inside GetShipmentInfo method. Fine, we’re done. What if the transport pricing will change so that it will depend on continent to which wine is shipped? No problem, we’ll just add more if-elses… &lt;/p&gt;&lt;p&gt;Is this really object-oriented programming we’re doing here? This obviously violates the open/closed principle. Few more changes in business rules and our GetShipmentInfo method has a few hundred lines of code. This level of complexity will surely lead to bugs and code maintenance will be a pain. While adding new code to WineOrder, there is a chance of breaking other things, that now work. Also shipment info generating logic testing is trickier, because you have to set WineOrder’s state so that right algorithm is picked. Last, but not least – we’re breaking the SRP. Let us do some refactoring and introduce strategy pattern in place of conditional logic:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IShipmentCalculator
&lt;/span&gt;{
    &lt;span style="color: #2b91af"&gt;ShipmentInfo &lt;/span&gt;GetShipmentInfo(&lt;span style="color: blue"&gt;int &lt;/span&gt;numberOfBottles);
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LocalShipmentCalculator &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IShipmentCalculator
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo &lt;/span&gt;GetShipmentInfo(&lt;span style="color: blue"&gt;int &lt;/span&gt;numberOfBottles)
    {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo&lt;/span&gt;()
        {
            EstimatedArrivalDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Today.AddDays(3),
            ShipmentCost = (numberOfBottles / 10 + 1) * 16.0M
        };
    }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;InternationalShipmentCalculator &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IShipmentCalculator
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo &lt;/span&gt;GetShipmentInfo(&lt;span style="color: blue"&gt;int &lt;/span&gt;numberOfBottles)
    {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo&lt;/span&gt;()
        {
            EstimatedArrivalDate = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Today.AddDays(7),
            ShipmentCost = (numberOfBottles / 5 + 1) * 12.0M
        };
    }
}

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WineOrder
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;NumberOfBottles { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public decimal &lt;/span&gt;BottlePrice { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public decimal &lt;/span&gt;OrderValue
    {
        &lt;span style="color: blue"&gt;get
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return &lt;/span&gt;NumberOfBottles * BottlePrice;
        }
    }

    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IShipmentCalculator &lt;/span&gt;_shipmentCalculator;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;WineOrder(&lt;span style="color: #2b91af"&gt;IShipmentCalculator &lt;/span&gt;shipmentCalculator)
    {
        _shipmentCalculator = shipmentCalculator;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ShipmentInfo &lt;/span&gt;GetShipmentInfo()
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;_shipmentCalculator.GetShipmentInfo(NumberOfBottles);
    }
}&lt;/pre&gt;&lt;p&gt;Now this looks much better. What have we achieved?&lt;/p&gt;&lt;ul&gt;&lt;li&gt;No need to modify WineOrder when shipment info generating rules change. No proven code will be broken. Class is closed to modification. &lt;/li&gt;
&lt;li&gt;Algorithm for generating shipment info can be chosen elsewhere, possibly in configuration. Class is open to extension. &lt;/li&gt;
&lt;li&gt;Less dependencies, SRP compatible. &lt;/li&gt;
&lt;/ul&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2010/04/openclosed-principle.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2010/04/openclosed-principle.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8840773947751745298?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8840773947751745298/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8840773947751745298' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8840773947751745298'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8840773947751745298'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2010/04/openclosed-principle.html' title='Open/closed principle'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8302529813335270648</id><published>2010-01-31T19:40:00.001+01:00</published><updated>2010-01-31T19:40:50.084+01:00</updated><title type='text'>Handling stylesheet references in ASP.NET MVC</title><content type='html'>&lt;p&gt;You can download code discussed in this post &lt;a href="http://marcinbudny.com/files/CssHandlingSample.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Linking CSS to a web page seems to be a trivial task. But when you’re just plainly using LINK tag to attach a stylesheet you have to be aware of at least three things:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;LINK tag is only valid within the HEAD section. This breaks encapsulation of partial views, since they cannot include stylesheets they’re using on their own, but instead they depend on master site or aspx page to include those stylesheets. &lt;/li&gt;    &lt;li&gt;If you have several stylesheets, each of them will be downloaded from server separately, which is considered to have significant impact on page’s loading time, because a web browser can request only a limited number of resources from a server at a time. &lt;/li&gt;    &lt;li&gt;If a partial view is rendered multiple times, you would like to have only one reference to stylesheet. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;My goal here is to provide a mechanism to overcome those problems. Note that while I’m talking about CSS here, similar rules apply to scripts used on the site. Scripts could be included anywhere in the page, but their number is usually greater than number of stylesheets and also they’re significantly larger. I’ll be showing how to manage CSS to keep things simple, but with a little work you can do the same fro scripts. For simplicity’s sake I also use things like HttpContext directly, but you would want them wrapped in something that’s actually mockable (like HttpContextWrapper from System.Web.Abstractions assembly).&lt;/p&gt;  &lt;p&gt;The idea is to gather all required stylesheet references and then to place them in HEAD section. Also we want to download all stylesheets at once, so we’re going to create a HttpHandler, that will take a list of files as a parameter and render their concatenated contents into the response. In order to gather required stylesheet references from any views rendered in current response and then to include them in HEAD section, there must be some kind of response postprocessing taking place. This is because you can’t modify header from within view or partial view, since it has already been rendered. We can do this by placing a placeholder for stylesheet reference inside HEAD section, and then replacing it with actual reference after all views have been rendered. &lt;/p&gt;  &lt;p&gt;Let’s start coding:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StylesheetManager
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; _stylesheets = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();

    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StylesheetManager &lt;/span&gt;Current
    {
        &lt;span style="color: blue"&gt;get
        &lt;/span&gt;{
            &lt;span style="color: blue"&gt;var &lt;/span&gt;manager = &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Items[&lt;span style="color: #a31515"&gt;&amp;quot;STYLESHEET_MANAGER&amp;quot;&lt;/span&gt;] &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StylesheetManager&lt;/span&gt;;
            &lt;span style="color: blue"&gt;if&lt;/span&gt;(manager == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
            {
                manager = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StylesheetManager&lt;/span&gt;();
                &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Items.Add(&lt;span style="color: #a31515"&gt;&amp;quot;STYLESHEET_MANAGER&amp;quot;&lt;/span&gt;, manager);
            }
            &lt;span style="color: blue"&gt;return &lt;/span&gt;manager;
        }
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;RegisterStylesheet(&lt;span style="color: blue"&gt;string &lt;/span&gt;file)
    {
        file = file.ToLower();
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(!_stylesheets.Contains(file))
            _stylesheets.Add(file);
    }

    &lt;span style="color: blue"&gt;public string &lt;/span&gt;GetStylesheetsReference()
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;filesParam = &lt;span style="color: #2b91af"&gt;HttpUtility&lt;/span&gt;.UrlEncode(&lt;span style="color: blue"&gt;string&lt;/span&gt;.Join(&lt;span style="color: #a31515"&gt;&amp;quot;,&amp;quot;&lt;/span&gt;, _stylesheets.ToArray()));
        &lt;span style="color: blue"&gt;var &lt;/span&gt;dateParam = &lt;span style="color: #2b91af"&gt;HttpUtility&lt;/span&gt;.UrlEncode(GetLatestModificationDate(_stylesheets).ToString(&lt;span style="color: #a31515"&gt;&amp;quot;s&amp;quot;&lt;/span&gt;));

        &lt;span style="color: blue"&gt;return string&lt;/span&gt;.Format(&lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;link href=\&amp;quot;Css.axd?f={0}&amp;amp;d={1}\&amp;quot; rel=\&amp;quot;stylesheet\&amp;quot; type=\&amp;quot;text/css\&amp;quot; /&amp;gt;&amp;quot;&lt;/span&gt;,
                             filesParam, dateParam);
    }

    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DateTime &lt;/span&gt;GetLatestModificationDate(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; files)
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(files.Count == 0)
            &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.MinValue;

        &lt;span style="color: blue"&gt;var &lt;/span&gt;latest = &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.MinValue;

        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;file &lt;span style="color: blue"&gt;in &lt;/span&gt;files)
        {
            &lt;span style="color: blue"&gt;var &lt;/span&gt;fileDate = &lt;span style="color: #2b91af"&gt;File&lt;/span&gt;.GetLastWriteTime(&lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Request.MapPath(file));
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(fileDate &amp;gt; latest)
                latest = fileDate;
        }
        &lt;span style="color: blue"&gt;return &lt;/span&gt;latest;
    }
}&lt;/pre&gt;

&lt;p&gt;This class manages references to stylesheet files and is used by view and partial views. Each reference is registered only once. As you may have noticed the URL to stylesheets references the Css.axd resource. This will be our HttpHandler, that receives file list as a parameter. There is also another parameter – date of latest modification among registered files. This parameter is included due to caching reasons, which I’ll explain later. An instance of StylesheetManager is bound to current HttpContext.&lt;/p&gt;

&lt;p&gt;Sample usage of StylesheetManager class is:&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; 
        StylesheetManager.Current.RegisterStylesheet(&amp;quot;~/Content/Site.css&amp;quot;); 
        StylesheetManager.Current.RegisterStylesheet(&amp;quot;~/Content/Skin.css&amp;quot;);
    &lt;span style="background: #ffee62"&gt;%&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Next step is to define the HttpHandler to serve requests to Css.axd resource:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StylesheetHttpHandler &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IHttpHandler
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;ProcessRequest(&lt;span style="color: #2b91af"&gt;HttpContext &lt;/span&gt;context)
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;fileParam = context.Request.QueryString[&lt;span style="color: #a31515"&gt;&amp;quot;f&amp;quot;&lt;/span&gt;];
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(&lt;span style="color: blue"&gt;string&lt;/span&gt;.IsNullOrEmpty(fileParam))
            &lt;span style="color: blue"&gt;return&lt;/span&gt;;
        
        &lt;span style="color: blue"&gt;string&lt;/span&gt;[] files = &lt;span style="color: #2b91af"&gt;HttpUtility&lt;/span&gt;.UrlDecode(fileParam).Split(&lt;span style="color: #a31515"&gt;','&lt;/span&gt;);
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(files.Any(f =&amp;gt; !&lt;span style="color: #2b91af"&gt;VirtualPathUtility&lt;/span&gt;.IsAppRelative(f) || &lt;span style="color: #2b91af"&gt;Path&lt;/span&gt;.GetExtension(f) != &lt;span style="color: #a31515"&gt;&amp;quot;.css&amp;quot;&lt;/span&gt;))
        {
            &lt;span style="color: green"&gt;// only CSS files within application are allowed
            &lt;/span&gt;context.Response.StatusCode = 403; &lt;span style="color: green"&gt;// forbidden
            &lt;/span&gt;&lt;span style="color: blue"&gt;return&lt;/span&gt;;
        }

        &lt;span style="color: blue"&gt;var &lt;/span&gt;responseBuilder = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StringBuilder&lt;/span&gt;();
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;file &lt;span style="color: blue"&gt;in &lt;/span&gt;files)
        {
            &lt;span style="color: blue"&gt;var &lt;/span&gt;content = &lt;span style="color: #2b91af"&gt;File&lt;/span&gt;.ReadAllText(context.Request.MapPath(file));
            responseBuilder.Append(content);
        }

        context.Response.ContentType = &lt;span style="color: #a31515"&gt;&amp;quot;text/css&amp;quot;&lt;/span&gt;;
        context.Response.Cache.SetCacheability(&lt;span style="color: #2b91af"&gt;HttpCacheability&lt;/span&gt;.Public);
        context.Response.Cache.SetExpires(&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Now.AddYears(1));
        context.Response.Write(responseBuilder.ToString());
    }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;IsReusable
    {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return true&lt;/span&gt;; }
    }
}&lt;/pre&gt;


&lt;p&gt;One interesting bit here is restriction to files with .css extension within application directory. We wouldn’t like anybody to download our web.config with connection strings, right? The other is setting cache control HTTP headers. We set the expiration date to one year ahead, so under normal circumstances user’s browser won’t have to request the stylesheet again after downloading it at first request.&lt;/p&gt;

&lt;p&gt;But what if we want to change the script? How can we force user’s browser to download new version? That’s exactly what the date parameter in stylesheet URL is for. When we change the file, the parameter changes. Browser treats this as a new resource and it has to download it form server.&lt;/p&gt;

&lt;p&gt;Of course the handler has to be configured in web.config:&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;httpHandlers&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;add &lt;/span&gt;&lt;span style="color: red"&gt;verb&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;GET,HEAD&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;path&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;Css.axd&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;CssHandlingSample.Utilities.StylesheetHttpHandler, CssHandlingSample&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;httpHandlers&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;One missing piece here is the postprocessing of the response. This is pretty easy to do by defining our own stream class. The most interesting is the Write method:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public override void &lt;/span&gt;Write(&lt;span style="color: blue"&gt;byte&lt;/span&gt;[] buffer, &lt;span style="color: blue"&gt;int &lt;/span&gt;offset, &lt;span style="color: blue"&gt;int &lt;/span&gt;count)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Response.ContentType != &lt;span style="color: #a31515"&gt;&amp;quot;text/html&amp;quot;&lt;/span&gt;)
    {
        &lt;span style="color: green"&gt;// when content type other than text/html, just forward content to 
        // wrapped stream
        &lt;/span&gt;_wrappedStream.Write(buffer, offset, count);
        &lt;span style="color: blue"&gt;return&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;var &lt;/span&gt;page = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StringBuilder&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Encoding&lt;/span&gt;.UTF8.GetString(buffer, offset, count));
    page.Replace(&lt;span style="color: #a31515"&gt;&amp;quot;#STYLESHEET_REFERENCE#&amp;quot;&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;StylesheetManager&lt;/span&gt;.Current.GetStylesheetsReference());

    &lt;span style="color: blue"&gt;var &lt;/span&gt;transformedPageBytes = &lt;span style="color: #2b91af"&gt;Encoding&lt;/span&gt;.UTF8.GetBytes(page.ToString());
    _wrappedStream.Write(transformedPageBytes, 0, transformedPageBytes.Length);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&amp;#160;&lt;/a&gt;Now we have to hook it into response processing. To do this, we have to define application’s BeginRequest handler:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;protected void &lt;/span&gt;Application_BeginRequest()
{
    &lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Response.Filter =
        &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PostprocessingStream&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HttpContext&lt;/span&gt;.Current.Response.Filter);
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Almost done! Last thing to do is to put the placeholder inside the page’s header:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;head &lt;/span&gt;&lt;span style="color: red"&gt;runat&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;server&amp;quot;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;title&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;asp&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;ContentPlaceHolder &lt;/span&gt;&lt;span style="color: red"&gt;ID&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;TitleContent&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;runat&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;server&amp;quot; /&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;title&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &lt;/span&gt;#STYLESHEET_REFERENCE#
&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;head&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;After running the application, this is what we get in page’s source:&lt;/p&gt;

&lt;pre class="code"&gt;&amp;lt;head&amp;gt;
&amp;lt;title&amp;gt;Home Page&amp;lt;/title&amp;gt;
&amp;lt;link href=&amp;quot;Css.axd?f=%7e%2fcontent%2fsite.css%2c%7e%2fcontent%2fskin.css&amp;amp;d=2010-01-30T19%3a15%3a57&amp;quot; rel=&amp;quot;stylesheet&amp;quot; type=&amp;quot;text/css&amp;quot; /&amp;gt;
&amp;lt;/head&amp;gt;&lt;/pre&gt;

&lt;p&gt;Great!&lt;/p&gt;

&lt;p&gt;Now, before putting this into production, there are some things to consider. Firstly you would probably provide some kind of server side caching of files’ modification dates and content. This way server won’t have to hit the disk at each new request. Secondly, be careful with client side caching. URL to the downloaded resource contains list of files being downloaded. If that list changes, the URL changes. That means ALL files are downloaded again as a new resource. Suppose you’re using this mechanism for scripts. You attach jQuery, MS AJAX and a custom script for currently displayed view. Those three scripts are concatenated, downloaded and stored in cache. Then browser is redirected to another view. Again you’re using jQuery, MS AJAX and a different custom script. File list changed. jQuery and MS AJAX are downloaded again, when they could be served from browser’s cache. To avoid such situation, in my production environment I decided to introduce resource categories. There are “Common” scripts and “View specific” scripts. There is one URL created for each category. This way common scripts never have to be downloaded again from server when another view is displayed.&lt;/p&gt;

&lt;p&gt;To make this mechanism better, you could employ some script and stylesheet compressing methods like removing whitespace before sending response to the browser. &lt;/p&gt;

&lt;p&gt;There is also an issue with script debugging. When script is downloaded as one resource, it is then hard to navigate in tools like FireBug and also information about line numbers is lost. To avoid this, I introduced a configuration switch that makes StylesheetManager class produce one resource reference per each registered file. I can turn this setting on when I need to debug scripts.&lt;/p&gt;

&lt;p&gt;You can download code discussed in this post &lt;a href="http://marcinbudny.com/files/CssHandlingSample.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2010/01/handling-stylesheet-references-in.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2010/01/handling-stylesheet-references-in.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8302529813335270648?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8302529813335270648/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8302529813335270648' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8302529813335270648'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8302529813335270648'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2010/01/handling-stylesheet-references-in.html' title='Handling stylesheet references in ASP.NET MVC'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8013013432895720457</id><published>2009-12-19T21:36:00.001+01:00</published><updated>2009-12-19T21:36:19.632+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='communication'/><category scheme='http://www.blogger.com/atom/ns#' term='AOP'/><category scheme='http://www.blogger.com/atom/ns#' term='WCF'/><title type='text'>Proxying a WCF client channel</title><content type='html'>&lt;p&gt;Recently I wanted to apply AOP when using a client channel to WCF service. I wanted to do this in order to manipulate the message being sent to the service, which involved attaching some additional information to the message. Creating a wrapper for this channel by hand by implementing channel’s interface (contract) would mean that I have to update this wrapper each time the services contract changes. This happens all too often during the development, so this solution was unacceptable. Hence the AOP. Unfortunately PostSharp doesn’t quite seem to support a scenario where you have to intercept calls to methods of existing instance returned by third party library. Especially because client channel returned by ChannelFactory&amp;lt;T&amp;gt; class is a remoting proxy created on the fly. &lt;/p&gt;  &lt;p&gt;Using a dynamic proxy seemed right way to go, so I decided to use well known Castle.DynamicProxy library. Implementation turned out to be quite easy:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;proxyGenerator = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ProxyGenerator&lt;/span&gt;();

service = &lt;span style="color: #2b91af"&gt;ChannelFactory&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IInvoicingService&lt;/span&gt;&amp;gt;.CreateChannel(
    &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;NetNamedPipeBinding&lt;/span&gt;(), &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EndpointAddress&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;net.pipe://something&amp;quot;&lt;/span&gt;));

service = proxyGenerator.CreateInterfaceProxyWithTarget(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;IInvoicingService&lt;/span&gt;),
    service, &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyInterceptor&lt;/span&gt;()) &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IInvoicingService&lt;/span&gt;;&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The channel is being proxied and the interceptor definition is as follows:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyInterceptor &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IInterceptor
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;#region &lt;/span&gt;IInterceptor Members

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Intercept(&lt;span style="color: #2b91af"&gt;IInvocation &lt;/span&gt;invocation)
    {
        &lt;span style="color: green"&gt;// do something with message, it's in invocation.Arguments
        
        &lt;/span&gt;invocation.Proceed();
        
    }

    &lt;span style="color: blue"&gt;#endregion
&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This works fine until you realize, that the client channel not only implements the service contract, but it also implements ICommunicationObject interface used to perform communication related operations like closing the channel. Normally you would cast the channel to ICommunicationObject and use appropriate methods. But now that channel is proxied, it no longer implements ICommunicationObject interface. Fortunately Castle.DynamicProxy provides a way to deal with such situations. When creating a proxy, you can specify what additional interfaces should be implemented along with the main proxied interface:&lt;/p&gt;

&lt;pre class="code"&gt;service = proxyGenerator.CreateInterfaceProxyWithTarget(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;IInvoicingService&lt;/span&gt;),
    &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;[] { &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;ICommunicationObject&lt;/span&gt;) }, service, 
    &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyInterceptor&lt;/span&gt;()) &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IInvoicingService&lt;/span&gt;;&lt;/pre&gt;

&lt;p&gt;But this is not all, because proxy won’t forward calls to methods defined on ICommunicationObject interface by default, since it considers those methods to have no target. It means that interceptor is solely responsible for acting as a method body for those calls and any attempt to call invocation.Proceed() will result in an exception. Fortunately I can forward those calls by hand: &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyInterceptor &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IInterceptor
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;#region &lt;/span&gt;IInterceptor Members

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Intercept(&lt;span style="color: #2b91af"&gt;IInvocation &lt;/span&gt;invocation)
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(invocation.Method.DeclaringType == &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;ICommunicationObject&lt;/span&gt;))
        {
            &lt;span style="color: blue"&gt;var &lt;/span&gt;target = (invocation.Proxy &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IProxyTargetAccessor&lt;/span&gt;).DynProxyGetTarget();
            &lt;span style="color: blue"&gt;var &lt;/span&gt;returnValue = invocation.Method.Invoke(target, invocation.Arguments);
            invocation.ReturnValue = returnValue;
        }
        &lt;span style="color: blue"&gt;else
        &lt;/span&gt;{
            &lt;span style="color: green"&gt;// do something with message, it's in invocation.Arguments

            &lt;/span&gt;invocation.Proceed();
        }

    }

    &lt;span style="color: blue"&gt;#endregion
&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;So this is a nice and clean way to apply AOP to WCF client channel and I have to say I impressed with how easy to use and powerful the Castle.DynamicProxy library is.

&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/12/proxying-wcf-client-channel.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/12/proxying-wcf-client-channel.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8013013432895720457?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8013013432895720457/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8013013432895720457' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8013013432895720457'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8013013432895720457'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/12/proxying-wcf-client-channel.html' title='Proxying a WCF client channel'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-7619009710829245153</id><published>2009-11-03T23:06:00.001+01:00</published><updated>2009-11-03T23:07:26.064+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='dependency injection'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Unity auto registration</title><content type='html'>&lt;p&gt;Auto registration is a great feature for any Dependency Injection container. Suppose you decided to implement the &lt;a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/"&gt;Domain Event pattern&lt;/a&gt;. So you have a bunch of events and some event handlers. These event handlers are classes implementing some common interface, say IHandlerFor&amp;lt;TEvent&amp;gt;. You also have a central registry of these handlers, so that you can easily find handlers for particular event – and run them passing the event data. But how does the registry know about these handlers? Well, you probably have to register all of them in the registry with some kind of configuration code. If your registry is built upon your DI container you can take advantage of auto registration feature. That is if your container supports it like Castle does.&lt;/p&gt;  &lt;p&gt;Unfortunately Unity doesn’t do that out of the box, but there is a nice &lt;a href="http://autoregistration.codeplex.com/"&gt;library by Artem Govorov&lt;/a&gt; on Codeplex, that will let you do just that. It has a nice syntax and offers a great deal of flexibility. Basically in order to achieve auto registration you:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Select which assemblies are scanned for types to register &lt;/li&gt;    &lt;li&gt;Specify which types are to be registered by providing conventions &lt;/li&gt;    &lt;li&gt;Specify how the types should be registered in the container (select an interface for type, select a name under which it is to be registered) &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Of course there are some predefined predicates and other methods that make working with the library easier. For more details, please visit the project’s page. &lt;/p&gt;  &lt;p&gt;What I found the library lacked is a predicate that would allow to select types, which implement a generic interface that is constructed from specified open-generic interface (generic type definition).To use an example of domain event: If I have an event called OrderAdded and a handler implementing IHandlerFor&amp;lt;OrderAdded&amp;gt;, the open-generic interface is IHandlerFor&amp;lt;&amp;gt;. By specifying this open-generic interface I can register all handlers at once and later access concrete generics when needed. Of course you can write the predicate yourself, but it would be nice to have it out of the box. &lt;/p&gt;  &lt;p&gt;So I introduced this predicate and Artem was kind enough to apply this patch to the library’s codebase. Now having this:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OrderAdded &lt;/span&gt;{ }

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;NotifySalesHandler &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IHandlerFor&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;OrderAdded&lt;/span&gt;&amp;gt; { }

&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;SendConfirmationHandler &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IHandlerFor&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;OrderAdded&lt;/span&gt;&amp;gt; { }&lt;/pre&gt;

&lt;p&gt;I can do this:&lt;/p&gt;

&lt;pre class="code"&gt;_container
    .ConfigureAutoRegistration()
    .IncludeAssemblies(_testAssemblies)
    .Include(type =&amp;gt; type.ImplementsOpenGeneric(&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;IHandlerFor&lt;/span&gt;&amp;lt;&amp;gt;)), 
        &lt;span style="color: #2b91af"&gt;Then&lt;/span&gt;.Register().AsFirstInterfaceOfType().WithTypeName())
    .ApplyAutoRegistration();

&lt;span style="color: blue"&gt;var &lt;/span&gt;orderAddedHandlers = _container.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IHandlerFor&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;OrderAdded&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;

&lt;p&gt;Of course with no additional setup required I am able to resolve any other hadlers for whatever events I might have. &lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/11/unity-auto-registration.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/11/unity-auto-registration.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-7619009710829245153?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/7619009710829245153/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=7619009710829245153' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7619009710829245153'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7619009710829245153'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/11/unity-auto-registration.html' title='Unity auto registration'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-4484894666519261585</id><published>2009-10-13T18:28:00.001+02:00</published><updated>2011-03-24T20:53:16.578+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='NHibernate'/><category scheme='http://www.blogger.com/atom/ns#' term='ORM'/><title type='text'>Typed Expand() for Linq to NHiberante</title><content type='html'>&lt;p&gt;// EDIT: as of NHibernate 3.0, there is new built-in LINQ provider with typed Fetch method (I don’t like it though). This post was intended for NHibernate 2.x with external LINQ provider.&lt;/p&gt;  &lt;p&gt;( You can get code discussed in this post &lt;a href="http://marcinbudny.com/files/TypedExpand.zip"&gt;here&lt;/a&gt; )&lt;/p&gt;  &lt;p&gt;One of things that keep me irritated in Linq to NHibernate is the way you specify eager fetching paths. Suppose you have domain model like this:&lt;/p&gt;  &lt;p&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/StSqj0abM8I/AAAAAAAAANM/TyJ14K6RZ1A/image%5B11%5D.png?imgmax=800" width="548" height="264" /&gt; &lt;/p&gt;  &lt;p&gt;Normally you do things like this:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;session = sessionFactory.OpenSession())
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;invoices = session.Linq&amp;lt;&lt;span style="color: #2b91af"&gt;Invoice&lt;/span&gt;&amp;gt;().Expand(&lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;).ToList();
}&lt;/pre&gt;




&lt;p&gt;I don’t like using strings to identify type members since this way they’re not impacted by refactoring changes using automatic tools. What’s more, Expand returns IQueryable&amp;lt;T&amp;gt; instead of INHibernateQueryable&amp;lt;T&amp;gt;, which means you can’t chain multiple paths and have to use some temporary variable. &lt;/p&gt;

&lt;p&gt;So to address those issues it would be nice to have ability to specify eager fetching path using labmda expressions and to chain them. For this purpose I created a little extension to INHibernateQueryable&amp;lt;T&amp;gt;, which allows you to do this:&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;CanExpandSimpleProperty()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;nhQueryable = 
        &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateStub&amp;lt;&lt;span style="color: #2b91af"&gt;INHibernateQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Invoice&lt;/span&gt;&amp;gt;&amp;gt;();
    nhQueryable.Expand(i =&amp;gt; i.Customer);

    nhQueryable.AssertWasCalled(nhq =&amp;gt; nhq.Expand(&lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;));
}

[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;CanExpandNestedProperties()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;nhQueryable =
        &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateStub&amp;lt;&lt;span style="color: #2b91af"&gt;INHibernateQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Invoice&lt;/span&gt;&amp;gt;&amp;gt;();
    nhQueryable.Expand(i =&amp;gt; i.Customer.CustomerCategory);

    nhQueryable.AssertWasCalled(nhq =&amp;gt; nhq.Expand(&lt;span style="color: #a31515"&gt;&amp;quot;Customer.CustomerCategory&amp;quot;&lt;/span&gt;));
}&lt;/pre&gt;


&lt;p&gt;This is pretty easy to do. But there is another scenario that complicates things a little: what if you would like to fetch invoices along with invoice items and with products. Since Items is a collection of InvoiceItem object, so there is no way of directly specifying a path like: Invoice –&amp;gt; Items –&amp;gt; Product. If Items is an IList or IList&amp;lt;T&amp;gt;, the extension allows you to do this:&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;CanExpandCollectionTraversal()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;nhQueryable =
        &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateStub&amp;lt;&lt;span style="color: #2b91af"&gt;INHibernateQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Invoice&lt;/span&gt;&amp;gt;&amp;gt;();
    nhQueryable.Expand(i =&amp;gt; i.Items[0].Product);

    nhQueryable.AssertWasCalled(nhq =&amp;gt; nhq.Expand(&lt;span style="color: #a31515"&gt;&amp;quot;Items.Product&amp;quot;&lt;/span&gt;));
}&lt;/pre&gt;

&lt;p&gt;So you can traverse collections using the indexer. But what if you have a collection like ISet, which doesn’t have an indexer? For this scenario, extension provides notion of subpaths:&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;CanExpandWithSubpath()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;nhQueryable =
        &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateStub&amp;lt;&lt;span style="color: #2b91af"&gt;INHibernateQueryable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Invoice&lt;/span&gt;&amp;gt;&amp;gt;();
    nhQueryable.Expand(i =&amp;gt; i.Items,
        &lt;span style="color: #2b91af"&gt;Subpath&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;InvoiceItem&lt;/span&gt;&amp;gt;().Add(item =&amp;gt; item.Product));

    nhQueryable.AssertWasCalled(nhq =&amp;gt; nhq.Expand(&lt;span style="color: #a31515"&gt;&amp;quot;Items.Product&amp;quot;&lt;/span&gt;));
}&lt;/pre&gt;

&lt;p&gt;You can also chain multiple Add calls in order to specify more than one subpath rooting from type provided in For&amp;lt;T&amp;gt; method.&lt;/p&gt;

&lt;p&gt;You can get this extension &lt;a href="http://marcinbudny.com/files/TypedExpand.zip"&gt;here&lt;/a&gt;. Hope this helps!&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-4484894666519261585?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/4484894666519261585/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=4484894666519261585' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4484894666519261585'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4484894666519261585'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/10/typed-expand-for-linq-to-nhiberante.html' title='Typed Expand() for Linq to NHiberante'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/_Egs311swNl0/StSqj0abM8I/AAAAAAAAANM/TyJ14K6RZ1A/s72-c/image%5B11%5D.png?imgmax=800' height='72' width='72'/><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8222583208998209648</id><published>2009-10-10T21:53:00.001+02:00</published><updated>2009-10-10T21:53:19.575+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='NHibernate'/><category scheme='http://www.blogger.com/atom/ns#' term='ORM'/><title type='text'>Linq to NHibernate First() bug</title><content type='html'>&lt;p&gt;As I suspected Linq to NHibernate has some flaws. I just discovered a bug showing up when eagerly loading collections and using IQueryable&amp;lt;T&amp;gt;.First(). Suppose you’ve got persistent class like this:&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Invoice &lt;/span&gt;&lt;span style="color: #2b91af"&gt;
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public virtual int &lt;/span&gt;Id { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public virtual &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;InvoiceItem&lt;/span&gt;&amp;gt; Items { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Normally, if you want to get and instance by id with eagerly loaded collection of items, you’d write something like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;session = sessionFactory.OpenSession())
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;nhQueryable = session.Linq&amp;lt;&lt;span style="color: #2b91af"&gt;Invoice&lt;/span&gt;&amp;gt;();
    nhQueryable.Expand(&lt;span style="color: #a31515"&gt;&amp;quot;Items&amp;quot;&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;invoice = nhQueryable.Where(i =&amp;gt; i.Id == id).First();
}&lt;/pre&gt;

&lt;p&gt;This code executes without any errors, but unfortunately you always get only one item in Items collection. A quick investigation there and it turns out there is a problem with SQL generated by this query. NHibernate performs eager fetching by means of outer joins. This means that SQL query would return as many rows as there are invoice items associated with this invoice. But usage of the First() method results in the SQL query having TOP(1) clause, which causes database to return only one invoice item. It seems to be a bug in Linq to NH because according to information found on the web, such queries expressed with Criteria API work just fine. Well, you can either not use Linq to NH or just write this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;invoice = nhQueryable.Where(i =&amp;gt; i.Id == id).ToArray()[0];&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/10/linq-to-nhibernate-first-bug.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/10/linq-to-nhibernate-first-bug.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8222583208998209648?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8222583208998209648/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8222583208998209648' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8222583208998209648'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8222583208998209648'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/10/linq-to-nhibernate-first-bug.html' title='Linq to NHibernate First() bug'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-1626931613564714099</id><published>2009-09-27T20:26:00.001+02:00</published><updated>2009-09-27T20:26:36.497+02:00</updated><title type='text'>When in doubt, write some code</title><content type='html'>&lt;p&gt;Well, that was some time since I last posted. I had some private matters going on, but hopefully I will be able to make up for that time.&lt;/p&gt;  &lt;p&gt;Currently I’m starting a new project – internet facing web application. Carefully considering technologies that I would use I came up with this:&lt;/p&gt;  &lt;p&gt;Web layer:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;ASP.NET MVC &lt;/li&gt;    &lt;li&gt;jQuery &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Application layer:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;WCF for exposing services &lt;/li&gt;    &lt;li&gt;NHibernate with additional help of Fluent NHiberante and Linq for NHibernate &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Common:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;PostSharp for AOP &lt;/li&gt;    &lt;li&gt;Unity for DI &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;However I still have some doubts related to those choices. ASP.NET MVC while being seemingly perfect for internet facing application, is still quite new on the market and not really proven. Because I don’t have any experience with this technology, I don’t know what can be expected. As for NHibernate I have some previous experience and I generally know where the traps are set for me. But Fluent NHibernate and Linq for NHibernate are also new for me. Especially Linq for NH, despite being version 1.0, seems immature. There are some bugs open for it, which seem to be &lt;a href="http://nhjira.koah.net/secure/IssueNavigator.jspa?reset=true&amp;amp;mode=hide&amp;amp;pid=10020&amp;amp;sorter/order=DESC&amp;amp;sorter/field=priority&amp;amp;resolution=-1&amp;amp;component=10060"&gt;quite serious&lt;/a&gt;. I’m not really sure if it will be Linq or if I will just stick with Criteria API, which supports a very interesting feature of &lt;a href="http://nhforge.org/blogs/nhibernate/archive/2009/04/27/nhibernate-futures.aspx"&gt;futures&lt;/a&gt; since NH 2.1. &lt;/p&gt;  &lt;p&gt;With all those doubts I would be crazy just jumping into full scale development. In my opinion the best way to verify architectural assumptions is to write some code. So I intend to create a prototype of the application, which will reflect structure of the final solution, but with some simplifications, that would allow to achieve some basic functionality in short time. After this is done, I hope to be able to assess my assumptions and – if something is wrong – to correct this, before changes in architecture start to cost some real money.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-1626931613564714099?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/1626931613564714099/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=1626931613564714099' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/1626931613564714099'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/1626931613564714099'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/09/when-in-doubt-write-some-code_50.html' title='When in doubt, write some code'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-2739539833622071456</id><published>2009-06-20T23:04:00.001+02:00</published><updated>2009-06-20T23:04:16.884+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Building a fluent interface</title><content type='html'>&lt;p&gt;Who doesn’t like fluent interfaces? They allow to write things down in more compact manner and keep them readable in the future. Almost all contemporary libraries have fluent APIs. Some of them don’t (see LLBLGen Pro for example, argh!), but they definitely should get one. &lt;/p&gt;  &lt;p&gt;In this post I’d like to show how to build a really simple fluent interface, and then – how to make it a little better. In the example, we’ll be writing a simple interface for creating and running SQL queries. What we want to achieve is ability to write code like this:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;query = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;QueryFactory&lt;/span&gt;().Create();

&lt;span style="color: blue"&gt;var &lt;/span&gt;result = query
    .From(&lt;span style="color: #a31515"&gt;&amp;quot;Employee&amp;quot;&lt;/span&gt;).Alias(&lt;span style="color: #a31515"&gt;&amp;quot;e&amp;quot;&lt;/span&gt;)
    .Join(&lt;span style="color: #a31515"&gt;&amp;quot;Order&amp;quot;&lt;/span&gt;).Alias(&lt;span style="color: #a31515"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;).On(&lt;span style="color: #a31515"&gt;&amp;quot;e.EmployeeID = o.EmployeeID&amp;quot;&lt;/span&gt;)
    .Where(&lt;span style="color: #a31515"&gt;&amp;quot;o.TotalPrice &amp;gt; 1000&amp;quot;&lt;/span&gt;)
    .Execute&amp;lt;&lt;span style="color: #2b91af"&gt;Employee&lt;/span&gt;&amp;gt;();&lt;/pre&gt;

&lt;p&gt;As you can see, fluency is gained by chaining method calls on an object. The QueryFactory class is our entry point and returns IQueryBuilder interface, which then serves as our fluent API for building the query. The IQueryBuilder interface is defined as follows:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder
&lt;/span&gt;{
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;From(&lt;span style="color: blue"&gt;string &lt;/span&gt;tableName);
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Join(&lt;span style="color: blue"&gt;string &lt;/span&gt;tableName);
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Alias(&lt;span style="color: blue"&gt;string &lt;/span&gt;alias);
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;On(&lt;span style="color: blue"&gt;string &lt;/span&gt;joinCondition);
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Where(&lt;span style="color: blue"&gt;string &lt;/span&gt;filter);

    &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;T&amp;gt; Execute&amp;lt;T&amp;gt;();
}&lt;/pre&gt;

&lt;p&gt;Every method returns IQueryBuilder interface, which allows to chain calls. A sample implementation could look like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Query &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IQueryBuilder
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TableOptions
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;public string &lt;/span&gt;TableName { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
        &lt;span style="color: blue"&gt;public string &lt;/span&gt;Alias { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
        &lt;span style="color: blue"&gt;public string &lt;/span&gt;JoinCondition { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    }

    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;TableOptions&lt;/span&gt;&amp;gt; tableOptionsList = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;TableOptions&lt;/span&gt;&amp;gt;();
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TableOptions &lt;/span&gt;currentTableOptions;
    &lt;span style="color: blue"&gt;private string &lt;/span&gt;filter;

    &lt;span style="color: blue"&gt;#region &lt;/span&gt;IQueryBuilder Members

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;From(&lt;span style="color: blue"&gt;string &lt;/span&gt;tableName)
    {
        currentTableOptions = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TableOptions&lt;/span&gt;() { TableName = tableName };
        tableOptionsList.Add(currentTableOptions);

        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Join(&lt;span style="color: blue"&gt;string &lt;/span&gt;tableName)
    {
        currentTableOptions = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TableOptions&lt;/span&gt;() { TableName = tableName };
        tableOptionsList.Add(currentTableOptions);

        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Alias(&lt;span style="color: blue"&gt;string &lt;/span&gt;alias)
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(currentTableOptions == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
            &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;First specify a table&amp;quot;&lt;/span&gt;);

        currentTableOptions.Alias = alias;
        
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;On(&lt;span style="color: blue"&gt;string &lt;/span&gt;joinCondition)
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(currentTableOptions == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
            &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;First specify a table&amp;quot;&lt;/span&gt;);

        currentTableOptions.JoinCondition = joinCondition;
        
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Where(&lt;span style="color: blue"&gt;string &lt;/span&gt;filter)
    {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter = filter;

        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;T&amp;gt; Execute&amp;lt;T&amp;gt;()
    {
        tableOptionsList
            .ForEach(options =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(
                &lt;span style="color: #a31515"&gt;&amp;quot;From table: {0}, alias: {1}, join on: {2}&amp;quot;&lt;/span&gt;, 
                options.TableName, options.Alias, options.JoinCondition));
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Where: {0}&amp;quot;&lt;/span&gt;, filter);    
        
        &lt;span style="color: green"&gt;// fake result
        &lt;/span&gt;&lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();
    }

    &lt;span style="color: blue"&gt;#endregion
&lt;/span&gt;}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The Query class always returns itself in each method, so that subsequent calls always refer to the same instance. This way information about query is collected step by step. &lt;/p&gt;

&lt;p&gt;There are however some problems with this code. Some parts of the query are mandatory, while other are optional. Some can appear only once. Some have to be provided in specific sequence in order to make sense. You can always validate conditions in code and throw exceptions if user of your library does something wrong, but it’s always better to guide user and detect errors at compile time. Also, we should make our interface more intuitive. Suppose you don’t know the structure of SQL query, but want to use the library. What do you do if Intellisense shows you this?&lt;/p&gt;

&lt;p&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh4.ggpht.com/_Egs311swNl0/Sj1OxCg6gMI/AAAAAAAAAKU/9W6Bz8vfvZM/image%5B10%5D.png?imgmax=800" width="256" height="215" /&gt; &lt;/p&gt;

&lt;p&gt;Well, you refer to the documentation. But who likes to do this? Wouldn’t it be better if the library took you by the hand? We are going to improve our interface a little by ensuring following things:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;From() is the only mandatory call here, so we’re not letting user do anything until this method is called &lt;/li&gt;

  &lt;li&gt;When Join() is called, only available options should be Alias() (to assign table an alias) and On() (to specify the join condition). After calling On() we want to return to regular interface. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In order to do this, we should define more than one interface for the Query class. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilderMandatory
&lt;/span&gt;{
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;From(&lt;span style="color: blue"&gt;string &lt;/span&gt;tableName);
}

&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder
&lt;/span&gt;{
    &lt;span style="color: #2b91af"&gt;IQueryJoinBuilder &lt;/span&gt;Join(&lt;span style="color: blue"&gt;string &lt;/span&gt;tableName);
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Alias(&lt;span style="color: blue"&gt;string &lt;/span&gt;alias);
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;Where(&lt;span style="color: blue"&gt;string &lt;/span&gt;filter);

    &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;T&amp;gt; Execute&amp;lt;T&amp;gt;();
}

&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryJoinBuilder
&lt;/span&gt;{
    &lt;span style="color: #2b91af"&gt;IQueryJoinBuilder &lt;/span&gt;Alias(&lt;span style="color: blue"&gt;string &lt;/span&gt;alias);
    &lt;span style="color: #2b91af"&gt;IQueryBuilder &lt;/span&gt;On(&lt;span style="color: blue"&gt;string &lt;/span&gt;joinCondition);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Create() method of the QueryFactory class now returns IQueryBuilderMandatory interface instead of IQueryBuilder. The Query class implements all three of the interfaces:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Query &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IQueryBuilderMandatory&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IQueryBuilder&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IQueryJoinBuilder
&lt;/span&gt;{
    ...
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Implementation also changes slightly. The Join() method now returns IQueryJoinBuilder interface (body stays the same).&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IQueryJoinBuilder &lt;/span&gt;Join(&lt;span style="color: blue"&gt;string &lt;/span&gt;tableName)
{
    ...
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;There also have to be two explicit implementations of the Alias() method (since it is defined in two interfaces with the same parameters, but different return type). Their body is the same as body of the Alias() method in first version of the class – or it can be extracted to private method of course.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;IQueryBuilder IQueryBuilder&lt;/span&gt;.Alias(&lt;span style="color: blue"&gt;string &lt;/span&gt;alias)
{
    ...
}

&lt;span style="color: #2b91af"&gt;IQueryJoinBuilder IQueryJoinBuilder&lt;/span&gt;.Alias(&lt;span style="color: blue"&gt;string &lt;/span&gt;alias)
{
    ...
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And that’s it. Now when user opens Intellisense at the begining of query definition, he sees only the From() method:&lt;/p&gt;

&lt;p&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_Egs311swNl0/Sj1OxgZxITI/AAAAAAAAAKY/qGsmKgyJ_io/image%5B14%5D.png?imgmax=800" width="559" height="129" /&gt; &lt;/p&gt;

&lt;p&gt;After calling From(), more options become available:&lt;/p&gt;

&lt;p&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/Sj1OyTbIuSI/AAAAAAAAAKc/R52CdRhQey4/image%5B22%5D.png?imgmax=800" width="497" height="196" /&gt; &lt;/p&gt;

&lt;p&gt;And when defining a joined table, only relevant methods are available:&lt;/p&gt;

&lt;p&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh4.ggpht.com/_Egs311swNl0/Sj1OyxufldI/AAAAAAAAAKg/e1CcFV7WJsM/image%5B26%5D.png?imgmax=800" width="526" height="177" /&gt; &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;This still is far from perfect. There are possible some combinations, which are not correct syntax or make no sense. But it serves as a good example. Where you can take it is up to you.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/06/building-fluent-interface.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/06/building-fluent-interface.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-2739539833622071456?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/2739539833622071456/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=2739539833622071456' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/2739539833622071456'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/2739539833622071456'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/06/building-fluent-interface.html' title='Building a fluent interface'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_Egs311swNl0/Sj1OxCg6gMI/AAAAAAAAAKU/9W6Bz8vfvZM/s72-c/image%5B10%5D.png?imgmax=800' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-4693438008583673834</id><published>2009-05-26T20:29:00.001+02:00</published><updated>2009-05-26T20:30:14.117+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><title type='text'>Code contracts in .NET 4.0</title><content type='html'>&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;Code contracts&lt;/a&gt; are a nice feature, that will be included in .NET 4.0’s BCL. They allow you to express assertions on method parameters and object state in explicit manner. Surely everyone has already written his Guard class to achieve &lt;a href="http://en.wikipedia.org/wiki/Design_by_contract"&gt;Design by Contract&lt;/a&gt; approach, but .NET’s code contracts work a little different. Look at this:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Account
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private decimal &lt;/span&gt;balance;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;Account(&lt;span style="color: blue"&gt;decimal &lt;/span&gt;balance)
    {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.balance = balance;
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Debit(&lt;span style="color: blue"&gt;decimal &lt;/span&gt;amount)
    {
        &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.Requires(10 &amp;lt; amount, 
            &lt;span style="color: #a31515"&gt;&amp;quot;Amount cannot be less than 10&amp;quot;&lt;/span&gt;);
        &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.Requires(amount &amp;lt;= &lt;span style="color: blue"&gt;this&lt;/span&gt;.balance, 
            &lt;span style="color: #a31515"&gt;&amp;quot;The amount to debit exceeds account balance&amp;quot;&lt;/span&gt;);
        &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.Ensures(&lt;span style="color: blue"&gt;this&lt;/span&gt;.balance == &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.OldValue(&lt;span style="color: blue"&gt;this&lt;/span&gt;.balance) - amount,
            &lt;span style="color: #a31515"&gt;&amp;quot;Operation has resulted in incorrect final balance&amp;quot;&lt;/span&gt;);

        &lt;span style="color: blue"&gt;this&lt;/span&gt;.balance -= amount;
    }

}

&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color: #2b91af"&gt;Account &lt;/span&gt;ac1 = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Account&lt;/span&gt;(100);
        ac1.Debit(5);
    }
}&lt;/pre&gt;

&lt;p&gt;There are at least two interesting things about this piece of code. First, note that expectations of exit condition are expressed before the value even gets calculated. Secondly, you can use variable’s old value (that is a value it had just before method invocation) in exit condition in order to compare it with this variable’s value after method has been executed. This is possible thanks to the way code contracts work. After compilation, assembly is processed and rewritten, so that assertions can be expressed in IL. This works in similar way as PostSharp. There are also other “special” values, that can be used in conditions like method’s return value or value of output parameter. Execution of the above code snippet results with this error notification:&lt;/p&gt;

&lt;p&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_Egs311swNl0/Shw1GnseAdI/AAAAAAAAAIg/ykKKYDmd8Y4/image%5B4%5D.png?imgmax=800" width="421" height="494" /&gt; &lt;/p&gt;

&lt;p&gt;Note, that you can actually see the condition in the message. You can also state conditions, that should always be true for object’s state:&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;ContractInvariantMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;protected void &lt;/span&gt;ObjectInvariant()
{
    &lt;span style="color: #2b91af"&gt;Contract&lt;/span&gt;.Invariant(&lt;span style="color: blue"&gt;this&lt;/span&gt;.balance &amp;gt;= 0);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;There are also means to express contracts over interfaces and abstract methods. Contracts are inherited, but cannot be modified in subtypes (&lt;a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle"&gt;Liskov Substitution Principle&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;So that was runtime checking, but there’s also another mode – static checking, which occurs during compilation. Warnings about possible assertion violations are displayed in Error List window. Unfortunately I was unable to get any satisfying results with the code snippet above.&amp;#160; All I got was information, that my assertions are “unproven”:&lt;/p&gt;

&lt;p&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh5.ggpht.com/_Egs311swNl0/Shw1HDfIiXI/AAAAAAAAAIk/0vxO3FCFZZA/image%5B7%5D.png?imgmax=800" width="594" height="279" /&gt; &lt;/p&gt;

&lt;p&gt;This is not really helpful ;) I checked tutorial videos and forums, but for other people this appears to work just fine. Strange I say. &lt;a href="http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf"&gt;Documentation&lt;/a&gt; only says:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;First, a word of caution: Static code checking or verification is a difficult endeavor. It requires a relatively large effort in terms of writing contracts, determining why a particular property cannot be proven, and finding a way to help the checker see the light.
    &lt;br /&gt;Before you start using the static checker in earnest, we suggest you spend enough time using contracts for runtime checking to familiarize yourself with contracts and the benefits they bring in that domain.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I don’t think this feature is going to be widely used if it will require special considerations from it’s users. Anyway, this feature seems to be only available for users of VSTS, which is a big disadvantage.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/05/code-contracts-in-net-40.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/05/code-contracts-in-net-40.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-4693438008583673834?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/4693438008583673834/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=4693438008583673834' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4693438008583673834'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4693438008583673834'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/05/code-contracts-in-net-40.html' title='Code contracts in .NET 4.0'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh5.ggpht.com/_Egs311swNl0/Shw1GnseAdI/AAAAAAAAAIg/ykKKYDmd8Y4/s72-c/image%5B4%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-6532896958904562143</id><published>2009-05-21T23:45:00.001+02:00</published><updated>2009-05-21T23:45:11.029+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='IIS'/><category scheme='http://www.blogger.com/atom/ns#' term='communication'/><category scheme='http://www.blogger.com/atom/ns#' term='WCF'/><title type='text'>Why does everything have to be so hard?</title><content type='html'>&lt;p&gt;All I wanted was to get a really simple functionality of uploading quite large files (~100 MB) from mobile device to a server. Seems easy to achieve, right? Well it’s not.&lt;/p&gt;  &lt;p&gt;My original idea was to create a web service, that would orchestrate the upload process. A client would request upload of one or more files. File information would be recorded in database, then the web service would return URLs for the client to perform HTTP PUT requests. After finishing upload of each file, the client would notify the web service. It is important that the upload has to be streamed, because buffering whole file in the memory on either client or web server would cause extreme performance penalty. Also, a mechanism for upload resuming should be provided, but this seemed easy to do with Content-Range header. I assumed I can use standard IIS mechanisms to achieve this and that’s where I was wrong.&lt;/p&gt;  &lt;p&gt;Firstly, in order to get HTT PUT on IIS, the WebDAV feature has to be installed. And it turns out that the standard implementation provided by Microsoft doesn’t support Content-Range header (attaching this header resulted in HTTP 50* status code). There are other implementations, but since this application was a small internal project, it had no budget to buy one. What’s more, PUT verb always requires authentication with this implementation of WebDAV and that prevents streaming. Why?&amp;#160; .NET’s HttpWebRequest needs to buffer whole request in order to perform authentication and setting AllowWriteStreamBuffering to false causes exception to be thrown. Well if you only need to perform Basic HTTP authentication this problem can be worked around by manually attaching authentication header to the request, but still!&lt;/p&gt;  &lt;p&gt;Ok, so if not that way, maybe another then - FTP. Oh yeah, I just forgot that .NET CF doesn’t have classes for FTP support. Darn. There are of course commercial libs, but as I said earlier, I could not buy them. Maybe I should put out a web page with upload control and POST files to the server? Oops – not resumable.&lt;/p&gt;  &lt;p&gt;Well why not implement my own http handler to handle the PUT requests? Yes, idea seemed brilliant, but unfortunately it turns out, that there’s no easy way to stream request from client. The request gets buffered in the memory and the http handler is called when whole request is completed. This was unacceptable. After a lot of digging I found this &lt;a href="http://darrenjohnstone.net/2008/07/03/aspnet-file-upload-revisted-part-1-iis-7-support/"&gt;post&lt;/a&gt;, which describes how to work around that problem, but hey – there’s a code that sets private fields of ASP.NET classes using reflection! This definitely isn’t a supported scenario. I decided, that I can’t accept this solution. I mean, shouldn’t request streaming be an easy to perform task? Isn’t that quite common thing to do?&lt;/p&gt;  &lt;p&gt;I ended up with solution, that uploads files by sequential web service requests, chunk by chunk. This is quite ugly and requires client to transfer around 33% percent more data than other solutions – due to Base64 encoding of binary data in SOAP messages. But at least it works!&lt;/p&gt;  &lt;p&gt;So what is the point of me ranting about this? There’s none really ;) Sometimes I just want to scream: “Why does everything have to be so hard?!”&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/05/why-does-everything-have-to-be-so-hard.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/05/why-does-everything-have-to-be-so-hard.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-6532896958904562143?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/6532896958904562143/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=6532896958904562143' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/6532896958904562143'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/6532896958904562143'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/05/why-does-everything-have-to-be-so-hard.html' title='Why does everything have to be so hard?'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-3173578308294201270</id><published>2009-05-14T20:15:00.001+02:00</published><updated>2009-05-14T20:15:07.608+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='identity and access'/><category scheme='http://www.blogger.com/atom/ns#' term='communication'/><category scheme='http://www.blogger.com/atom/ns#' term='WCF'/><title type='text'>The Geneva framework</title><content type='html'>&lt;p&gt;The “Geneva”, while being a very interesting framework developed by Microsoft, isn’t getting much buzz on the blogs. A beta 2 version &lt;a href="http://devlicio.us/blogs/ziemowit_skowronski/archive/2009/05/12/geneva-beta-2-released.aspx"&gt;was just recently released&lt;/a&gt; and the final version is planned somewhere in 2009.&lt;/p&gt;  &lt;p&gt;The framework aims at providing an easy to use solution for &lt;a href="http://en.wikipedia.org/wiki/Federated_identity"&gt;federated authentication&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc163366(en-us).aspx"&gt;claims based security&lt;/a&gt;. None of those concepts are new in IT world. There are standards from WS-* family, which encompass both. In fact, WCF provides both claims based security plumbing code and bindings compatible with WS-Federation standard. The problem was, that those concepts were hard to implement in applications and required a lot of effort from developers. There also were no easy means of implementing own STS (Security Token Service). This changes with “Geneva”, which tries to make usage of federation and claims based security as easy as possible. As for claims, a developer can access them using IClaimsPrincipal interface (which derives from IPrincipal) – this integrates very well with security mechanisms built into .NET. There are even ASP.NET controls provided making implementation of ASP.NET based Relaying Parties and Security Token Services a lot easier.&amp;#160; But Geneva is not only a library to use in your code. It also consists of two more components – the Geneva Server, which is a STS (with identity database and GUI for administration) as well as extensions to Windows CardSpace. I’m not going to go into details with this – there are very &lt;a href="http://download.microsoft.com/download/7/d/0/7d0b5166-6a8a-418a-addd-95ee9b046994/Introducing_Geneva_Beta1_Whitepaper.pdf"&gt;good&lt;/a&gt; &lt;a href="http://download.microsoft.com/download/7/d/0/7d0b5166-6a8a-418a-addd-95ee9b046994/GenevaFrameworkWhitepaperForDevelopers.pdf"&gt;whitepapers&lt;/a&gt; on this topic and I’d hate to just copy them here. Instead I would like to write about two usage cases, that got me most interested. &lt;/p&gt;  &lt;h3&gt;Authentication Assurance&lt;/h3&gt;  &lt;p&gt;Not directly related to federation, “Authentication assurance” sample from Geneva SDK presents a case, where different parts of system require different levels of security. For example browsing the order list is not a security critical operation and user can be authenticated based on his Windows account (not to bother him with different form of authentication). When performing more sensitive operations like canceling an order, system might require a stronger proof of user’s identity like a certificate stored on a smart card. Geneva’s programming model makes it easy to secure operations according to their sensitivity level. Developer just needs to access authentication type stored as one of user claims in IClaimsPrincipal. Then, if authentication type is too weak, user is required to prove his identity in another way (and possibly in another STS).&lt;/p&gt;  &lt;h3&gt;“Act As” Scenario&lt;/h3&gt;  &lt;p&gt;In one of the &lt;a href="http://download.microsoft.com/download/7/d/0/7d0b5166-6a8a-418a-addd-95ee9b046994/GenevaFrameworkWhitepaperForDevelopers.pdf"&gt;whitepapers&lt;/a&gt; you can read:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;When you build a multi-tier system, typically with a web front end and a collection of web services and other resources on the back end, you have a tough choice to make. Should the web front end use its own identity to access those back end resources, or should delegate the user’s credentials to make those requests? If you choose the first option, you end up with what is known as a trusted subsystem model. If you choose the second, you’ll need some way to delegate the client’s identity to the back end. There are performance and security tradeoffs for both of these choices, with the trusted subsystem model generally favoring performance over security and the delegation model generally favoring security over performance.&lt;/p&gt;    &lt;p&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The example is:&lt;/p&gt;  &lt;p&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/SgxfpypHM6I/AAAAAAAAAIA/THt__UP-xSA/image%5B16%5D.png?imgmax=800" width="504" height="263" /&gt; &lt;/p&gt;  &lt;p&gt;Web application talks to Service1, which in turn talks to Service2. How should Service1 authenticate at Service2? First solution is to use same credentials for each user of web application. This creates the trusted subsystem and Service2 has to trust Servce1 to only perform those operations, which are permitted for the user. The other solution requires Service1 to act on behalf of the user, which allows Service2 to make it’s own security assertions. In order to achieve that, a special kind of security token has to be issued for Service1, which contains ActAs property set to the users identity.&lt;/p&gt;  &lt;p&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/SgxfqXJRFiI/AAAAAAAAAIE/e5KbnSMZymY/image%5B20%5D.png?imgmax=800" width="504" height="264" /&gt; &lt;/p&gt;  &lt;p&gt;What’s more, Geneva provides means of transforming security token into Windows identity, which for example allows for using Windows authentication while accessing SQL Server data store by back end services. I recommend you download the beta and check it out yourself.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/05/geneva-framework.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/05/geneva-framework.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-3173578308294201270?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/3173578308294201270/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=3173578308294201270' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3173578308294201270'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3173578308294201270'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/05/geneva-framework.html' title='The Geneva framework'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/_Egs311swNl0/SgxfpypHM6I/AAAAAAAAAIA/THt__UP-xSA/s72-c/image%5B16%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-6715757642939927623</id><published>2009-04-09T20:58:00.001+02:00</published><updated>2009-04-09T20:58:52.866+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='testing'/><title type='text'>Tips on refactoring towards testability</title><content type='html'>&lt;p&gt;Last time I was expressing my doubts about the value of unit testing. This time I decided to go back to the beginning and show how to start with testing. Newcomers to unit testing often ask themselves how to test things, that are seemingly untestable. Here I gathered some tips on restructuring application’s code in order to achieve testability.&lt;/p&gt;  &lt;h3&gt;Base principles&lt;/h3&gt;  &lt;p&gt;What you really want to achieve is two things: possibly low level of component coupling and separated responsibilities. Both things mean ease of testing of one component in separation from other components in the system. The simplest thing to do in order to decouple two classes is to remove direct dependency between them by means of interfaces. When the class we chose for a test subject depends only on interfaces – not concrete classes – these interfaces can be easily mocked, either by hand or using one of the numerous mocking libraries. This allows you to test your class in separation and assert both it’s state and behavior. The single responsibility principle states, that each class should have only one responsibility. In practice this means, that classes performing business logic should not contain code related to any other of the application concerns, for example persistence. This way your logic is testable without necessity to have a database in place. &lt;/p&gt;  &lt;p&gt;Where interfaces are not applicable, you can usually use inheritance.This however requires you to mark methods and properties of mocked classes as virtual. Most mocking frameworks support mocking of classes. Remember, that high coupling between application components makes unit testing very hard or even impossible due to extensive setup required to perform even simplest test.&lt;/p&gt;  &lt;h3&gt;Dependency injection containers&lt;/h3&gt;  &lt;p&gt;You may wonder how to wire up components of your application when they are supposed to be dependent merely on interfaces. Somewhere the instances of concrete types have to be instantiated anyway, right? This is where DI container come to the rescue. The idea is to register application’s components in a container using the component’s interface as a key. Then, all component dependencies defined in it’s constructor or as public properties can be injected with container’s contents. Components are added to the container at application’s setup phase, for example in entry point method or even declared in XML configuration (although I’m not a fan of this solution). This enables you to easily change container’s registrations during a test and to use mocks instead of real components. Don’t think that DI containers serve only the purpose of making your application testable. As &lt;a href="http://ayende.com/Blog/archive/2008/03/26/DI-amp-IoC-are-not-about-testing.aspxhttp://ayende.com/Blog/archive/2008/03/26/DI-amp-IoC-are-not-about-testing.aspx"&gt;Ayende Rahien writes&lt;/a&gt;, it’s not their main purpose. They help a lot, but what they mainly do is to enable you to structure your application in a better way.&lt;/p&gt;  &lt;h3&gt;Laws and principles&lt;/h3&gt;  &lt;p&gt;All principles of good object oriented design positively influence testability. Like for example Single Responsibility Principle (SRP) mentioned earlier. Please see &lt;a href="http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf"&gt;“Design Principles and Design Patterns” by Robert C. Martin&lt;/a&gt; for more detailed information. I’ll just mention the &lt;a href="http://en.wikipedia.org/wiki/Law_Of_Demeter"&gt;Law of Demeter&lt;/a&gt; here. It states that a component should only directly interact with it’s immediate neighbors in dependency graph. The component should not know nothing of it’s neighbor’s properties structure. In code instead of:&lt;/p&gt;  &lt;div class="code"&gt;musician.Trumpet.Blow();&lt;/div&gt;  &lt;p&gt;you'd write:&lt;/p&gt;  &lt;div class="code"&gt;musician.PlayInstrument();&lt;/div&gt;  &lt;p&gt;You don’t care about PlayInstrument’s implementation. This way test subject is not dependent on Trumpet class, just the Musician class. There is less coupling and testing and mocking is easier. This law also applies to application’s layers – each layer should only interact with a layer directly underneath it. &lt;/p&gt;  &lt;h3&gt;What about the UI?&lt;/h3&gt;  &lt;p&gt;There are applications, that have a lot of logic related to user interface: disable this, change color of that… In traditional approach testing of that logic is almost impossible – unless you’re using GUI automated test’s, which didn’t convinced me yet as I wrote in my last post. However there are some design patterns like MVP, MVC and MVVM which allow you to achieve testability in this area. The idea behind all of those patterns is to extract view logic from views and place it in separate classes. Those classes interact with the view itself through interface (MVP, MVC) or don’t interact at all (MVVM) and therefore are testable without need to really make use of any real controls. As for the view itself – you need to keep it as dumb as possible. If there is almost no complexity, it’s not likely to break.&lt;/p&gt;  &lt;h3&gt;The framework doesn’t allow me to test this…&lt;/h3&gt;  &lt;p&gt;Quite often you have to make use of third party APIs that are not really designed with testability in mind. This API may be for a component that is slow or requires extensive setup in order to test. It would be better not to have it in test at all, but how to do this when we have direct dependency and no control of API’s structure? The answer is: build a layer of abstraction over this API. An example here is very easy to find: the System.IO.File class. It’ static methods are very useful, but couple your code with file system directly. Instead I suggest you build an &lt;a href="http://en.wikipedia.org/wiki/Adapter_pattern"&gt;adapter&lt;/a&gt; and extract it’s interface. &lt;/p&gt;  &lt;h3&gt;Final thoughts&lt;/h3&gt;  &lt;p&gt;Although mocking frameworks give you a lot of power, try to assert component’s state after operation, not it’s behavior during. Asserting behavior tends to couple the test and components implementation, which is not really good, because increases cost of maintenance. Testing is hard to start, but it gets easier with each step.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/04/tips-on-refactoring-towards-testability.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/04/tips-on-refactoring-towards-testability.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-6715757642939927623?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/6715757642939927623/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=6715757642939927623' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/6715757642939927623'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/6715757642939927623'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/04/tips-on-refactoring-towards-testability.html' title='Tips on refactoring towards testability'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8510230698784903604</id><published>2009-03-31T22:14:00.001+02:00</published><updated>2009-03-31T22:14:42.166+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='testing'/><title type='text'>Random thoughts on automated testing</title><content type='html'>&lt;p&gt;Recently I’ve been thinking what is required for unit tests to be valuable. First conclusions is that you need good code coverage of critical areas and the tests need to be comprehensive. What is the value of a good test suite? It allows you to easily detect bugs introduced by making software modifications. If you lack test coverage in some areas, a bug can easily slip into your application unnoticed. The other conclusion was, that tests need to be written by people who fully understand the purpose. What I noticed is that some developers just want to “write a test” without any thought on what they really want to test. In worst case they just copy from another test and there you have it – useless piece of code that introduces problems only. So first state what is the purpose of your test (I’m a fan of naming convention, that describes test’s role), then implement it. With those two things you can say that build in your CI environment was successful. &lt;/p&gt;  &lt;p&gt;Can you really prove unit tests are worth the effort? What if your manager comes to you and asks you for an example, where well written test suite saved the day? Or at least made your work easier? I whish there was a study on what types of application benefit the most from automated testing. I think that apps concerned mainly with complex business logic or mathematical calculations are at the top of the list, while CRUD and rich-UI-hardly-any-content applications are at the very bottom. With business logic it’s all about whether you can or cannot test components in separation from rest of the system. With UI the only way to automate testing process is to use some UI test automation tools, but they are specific to technology and usually very clumsy and therefore not popular.The best way to test in those cases is just to let your testers take over.&lt;/p&gt;  &lt;p&gt;In any case one may wonder if automated tests are really worth the amount of work, that is put into their creation and maintenance. In my actual project I made an observation, that usually when test fails, it is due to desired modifications in code and correction has to be made in the test itself, not the code, in order to make it pass. I tried to think of the reason of this situation, but all I came up with was a conclusion, that the tests are too complicated. We try to keep components of our application as loosely coupled as possible, nonetheless they have dependencies, that need to be set up in order to run the test case. Usually a change in program’s structure causes a few tests to fail. We use RhinoMocks extensively and I’m aware, that state-based testing introduces a lot less complexity than behavior-based testing, but most of the components are about behavior and interaction and this way of testing is unavoidable. What I’m trying to say is that it’s not clear to me if automated tests save money for my organization. Maybe manual-only testing would be cheaper? A nice experiment would be to run same project on two different teams with two approaches to testing and see which works more effectively. It’s all about the money in the end. But how do you measure savings? When releasing buggy software you have to count both money lost for maintenance and money you won’t earn in future because of poor quality image of organization’s software. This is very hard to measure.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/03/random-thoughts-on-automated-testing.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/03/random-thoughts-on-automated-testing.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8510230698784903604?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8510230698784903604/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8510230698784903604' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8510230698784903604'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8510230698784903604'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/03/random-thoughts-on-automated-testing.html' title='Random thoughts on automated testing'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-1502933470570216502</id><published>2009-02-28T21:35:00.001+01:00</published><updated>2009-02-28T21:35:26.071+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><title type='text'>Handling complex use case flows</title><content type='html'>&lt;p&gt;There are applications, that have fairly complex flows in user interface. In application I’m currently working on there are forms which can be visited many times during execution of one business process, each time behaving differently according to context (values collected earlier). The challenge here is how to write code, that will be testable and maintainable and also not too complex? &lt;/p&gt;  &lt;p&gt;I will use a simplified example here. Let’s say the application is used to collect information about car parts. Parts can grouped and each group get’s it’s own ID. You can also associate parts with a car, in which they have been mounted. If you decide to enter car information, it is obligatory to also enter information about car body (treated as car part). The business analyst says, he wants application to work following way:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;If I want to enter car part information, I choose “Enter car part” from menu. Car part form is shown.&lt;/li&gt;    &lt;li&gt;I then enter car part information and I have to provide car part group identifier.&lt;/li&gt;    &lt;li&gt;I click OK and return to menu. Now I have two options: “Enter car part” as previously – this will create new car part group, and “Enter additional car part” – this will add a car part to previously created group (it’s number is a context).&lt;/li&gt;    &lt;li&gt;There also is a possibility to choose “Enter car” from the menu. This option also creates new group, but shows car form instead of car part form.&lt;/li&gt;    &lt;li&gt;After filling car information, I’m automatically redirected to car part form with car part type set to “car body”. I have to provide group identifier.&lt;/li&gt;    &lt;li&gt;If car body number meets certain criteria, I’m redirected to registration certificate form, where I have to provide registration certificate information.&lt;/li&gt;    &lt;li&gt;After doing this, I return to the menu and have option to start a new group or add parts to recently created group. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Let’s not go into details why exactly is the UI so awkwardly designed. Sometimes your users think differently than you do. Instead, let’s look at navigation between forms:&lt;/p&gt;  &lt;p&gt;&lt;img title="Form navigation diagram" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="254" alt="Form navigation diagram" src="http://lh3.ggpht.com/_Egs311swNl0/SamgA0PCaDI/AAAAAAAAAGw/9_Vbbgtqm4o/image%5B5%5D.png?imgmax=800" width="377" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;Looks pretty simple, but it doesn’t reflect the use case flow at all. The car part form in this simple example can work in 3 modes: entering a car part, entering additional car part and entering car body. This introduces some complexity already, but the tricky part is this: where do you go after completing the car part form? It can be either application menu or registration certificate form depending on car part information and what happened earlier in the flow. Basically what we need here is a state diagram.&lt;/p&gt;  &lt;p&gt;&lt;img title="Application state diagram" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="327" alt="Application state diagram" src="http://lh3.ggpht.com/_Egs311swNl0/SamgBQrYh8I/AAAAAAAAAG0/3-Efv45p_4U/image%5B13%5D.png?imgmax=800" width="599" border="0" /&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;This state machine represents our business process of collection car part group information. As you can see the transitions of states are a little more complex than navigation between forms. Three of the states use the same form to perform different tasks: Car, Car part and Car body. Transitions marked with light gray are not directly part of business process, but rather initiate new car part group. It now becomes clear where should we go after leaving car part form – this depends on what state are we currently in. &lt;/p&gt;  &lt;p&gt;This diagram makes it clear for us how the application should behave. But how to implement this process? First and most obvious thought is to create a bunch of flag variables and implement some if-else statements. While this is OK in simple scenarios, the real world complexity will make such code completely unreadable and hard to maintain. Next you may consider a workflow engine. This allows you to express transition logic in readable way, but in most cases this is too heavyweight for regular applications. And what if you have to implement this on mobile device? No workflow engine there.&lt;/p&gt;  &lt;p&gt;Suppose this application uses MVC pattern. We focus on the “C” here. The controller most probably has methods like “OnCarPartEntered” taking in car part information object as parameter. This method saves the information and decides what view to show next and in what mode. This is where your “if-else” would go if you opted for the first solution. In this post I suggest using the state machine pattern to implement the controller (a similar was used in my &lt;a href="http://marcinbudny.blogspot.com/2008/11/circuit-breaker-pattern-aop-style.html"&gt;post on circuit breaker pattern&lt;/a&gt;). You have to implement your controller interface for each state separately. Following diagram depicts the situation:&lt;/p&gt;  &lt;p&gt;&lt;img title="Class diagram" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="320" alt="Class diagram" src="http://lh4.ggpht.com/_Egs311swNl0/SamgBwZPGaI/AAAAAAAAAG4/csiOcqH5edc/image%5B25%5D.png?imgmax=800" width="467" border="0" /&gt;&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;The context class is an access point to the state machine. It knows all the states and knows which state is the current one. It exposes business process context (group number here) and methods used to switch states through IContext interface. Since it also implements the controller interface, it forwards all method calls to current state. Each application state has it’s own implementation of IMyController. These classes derive from StateBase, which can contain behavior common to all states. Derived classes override this behavior when appropriate. For example the CarBodyState will check the car body number criteria match after leaving car part form. The CarPartState will just return to main menu in this situation. The state classes are also responsible for switching states in reaction to certain actions of the user. Following diagram shows sample state transition:&lt;/p&gt;  &lt;p&gt;&lt;img title="Interaction during state switching" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="435" alt="Interaction during state switching" src="http://lh5.ggpht.com/_Egs311swNl0/SamgCdh6SLI/AAAAAAAAAG8/I8frmRxjoC8/image%5B29%5D.png?imgmax=800" width="758" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Before executing this sequence, application is in Car body state and car part form is displayed. After execution, application is in Additional part state and menu form is displayed. The code is quite straightforward, so I won’t be cluttering this post with it :)&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/02/handling-complex-use-case-flows.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/02/handling-complex-use-case-flows.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-1502933470570216502?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/1502933470570216502/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=1502933470570216502' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/1502933470570216502'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/1502933470570216502'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/02/handling-complex-use-case-flows.html' title='Handling complex use case flows'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/_Egs311swNl0/SamgA0PCaDI/AAAAAAAAAGw/9_Vbbgtqm4o/s72-c/image%5B5%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8061157173607407946</id><published>2009-02-11T21:05:00.001+01:00</published><updated>2009-02-11T21:05:13.453+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='team work'/><title type='text'>Zero friction APIs</title><content type='html'>&lt;p&gt;This is what Ayende &lt;a href="http://ayende.com/Blog/archive/2008/02/08/Dont-make-me-THINK.aspx"&gt;talked about&lt;/a&gt; some time ago now and got a few interesting comments. The essence of his post is that you (an architect) should be able to setup a project in a way that will make the easiest way of doing things also the best way in terms of the architecture. &lt;/p&gt;  &lt;p&gt;There is a lot of base code to be developed before the actual business functionality can be implemented. I mean, even if you’re in position when you can take advantage of latest technologies, all the jEntityMVCInjectionFoundation libraries, you usually build your own abstractions and base class libraries in order to both remove dependency on particular technology and encapsulate some reusable behaviors. These base class libraries of yours are used by developers on your team. The question is do you put enough effort in designing these libraries to be zero friction? I’ve seen some APIs being pretty slick (StructureMap) and some really ugly (LLBLGen Pro), but these are widely used libraries and their authors have to design friendly APIs as part of their job. You should too. Especially because the developers will most probably make direct use those other libraries less often than will use your base class library.&lt;/p&gt;  &lt;p&gt;If I were to create a list of things that should be considered when creating a library, this would be in order of importance:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Your library should get things done. And do it the best way possible in terms of complexity, performance and maintainability. (Yes, this is always most important and it’s the point of creating the library in the first place. The other are worthless without this one – keep this in mind).     &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Name classes, methods, etc. so that they are self-explanatory and obvious. Don’t make me refer to any documentation. (This, as everything, is not always possible. If that’s the case, provide a friendly and useful documentation for me).      &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Think about testing. Is your library designed so that testing is easy&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin: 5px; border-right-width: 0px" height="176" alt="image" src="http://lh5.ggpht.com/_Egs311swNl0/SZMvdB2RcNI/AAAAAAAAAGs/p3YrMwGPdwk/image%5B8%5D.png?imgmax=800" width="244" align="right" border="0" /&gt;? Can I mock your classes?       &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Make sure you don’t have any hidden dependencies. Your classes will be used by other people that won’t have an insight on their inner workings. Suppose you have method X. In order to call it, you have to call Y before. Y doesn’t return any value that is used as X’s parameter. It’s a hidden dependency and most probably you’re doing something wrong. Don’t make me refer to sample code in order to do event the simplest things (although samples will never hurt).     &lt;br /&gt;      &lt;br /&gt;&amp;#160;&lt;/li&gt;    &lt;li&gt;Think about whether your library is easy to extend and maintain. Also think about API versioning policy if applicable.     &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Don’t overcomplicate things. Do not provide a hundred layers of abstraction just because you think in few years they may come in handy. If they will, you can add them at that time – and refactor other things too. Remember, YAGNI.      &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Provide a slick syntax for me. A fluent one if applicable. Make the code look elegant, compact and easy to read. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;If your base and helper class library fulfills most of those things, people using it will be grateful.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/02/zero-friction-apis.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/02/zero-friction-apis.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8061157173607407946?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8061157173607407946/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8061157173607407946' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8061157173607407946'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8061157173607407946'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/02/zero-friction-apis.html' title='Zero friction APIs'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh5.ggpht.com/_Egs311swNl0/SZMvdB2RcNI/AAAAAAAAAGs/p3YrMwGPdwk/s72-c/image%5B8%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-6528614175542011410</id><published>2009-02-04T22:21:00.001+01:00</published><updated>2009-02-04T22:21:46.229+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='.NET CF'/><category scheme='http://www.blogger.com/atom/ns#' term='security'/><title type='text'>HTTPS with client certificate authentication in .NET CF</title><content type='html'>&lt;p&gt;The struggle with .NET CF 1.0 continues.&lt;/p&gt;  &lt;p&gt;The HTTPS is just ordinary HTTP sent over a secure TLS (extension of SSL) connection. The secure connection is initiated in following way:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Server and client negotiate strongest cipher algorithms supported by both parties &lt;/li&gt;    &lt;li&gt;Server sends its certificate to the client &lt;/li&gt;    &lt;li&gt;Client can verify correctness of the certificate by verifying digital signature of the Certification Authority that issued the certificate &lt;/li&gt;    &lt;li&gt;Client generates a random number (master secret), encrypts it with server’s public key and sends it to server. Only server can decrypt this message with its private key. &lt;/li&gt;    &lt;li&gt;Both parties derive a key for symmetric algorithm from the master secret. Following communication is encrypted using this key. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;After completing those steps, client and server have a secure way to communicate. Additionally the client knows, that server is trusted. The server on the other hand doesn’t have any information about the client. It often is required to authenticate the client before allowing it to access confidential resources. This can be done in many different ways, one of which is a client certificate. This option is supported directly in TLS – the client sends its certificate right after it receives certificate from server. To confirm, that it owns this certificate, the client also has to prove, that it owns the private key associated with certificate. In order to do this, after establishing master secret the client sends digital signature over all messages exchanged with server up to that point. Server verifies this signature using client’s public key. &lt;/p&gt;  &lt;p&gt;I’m developing a client that has to authenticate at HTTPS web service with client certificate. Unfortunately this scenario is not supported in .NET CF prior to version 3.5. While looking for a way to work around this problem, I came by library called &lt;a href="http://www.eldos.com/sbbdev/index.php"&gt;SecureBlackbox&lt;/a&gt;. The package called SSLBlackbox supports my scenario and additionally provides very comprehensive support for X509 certificates, which .NET CF lacks. What is interesting, the library developers don’t use any external APIs to perform the cryptography. The implemented all algorithms from scratch. To evaluate this library I needed a test environment. I decided to use simple ASP.NET page hosted on IIS server that would display client certificate information associated with request. The code comes from MSDN:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;protected void &lt;/span&gt;Page_Load(&lt;span style="color: blue"&gt;object &lt;/span&gt;sender, &lt;span style="color: #2b91af"&gt;EventArgs &lt;/span&gt;e)
{
    &lt;span style="color: #2b91af"&gt;HttpClientCertificate &lt;/span&gt;cs = Request.ClientCertificate;
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(cs != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
    {
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;ClientCertificate Settings:&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;Certificate = &amp;quot; &lt;/span&gt;+ cs.Certificate + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;Cookie = &amp;quot; &lt;/span&gt;+ cs.Cookie + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;Flags = &amp;quot; &lt;/span&gt;+ cs.Flags + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;IsPresent = &amp;quot; &lt;/span&gt;+ cs.IsPresent + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;Issuer = &amp;quot; &lt;/span&gt;+ cs.Issuer + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;IsValid = &amp;quot; &lt;/span&gt;+ cs.IsValid + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;KeySize = &amp;quot; &lt;/span&gt;+ cs.KeySize + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;SecretKeySize = &amp;quot; &lt;/span&gt;+ cs.SecretKeySize + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;SerialNumber = &amp;quot; &lt;/span&gt;+ cs.SerialNumber + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;ServerIssuer = &amp;quot; &lt;/span&gt;+ cs.ServerIssuer + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;ServerSubject = &amp;quot; &lt;/span&gt;+ cs.ServerSubject + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;Subject = &amp;quot; &lt;/span&gt;+ cs.Subject + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;ValidFrom = &amp;quot; &lt;/span&gt;+ cs.ValidFrom + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;ValidUntil = &amp;quot; &lt;/span&gt;+ cs.ValidUntil + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;What's this = &amp;quot; &lt;/span&gt;+ cs.ToString() + &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;br&amp;gt;&amp;quot;&lt;/span&gt;);
    }
    &lt;span style="color: blue"&gt;else
    &lt;/span&gt;{
        Response.Write(&lt;span style="color: #a31515"&gt;&amp;quot;No certificate&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;

&lt;p&gt;I also needed to generate certificate for server and client. I used makecert.exe according to hints from &lt;a href="http://blogs.microsoft.co.il/blogs/applisec/archive/2008/04/08/creating-x-509-certificates-using-makecert-exe.aspx"&gt;Manu Cohen-Yashar’s post&lt;/a&gt;. The only modification I made is to generate a personal client certificate rather a one for machine. To do this just specify CurrentUser instead of LocalMachine as a target certificate store.&lt;/p&gt;

&lt;p&gt;Next step is to configure IIS, I use version 7. You need to configure HTTPS binding with created server certificate – configured at web site level. Then you have to add an application under this web site for previously created ASP.NET page. Then, for this application you need to set SSL setting so that SSL is enabled and client certificates are required:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="249" alt="image" src="http://lh6.ggpht.com/_Egs311swNl0/SYoG5McfG6I/AAAAAAAAAGk/m10LsMnFOFA/image%5B4%5D.png?imgmax=800" width="494" border="0" /&gt; &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The easiest way to verify if server’s setup is ok is to browse create page with Internet Explorer. Since IE uses certificates installed in personal store, no additional setup is required for this browser. You can also use Firefox for example, but you need to export the client certificate to PFX file (with private key) and import it to the browser. When a page requests client certificate, the browser will let you choose certificate to be sent. Following is the result from my page:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="326" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/SYoG5qjShKI/AAAAAAAAAGo/AYkV75Jmhu4/image%5B7%5D.png?imgmax=800" width="619" border="0" /&gt; &lt;/p&gt;

&lt;p&gt;Ok, after setting up the server, it was time to write some client code.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TElX509Certificate &lt;/span&gt;cert = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TElX509Certificate&lt;/span&gt;();
    
    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args)
    {
        SBUtils.&lt;span style="color: #2b91af"&gt;Unit&lt;/span&gt;.SetLicenseKey(&lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;license key here&amp;gt;&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue"&gt;var &lt;/span&gt;stream = &lt;span style="color: #2b91af"&gt;File&lt;/span&gt;.OpenRead(&lt;span style="color: #a31515"&gt;@&amp;quot;&amp;lt;client certificate file&amp;gt;.pfx&amp;quot;&lt;/span&gt;);&lt;br /&gt;        cert.LoadFromStreamPFX(stream, &lt;span style="color: #a31515"&gt;&amp;quot;&amp;lt;private key password here&amp;gt;&amp;quot;&lt;/span&gt;, 0);
        stream.Close();&lt;br /&gt;
        &lt;span style="color: #2b91af"&gt;TElHTTPSClient &lt;/span&gt;https = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TElHTTPSClient&lt;/span&gt;();
        https.OnData += &lt;span style="color: blue"&gt;new &lt;/span&gt;SBSSLCommon.&lt;span style="color: #2b91af"&gt;TSBDataEvent&lt;/span&gt;(https_OnData);
        https.OnCertificateValidate += 
            &lt;span style="color: blue"&gt;new &lt;/span&gt;SBSSLCommon.&lt;span style="color: #2b91af"&gt;TSBCertificateValidateEvent&lt;/span&gt;(https_OnCertificateValidate);
        https.OnCertificateNeededEx += 
            &lt;span style="color: blue"&gt;new &lt;/span&gt;SBClient.&lt;span style="color: #2b91af"&gt;TSBCertificateNeededExEvent&lt;/span&gt;(https_OnCertificateNeededEx);
&lt;span style="color: green"&gt;        
        &lt;/span&gt;&lt;span style="color: blue"&gt;int &lt;/span&gt;code = https.Get(&lt;span style="color: #a31515"&gt;&amp;quot;https://myurl/&amp;quot;&lt;/span&gt;);
&lt;span style="color: #2b91af"&gt;        Console&lt;/span&gt;.WriteLine(code);

        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.ReadLine();
        https.Close(&lt;span style="color: blue"&gt;true&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;static bool &lt;/span&gt;wasCert = &lt;span style="color: blue"&gt;false&lt;/span&gt;;

    &lt;span style="color: blue"&gt;static void &lt;/span&gt;https_OnCertificateNeededEx(&lt;span style="color: blue"&gt;object &lt;/span&gt;Sender, &lt;span style="color: blue"&gt;ref &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TElX509Certificate &lt;/span&gt;Certificate)
    {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(wasCert)
            &lt;span style="color: blue"&gt;return&lt;/span&gt;;

        Certificate = cert;
        wasCert = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;static void &lt;/span&gt;https_OnCertificateValidate(&lt;span style="color: blue"&gt;object &lt;/span&gt;Sender, &lt;span style="color: #2b91af"&gt;TElX509Certificate &lt;/span&gt;X509Certificate,
        &lt;span style="color: blue"&gt;ref bool &lt;/span&gt;Validate)
    {
        Validate = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;static void &lt;/span&gt;https_OnData(&lt;span style="color: blue"&gt;object &lt;/span&gt;Sender, &lt;span style="color: blue"&gt;byte&lt;/span&gt;[] Buffer)
    {
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #2b91af"&gt;Encoding&lt;/span&gt;.UTF8.GetString(Buffer));
    }
}&lt;/pre&gt;

&lt;p&gt;Am I the only one that gets impression that syntax could be improved here? Anyway this works just fine. If requested URL requires client certificate, the OnCertificateNeededEx event is called and you can return the certificate. This method is supposed to be called over and over until it returns null in Certificate parameter. This way you can return whole certificate chain. A developer is also required to validate server’s certificate (OnCertificateValidate event). I just return true here, so all certificates are accepted – not a production ready solution.&lt;/p&gt;

&lt;p&gt;All would be great if not for performance issues on mobile devices. It seems that HTTPS handshake requires a lot of computation power, which mobile devices lack. I got results up to 14s for first handshake! I’m still trying to get around this. Also the library’s size is considerable – over 2mb is significant on mobile device.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/02/https-with-client-certificate.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/02/https-with-client-certificate.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-6528614175542011410?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/6528614175542011410/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=6528614175542011410' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/6528614175542011410'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/6528614175542011410'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/02/https-with-client-certificate.html' title='HTTPS with client certificate authentication in .NET CF'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh6.ggpht.com/_Egs311swNl0/SYoG5McfG6I/AAAAAAAAAGk/m10LsMnFOFA/s72-c/image%5B4%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-3307085196857898495</id><published>2009-01-23T17:53:00.001+01:00</published><updated>2009-02-04T22:23:42.435+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='.NET CF'/><category scheme='http://www.blogger.com/atom/ns#' term='web services'/><title type='text'>Java web service interoperability from .NET CF 1.0</title><content type='html'>&lt;p&gt;I don’t suppose anyone else is developing in .NET CF 1.0 now in 2009. Well those are the constraints for project I’m involved in and I prefer to think about this as a challenge :)&lt;/p&gt;  &lt;p&gt;Anyway current topic is interoperability with Java web services. This causes a lot of problems in .NET CF 1.0, some of them weren’t addressed until .NET CF 3.5. In my case it started with inability to generate web service client proxy using standard wsdl.exe tool. &lt;/p&gt;  &lt;p&gt;In this example we have a Java web service for querying cars by name. It returns car description with name and collection of car parts. Each car parts can have a set of string attributes. The model looks like this:&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="111" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/SXn18X00rzI/AAAAAAAAAGg/dvgqh7KMldU/image%5B9%5D.png?imgmax=800" width="532" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160; Let’s say we have WSDL like this one:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;?&lt;/span&gt;&lt;span style="color: #a31515"&gt;xml &lt;/span&gt;&lt;span style="color: red"&gt;version&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1.0&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;encoding&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;UTF-8&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;?&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:definitions &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;ws&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;targetNamespace&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org&lt;/span&gt;&amp;quot; 
                  &lt;span style="color: red"&gt;xmlns:soap&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://schemas.xmlsoap.org/wsdl/soap/&lt;/span&gt;&amp;quot; 
                  &lt;span style="color: red"&gt;xmlns:tns&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org&lt;/span&gt;&amp;quot; 
                  &lt;span style="color: red"&gt;xmlns:wsdl&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://schemas.xmlsoap.org/wsdl/&lt;/span&gt;&amp;quot; 
                  &lt;span style="color: red"&gt;xmlns:xsd&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://www.w3.org/2001/XMLSchema&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:types&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:schema &lt;/span&gt;&lt;span style="color: red"&gt;targetNamespace&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;xmlns:pref&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org/to&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:import &lt;/span&gt;&lt;span style="color: red"&gt;namespace&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org/to&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;schemaLocation&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;myschema.xsd&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;getCarDesc&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:complexType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;carQuery&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;pref:CarQuery&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;maxOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;minOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
          &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:complexType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:element&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;getCatDescResponse&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:complexType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
                &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
                    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;response&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;pref:Car&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;maxOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;minOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;0&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
                &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:complexType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:element&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:schema&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:types&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:message &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;carRequest&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:part &lt;/span&gt;&lt;span style="color: red"&gt;element&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;tns:getCarDesc&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;parameters&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:message&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:message &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;carResponse&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:part &lt;/span&gt;&lt;span style="color: red"&gt;element&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;tns:getCarResponse&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;parameters&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:message&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:portType &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;ws&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:operation &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;getCar&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:input &lt;/span&gt;&lt;span style="color: red"&gt;message&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;tns:carRequest&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:output &lt;/span&gt;&lt;span style="color: red"&gt;message&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;tns:carResponse&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:operation&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:portType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:binding &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;wsSOAP&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;tns:ws&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;soap:binding &lt;/span&gt;&lt;span style="color: red"&gt;style&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;document&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;transport&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://schemas.xmlsoap.org/soap/http&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:operation &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;getCar&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:input&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;soap:body &lt;/span&gt;&lt;span style="color: red"&gt;use&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;literal&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:input&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:output&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;soap:body &lt;/span&gt;&lt;span style="color: red"&gt;use&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;literal&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:output&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:operation&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:binding&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:service &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;ws&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:port &lt;/span&gt;&lt;span style="color: red"&gt;binding&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;tns:wsSOAP&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;wsSOAP&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;soap:address &lt;/span&gt;&lt;span style="color: red"&gt;location&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://myhost/get-cat-web/ws&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:port&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:service&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:definitions&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;There is one service and it has one method, getCar. This method takes CarQuery object as a parameter and returns a Car object as response. The WSDL refers to external schema in myschema.xsd file, which contains type definitions. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;?&lt;/span&gt;&lt;span style="color: #a31515"&gt;xml &lt;/span&gt;&lt;span style="color: red"&gt;version&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1.0&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;encoding&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;UTF-8&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;?&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;schema &lt;/span&gt;&lt;span style="color: red"&gt;xmlns&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://www.w3.org/2001/XMLSchema&lt;/span&gt;&amp;quot; 
        &lt;span style="color: red"&gt;targetNamespace&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org/to&lt;/span&gt;&amp;quot; 
        &lt;span style="color: red"&gt;xmlns:tns&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org/to&lt;/span&gt;&amp;quot; 
        &lt;span style="color: red"&gt;elementFormDefault&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;qualified&lt;/span&gt;&amp;quot;
        &lt;span style="color: red"&gt;xmlns:jaxb&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://java.sun.com/xml/ns/jaxb&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;jaxb:version&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1.0&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;complexType &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;CarPart&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;attribute&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;maxOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;unbounded&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;minOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;complexType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;complexType &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;Car&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;name&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;maxOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;minOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
          &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;parts&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;tns:CarPart&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;maxOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;unbounded&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;minOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;0&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;complexType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;complexType &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;CarQuery&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;element &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;name&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;type&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;maxOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;minOccurs&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;1&lt;/span&gt;&amp;quot; &lt;span style="color: blue"&gt;/&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;sequence&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;complexType&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;schema&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;This works perfectly in Java and is used by Java guys to generate a web service. When you try to feed this to wsdl.exe, the only thing it has to say is:&lt;/p&gt;

&lt;pre class="code"&gt;Error: Unable to import binding 'wsSOAP' from namespace 'http://tempuri.org'.
 - Unable to import operation 'getCar'.
 - The operation binding 'getCar' from namespace 'http://tempuri.org' had invalid syntax.
Missing soap:operation binding.&lt;/pre&gt;

&lt;p&gt;At least wsdl.exe is being quite specific about this one. I went to validate my WSDL at &lt;a href="http://xmethods.net/ve2/Tools.po"&gt;this site&lt;/a&gt; and it confirmed, that I lack soap:operation tag. So I added it and specified operation URI: &lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:operation &lt;/span&gt;&lt;span style="color: red"&gt;name&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;getCar&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;soap:operation &lt;/span&gt;&lt;span style="color: red"&gt;soapAction&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org/ws/getCar&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;style&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;document&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:input&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;soap:body &lt;/span&gt;&lt;span style="color: red"&gt;use&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;literal&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:input&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:output&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;soap:body &lt;/span&gt;&lt;span style="color: red"&gt;use&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;literal&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;/&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:output&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:operation&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The wsdl.exe finished successfully and generated proxy class along with used types. This however was not the end of my struggle. It turned out, that the generated code won’t compile int .NET CF 1.0 as there is no support for Form property of XmlElementAttribute class. The web service method was decorated with this attribute in following way:&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: blue"&gt;return&lt;/span&gt;: System.Xml.Serialization.XmlElementAttribute(&lt;span style="color: #a31515"&gt;&amp;quot;response&amp;quot;&lt;/span&gt;, 
    Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
&lt;span style="color: blue"&gt;public &lt;/span&gt;Car getCar(
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] 
    CarQuery carQuery) 
{
    ...
}&lt;/pre&gt;

&lt;p&gt;It’s really strange that this tool would generate code that won’t compile (and yes, the result was the same when created using Add Web Reference in Smart Device project). I went to look for solution on the web and came up with this modification to WSDL (added elementFormDefault attribute):&lt;/p&gt;

&lt;pre class="code"&gt;...
&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;wsdl:types&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;xsd:schema &lt;/span&gt;&lt;span style="color: red"&gt;elementFormDefault&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;qualified&lt;/span&gt;&amp;quot; 
                &lt;span style="color: red"&gt;targetNamespace&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org&lt;/span&gt;&amp;quot; &lt;span style="color: red"&gt;xmlns:pref&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;http://tempuri.org/to&lt;/span&gt;&amp;quot;&lt;span style="color: blue"&gt;&amp;gt;
...
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;This removed all usages of the Form property of XmlElementAttribute class. The code would now compile, but looked a little different than I expected. Take a look at the Car class:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Car &lt;/span&gt;{
    
    &lt;span style="color: blue"&gt;private string &lt;/span&gt;nameField;
    
    &lt;span style="color: blue"&gt;private string&lt;/span&gt;[][] partsField;
    
    &lt;span style="color: gray"&gt;/// &amp;lt;remarks/&amp;gt;
    &lt;/span&gt;&lt;span style="color: blue"&gt;public string &lt;/span&gt;name {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return this&lt;/span&gt;.nameField;
        }
        &lt;span style="color: blue"&gt;set &lt;/span&gt;{
            &lt;span style="color: blue"&gt;this&lt;/span&gt;.nameField = &lt;span style="color: blue"&gt;value&lt;/span&gt;;
        }
    }
    
    &lt;span style="color: gray"&gt;/// &amp;lt;remarks/&amp;gt;
    &lt;/span&gt;[System.Xml.Serialization.XmlArrayItemAttribute(&lt;span style="color: #a31515"&gt;&amp;quot;attribute&amp;quot;&lt;/span&gt;, &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: blue"&gt;string&lt;/span&gt;), IsNullable=&lt;span style="color: blue"&gt;false&lt;/span&gt;)]
    &lt;span style="color: blue"&gt;public string&lt;/span&gt;[][] parts {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return this&lt;/span&gt;.partsField;
        }
        &lt;span style="color: blue"&gt;set &lt;/span&gt;{
            &lt;span style="color: blue"&gt;this&lt;/span&gt;.partsField = &lt;span style="color: blue"&gt;value&lt;/span&gt;;
        }
    }
}&lt;/pre&gt;

&lt;p&gt;There’s no CarPart object collection. There was no CarPart class in generated code at all. Instead, the tool generated string[][] array for me. Well it’s not what I would like to have, but I could live with it. So I went on to code that test the web service and to my surprise the constructor of the proxy class threw FileNotFoundException as the application was unable to find a dynamically created assembly used by XML serializer. I tried to do the same with Visual Studio 2008 and here’s what I got:&lt;/p&gt;

&lt;pre class="code"&gt;InvalidOperationException was unhandled
Unable to generate a temporary class (result=1).
error CS0029: Cannot implicitly convert type 'string' to 'string[]'&lt;/pre&gt;

&lt;p&gt;Not only the wsdl.exe changed the object model, but also the XML Serializer was unable to deal with it. At this point I decided to manually modify the generated code and added the CarPart class. I also changed parts collection to CarPart[] type. And it finally worked. Yet I feel disappointed that I have to manually create proxy classes to work with Java web services.&lt;/p&gt;

&lt;p&gt;A whole different thing is performance of web services on the smart device. SOAP and XML imply large message sizes and extensive use of reflection, which has a great impact on the application’s performance. &lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/01/java-web-service-interoperability-from.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/01/java-web-service-interoperability-from.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-3307085196857898495?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/3307085196857898495/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=3307085196857898495' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3307085196857898495'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3307085196857898495'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/01/java-web-service-interoperability-from.html' title='Java web service interoperability from .NET CF 1.0'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/_Egs311swNl0/SXn18X00rzI/AAAAAAAAAGg/dvgqh7KMldU/s72-c/image%5B9%5D.png?imgmax=800' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-3315959618317047201</id><published>2009-01-17T00:10:00.001+01:00</published><updated>2009-02-04T22:24:39.079+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='.NET CF'/><title type='text'>Dependency injection in .NET CF 1.0</title><content type='html'>&lt;p&gt;Recently I got involved in building an application for mobile devices. The problem is that they are old Pocket PC 2002 devices, so the only option to write managed code is to use also old .NET CF 1.0. Don’t even get me started on how limited it is and how much pain it is to work with VS2003 – do you remember the times when you had to add namespace imports by hand? Without ReSharper it’s almost unbearable. &lt;/p&gt;  &lt;p&gt;Anyway I’m responsible for the design of the solution. I thought it would be nice to have DI container, but there are some constraints on the mobile platform:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Performance – There’s no possibility to use reflection extensively without running into performance problems. &lt;/li&gt;    &lt;li&gt;Limited BCL - .NET CF 1.0 base class library is only a small subset the .NET 1.1 BCL, not to mention .NET 2.0 &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Taking this into account I thought it would be best to implement a really simple solution myself. The features of my simple container are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Mapping interfaces to implementing types &lt;/li&gt;    &lt;li&gt;Registering types both as singleton and as transient instance &lt;/li&gt;    &lt;li&gt;Registering existing instances &lt;/li&gt;    &lt;li&gt;Resolving both mapped interfaces and unmapped types &lt;/li&gt;    &lt;li&gt;Injecting dependencies into constructors (recursively) &lt;/li&gt;    &lt;li&gt;Fluent registration syntax &lt;/li&gt;    &lt;li&gt;Reflection usage reduced to a minimum &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;This set of functionalities should allow me to work comfortably with dependency injection and keep the container as simple as possible. Here is the code, first the container interface:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IContainer
&lt;/span&gt;{
    &lt;span style="color: #2b91af"&gt;IContainer &lt;/span&gt;Register(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapTo);
    &lt;span style="color: #2b91af"&gt;IContainer &lt;/span&gt;RegisterSingleton(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapTo);
    &lt;span style="color: #2b91af"&gt;IContainer &lt;/span&gt;RegisterSingleton(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: blue"&gt;object &lt;/span&gt;toInstance);
    &lt;span style="color: blue"&gt;object &lt;/span&gt;Resolve(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type);
}&lt;/pre&gt;

&lt;p&gt;Register method allows you to register a mapping of a transient objects (instantiated on every resolve). RegisterSingleton is overloaded and allows you to register either a type mapping or type to existing instance mapping as a singleton (instantiated only once). Resolve returns instance of requested type – either mapped or not.&lt;/p&gt;

&lt;p&gt;Now TypeItem class used to store type mappings (in a Hashtable):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeItem
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;targetType;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;TargetType { &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;targetType; } }

    &lt;span style="color: blue"&gt;private bool &lt;/span&gt;sigleton;

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;Singleton { &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;sigleton; } }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;TypeItem(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;targetType, &lt;span style="color: blue"&gt;bool &lt;/span&gt;singleton)
    {
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.targetType = targetType;
        &lt;span style="color: blue"&gt;this&lt;/span&gt;.sigleton = singleton;
    }
}&lt;/pre&gt;

&lt;p&gt;And the container itself:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Container &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IContainer
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Hashtable &lt;/span&gt;typeMap = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Hashtable&lt;/span&gt;();
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Hashtable &lt;/span&gt;singletonCache = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Hashtable&lt;/span&gt;();
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArrayList &lt;/span&gt;targetTypeList = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArrayList&lt;/span&gt;();

    &lt;span style="color: blue"&gt;#region &lt;/span&gt;IContainer Members

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IContainer &lt;/span&gt;Register(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapTo)
    {
        CheckRegistrationConditions(mapFrom, mapTo, &lt;span style="color: blue"&gt;true&lt;/span&gt;);

        &lt;span style="color: #2b91af"&gt;TypeItem &lt;/span&gt;item = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeItem&lt;/span&gt;(mapTo, &lt;span style="color: blue"&gt;false&lt;/span&gt;);
        AddItem(mapFrom, item);
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IContainer &lt;/span&gt;RegisterSingleton(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapTo)
    {
        CheckRegistrationConditions(mapFrom, mapTo, &lt;span style="color: blue"&gt;true&lt;/span&gt;);

        &lt;span style="color: #2b91af"&gt;TypeItem &lt;/span&gt;item = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeItem&lt;/span&gt;(mapTo, &lt;span style="color: blue"&gt;true&lt;/span&gt;);
        AddItem(mapFrom, item);
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IContainer &lt;/span&gt;RegisterSingleton(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: blue"&gt;object &lt;/span&gt;toInstance)
    {
        CheckRegistrationConditions(mapFrom, &lt;span style="color: blue"&gt;null&lt;/span&gt;, &lt;span style="color: blue"&gt;false&lt;/span&gt;);
        &lt;span style="color: #2b91af"&gt;Guard&lt;/span&gt;.AgainstNullArgument(toInstance, &lt;span style="color: #a31515"&gt;&amp;quot;toInstance&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #2b91af"&gt;TypeItem &lt;/span&gt;item = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeItem&lt;/span&gt;(toInstance.GetType(), &lt;span style="color: blue"&gt;true&lt;/span&gt;);
        &lt;span style="color: blue"&gt;if&lt;/span&gt;(targetTypeList.Contains(item.TargetType))
        {
            &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(
                &lt;span style="color: #a31515"&gt;&amp;quot;Cannot register singleton because another singleton mapping &amp;quot; &lt;/span&gt;+ 
                &lt;span style="color: #a31515"&gt;&amp;quot;uses the type of the instance&amp;quot;&lt;/span&gt;,
                &lt;span style="color: #a31515"&gt;&amp;quot;toInstance&amp;quot;&lt;/span&gt;);
        }
        AddItem(mapFrom, item);
        singletonCache.Add(item.TargetType, toInstance);
        &lt;span style="color: blue"&gt;return this&lt;/span&gt;;
    }

    &lt;span style="color: blue"&gt;public object &lt;/span&gt;Resolve(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type)
    {
        &lt;span style="color: #2b91af"&gt;Guard&lt;/span&gt;.AgainstNullArgument(type, &lt;span style="color: #a31515"&gt;&amp;quot;type&amp;quot;&lt;/span&gt;);

        &lt;span style="color: blue"&gt;if &lt;/span&gt;(typeMap.ContainsKey(type))
        {
            &lt;span style="color: green"&gt;// mapped type
            &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeItem &lt;/span&gt;item = typeMap[type] &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeItem&lt;/span&gt;;

            &lt;span style="color: blue"&gt;if &lt;/span&gt;(item.Singleton &amp;amp;&amp;amp; singletonCache.ContainsKey(item.TargetType))
                &lt;span style="color: blue"&gt;return &lt;/span&gt;singletonCache[item.TargetType];

            &lt;span style="color: blue"&gt;object &lt;/span&gt;instance = BuildInstance(item.TargetType);

            &lt;span style="color: blue"&gt;if &lt;/span&gt;(item.Singleton)
                singletonCache.Add(item.TargetType, instance);

            &lt;span style="color: blue"&gt;return &lt;/span&gt;instance;
        }
        &lt;span style="color: blue"&gt;else
        &lt;/span&gt;{
            &lt;span style="color: green"&gt;// unmapped type
            &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;(!type.IsClass || !type.IsPublic)
                &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeResolveException&lt;/span&gt;(
                    &lt;span style="color: #a31515"&gt;&amp;quot;The type &amp;quot; &lt;/span&gt;+ type.Name + 
                    &lt;span style="color: #a31515"&gt;&amp;quot; is neither mapped nor can it be instantiated&amp;quot;&lt;/span&gt;);

            &lt;span style="color: blue"&gt;return &lt;/span&gt;BuildInstance(type);
        }
    }

    &lt;span style="color: blue"&gt;#endregion

    private void &lt;/span&gt;CheckRegistrationConditions(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapTo, &lt;span style="color: blue"&gt;bool &lt;/span&gt;mapToValid)
    {
        &lt;span style="color: #2b91af"&gt;Guard&lt;/span&gt;.AgainstNullArgument(mapFrom, &lt;span style="color: #a31515"&gt;&amp;quot;mapFrom&amp;quot;&lt;/span&gt;);
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(mapToValid)
        {
            &lt;span style="color: #2b91af"&gt;Guard&lt;/span&gt;.AgainstNullArgument(mapTo, &lt;span style="color: #a31515"&gt;&amp;quot;mapTo&amp;quot;&lt;/span&gt;);
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(!mapTo.IsClass || !mapTo.IsPublic)
                &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;The type &amp;quot; &lt;/span&gt;+ mapTo.Name + 
                    &lt;span style="color: #a31515"&gt;&amp;quot; cannot be instantiated&amp;quot;&lt;/span&gt;);
        }

        &lt;span style="color: blue"&gt;if &lt;/span&gt;(typeMap.ContainsKey(mapFrom))
            &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Provided type is already mapped&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;mapFrom&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;private void &lt;/span&gt;AddItem(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;mapFrom, &lt;span style="color: #2b91af"&gt;TypeItem &lt;/span&gt;item)
    {
        typeMap.Add(mapFrom, item);
        targetTypeList.Add(item.TargetType);
    }

    &lt;span style="color: blue"&gt;private object &lt;/span&gt;BuildInstance(&lt;span style="color: #2b91af"&gt;Type &lt;/span&gt;type)
    {
        &lt;span style="color: #2b91af"&gt;ConstructorInfo&lt;/span&gt;[] constructors = type.GetConstructors(
            &lt;span style="color: #2b91af"&gt;BindingFlags&lt;/span&gt;.Public | &lt;span style="color: #2b91af"&gt;BindingFlags&lt;/span&gt;.Instance);

        &lt;span style="color: blue"&gt;if &lt;/span&gt;(constructors.Length == 0)
            &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TypeResolveException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;The type &amp;quot; &lt;/span&gt;+ type.Name +
                &lt;span style="color: #a31515"&gt;&amp;quot; has no public constructors&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #2b91af"&gt;ParameterInfo&lt;/span&gt;[] parameters = constructors[0].GetParameters();
        &lt;span style="color: blue"&gt;object&lt;/span&gt;[] paramValues = &lt;span style="color: blue"&gt;new object&lt;/span&gt;[parameters.Length];

        &lt;span style="color: blue"&gt;for &lt;/span&gt;(&lt;span style="color: blue"&gt;int &lt;/span&gt;i = 0; i &amp;lt; parameters.Length; i++)
        {
            paramValues[i] = Resolve(parameters[i].ParameterType);
        }

        &lt;span style="color: blue"&gt;return &lt;/span&gt;constructors[0].Invoke(paramValues);
    }

}&lt;/pre&gt;

&lt;p&gt;As you might noticed, the BuildInstance method just takes the first public constructor returned by GetConstructors and uses it to create instance. This is enough for my scenario, but you might want to mark injection constructor with a custom attribute or select constructor basing on some criteria (ex. most resolvable parameters).&lt;/p&gt;

&lt;p&gt;There are also some tests for the container, but I won’t be posting them here.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/01/dependency-injection-in-net-cf-10.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/01/dependency-injection-in-net-cf-10.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-3315959618317047201?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/3315959618317047201/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=3315959618317047201' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3315959618317047201'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3315959618317047201'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/01/dependency-injection-in-net-cf-10.html' title='Dependency injection in .NET CF 1.0'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-4553468716274229164</id><published>2009-01-12T23:15:00.001+01:00</published><updated>2009-01-12T23:15:25.483+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ASP.NET'/><category scheme='http://www.blogger.com/atom/ns#' term='identity and access'/><title type='text'>Comparing OpenID and canonical Subject-IP-RP pattern</title><content type='html'>&lt;p&gt;A hot topic lately is identity management in distributed environments and there are some interesting articles on this in the &lt;a href="http://msdn.microsoft.com/en-us/architecture/bb410935.aspx"&gt;Architecture Journal&lt;/a&gt;. The basic thing to do in distributed environment, presumably SOA, is to delegate the identity management to separate component called Identity Provider (IP). It is responsible for maintaining user database and issuing security tokens. This security tokens are used by the subject (a user who wants to gain access to a resource) to authenticate at the Relaying Party (a component that maintains the resource). This way user doesn’t have to have separate user account on each Relaying Party and presumably authenticate in different way using different credentials. The Relaying Party trusts the Identity Provider to perform user authentication. Following diagram presents this situation:&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="201" alt="image" src="http://lh4.ggpht.com/_Egs311swNl0/SWvA8HWwBHI/AAAAAAAAAGU/7T_wyWpyj8o/image%5B9%5D.png?imgmax=800" width="336" border="0" /&gt;&amp;#160; &lt;/p&gt;  &lt;p&gt;Now in order to authenticate at the Relaying Party, following steps are taken [1]:&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="418" alt="image" src="http://lh4.ggpht.com/_Egs311swNl0/SWvA87HZYJI/AAAAAAAAAGY/0DEHBWZvvR8/image%5B13%5D.png?imgmax=800" width="635" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;Subject first discovers how to authenticate at Relaying Party by getting the security policy. It then authenticates at Identity Provider using proper credentials and receives a security token, which is used to authenticate resource requests at Replaying Party. Relaying Party verifies the token’s signature to ensure it comes from the trusted Identity Provider.&lt;/p&gt;  &lt;p&gt;OpenID is a decentralized and open identification standard basing on a concept of trusted Identity Provider. The “distributed” in practice means, that there are many IPs on the web and it’s up to user to decide which one will suit him. For example there is &lt;a href="http://code.google.com/apis/accounts/docs/OpenID.html"&gt;OpenID provider for Google’s Federated Login API&lt;/a&gt;, which you can use your Google account to authenticate with OpenID. There are also some &lt;a href="https://www.myopenid.com/"&gt;dedicated IPs&lt;/a&gt; and you even can easily &lt;a href="http://www.intertwingly.net/blog/2007/01/03/OpenID-for-non-SuperUsers"&gt;setup your own IP&lt;/a&gt; if you do not trust anybody else :). OpenID was created with authentication at web portals and communities in mind (it’s being used by &lt;a href="http://stackoverflow.com/"&gt;Stack Overflow&lt;/a&gt; for instance). It’s well suited for this task and differs from the canonical Subject-IP-RP pattern. It is assumed, that user uses web browser to authenticate and the protocol relies heavily on HTTP/HTML (but implementation in desktop apps is also possible). Authentication process orchestration is taken from hands of the subject and directed by Relaying Party instead. Username has a form of URL and plays significant role during the process of authentication as follows [2](a rough view):&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="393" alt="image" src="http://lh5.ggpht.com/_Egs311swNl0/SWvA9hS_MpI/AAAAAAAAAGc/CqmNIvgl4g4/image%5B17%5D.png?imgmax=800" width="673" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;Relaying Party queries username URL to discover information on Identity Provider used by given user. Then, user’s browser is redirected to IP’s login site. After logging in, IP redirects user to RP’s return URL including information about authentication result in the request. RP verifies whether the login status information is legitimate by querying IP.&lt;/p&gt;  &lt;p&gt;There are also some modifications and extensions to this protocol like for example ability for RP and IP to establish a shared secret used to verify login status information without the need to query IP every time a user logs in. &lt;/p&gt;  &lt;p&gt;Implementation of OpenID authentication is easy, because there are &lt;a href="http://wiki.openid.net/Libraries"&gt;many open libraries&lt;/a&gt; for each platform. For .NET there is DotNetOpenId, which even provides ready to use controls for ASP.NET. I suggest you read OpenID specs [2] for more detailed information on this topic. Anyway it would be nice to see OpenID authentication more popular and used by all community portals.&lt;/p&gt;  &lt;p&gt;Resources:&lt;/p&gt;  &lt;p&gt;[1] Vittorio Bertocci, “Claims and Identity: On-Premise and Cloud Solutions”. The Architecture Journal, Journal 16.&lt;/p&gt;  &lt;p&gt;[2] OpenID Authentication 2.0 – Final. &lt;a title="http://openid.net/specs/openid-authentication-2_0.html" href="http://openid.net/specs/openid-authentication-2_0.html"&gt;http://openid.net/specs/openid-authentication-2_0.html&lt;/a&gt;, 2009.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2009/01/comparing-openid-and-canonical-subject.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2009/01/comparing-openid-and-canonical-subject.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-4553468716274229164?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/4553468716274229164/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=4553468716274229164' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4553468716274229164'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4553468716274229164'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2009/01/comparing-openid-and-canonical-subject.html' title='Comparing OpenID and canonical Subject-IP-RP pattern'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_Egs311swNl0/SWvA8HWwBHI/AAAAAAAAAGU/7T_wyWpyj8o/s72-c/image%5B9%5D.png?imgmax=800' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8061503512862629625</id><published>2008-12-26T14:11:00.001+01:00</published><updated>2009-01-24T11:05:52.368+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Boo'/><title type='text'>Exploring Boo’s Abstract Syntax Tree (AST)</title><content type='html'>&lt;p&gt;Currently I’m going through AST, but the documentation is scarce. AST is in-memory tree representation of code that can be modified and is used while creating syntactic macros. I was wondering what is the best way to check how syntax is transformed to AST when I came across &lt;a href="http://langexplr.blogspot.com/2007/06/calling-boo-compiler-from-boo-program.html"&gt;Luis Diego Fallas’ post&lt;/a&gt; in which he shows a little application that parses Boo source file and displays AST in tree control. Unfortunately there are some issues with this application. Firstly, it contains a bug and doesn’t show full syntax tree. Secondly, it only displays node names without information what code the node represents. So I decided to modify his code and fix this. Here is a sample screenshot:&lt;/p&gt;  &lt;p&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/SVTYGdYBmSI/AAAAAAAAAGQ/5uHo0PwqvdY/image%5B3%5D.png?imgmax=800" width="791" height="406" /&gt; &lt;/p&gt;  &lt;p&gt;There is AST tree structure of code on the left and information about selected subtree on the right. It includes the code itself and serialized form of the subtree. Name of the file to parse is passed to the application as a parameter.&lt;/p&gt;  &lt;p&gt;Visitor pattern is employed to visit all nodes in AST tree. Unfortunately deriving from Boo’s DepthFirstVisitor is a tedious task, because there are as many methods to override as there are AST node types. Luis proposed a solution basing on dynamically created type, that derives from DepthFirstVisitor. Method overrides are constructed in-memory from AST nodes and then the dynamic type is compiled. While being compact, this solution is not very readable, especially when you’re not familiar with AST. Fortunately there seems to be alternative way to do this, namely the mysterious [| &amp;lt;code here&amp;gt; |] syntax. I think it’s called quasiquotes. I couldn’t find any documentation for this, only one example in Boo package. From what I was able to figure out, this code (where m is instance of MethodInfo class):&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: #999999"&gt;// Node for TreeNode('')
&lt;/span&gt;&lt;span style="color: #04abab"&gt;tnCreation &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;MethodInvocationExpression&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;ReferenceExpression&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;TreeNode&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;))                                 
&lt;/span&gt;&lt;span style="color: black"&gt;tnCreation&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Arguments&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(
        &lt;/span&gt;&lt;span style="color: #191970"&gt;StringLiteralExpression&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;m&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetParameters&lt;/span&gt;&lt;span style="color: #006400"&gt;()[&lt;/span&gt;&lt;span style="color: #00008b"&gt;0&lt;/span&gt;&lt;span style="color: #006400"&gt;].&lt;/span&gt;&lt;span style="color: black"&gt;ParameterType&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Name&lt;/span&gt;&lt;span style="color: #006400"&gt;))

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Create node for 't = TreeNode('')' 
&lt;/span&gt;&lt;span style="color: #04abab"&gt;decl &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;DeclarationStatement&lt;/span&gt;&lt;span style="color: #006400"&gt;(
      &lt;/span&gt;&lt;span style="color: black"&gt;Declaration: &lt;/span&gt;&lt;span style="color: #191970"&gt;Declaration&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Name:&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;t&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;,
                 &lt;/span&gt;&lt;span style="color: black"&gt;Type: &lt;/span&gt;&lt;span style="color: #191970"&gt;SimpleTypeReference&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;System.Windows.Forms.TreeNode&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)),
      &lt;/span&gt;&lt;span style="color: black"&gt;Initializer: tnCreation&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;is equivalent to this code:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: black"&gt;decl &lt;/span&gt;&lt;span style="color: #006400"&gt;= [| &lt;/span&gt;&lt;span style="color: black"&gt;t &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;TreeNode&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;$&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;m&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetParameters&lt;/span&gt;&lt;span style="color: #006400"&gt;()[&lt;/span&gt;&lt;span style="color: #00008b"&gt;0&lt;/span&gt;&lt;span style="color: #006400"&gt;].&lt;/span&gt;&lt;span style="color: black"&gt;ParameterType&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Name&lt;/span&gt;&lt;span style="color: #006400"&gt;)) |] 
&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;So there is a huge improvement. Code between [| and |] is being transformed to AST and assigned to a variable. The $() construct is similar to string interpolation construct. It allows you to insert a string from variable as if it was part of the code (here it is a parameter of the TreeNode constructor, but it also can be a method name for example). When using this syntax, you have to be careful about the indentation. It seems that statements can be in the same line as [|, but when declaring members, they have to be in new line and indented. Otherwise you get compilation errors.&lt;/p&gt;

&lt;p&gt;Luis has overridden “Enter*” and “Leave*” (for example EnterBlockExpression) methods of DepthFirstVisitor, which is a problem because “Enter*” and ”Leave*” methods exist only for nodes that can contain subnodes. So for example there is no Enter method for IntegerLiteralExpression node. In my code I override the “On*” methods.&lt;/p&gt;

&lt;p&gt;Here is the full code:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Reflection
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;IO
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;Boo&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Lang&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Compiler
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;Boo&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Lang&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Compiler&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Ast
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;Boo&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Lang&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Compiler&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Ast&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Visitors
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;Boo&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Lang&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Parser
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Windows&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Forms
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Xml&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Serialization
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Drawing


&lt;/span&gt;&lt;span style="color: #999999"&gt;// Get the type instance for DepthFirstVisitor
&lt;/span&gt;&lt;span style="color: #04abab"&gt;a &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;Assembly&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Load&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Boo.Lang.Compiler&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;visitorType &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;a&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetType&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Boo.Lang.Compiler.Ast.DepthFirstVisitor&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Create a class definition for a custom visitor
&lt;/span&gt;&lt;span style="color: #04abab"&gt;myVisitor &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;ClassDefinition&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Name: &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;DynamicVisitor&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;myVisitor&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;BaseTypes&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;SimpleTypeReference&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Boo.Lang.Compiler.Ast.DepthFirstVisitor&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;))

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Add a new field for our node stack
&lt;/span&gt;&lt;span style="color: #04abab"&gt;stackField &lt;/span&gt;&lt;span style="color: #006400"&gt;= [| 
    &lt;/span&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: black"&gt;stack &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Collections&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Stack 
&lt;/span&gt;&lt;span style="color: #006400"&gt;|]
&lt;/span&gt;&lt;span style="color: black"&gt;myVisitor&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Members&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;stackField&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Override On* methods
&lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;&lt;span style="color: black"&gt;m &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;MethodInfo &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #006400"&gt;[&lt;/span&gt;&lt;span style="color: black"&gt;m &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;&lt;span style="color: black"&gt;m &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: black"&gt;visitorType&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetMethods&lt;/span&gt;&lt;span style="color: #006400"&gt;() &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;&lt;span style="color: black"&gt;m&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Name&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;StartsWith&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;On&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)]&lt;/span&gt;&lt;span style="color: black"&gt;:
    method &lt;/span&gt;&lt;span style="color: #006400"&gt;= [|
        &lt;/span&gt;&lt;span style="color: blue"&gt;def &lt;/span&gt;&lt;span style="color: #191970"&gt;$&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;m&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Name&lt;/span&gt;&lt;span style="color: #006400"&gt;)(&lt;/span&gt;&lt;span style="color: black"&gt;node &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #191970"&gt;$&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;m&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetParameters&lt;/span&gt;&lt;span style="color: #006400"&gt;()[&lt;/span&gt;&lt;span style="color: #00008b"&gt;0&lt;/span&gt;&lt;span style="color: #006400"&gt;].&lt;/span&gt;&lt;span style="color: black"&gt;ParameterType&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;FullName&lt;/span&gt;&lt;span style="color: #006400"&gt;))&lt;/span&gt;&lt;span style="color: black"&gt;:
            t &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;TreeNode&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;$&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;m&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetParameters&lt;/span&gt;&lt;span style="color: #006400"&gt;()[&lt;/span&gt;&lt;span style="color: #00008b"&gt;0&lt;/span&gt;&lt;span style="color: #006400"&gt;].&lt;/span&gt;&lt;span style="color: black"&gt;ParameterType&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Name&lt;/span&gt;&lt;span style="color: #006400"&gt;))
            &lt;/span&gt;&lt;span style="color: black"&gt;t&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Tag &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;node&lt;/span&gt;&lt;span style="color: #006400"&gt;;
            (&lt;/span&gt;&lt;span style="color: black"&gt;stack&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Peek&lt;/span&gt;&lt;span style="color: #006400"&gt;() &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;TreeNode&lt;/span&gt;&lt;span style="color: #006400"&gt;).&lt;/span&gt;&lt;span style="color: black"&gt;Nodes&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;t&lt;/span&gt;&lt;span style="color: #006400"&gt;)
            &lt;/span&gt;&lt;span style="color: black"&gt;stack&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Push&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;t&lt;/span&gt;&lt;span style="color: #006400"&gt;)
            &lt;/span&gt;&lt;span style="color: #999999"&gt;// call method in superclass to visit subtrees
            &lt;/span&gt;&lt;span style="color: black"&gt;super&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;$&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;m&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Name&lt;/span&gt;&lt;span style="color: #006400"&gt;)(&lt;/span&gt;&lt;span style="color: black"&gt;node&lt;/span&gt;&lt;span style="color: #006400"&gt;)
            &lt;/span&gt;&lt;span style="color: black"&gt;stack&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Pop&lt;/span&gt;&lt;span style="color: #006400"&gt;() 
    |]
    &lt;/span&gt;&lt;span style="color: black"&gt;myVisitor&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Members&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;method&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Compile unit and module creation
&lt;/span&gt;&lt;span style="color: #04abab"&gt;cu &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;CompileUnit&lt;/span&gt;&lt;span style="color: #006400"&gt;()
&lt;/span&gt;&lt;span style="color: #04abab"&gt;mod &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;Boo&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Lang&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Compiler&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Ast&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Module&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Name:&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Module&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;cu&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Modules&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;mod&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: black"&gt;mod&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Imports&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;Import&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Namespace:&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;System&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;))
&lt;/span&gt;&lt;span style="color: black"&gt;mod&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Imports&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;Import&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Namespace:&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;System.Windows.Forms&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;))
&lt;/span&gt;&lt;span style="color: black"&gt;mod&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Imports&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;Import&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Namespace:&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Boo.Lang.Compiler.Ast&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;))
&lt;/span&gt;&lt;span style="color: black"&gt;mod&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Members&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;myVisitor&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Initialize compiler preferences
&lt;/span&gt;&lt;span style="color: #04abab"&gt;pipeline &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;Pipelines&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;CompileToMemory&lt;/span&gt;&lt;span style="color: #006400"&gt;()
&lt;/span&gt;&lt;span style="color: #04abab"&gt;ctxt &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;CompilerContext&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;cu&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Run the compiler
&lt;/span&gt;&lt;span style="color: black"&gt;pipeline&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Run&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;ctxt&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Check the results
&lt;/span&gt;&lt;span style="color: blue"&gt;if&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;ctxt&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;GeneratedAssembly &lt;/span&gt;&lt;span style="color: #006400"&gt;== &lt;/span&gt;&lt;span style="color: black"&gt;null&lt;/span&gt;&lt;span style="color: #006400"&gt;)&lt;/span&gt;&lt;span style="color: black"&gt;:
    &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;&lt;span style="color: black"&gt;e &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: black"&gt;ctxt&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Errors:
        &lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: black"&gt;e
    Console&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;ReadLine&lt;/span&gt;&lt;span style="color: #006400"&gt;()
    &lt;/span&gt;&lt;span style="color: navy"&gt;return    

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Create an instance of the new visitor and initialize it
&lt;/span&gt;&lt;span style="color: black"&gt;visitorInstance &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;object &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;ctxt&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;GeneratedAssembly&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;CreateInstance&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;DynamicVisitor&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;);
&lt;/span&gt;&lt;span style="color: black"&gt;visitorType &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;ctxt&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;GeneratedAssembly&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetType&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;DynamicVisitor&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;tStack &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Collections&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Stack&lt;/span&gt;&lt;span style="color: #006400"&gt;()
&lt;/span&gt;&lt;span style="color: black"&gt;tStack&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Push&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;TreeNode&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;root&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;))
&lt;/span&gt;&lt;span style="color: black"&gt;visitorType&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetField&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;stack&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;).&lt;/span&gt;&lt;span style="color: #191970"&gt;SetValue&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;visitorInstance&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;tStack&lt;/span&gt;&lt;span style="color: #006400"&gt;);

&lt;/span&gt;&lt;span style="color: #999999"&gt;// Parse a file an run the visitor
&lt;/span&gt;&lt;span style="color: #04abab"&gt;compileUnit &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;BooParser&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;ParseFile&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;argv&lt;/span&gt;&lt;span style="color: #006400"&gt;[&lt;/span&gt;&lt;span style="color: #00008b"&gt;0&lt;/span&gt;&lt;span style="color: #006400"&gt;])
&lt;/span&gt;&lt;span style="color: black"&gt;compileUnit&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Accept&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;visitorInstance&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;//Initialize a form an show the results
&lt;/span&gt;&lt;span style="color: #04abab"&gt;frm &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;Form&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Text: &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;AST content&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Width: &lt;/span&gt;&lt;span style="color: #00008b"&gt;800&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Height: &lt;/span&gt;&lt;span style="color: #00008b"&gt;600&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;outerSplit &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;SplitContainer&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Dock: DockStyle&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Fill&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Orientation: Orientation&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Vertical&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;innerSplit &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;SplitContainer&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Dock: DockStyle&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Fill&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Orientation: Orientation&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Horizontal&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;definitionText &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;TextBox&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Dock: DockStyle&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Fill&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Multiline: true&lt;/span&gt;&lt;span style="color: #006400"&gt;, 
    &lt;/span&gt;&lt;span style="color: black"&gt;ScrollBars: ScrollBars&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Both&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Font: &lt;/span&gt;&lt;span style="color: #191970"&gt;Font&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Courier New&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;8.0&lt;/span&gt;&lt;span style="color: #006400"&gt;))
&lt;/span&gt;&lt;span style="color: #04abab"&gt;xmlText &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;TextBox&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Dock: DockStyle&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Fill&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Multiline: true&lt;/span&gt;&lt;span style="color: #006400"&gt;, 
    &lt;/span&gt;&lt;span style="color: black"&gt;ScrollBars: ScrollBars&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Both&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;Font: &lt;/span&gt;&lt;span style="color: #191970"&gt;Font&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Courier New&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;8.0&lt;/span&gt;&lt;span style="color: #006400"&gt;))

&lt;/span&gt;&lt;span style="color: #04abab"&gt;tv &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;TreeView&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;Dock: DockStyle&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Fill&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: black"&gt;tv&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;AfterSelect &lt;/span&gt;&lt;span style="color: #006400"&gt;+= &lt;/span&gt;&lt;span style="color: blue"&gt;def &lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;sender &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;e &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;TreeViewEventArgs&lt;/span&gt;&lt;span style="color: #006400"&gt;)&lt;/span&gt;&lt;span style="color: black"&gt;:
    &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;&lt;span style="color: black"&gt;e&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Node&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Tag &lt;/span&gt;&lt;span style="color: #006400"&gt;!= &lt;/span&gt;&lt;span style="color: black"&gt;null:
        writer &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;StringWriter&lt;/span&gt;&lt;span style="color: #006400"&gt;()
        &lt;/span&gt;&lt;span style="color: #191970"&gt;BooPrinterVisitor&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;writer&lt;/span&gt;&lt;span style="color: #006400"&gt;).&lt;/span&gt;&lt;span style="color: #191970"&gt;Visit&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;e&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Node&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Tag &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;Node&lt;/span&gt;&lt;span style="color: #006400"&gt;)
        &lt;/span&gt;&lt;span style="color: black"&gt;definitionText&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Text &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;writer&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;ToString&lt;/span&gt;&lt;span style="color: #006400"&gt;()
        
        &lt;/span&gt;&lt;span style="color: black"&gt;serializer &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;XmlSerializer&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;e&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Node&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Tag&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetType&lt;/span&gt;&lt;span style="color: #006400"&gt;())
        &lt;/span&gt;&lt;span style="color: black"&gt;writer &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;StringWriter&lt;/span&gt;&lt;span style="color: #006400"&gt;()
        &lt;/span&gt;&lt;span style="color: black"&gt;serializer&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Serialize&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;writer&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;e&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Node&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Tag&lt;/span&gt;&lt;span style="color: #006400"&gt;)
        &lt;/span&gt;&lt;span style="color: black"&gt;xmlText&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Text &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;writer&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;ToString&lt;/span&gt;&lt;span style="color: #006400"&gt;()

&lt;/span&gt;&lt;span style="color: black"&gt;tv&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Nodes&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;tStack&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Pop&lt;/span&gt;&lt;span style="color: #006400"&gt;() &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;TreeNode&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;frm&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Controls&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;outerSplit&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;outerSplit&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Panel1&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Controls&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;tv&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;outerSplit&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Panel2&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Controls&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;innerSplit&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;innerSplit&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Panel1&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Controls&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;definitionText&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;innerSplit&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Panel2&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Controls&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;xmlText&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: black"&gt;Application&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Run&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;frm&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;Some highlights:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;There is a BooPrinterVisitor class in Boo.Lang.Compiler.Ast.Visitors namespace, that converts AST to source code. Unfortunately this class doesn’t support quasiquotes, so passing a file with quasiquotes will result in exception. &lt;/li&gt;

  &lt;li&gt;The file passed to the application doesn’t necessarily have to be compilation error free. It can contain macros, that are not yet defined. This way you can write your desired syntax, and then use this application to see how it is parsed. This should make macro implementation easier. &lt;/li&gt;
&lt;/ul&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/12/exploring-boos-abstract-syntax-tree-ast.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/12/exploring-boos-abstract-syntax-tree-ast.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8061503512862629625?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8061503512862629625/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8061503512862629625' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8061503512862629625'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8061503512862629625'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/12/exploring-boos-abstract-syntax-tree-ast.html' title='Exploring Boo’s Abstract Syntax Tree (AST)'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/_Egs311swNl0/SVTYGdYBmSI/AAAAAAAAAGQ/5uHo0PwqvdY/s72-c/image%5B3%5D.png?imgmax=800' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-1638771886229583187</id><published>2008-12-14T12:40:00.001+01:00</published><updated>2008-12-14T12:40:40.984+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Boo'/><title type='text'>An example of IQuackFu usage in Boo</title><content type='html'>&lt;p&gt;The IQuackFu interface lets you intercept calls to a duck type when called method or property doesn’t exist. You can use this to achieve many interesting things. In Boo’s examples there is a class for accessing XML data and also a class that allows &lt;a href="http://docs.codehaus.org/pages/viewpage.action?pageId=13653"&gt;dynamic inheritance&lt;/a&gt;. The IQuackFu interface has three methods:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;QuackInvoke(name as string, args as (object)) as object&lt;/strong&gt; – intercepts method calls &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;QuackSet(name as string, parameters as (object), value) as object&lt;/strong&gt; – intercepts property setter calls &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;QuackGet(name as string, parameters as (object)) as object &lt;/strong&gt;– intercepts property getter calls &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;As you can see each method has a name argument, which contains a name of the called method or property. This name can be parsed and appropriate action can be taken. My example will be a simple class for accessing data in a database table. Methods called on this class should be in form of:&lt;/p&gt;  &lt;p&gt;Get &amp;lt;table name&amp;gt; By &amp;lt;column 1&amp;gt; [And &amp;lt;column 2&amp;gt; And …] ( &amp;lt;value 1&amp;gt; [, &amp;lt;value 2&amp;gt;, …] )&lt;/p&gt;  &lt;p&gt;The method name specifies which table will be queried and what columns will be used in the WHERE clause. Arguments of the method specify values for the filter. The method returns a DataSet. Here is the code:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Text&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;RegularExpressions
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Collections&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Generic
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Data&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;SqlClient
&lt;/span&gt;&lt;span style="color: green"&gt;import &lt;/span&gt;&lt;span style="color: black"&gt;System&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Data

&lt;/span&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #191970"&gt;Repository&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;IQuackFu&lt;/span&gt;&lt;span style="color: #006400"&gt;)&lt;/span&gt;&lt;span style="color: black"&gt;:
    
    &lt;/span&gt;&lt;span style="color: blue"&gt;def &lt;/span&gt;&lt;span style="color: #191970"&gt;QuackInvoke&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;name &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;string&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;args &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: #006400"&gt;)) &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: black"&gt;:

        &lt;/span&gt;&lt;span style="color: #04abab"&gt;match &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #ff6600"&gt;/^Get(?&amp;lt;table&amp;gt;\w+)By(?&amp;lt;column&amp;gt;\w+?)(And(?&amp;lt;column&amp;gt;\w+?))*$/&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Match&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;name&lt;/span&gt;&lt;span style="color: #006400"&gt;)
        &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;&lt;span style="color: black"&gt;match &lt;/span&gt;&lt;span style="color: #006400"&gt;!= &lt;/span&gt;&lt;span style="color: black"&gt;null &lt;/span&gt;&lt;span style="color: #008b8b"&gt;and &lt;/span&gt;&lt;span style="color: black"&gt;match&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Success:
            &lt;/span&gt;&lt;span style="color: #04abab"&gt;table &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;match&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Groups&lt;/span&gt;&lt;span style="color: #006400"&gt;[&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;table&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;].&lt;/span&gt;&lt;span style="color: black"&gt;Value
            
            &lt;/span&gt;&lt;span style="color: #04abab"&gt;params &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;List&lt;/span&gt;&lt;span style="color: #006400"&gt;[&lt;/span&gt;&lt;span style="color: blue"&gt;of &lt;/span&gt;&lt;span style="color: purple"&gt;string&lt;/span&gt;&lt;span style="color: #006400"&gt;]()
            &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;&lt;span style="color: black"&gt;c &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;Capture &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: black"&gt;match&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Groups&lt;/span&gt;&lt;span style="color: #006400"&gt;[&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;column&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;].&lt;/span&gt;&lt;span style="color: black"&gt;Captures:
                params&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;c&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Value&lt;/span&gt;&lt;span style="color: #006400"&gt;)
            
            &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;&lt;span style="color: #191970"&gt;len&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;args&lt;/span&gt;&lt;span style="color: #006400"&gt;) == &lt;/span&gt;&lt;span style="color: #191970"&gt;len&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;params&lt;/span&gt;&lt;span style="color: #006400"&gt;)&lt;/span&gt;&lt;span style="color: black"&gt;:
                &lt;/span&gt;&lt;span style="color: navy"&gt;return &lt;/span&gt;&lt;span style="color: #191970"&gt;RunQuery&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;table&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;params&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;ToArray&lt;/span&gt;&lt;span style="color: #006400"&gt;(), &lt;/span&gt;&lt;span style="color: black"&gt;args&lt;/span&gt;&lt;span style="color: #006400"&gt;)
            &lt;/span&gt;&lt;span style="color: blue"&gt;else&lt;/span&gt;&lt;span style="color: black"&gt;:
                &lt;/span&gt;&lt;span style="color: teal"&gt;raise &lt;/span&gt;&lt;span style="color: #191970"&gt;InvalidOperationException&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Column count doesn't match parameter count&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
        &lt;/span&gt;&lt;span style="color: blue"&gt;else&lt;/span&gt;&lt;span style="color: black"&gt;:
            &lt;/span&gt;&lt;span style="color: teal"&gt;raise &lt;/span&gt;&lt;span style="color: #191970"&gt;InvalidOperationException&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Method name has incorrect format&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
    
    &lt;/span&gt;&lt;span style="color: blue"&gt;private def &lt;/span&gt;&lt;span style="color: #191970"&gt;RunQuery&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;table &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;string&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;params &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: purple"&gt;string&lt;/span&gt;&lt;span style="color: #006400"&gt;), &lt;/span&gt;&lt;span style="color: black"&gt;args &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: #006400"&gt;))&lt;/span&gt;&lt;span style="color: black"&gt;:
        &lt;/span&gt;&lt;span style="color: #04abab"&gt;paramString &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;&amp;quot;
        for &lt;/span&gt;&lt;span style="color: black"&gt;i &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #191970"&gt;range&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;len&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;params&lt;/span&gt;&lt;span style="color: #006400"&gt;))&lt;/span&gt;&lt;span style="color: black"&gt;:
            paramString &lt;/span&gt;&lt;span style="color: #006400"&gt;+= &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot; and &lt;/span&gt;&lt;span style="color: #993366"&gt;${params[i]} &lt;/span&gt;&lt;span style="color: blue"&gt;= @p&lt;/span&gt;&lt;span style="color: #993366"&gt;${i}&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;
        &lt;/span&gt;&lt;span style="color: #04abab"&gt;commandText &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;select * from &lt;/span&gt;&lt;span style="color: #993366"&gt;${table} &lt;/span&gt;&lt;span style="color: blue"&gt;where (1 = 1)&lt;/span&gt;&lt;span style="color: #993366"&gt;${paramString}&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;;
        
        &lt;/span&gt;&lt;span style="color: maroon"&gt;using &lt;/span&gt;&lt;span style="color: #04abab"&gt;connection &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;SqlConnection&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;&amp;lt;your connection string here&amp;gt;&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)&lt;/span&gt;&lt;span style="color: black"&gt;:
            &lt;/span&gt;&lt;span style="color: #04abab"&gt;command &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;SqlCommand&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;commandText&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;connection&lt;/span&gt;&lt;span style="color: #006400"&gt;)
            
            &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;&lt;span style="color: black"&gt;i &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #191970"&gt;range&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #191970"&gt;len&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;args&lt;/span&gt;&lt;span style="color: #006400"&gt;))&lt;/span&gt;&lt;span style="color: black"&gt;:
                command&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: black"&gt;Parameters&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;AddWithValue&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;@p&lt;/span&gt;&lt;span style="color: #993366"&gt;${i}&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;args&lt;/span&gt;&lt;span style="color: #006400"&gt;[&lt;/span&gt;&lt;span style="color: black"&gt;i&lt;/span&gt;&lt;span style="color: #006400"&gt;])

            &lt;/span&gt;&lt;span style="color: black"&gt;connection&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Open&lt;/span&gt;&lt;span style="color: #006400"&gt;()
            
            &lt;/span&gt;&lt;span style="color: #04abab"&gt;dataSet &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;DataSet&lt;/span&gt;&lt;span style="color: #006400"&gt;()
            &lt;/span&gt;&lt;span style="color: #191970"&gt;SqlDataAdapter&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;command&lt;/span&gt;&lt;span style="color: #006400"&gt;).&lt;/span&gt;&lt;span style="color: #191970"&gt;Fill&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;dataSet&lt;/span&gt;&lt;span style="color: #006400"&gt;)
            &lt;/span&gt;&lt;span style="color: navy"&gt;return &lt;/span&gt;&lt;span style="color: black"&gt;dataSet
    
    &lt;/span&gt;&lt;span style="color: blue"&gt;def &lt;/span&gt;&lt;span style="color: #191970"&gt;QuackSet&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;name &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;string&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;parameters &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: #006400"&gt;), &lt;/span&gt;&lt;span style="color: black"&gt;value&lt;/span&gt;&lt;span style="color: #006400"&gt;) &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: black"&gt;:
        &lt;/span&gt;&lt;span style="color: gray"&gt;pass
    
    &lt;/span&gt;&lt;span style="color: blue"&gt;def &lt;/span&gt;&lt;span style="color: #191970"&gt;QuackGet&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;name &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;string&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;parameters &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: #006400"&gt;)) &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;object&lt;/span&gt;&lt;span style="color: black"&gt;:
        &lt;/span&gt;&lt;span style="color: gray"&gt;pass
    &lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Sample usage of this class is:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #04abab"&gt;repository &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: #191970"&gt;Repository&lt;/span&gt;&lt;span style="color: #006400"&gt;()
&lt;/span&gt;&lt;span style="color: #04abab"&gt;customers &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;repository&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetCustomersByCountry&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Germany&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;) &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;DataSet
&lt;/span&gt;&lt;span style="color: #04abab"&gt;products &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;repository&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;GetProductsByUnitsInStockAndReorderLevel&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #00008b"&gt;0&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;0&lt;/span&gt;&lt;span style="color: #006400"&gt;) &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: black"&gt;DataSet
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, the result of the method is casted to DataSet. Without this, the result would be of the duck type, which means its members would be resolved at runtime. While this may be OK, you should consider two things:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Duck typing is &lt;a href="http://docs.codehaus.org/display/BOO/Duck+Typing+Benchmark"&gt;approx. 160 times slower&lt;/a&gt; than static typing. &lt;/li&gt;

  &lt;li&gt;There is a &lt;a href="https://svn.sxc.codehaus.org/browse/BOO-1033"&gt;known issue&lt;/a&gt; with Boo 0.8.2 causing AmbiguousMatchException to be thrown when an overloaded indexer is accessed on a duck type. This means that accessing indexer of Tables collection of the DataSet class through duck typing will result in this exception. &lt;/li&gt;
&lt;/ul&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/12/example-of-iquackfu-usage-in-boo.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/12/example-of-iquackfu-usage-in-boo.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-1638771886229583187?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/1638771886229583187/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=1638771886229583187' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/1638771886229583187'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/1638771886229583187'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/12/example-of-iquackfu-usage-in-boo.html' title='An example of IQuackFu usage in Boo'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-4385353851665550515</id><published>2008-12-13T14:04:00.001+01:00</published><updated>2009-01-24T11:08:10.474+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Boo'/><title type='text'>Boo language with SharpDevelop</title><content type='html'>&lt;p&gt;Recently I had urge to wander off the track laid by almighty Microsoft and take a peek into open source community. And there it is – the &lt;a href="http://boo.codehaus.org/"&gt;Boo language&lt;/a&gt; for CLI. It is announced as a “wrist friendly” language, which basically means that it has smooth syntax and other facilities that ease the hard life of a developer. The syntax is Python-like (or Ruby-like if you prefer), but the language itself is statically typed. It imitates dynamically typed language by type inference (where possible). The greatest power of Boo lies in extensibility of the language and the compiler, but let’s start at the beginning.&lt;/p&gt;  &lt;p&gt;True programmers use the notepad, but lazy ones prefer to have some IDE. There is Boo support built into open source &lt;a href="http://www.icsharpcode.net/OpenSource/SD/"&gt;SharpDevelop&lt;/a&gt; IDE. You get project templates, syntax highlighting, debugger and NUnit integration for free.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="441" alt="image" src="http://lh3.ggpht.com/_Egs311swNl0/SUOy7tQpSYI/AAAAAAAAAF0/qzvDDFeuHEo/image14.png?imgmax=800" width="644" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;This is no Visual Studio, but still impressive. &lt;/p&gt;  &lt;p&gt;If you would like to learn about Boo, just visit it’s &lt;a href="http://boo.codehaus.org/"&gt;home page&lt;/a&gt;. As for this post I would like to bullet point some features that make programming in Boo more pleasant than C#:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;First class functions. No need to declare a class, even for entry point. &lt;/li&gt;    &lt;li&gt;Puts your code on a diet. It’s this:      &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: black"&gt;Calculator:
    &lt;/span&gt;&lt;span style="color: blue"&gt;def &lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;a &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;int&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: black"&gt;b &lt;/span&gt;&lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: purple"&gt;int&lt;/span&gt;&lt;span style="color: #006400"&gt;)&lt;/span&gt;&lt;span style="color: black"&gt;:
        &lt;/span&gt;&lt;span style="color: navy"&gt;return &lt;/span&gt;&lt;span style="color: black"&gt;a &lt;/span&gt;&lt;span style="color: #006400"&gt;+ &lt;/span&gt;&lt;span style="color: black"&gt;b

&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: #191970"&gt;Calculator&lt;/span&gt;&lt;span style="color: #006400"&gt;().&lt;/span&gt;&lt;span style="color: #191970"&gt;Add&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #00008b"&gt;1&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;2&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;/pre&gt;
    

    &lt;p&gt;versus this:&lt;/p&gt;

    &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Calculator
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;Add(&lt;span style="color: blue"&gt;int &lt;/span&gt;a, &lt;span style="color: blue"&gt;int &lt;/span&gt;b)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;a + b;
    }
}

&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;Main()
    {
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Calculator&lt;/span&gt;().Add(1, 2));
    }
}&lt;/pre&gt;
    &lt;/li&gt;

  &lt;li&gt;Builtin literals for arrays, lists and hashes (like Hashtable) 
    &lt;pre class="code"&gt;&lt;span style="color: #04abab"&gt;myArray &lt;/span&gt;&lt;span style="color: #006400"&gt;= (&lt;/span&gt;&lt;span style="color: #00008b"&gt;1&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;2&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;4&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;myList &lt;/span&gt;&lt;span style="color: #006400"&gt;= [&lt;/span&gt;&lt;span style="color: #00008b"&gt;1&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;2&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;]
&lt;/span&gt;&lt;span style="color: #04abab"&gt;myHash &lt;/span&gt;&lt;span style="color: #006400"&gt;= { &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;key1&amp;quot; &lt;/span&gt;&lt;span style="color: black"&gt;: &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;value1&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;key2&amp;quot; &lt;/span&gt;&lt;span style="color: black"&gt;: &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Value2&amp;quot; &lt;/span&gt;&lt;span style="color: #006400"&gt;}

&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: black"&gt;myArray
&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: black"&gt;myList
&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: black"&gt;myHash

&lt;/span&gt;&lt;span style="color: #999999"&gt;// outputs:
// System.Int32[]
// [1, 2, apple]
// Boo.Lang.Hash&lt;/span&gt;&lt;/pre&gt;
    &lt;/li&gt;

  &lt;li&gt;Generators, which are basically expressions for defining a sequence based on condition. Those sequences are not stored in memory, but rather executed on demand (yeah, you can do this with LINQ too) 
    &lt;pre class="code"&gt;&lt;span style="color: #04abab"&gt;squaresForEvenNumbers &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: black"&gt;i&lt;/span&gt;&lt;span style="color: #006400"&gt;*&lt;/span&gt;&lt;span style="color: black"&gt;i &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;&lt;span style="color: black"&gt;i &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #191970"&gt;range&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: #00008b"&gt;10&lt;/span&gt;&lt;span style="color: #006400"&gt;) &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;&lt;span style="color: black"&gt;i &lt;/span&gt;&lt;span style="color: #006400"&gt;% &lt;/span&gt;&lt;span style="color: #00008b"&gt;2 &lt;/span&gt;&lt;span style="color: #006400"&gt;== &lt;/span&gt;&lt;span style="color: #00008b"&gt;0
&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: #191970"&gt;join&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;squaresForEvenNumbers&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;', '&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;fruits &lt;/span&gt;&lt;span style="color: #006400"&gt;= (&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;bannana&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;strawberry&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;raspberry&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: #04abab"&gt;berries &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Berry: &amp;quot; &lt;/span&gt;&lt;span style="color: #006400"&gt;+ &lt;/span&gt;&lt;span style="color: black"&gt;fruit &lt;/span&gt;&lt;span style="color: blue"&gt;for &lt;/span&gt;&lt;span style="color: black"&gt;fruit &lt;/span&gt;&lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: black"&gt;fruits &lt;/span&gt;&lt;span style="color: blue"&gt;if &lt;/span&gt;&lt;span style="color: black"&gt;fruit&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;Contains&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;berry&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: #191970"&gt;join&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;berries&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;', '&lt;/span&gt;&lt;span style="color: #006400"&gt;)

&lt;/span&gt;&lt;span style="color: #999999"&gt;// outputs:
// 0, 4, 16, 36, 64
// Berry: strawberry, Berry: raspberry
&lt;/span&gt;&lt;/pre&gt;
    &lt;/li&gt;

  &lt;li&gt;String interpolation (no more String.Format) 
    &lt;pre class="code"&gt;&lt;span style="color: #04abab"&gt;name &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Marcin&amp;quot;
&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Hello &lt;/span&gt;&lt;span style="color: #993366"&gt;${name}&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;
&lt;/span&gt;&lt;/pre&gt;
    &lt;/li&gt;

  &lt;li&gt;Builtin literals for regular expressions. 
    &lt;pre class="code"&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: #ff6600"&gt;/\d{2}-\d{3}/&lt;/span&gt;&lt;span style="color: #006400"&gt;.&lt;/span&gt;&lt;span style="color: #191970"&gt;IsMatch&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;12-333&amp;quot;&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;/pre&gt;
    &lt;/li&gt;

  &lt;li&gt;Slicing 
    &lt;pre class="code"&gt;&lt;span style="color: #04abab"&gt;numbers &lt;/span&gt;&lt;span style="color: #006400"&gt;= (&lt;/span&gt;&lt;span style="color: #00008b"&gt;1&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;2&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;3&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;4&lt;/span&gt;&lt;span style="color: #006400"&gt;, &lt;/span&gt;&lt;span style="color: #00008b"&gt;5&lt;/span&gt;&lt;span style="color: #006400"&gt;)
&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: #191970"&gt;join&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;numbers&lt;/span&gt;&lt;span style="color: #006400"&gt;[&lt;/span&gt;&lt;span style="color: #00008b"&gt;1&lt;/span&gt;&lt;span style="color: black"&gt;:&lt;/span&gt;&lt;span style="color: #00008b"&gt;3&lt;/span&gt;&lt;span style="color: #006400"&gt;])
&lt;/span&gt;&lt;span style="color: black"&gt;name &lt;/span&gt;&lt;span style="color: #006400"&gt;= &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;quot;Marcin&amp;quot;
&lt;/span&gt;&lt;span style="color: purple"&gt;print &lt;/span&gt;&lt;span style="color: #191970"&gt;join&lt;/span&gt;&lt;span style="color: #006400"&gt;(&lt;/span&gt;&lt;span style="color: black"&gt;name&lt;/span&gt;&lt;span style="color: #006400"&gt;[-&lt;/span&gt;&lt;span style="color: #00008b"&gt;3&lt;/span&gt;&lt;span style="color: black"&gt;:&lt;/span&gt;&lt;span style="color: #006400"&gt;])

&lt;/span&gt;&lt;span style="color: #999999"&gt;// outputs
// 2 3
// c i n
&lt;/span&gt;&lt;/pre&gt;
    &lt;/li&gt;

  &lt;li&gt;Duck typing, which is what you will get with the dynamic keyword in C# 4. This means being able to resolve member names at runtime. But Boo also implements mechanism of missing methods (also present in Ruby for example). When a method is not found on object implementing IQuackFu interface, then a special method of this interface is called and the name of missing method along with its parameters are passed. Developer can implement some behavior basing on the method’s name or its parameters. I hope to cover this in more detail in future.&lt;/li&gt;

  &lt;li&gt;Boo allows creating &lt;a href="http://boo.codehaus.org/Syntactic+Macros"&gt;syntactic macros&lt;/a&gt; which you can use to extend language. While implementing a macro, developer has access to object tree representation of code (AST – abstract syntax tree) and is able to modify this tree. This opens a lot of possibilities. For examle &lt;a href="http://www.manning.com/rahien/"&gt;Ayende Rahien uses this feature&lt;/a&gt; to create DSLs. Also you can build your own compiler steps – an example is to check the naming convenstions during compilation or automatically include assembly references for used types.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hopefully I’ll be able to write more on Boo in future. For now I encourage you to explore it on your own.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/12/boo-language-with-sharpdevelop.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/12/boo-language-with-sharpdevelop.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-4385353851665550515?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/4385353851665550515/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=4385353851665550515' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4385353851665550515'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4385353851665550515'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/12/boo-language-with-sharpdevelop.html' title='Boo language with SharpDevelop'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/_Egs311swNl0/SUOy7tQpSYI/AAAAAAAAAF0/qzvDDFeuHEo/s72-c/image14.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-9039340522929592830</id><published>2008-12-04T20:45:00.001+01:00</published><updated>2009-01-24T11:09:27.398+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>How to get property name from lambda expression</title><content type='html'>&lt;p&gt;Just a quick tip here. If you need a property name for reflection or any other purpose, the simplest solution is to pass it as a parameter of your method. This unfortunately has a serious disadvantage of not being influenced by automatic refactoring. Alternate way is to take advantage of lambda expressions and expression trees:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public void &lt;/span&gt;UseProperty&amp;lt;T, K&amp;gt;(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, K&amp;gt;&amp;gt; propertySelector)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(propertySelector.Body.NodeType != &lt;span style="color: #2b91af"&gt;ExpressionType&lt;/span&gt;.MemberAccess)
    {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(
            &lt;span style="color: #a31515"&gt;&amp;quot;A property selector expression has an incorrect format&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: #2b91af"&gt;MemberExpression &lt;/span&gt;memberAccess = propertySelector.Body &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MemberExpression&lt;/span&gt;;

    &lt;span style="color: blue"&gt;if &lt;/span&gt;(memberAccess.Member.MemberType != &lt;span style="color: #2b91af"&gt;MemberTypes&lt;/span&gt;.Property)
    {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;A selected member is not a property&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;string &lt;/span&gt;property = memberAccess.Member.Name;
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(property);
}&lt;/pre&gt;

&lt;p&gt;The usage:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;myClass = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;();
myClass.UseProperty((&lt;span style="color: #2b91af"&gt;Exception &lt;/span&gt;ex) =&amp;gt; ex.Message);&lt;/pre&gt;


&lt;p&gt;Notice there is no need to explicitly provide parameter types as they are inferred from the lambda expression, but you have to explicitly type the lambda expression. If your class operates on a specific type, you can make it generic and move type declaration to the point, where an instance is created. This is useful if you have more methods using lambda to retrieve property name.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;public void &lt;/span&gt;UseProperty&amp;lt;K&amp;gt;(&lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, K&amp;gt;&amp;gt; propertySelector)
    {
        &lt;span style="color: green"&gt;// same as previously
    &lt;/span&gt;}
}&lt;/pre&gt;


&lt;p&gt;The usage:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;myClass = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Exception&lt;/span&gt;&amp;gt;();
myClass.UseProperty(ex =&amp;gt; ex.Message);&lt;/pre&gt;


&lt;p&gt;Hope this helps. 
  &lt;br /&gt;&lt;/p&gt;

&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/12/how-to-get-property-name-from-lambda.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/12/how-to-get-property-name-from-lambda.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-9039340522929592830?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/9039340522929592830/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=9039340522929592830' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/9039340522929592830'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/9039340522929592830'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/12/how-to-get-property-name-from-lambda.html' title='How to get property name from lambda expression'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-4483374893024544253</id><published>2008-12-03T00:21:00.001+01:00</published><updated>2008-12-03T20:54:37.653+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ORM'/><title type='text'>Some thoughts on LLBLGen</title><content type='html'>&lt;p&gt;While there are many popular ORMs, the LLBLGen doesn’t get too much buzz on the blogs. Possibly because it is a commercial product and people rather use free tools if available. I think it is one of the first .NET ORMs on the market and it surely is a mature product. I had an opportunity to work a little with LLBLGen so I’d like to sum up some of my observations. &lt;/p&gt;  &lt;p&gt;An overall impression I got was that LLBLGen is very ADO.NET-like. There’s no equivalent of session (or object context) unless explicitly specified, so the &lt;a href="http://martinfowler.com/eaaCatalog/identityMap.html"&gt;Identity Map pattern&lt;/a&gt; is not used by default, which is OK in most scenarios (and more intuitive in my opinion). Instead of session, you use a DataAccessAdapter class, which behaves like a smart connection to a database. There’s the EntityCollection class which is basically something like a DataSet – a data container, that tracks changes . There are typed lists which allow to create a custom view over a set of related entities.&lt;/p&gt;  &lt;p&gt;The pros of LLBLGen are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Allows you to just get things done quickly. Maybe not in the best style, but still. &lt;/li&gt;    &lt;li&gt;Has a nice designer and a very sophisticated text templating engine with ORM oriented syntax. Take a look at this:      &lt;pre class="code"&gt;/// &amp;lt;summary&amp;gt; 
/// CTor which initializes the DTO with values from its corresponding entity 
/// &amp;lt;/summary&amp;gt; 
/// &amp;lt;param name=&amp;quot;entityInstance&amp;quot;&amp;gt;The entity instance which holds the values for this DTO&amp;lt;/param&amp;gt; 
public &amp;lt;[CurrentEntityName]&amp;gt;DTO(&amp;lt;[CurrentEntityName]&amp;gt;Entity entityInstance)&amp;lt;[ If IsSubType ]&amp;gt; 
    : base(entityInstance)&amp;lt;[ EndIf]&amp;gt; 
{ 
    &amp;lt;[Foreach EntityField CrLf]&amp;gt; _&amp;lt;[CaseCamel EntityFieldName]&amp;gt; = 
        entityInstance.&amp;lt;[EntityFieldName]&amp;gt;;&amp;lt;[NextForeach]&amp;gt; 
} &lt;/pre&gt;
I consider this to be a nice example of DSL. &lt;/li&gt;

  &lt;li&gt;Has an advanced LINQ support together with extensions allowing you to define prefetch paths on IQueryable&amp;lt;&amp;gt; &lt;/li&gt;

  &lt;li&gt;Extensive predicate mechanism (&lt;a href="http://en.wikipedia.org/wiki/Specification_pattern"&gt;Specification pattern&lt;/a&gt;) when not using LINQ&lt;/li&gt;

  &lt;li&gt;Supports both adapter mode (the usual with entities loaded and saved using external object, adapter) and self-serviced mode(&lt;a href="http://martinfowler.com/eaaCatalog/activeRecord.html"&gt;Active record pattern&lt;/a&gt;) &lt;/li&gt;

  &lt;li&gt;Has some advanced features including auditing, authorization and own dependency injection, but presumably you will use specialized libraries for this aspects anyway.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While the cons are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Entities generated by default templates are cluttered with ORM related code and really heavyweight. &lt;/li&gt;

  &lt;li&gt;The syntax imposed by runtime libraries is clumsy and awkward. An example: 
    &lt;pre class="code"&gt;EntityCollection customers = new EntityCollection(new CustomerEntityFactory());
DataAccessAdapter adapter = new DataAccessAdapter();
adapter.FetchEntityCollection(customers, null);
customers.Sort((int)CustomerFieldIndex.CompanyName, ListSortDirection.Descending);&lt;/pre&gt;
Fortunately this is remedied to some extent by usage of LINQ. &lt;/li&gt;

  &lt;li&gt;Does not support lazy loading.&lt;/li&gt;

  &lt;li&gt;While prefetching related entities, LLBLGen generates separate SELECT statement for each entity type instead of performing a join.&lt;/li&gt;

  &lt;li&gt;While having a very nice templating engine and template designer, there is virtually no repository for community created templates. Sure, there is a forum section, but it is unstructured and you can browse posts from last year only!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Still, overall impression is good. I hope to get some comments on this :)&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/12/some-thoughts-on-llbl-gen.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/12/some-thoughts-on-llbl-gen.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-4483374893024544253?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/4483374893024544253/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=4483374893024544253' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4483374893024544253'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4483374893024544253'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/12/some-thoughts-on-llbl-gen.html' title='Some thoughts on LLBLGen'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-8420998500984666786</id><published>2008-11-28T00:28:00.002+01:00</published><updated>2009-01-08T22:55:03.254+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Entity Framework'/><category scheme='http://www.blogger.com/atom/ns#' term='WCF'/><title type='text'>Using MetaLinq to simulate NHibernate’s DetachedCriteria in Entity Framework</title><content type='html'>&lt;p&gt;NHibernate’s DetachedCriteria allow you to specify a query filter outside session context and then pass it to code that actually uses a session in order to retrieve data. What’s more, DetachedCriteria is serializable, so you could imagine a scenario in which a client forms criteria and passes it to a service in order to query data.&lt;/p&gt;  &lt;p&gt;Entity Framework has no such thing as DetachedCriteria, but you can use LINQ and expression trees in similar fashion. The only problem is that the expression trees are immutable and nonserializable. There is however a project called &lt;a href="http://www.codeplex.com/metalinq"&gt;MetaLinq&lt;/a&gt; that copies an expression tree’s structure into mutable clone (built from custom set of classes that mirror the System.Linq.Expressions namespace) and enables you to both edit the tree and serialize it. &lt;/p&gt;  &lt;p&gt;So I performed a little experiment. Following is the code of WCF service operation.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Customer&lt;/span&gt;[] GetCustomersBy(&lt;span style="color: #2b91af"&gt;EditableLambdaExpression &lt;/span&gt;filter)
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;filterLambda = filter.ToExpression() &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LambdaExpression&lt;/span&gt;;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;filterDelegate = filterLambda.Compile() &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Customer&lt;/span&gt;, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;;

    &lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;context = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;NorthwindContext&lt;/span&gt;())
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;context.CustomerSet.Where(filterDelegate).ToArray();
    }
}&lt;/pre&gt;

&lt;p&gt;The method receives a filter in a parameter. It is of type EditableLambdaExpression, which is one of MetaLinq’s expression types. By calling it’s ToExpression method you get the regular expression tree. Then there’s a compilation resulting in a delagate of type Func&amp;lt;Customer,bool&amp;gt; (it’s a quiet assumption) that is finally passed to the Where method of ObjectContext. Quite straightforward.&lt;/p&gt;

&lt;p&gt;So is the client code: &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Service1Client &lt;/span&gt;client = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Service1Client&lt;/span&gt;())
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;filter = &lt;span style="color: #2b91af"&gt;EditableExpression&lt;/span&gt;.CreateEditableExpression(
        (&lt;span style="color: #2b91af"&gt;Customer &lt;/span&gt;c) =&amp;gt; c.CustomerID == &lt;span style="color: #a31515"&gt;&amp;quot;ALFKI&amp;quot;&lt;/span&gt;) &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EditableLambdaExpression&lt;/span&gt;;

    &lt;span style="color: blue"&gt;var &lt;/span&gt;customers = client.GetCustomersBy(filter);
}&lt;/pre&gt;

&lt;p&gt;The filter expressed as a lambda has to be converted to MetaLinq’s EditableLambdaExpression. Then it can be serialized and passed to the service. And this works just fine. What also works is:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;filter = &lt;span style="color: #2b91af"&gt;EditableExpression&lt;/span&gt;.CreateEditableExpression(
    (&lt;span style="color: #2b91af"&gt;Customer &lt;/span&gt;c) =&amp;gt; c.CustomerID.StartsWith(&lt;span style="color: #a31515"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;)) &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EditableLambdaExpression&lt;/span&gt;;&lt;/pre&gt;

&lt;p&gt;What does not work is for example:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;filter = &lt;span style="color: #2b91af"&gt;EditableExpression&lt;/span&gt;.CreateEditableExpression(
    (&lt;span style="color: #2b91af"&gt;Customer &lt;/span&gt;c) =&amp;gt; c.Orders.Any(o =&amp;gt; o.Freight &amp;gt; 100.0M)) 
    &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EditableLambdaExpression&lt;/span&gt;;&lt;/pre&gt;

&lt;p&gt;It turns out MetaLinq (as for now) is having trouble deserializing expressions with generic and extension methods. &lt;/p&gt;

&lt;p&gt;This was an interesting experiment and now there is time for:&lt;/p&gt;

&lt;h3&gt;The criticism&lt;/h3&gt;

&lt;p&gt;I wouldn’t recommend using this idea in any production environment. It has several disadvantages:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;MetaLinq itself is just an experiment, it definitely is not finished. There potentially are some hidden problems and you can’t express more advanced scenarios (unless of course you fix the code yourself :). &lt;/li&gt;

  &lt;li&gt;Building mutable expressions, serializing them, then deserializing and then compiling again imposes a performance penalty. &lt;/li&gt;

  &lt;li&gt;You can’t enforce the lambda passed to your service to be Func&amp;lt;Customer, bool&amp;gt;. You always has to check it and throw when it’s not. &lt;/li&gt;

  &lt;li&gt;And last but not least – it threats security of your service. What you’re doing is just executing some code that came from outside the service’s boundaries. This could allow someone to perform, let’s say, LINQ injection :) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&amp;#160;&lt;/a&gt;&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/11/using-metalinq-to-simulate-nhbernates.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/11/using-metalinq-to-simulate-nhbernates.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-8420998500984666786?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/8420998500984666786/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=8420998500984666786' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8420998500984666786'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/8420998500984666786'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/11/using-metalinq-to-simulate-nhbernates.html' title='Using MetaLinq to simulate NHibernate’s DetachedCriteria in Entity Framework'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-3844668403051368593</id><published>2008-11-24T00:17:00.001+01:00</published><updated>2008-11-24T22:56:35.604+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='book'/><title type='text'>[Book] Application Architecture Guide 2.0</title><content type='html'>&lt;p&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="262" alt="image" src="http://lh6.ggpht.com/_Egs311swNl0/SSnkfdKLmdI/AAAAAAAAAFw/WEfhNc_q0DI/image%5B3%5D.png?imgmax=800" width="204" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;I just skimmed through Application Architecture Guide 2.0 by Patterns &amp;amp; Practices (beta). So I think it's a nice checklist for your project, whatever that is. The guide lists patterns and consideration points categorized both by layers and application types. Yet, if your not already familiar with those concepts, you might have trouble learning them from that book, because there are only short explanations without any examples and there are no specific technologies listed. It's a good starting point for your research. I myself was a little disappointed, because I expected more insight into advanced topics.&lt;/p&gt;  &lt;div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:adc71f7e-42ed-427a-9390-c18a5ea41c27" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;!--dotnetkickit--&gt;&lt;/div&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/11/book-application-architecture-guide-20.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/11/book-application-architecture-guide-20.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-3844668403051368593?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/3844668403051368593/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=3844668403051368593' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3844668403051368593'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/3844668403051368593'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/11/book-application-architecture-guide-20.html' title='[Book] Application Architecture Guide 2.0'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh6.ggpht.com/_Egs311swNl0/SSnkfdKLmdI/AAAAAAAAAFw/WEfhNc_q0DI/s72-c/image%5B3%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-5791150683074859567</id><published>2008-11-20T19:11:00.001+01:00</published><updated>2008-11-24T22:55:01.457+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='AOP'/><title type='text'>Should transaction management be implemented as an aspect?</title><content type='html'>&lt;p&gt;As usually the right answer is: that depends :) But let's think think about this a little.&lt;/p&gt;  &lt;p&gt;When considering aspect oriented programming, there are a lot of very good examples of cross-cutting concerns whose implementation as an aspect is a very good idea (logging, exception handling, etc). But is transaction management such? Suppose there is situation like following:&lt;/p&gt;  &lt;p&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="123" alt="image" src="http://lh4.ggpht.com/_Egs311swNl0/SSWoMwSD_fI/AAAAAAAAAFY/DAf0sCNkenw/image%5B8%5D.png?imgmax=800" width="470" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;(the service here is not to be understood as a part of distributed system, but rather as fragment of &lt;a href="http://martinfowler.com/eaaCatalog/transactionScript.html"&gt;transaction script&lt;/a&gt; business logic)&lt;/p&gt;  &lt;p&gt;Now, what are the pros of opening transaction in an advice (a handler) for DoSomethingTransactional():&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You don't have to do it manually &lt;/li&gt;    &lt;li&gt;Each new method and class matching a pointcut (or matching rules in Enterprise Library terminology) gets a &amp;quot;free&amp;quot; transaction without any effort &lt;/li&gt;    &lt;li&gt;Transaction creation code is centralized and easy to modify &lt;/li&gt;    &lt;li&gt;When the Service calls another service, say Service2, the operation should be implicitly enlisted to transaction that was created for Service1 &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now the cons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Transactions are a very serious matter. If for some reason your pointcut contains an error, some operations can execute without opening database transaction, which leads to violated data integrity in case of an unexpected error. This can cause some serious damage and is not easily detectable. I suppose you could roll out some unit tests for that. &lt;/li&gt;    &lt;li&gt;Your transactions sometimes cover too much. Suppose your DoSomethingTransactional1 method does two things: updates a database record and then send a notification email. If sending an email fails, whole operation is rolled back. In some cases this is not a desirable behavior. A notification might be significantly less important than the business operation which was successful. This business operation might be your holiday trip reservation when there's just one place left :) Surely you could explicitly handle this error, but your code has to be aware of that specific error. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So you may consider using explicit transactions instead of AOP. Also remember, that .NET's TransactionScope is a nice way of determining what portion of code should run in a transaction.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/11/should-transaction-management-be.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/11/should-transaction-management-be.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-5791150683074859567?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/5791150683074859567/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=5791150683074859567' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/5791150683074859567'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/5791150683074859567'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/11/should-transaction-management-be.html' title='Should transaction management be implemented as an aspect?'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_Egs311swNl0/SSWoMwSD_fI/AAAAAAAAAFY/DAf0sCNkenw/s72-c/image%5B8%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-7201347682546072428</id><published>2008-11-15T15:46:00.001+01:00</published><updated>2008-11-24T22:54:44.830+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='team work'/><title type='text'>A digression on UML modeling</title><content type='html'>&lt;p&gt;What do you need UML diagrams for? &lt;/p&gt;  &lt;p&gt;UML is a language and a language is used for communication. This is also true for programming languages because through them you are communicating a compiler what you want to achieve. So anyway, the communication is the goal. &lt;/p&gt;  &lt;p&gt;Who do you communicate with? This depends, really. For one, you may be trying to describe your application's structure in technical documentation. This means you're communicating with people that will require knowledge on your application in the future. Then there are design meetings. You can use UML to express your thoughts more clearly than in regular spoken language. Once other people get your idea, they can discuss, suggest changes and modify your diagrams. &lt;/p&gt;  &lt;p&gt;How accurate should the diagrams be? This also depends. While writing a science book you would want to be a little more accurate than when making notes for your next grocery shopping. But this doesn't make your shopping list worse than a science book in terms of communication. It's accurate ENOUGH.&lt;/p&gt;  &lt;p&gt;What I'm driving at is that you only need to make your UML diagrams (or any other diagrams) as good as it gets to communicate your ideas to your audience. In my opinion, once this is done, diagrams can be disposed. Well if you need them for future reference, that's fine, but treat them as a way of communication. As analogy I might ask you if you keep transcript of every meeting.&lt;/p&gt;  &lt;p&gt;Finally, the language itself. Do you really need UML? Think twice before you use it, because maybe a few boxes connected with arrows will tell your audience more than an elaborate UML diagram. Not everyone can tell the difference between solid and dashed line, but that doesn't make them less able to comprehend your ideas.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/11/digression-on-uml-modeling.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/11/digression-on-uml-modeling.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-7201347682546072428?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/7201347682546072428/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=7201347682546072428' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7201347682546072428'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/7201347682546072428'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/11/digression-on-uml-modeling.html' title='A digression on UML modeling'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-4917586337149274041</id><published>2008-11-11T16:54:00.001+01:00</published><updated>2008-11-24T22:54:05.929+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='communication'/><title type='text'>nServiceBus</title><content type='html'>&lt;p&gt;Last time I &lt;a href="http://marcinbudny.blogspot.com/2008/11/asynchronous-and-durable-messaging.html"&gt;wrote about&lt;/a&gt; asynchronous communication as a way to improve availability and capacity of a distributed system. To dig further on this topic I played a little with the &lt;a href="http://www.nservicebus.com/"&gt;nServiceBus&lt;/a&gt; project by &lt;a href="http://www.udidahan.com/"&gt;Udi Dahan&lt;/a&gt;. This is a communications framework built upon a concept of a bus. It promotes asynchronous communication model both in one way and publish/subscribe models. &lt;/p&gt;  &lt;p&gt;As the documentation is close to none I had to look into source code to get a grasp on what's going on in there. There are some samples provided, in order to run which you need to install Microsoft Message Queuing component. Samples demonstrate basic messaging, publish/subscribe model and the concept of saga. &lt;/p&gt;  &lt;p&gt;The saga is a set of related messages. This takes asynchronous messaging a step further allowing you to deal with workflows. Suppose you have to make two calls to external system: first one to get a order status, then depending on this status you would either cancel the order or change it's priority. In traditional approach you would have a method similar to following:&lt;/p&gt;  &lt;p&gt;&lt;code style="color: black"&gt;orderStatus = externalSystemPoxy.GetOrderStatus(orderId)      &lt;br /&gt;if (orderStatus == Status.Postponed)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; operationStatus = externalSystemProxy.CancelOrder(orderId)       &lt;br /&gt;else       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; operationStatus = externalSystemProxy.SetLowPriority(orderId)       &lt;br /&gt;// notify user about operationStatus&lt;/code&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;EDIT:&amp;#160; As Udi pointed out, I should explicitly say, that the code above is time-bound. Execution of the GetOrderStatus method is blocking, which implies that if the external system is too busy to process the request (or it's not available for other reason), whole operation fails. Also if the response is taking long, a thread on client side is waiting idle instead of serving another request. If client crashes during execution of this &amp;quot;workflow&amp;quot;, all progress is lost. The reason to use the asynchronous model here is to remove that time dependency.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;When migrating this code to asynchronous model the situation gets complicated because you can't tell when the response to GetOrderStatus() will arrive. So you need to have an event handler for message arrival event, but you also need to maintain a state of the particular workflow instance (in this case the orderId value). A saga is a nice way to encapsulate such workflow. It contains a state and also handles for any of messages involved in the workflow. So with saga you would:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Define the class deriving from ISaga&amp;lt;OrderStatusResponse&amp;gt; and ISaga&amp;lt;OperationStatusResponse&amp;gt; &lt;/li&gt;    &lt;li&gt;Define the state inside the class, ex. public property OrderId &lt;/li&gt;    &lt;li&gt;Define message handlers for OrderStatusResponse and OperationStatusResponse &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The saga itself is persisted in a database using implementation of ISagaPersister, I think you need to roll out your own. Speaking of which, nServiceBus provides some extensibility points like for example the transport. There are two provided in the project: MSMQ and HTTP and you can add your own by implementing ITransport.&lt;/p&gt;  &lt;p&gt;So to sum up, nServiceBus is worth looking at when dealing with asynchronous communication. Hope it gets better documentation soon.&lt;/p&gt;&lt;div class="wlWriterHeaderFooter" style="text-align:left; margin:0px; padding:4px 4px 4px 4px;"&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://marcinbudny.blogspot.com/2008/11/nservicebus.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://marcinbudny.blogspot.com/2008/11/nservicebus.html&amp;amp;bgcolor=0080C0&amp;amp;fgcolor=FFFFFF&amp;amp;border=000000&amp;amp;cbgcolor=D4E1ED&amp;amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"&gt;&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4923273354692358330-4917586337149274041?l=marcinbudny.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://marcinbudny.blogspot.com/feeds/4917586337149274041/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=4923273354692358330&amp;postID=4917586337149274041' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4917586337149274041'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4923273354692358330/posts/default/4917586337149274041'/><link rel='alternate' type='text/html' href='http://marcinbudny.blogspot.com/2008/11/nservicebus.html' title='nServiceBus'/><author><name>Marcin Budny</name><uri>http://www.blogger.com/profile/03700203897522406849</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://1.bp.blogspot.com/_Egs311swNl0/Sdzhs9oHkeI/AAAAAAAAAHI/XvqzDPS0TP8/S220/DSC07167_sm.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4923273354692358330.post-5541110749272612635</id><published>2008-11-08T20:28:00.001+01:00</published><updated>2008-11-24T22:53:26.726+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='communication'/><title type='text'>Asynchronous and durable messaging</title><content type='html'>&lt;p&gt;If you're following this blog, you might have noticed that I'm jumping from topic to topic. Well I don't really have time to put it into one topic while there are many things waiting to be covered in this blog :)&lt;/p&gt;  &lt;p&gt;So today the topic is asynchronous messaging and I'll kick off with a case study. Suppose there are two system that need to interact. There's a warehousing system managing stock levels. When a certain product is running low, the warehousing system sends an order to a vendor's system. This order can be either accepted, postponed or rejected based on vendor's production abilities and current work load. Warehousing system needs to know what is the order's status and take appropriate actions - like informing a warehouse manager. The diagram below shows high level view over what the communications look like. &lt;/p&gt;  &lt;p&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="167" alt="image" src="http://lh6.ggpht.com/_Egs311swNl0/SRXoZ5INlDI/AAAAAAAAAE4/xFw5EaFa5y8/image%5B4%5D.png?imgmax=800" width="480" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;Classic request/response (synchronous) communication schema would be to call the vendor's web service, passing order as parameter, and wait for a response. This has some implications:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;If a vendor's system is down, the order placing activity fails. If it was started manually, a user receives unpleasant error message. The call has to be repeated when the system is back up. The call can also fail during the operation - in that case, warehousing system won't know whether the order was placed and can easily duplicate the order. &lt;/li&gt;    &lt;li&gt;Waiting for response from vendor system means that there's a thread in this system bound to this request, processing the order. If there are a lot of calls from different warehouses, the vendor system can easily be overloaded. Sure - you can scale it, but the question is whether real time order processing is worth the expense. Suppose there is only one hour during the day when order amount peaks - you would have to provide hardware that would deal with this traffic during that hour and stay almost idle at other times. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Following diagram represents synchronous communication:&lt;/p&gt;  &lt;p&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="228" alt="image" src="http://lh4.ggpht.com/_Egs311swNl0/SRXoauoUjBI/AAAAAAAAAE8/M2G14aA-9wI/image%5B9%5D.png?imgmax=800" width="292" border="0" /&gt; &lt;/p&gt;  &lt;p&gt;To avoid this issues you could make the communication asynchronous. In this model, communication is based on messages. Warehouse system sends a message containing order information to vendor system. It doesn't wait for a reply (fire and forget). This message is queued at vendor system for processing. When processing finishes, vendor system sends a message with order status information to warehouse system. If the system we want to communicate with is currently unavailable, the message should be put to a sender's queue. Later, when communication is restored, the message would be sent to the other system.&lt;/p&gt;  &lt;p&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="312" alt="image" src="http:/
