<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.abdullin.com/~d/styles/itemcontent.css"?><!--Generated by Squarespace Site Server v5.9.2 (http://www.squarespace.com/) on Mon, 08 Mar 2010 19:46:38 GMT--><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0"><title type="text">Rinat Abdullin on Lokad Shared Libraries</title><subtitle>Journal</subtitle><id>http://abdullin.com/journal/</id><link rel="alternate" type="application/xhtml+xml" href="http://abdullin.com/journal/" /><updated>2010-03-05T13:58:37Z</updated><generator uri="http://www.squarespace.com/" version="Squarespace Site Server v5.9.2 (http://www.squarespace.com/)">Squarespace</generator><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.abdullin.com/Shared-Libraries" /><feedburner:info uri="shared-libraries" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry><title>Microsoft Feedback 2010</title><category term="Lokad" /><id>http://abdullin.com/journal/2009/12/10/microsoft-feedback-2010.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/cpD8LZia9Pk/microsoft-feedback-2010.html" /><author><name>Rinat Abdullin</name></author><published>2009-12-10T07:56:34Z</published><updated>2009-12-10T07:56:34Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;There is usually a lot to learn from large companies like Microsoft, or less large ones.&lt;/p&gt;  &lt;p&gt;However, it takes a bit of learning on your own before you could understand and appreciate details and partially hidden interactions behind what is revealed.&lt;/p&gt;  &lt;p&gt;Fore example, that’s how Jetbrains ReSharper feedback looks like:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://abdullin.com/resource/WindowsLiveWriter-MicrosoftFeedback2010_B5FE-?fileId=5023971"&gt;&lt;img style="display: inline" title="2009-12-10_JetBrains_Feedback" alt="2009-12-10_JetBrains_Feedback" src="http://abdullin.com/resource/WindowsLiveWriter-MicrosoftFeedback2010_B5FE-?fileId=5023972" width="205" height="240" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here’s the one currently employed by us at &lt;a href="http://lokad.com" target="_blank"&gt;Lokad&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://abdullin.com/resource/WindowsLiveWriter-MicrosoftFeedback2010_B5FE-?fileId=5023974"&gt;&lt;img style="display: inline" title="2009-12-10_Lokad_Feedback" alt="2009-12-10_Lokad_Feedback" src="http://abdullin.com/resource/WindowsLiveWriter-MicrosoftFeedback2010_B5FE-?fileId=5023975" width="232" height="240" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;And that’s how Microsoft Office 2010 feedback looks like:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://abdullin.com/resource/WindowsLiveWriter-MicrosoftFeedback2010_B5FE-?fileId=5023976"&gt;&lt;img style="display: inline" title="2009-12-10_Microsoft_feedback" alt="2009-12-10_Microsoft_feedback" src="http://abdullin.com/resource/WindowsLiveWriter-MicrosoftFeedback2010_B5FE-?fileId=5023977" width="500" height="395" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Each of these three has it’s own benefits, including but not limited to:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;UI simplicity;&lt;/li&gt;    &lt;li&gt;Level of complexity of cliend-side and server-side infrastructure behind the feature;&lt;/li&gt;    &lt;li&gt;Support for multiple software applications within the same product line (all the way through various versions, deployment options);&lt;/li&gt;    &lt;li&gt;Ability to offer user to provide additional data, essential for the problem resolution;&lt;/li&gt;    &lt;li&gt;Level and quality of sensible automation behind the interaction.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;There is a lot to learn from large companies for Lokad.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=cpD8LZia9Pk:acMF5mqspIc:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=cpD8LZia9Pk:acMF5mqspIc:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=cpD8LZia9Pk:acMF5mqspIc:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=cpD8LZia9Pk:acMF5mqspIc:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=cpD8LZia9Pk:acMF5mqspIc:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=cpD8LZia9Pk:acMF5mqspIc:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=cpD8LZia9Pk:acMF5mqspIc:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/cpD8LZia9Pk" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/12/10/microsoft-feedback-2010.html</feedburner:origLink></entry><entry><title>Infrastructure Shards and Optional Components</title><category term="Articles" /><category term="C#" /><category term="IoC" /><category term="Lokad" /><category term="Snippets" /><category term="Theory" /><id>http://abdullin.com/journal/2009/10/21/infrastructure-shards-and-optional-components.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/zbWCBO4o6Hk/infrastructure-shards-and-optional-components.html" /><author><name>Rinat Abdullin</name></author><published>2009-10-21T05:56:05Z</published><updated>2009-10-21T05:56:05Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;&lt;a href="http://abdullin.com/wiki/component-driven-development.html"&gt;Component-driven development&lt;/a&gt; really helps to deliver multiple applications and systems efficiently. It happens because:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;important functionality is abstracted in components;&lt;/li&gt;
&lt;li&gt;components are coded and unit-tested only once;&lt;/li&gt;
&lt;li&gt;every component has multiple use cases that provide additional feedback and help to find problems or limitations, if there are any;&lt;/li&gt;
&lt;li&gt;whenever a component is fixed or improved, all its consumers would benefit from that automatically.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As we go up in the complexity of the development, it becomes too cumbersome to manage components on the individual basis. That's where &lt;em&gt;infrastructure shards&lt;/em&gt; come into the play.&lt;/p&gt;

&lt;h2&gt;Infrastructure Shards&lt;/h2&gt;

&lt;p&gt;Infrastructure shard is a group of components that work together to carry out some specific job in the application or system. They are joined to simplify reuse in multiple applications and contexts.&lt;/p&gt;

&lt;p&gt;Normally all these components are developed to support &lt;a href="http://abdullin.com/wiki/inversion-of-control-ioc.html"&gt;Inversion of Control&lt;/a&gt;, but if needed they could be wired together manually. In the IoC scenario, components are fit together using registration modules (or xml configuration blocks for the legacy containers). In the rare cases, when IoC context is not available (i.e.: we need to offer minimal feedback reporting to deal with possible unhandled exceptions on startup), a simple factory method would do the job.&lt;/p&gt;

&lt;p&gt;A single infrastructure shard could join components coming from the different libraries and application blocks. &lt;/p&gt;

&lt;p&gt;Feedback infrastructure shard (&lt;a href="http://code.google.com/p/lokad-sdk/" target="_blank" class="offsite-link-inline"&gt;sources&lt;/a&gt;), for example, would include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Model-View-Controller elements:
&lt;ul&gt;
&lt;li&gt;User control view to be shown in the currently available &lt;em&gt;IViewspace&lt;/em&gt;;&lt;/li&gt;
&lt;li&gt;Immutable models used to pass feedback reports and information around;&lt;/li&gt;
&lt;li&gt;Controller responsible for managing the view and user interactions;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://abdullin.com/journal/2008/11/23/net-application-block-for-validation-and-business-rules.html"&gt;Validation rules&lt;/a&gt; injected into the view in order to check and enforce user input.&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Feedback helper components, aggregating system information to be attached to the report.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, if we attempt to start our feedback reporting window, just with these few components, we would fail. This would happen because usually in the IoC environment &lt;em&gt;an infrastructure shard is not self-sufficient&lt;/em&gt;. It has to interact with the other components and services as well. The view, for instance, does not even have a window to present itself in; it is merely a user control:&lt;/p&gt;

&lt;p&gt;&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/10/2009-10-21_093717.png?__SQUARESPACE_CACHEVERSION=1256110659023" alt=""/&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;So in order for the shard to work, we need to provide some external services. These are really easy to spot in the code if we consistently stick to the guidelines of:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;only constructor injection is used (no property injection);&lt;/li&gt;
&lt;li&gt;every component has only a single constructor;&lt;/li&gt;
&lt;li&gt;components can inherit only from the interfaces (except for the views that have to derive from some user control).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Given that we could find out that core feedback service components use these components:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;IViewspace - responsible for displaying view properly in the UI environment available;&lt;/li&gt;
&lt;li&gt;IReportService - responsible for establishing contact with the communication service shard (which will handle all the exception handling and reliability on its own) and sending the feedback report;&lt;/li&gt;
&lt;li&gt;IClientInteractions - provides UI-specific methods that allow to interact with user;&lt;/li&gt;
&lt;li&gt;Optional{ServiceConnection}.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The last item is the most interesting one here. Here's why and how it works.&lt;/p&gt;

&lt;h2&gt;Optional Components&lt;/h2&gt;

&lt;p&gt;When we show feedback report window - we want to suggest user to use his existing email address and connection information. This way the feedback could be routed to the appropriate server and associated with the user's account. &lt;/p&gt;

&lt;p&gt;And we want to have code working in situations, when user context is not available (i.e.: user logged off or context is not even known).&lt;/p&gt;

&lt;p&gt;That's what the Optional{ServiceConnection} does. It allows to pass some information via IoC container, while indicating that the reference could be empty at the moment of retrieval. It's declaration is extremely simple:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt; Simple delegate that returns optional result &amp;lt;/summary&amp;gt;
public delegate Maybe&amp;lt;TResult&amp;gt; Optional&amp;lt;TResult&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That's it. Yes, that resembles &lt;em&gt;Lazy&lt;/em&gt; of MEF, but is a bit simpler, does not require MEF libraries and can benefit from the synergy with &lt;a href="http://abdullin.com/journal/2009/10/6/zen-development-practices-c-maybe-monad.html"&gt;Maybe Monad&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;For example, if we want to get current user name in one of the views (if the user name is available), the code might look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// somewhere in the class
readonly Optional&amp;lt;ServiceConnection&amp;gt; _contextProvider;

// somewhere in the code
var sender = _contextProvider()
  .Convert(sc =&amp;gt; sc.Username)
  .GetValue(AnonymousUserName);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While the registration of the optional might look like:   &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// extension method for Autofac ContainerBuilder
public static void RegisterExport&amp;lt;TComponent, TExported&amp;gt;(
  this ContainerBuilder builder,
  Func&amp;lt;TComponent, Maybe&amp;lt;TExported&amp;gt;&amp;gt; func)
{
  builder.Register&amp;lt;Optional&amp;lt;TExported&amp;gt;&amp;gt;(c =&amp;gt; 
    () =&amp;gt; func(c.Resolve&amp;lt;TComponent&amp;gt;()));
}

// actual registration
builder.RegisterExport&amp;lt;IApplicationController, ServiceConnection&amp;gt;(c =&amp;gt; 
  c.Context.Convert(ec =&amp;gt; ec.Connection));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this registration at hand, all trusted components that need to have access to the current connection context, can do that by requesting an instance of Optional{ServiceContext}.&lt;/p&gt;

&lt;p&gt;This technique is really useful when defining boundaries of infrastructure shards, required and optional dependencies that they might have.&lt;/p&gt;

&lt;h2&gt;Unit Testing&lt;/h2&gt;

&lt;p&gt;We can even easily isolate the shard in unit test in order to allow manual testing of feedback reporting:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Test, Explicit]
public void Show_synthetic_feedback()
{
  var data = RandFeedbackModels.NextTextDatas(0, 3);
  CreateService().ReportFeedback(data);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where &lt;em&gt;CreateService&lt;/em&gt; explicitly establishes all dependencies in the MockContainer and grabs the service:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IFeedbackService CreateService()
{
  Build(cb =&amp;gt;
  {
    // factories
    cb.Register&amp;lt;Func&amp;lt;ServiceConnection, ILokadService&amp;gt;&amp;gt;(ServiceFactory.GetConnector);
    cb.Register&amp;lt;Optional&amp;lt;ServiceConnection&amp;gt;&amp;gt;(() =&amp;gt; Maybe&amp;lt;ServiceConnection&amp;gt;.Empty);

    // services
    cb.Register&amp;lt;FeedbackService&amp;gt;().As&amp;lt;IFeedbackService&amp;gt;();
    cb.Register&amp;lt;ReportService&amp;gt;().As&amp;lt;IReportService&amp;gt;();

    cb.Register&amp;lt;FeedbackSenderController&amp;gt;().As&amp;lt;IFeedbackSenderState&amp;gt;();
  });

  WhenViewIsShown.Do(f =&amp;gt; f.ShowDialog());

  return Resolve&amp;lt;IFeedbackService&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see for the service connection provider we are passing a lambda expression that returns an empty connection context. &lt;/p&gt;

&lt;p&gt;Note that we are not establishing any view-related components, since ViewFixture (this test fixture derives from it) already does this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cb.Register&amp;lt;TView&amp;gt;().As&amp;lt;TView, TInterface&amp;gt;();
cb.Register&amp;lt;TestViewspace&amp;gt;().As&amp;lt;IViewspace, TestViewspace&amp;gt;();
cb.Register&amp;lt;TestInteractions&amp;gt;().As&amp;lt;IClientInteractions, TestInteractions&amp;gt;();
cb.Register(Specifics.Empty);
OnBuild(cb);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Result looks like this:&lt;/p&gt;

&lt;p&gt;&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/10/2009-10-21_093127.png?__SQUARESPACE_CACHEVERSION=1256110458483" alt=""/&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Filling in the information and clicking Send would create a ticket in &lt;a href="http://www.lokad.com" target="_blank" class="offsite-link-inline"&gt;Lokad&lt;/a&gt; support system. By the way, you can use this opportunity to say what you think about the company.&lt;/p&gt;

&lt;h2&gt;Shard Synergies&lt;/h2&gt;

&lt;p&gt;Here are some additional synergy effects that come from using infrastructure shards to reuse similar components between multiple applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Business functionality could be used to extend multiple applications. Since UI is shared, we could use shared documentation, tutorials and screenshots as well.&lt;/li&gt;
&lt;li&gt;Sometimes context requires infrastructure shard to be evolved. This brings potential improvements in all existing and new applications.&lt;/li&gt;
&lt;li&gt;When a group of components is developed to be used in multiple scenarios from the start, this polishes the overall design even further than &lt;a href="http://abdullin.com/wiki/test-driven-development-tdd.html"&gt;TDD&lt;/a&gt; or &lt;a href="http://abdullin.com/wiki/component-driven-development.html"&gt;CDD&lt;/a&gt; would alone.&lt;/li&gt;
&lt;li&gt;Localization or UI changes across the software product line become easier, since the effort does not have to be duplicated and tested in multiple codebases.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;What do you think about all that?&lt;/em&gt; &lt;/p&gt;

&lt;h2&gt;Notes&lt;/h2&gt;

&lt;p&gt;I understand that this looks really similar to what Microsoft Extensibility Framework does with &lt;em&gt;Lazy&lt;/em&gt; and &lt;em&gt;Export&lt;/em&gt; . However, my belief is that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;extensibility discovery and management framework should stay completely detached from the components;&lt;/li&gt;
&lt;li&gt;inversion of control container should stay completely detached from the framework as well;&lt;/li&gt;
&lt;li&gt;attribute-based declarations on the components are evil;&lt;/li&gt;
&lt;li&gt;all component dependencies should be explicitly declared in the orchestrating code in strongly-typed manner.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This means that the core components should not use extensibility framework. Infrastructure shard boundaries might do that, while acting as a simple gateways. But that's another story.&lt;/p&gt;

&lt;p&gt;You can &lt;a href="http://feeds.abdullin.com/RinatAbdullin"&gt;subscribe to this journal&lt;/a&gt; to get all the updates. &lt;a href="http://abdullin.uservoice.com/" target="_blank" class="offsite-link-inline"&gt;Voting for the next article to be written&lt;/a&gt; is also possible.&lt;/p&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=zbWCBO4o6Hk:ovgkZpXlJAs:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=zbWCBO4o6Hk:ovgkZpXlJAs:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=zbWCBO4o6Hk:ovgkZpXlJAs:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=zbWCBO4o6Hk:ovgkZpXlJAs:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=zbWCBO4o6Hk:ovgkZpXlJAs:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=zbWCBO4o6Hk:ovgkZpXlJAs:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=zbWCBO4o6Hk:ovgkZpXlJAs:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/zbWCBO4o6Hk" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/10/21/infrastructure-shards-and-optional-components.html</feedburner:origLink></entry><entry><title>Efficient Development, Deployment and Customer Feedback at Lokad</title><category term="Articles" /><category term="Integration" /><category term="Lifehacks" /><category term="Lokad" /><category term="TechOverview" /><category term="Theory" /><category term="xLim" /><id>http://abdullin.com/journal/2009/10/19/efficient-development-deployment-and-customer-feedback-at-lo.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/KjlxWpZyack/efficient-development-deployment-and-customer-feedback-at-lo.html" /><author><name>Rinat Abdullin</name></author><published>2009-10-19T07:25:27Z</published><updated>2009-10-19T07:25:27Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;A while ago I wrote about &lt;a href="http://abdullin.com/journal/2009/7/8/deployment-and-updates-of-desktop-applications-wix-clickonce.html"&gt;deployment and updates of the desktop applications&lt;/a&gt; and outlined the technology we use at &lt;a href="http://lokad.com/" target="_blank" class="offsite-link-inline"&gt;Lokad&lt;/a&gt; for rapid and efficient delivery of various updates to the customers.&lt;/p&gt;

&lt;p&gt;Let's expand on the topic a little bit more, showing how a small company could create quite a bit of business value via some efficient development practices.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;There will be a small questionnaire at the end of this article as well.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Development and Deployment Experience&lt;/h2&gt;

&lt;p&gt;Current application deployment and publication loop for &lt;a href="http://www.lokad.com/products.ashx" target="_blank" class="offsite-link-inline"&gt;Lokad Client Applications&lt;/a&gt; works like this: when developers commit new features or fixes to &lt;a href="http://abdullin.com/wiki/version-control-system-vcs.html"&gt;version control repository&lt;/a&gt; and hit a special build button on &lt;a href="http://abdullin.com/wiki/continuous-integration.html"&gt;integration server&lt;/a&gt;, following happens automatically:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;All &lt;a href="http://abdullin.com/wiki/unit-testing.html"&gt;unit tests&lt;/a&gt;, integration and code quality tests are executed against the latest codebase (build breaks if these fail).&lt;/li&gt;
&lt;li&gt;New version of install package (and optional downloads) is deployed to publicly available location.&lt;/li&gt;
&lt;li&gt;Download page is updated with the links to the new version.&lt;/li&gt;
&lt;li&gt;Existing users of an application get a nice "Update Available!" notification in the corner of their toolbar. Clicking on it launches semi-automatic download and upgrade process.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note, that we are not using ClickOnce technology here, since it has important limitations we couldn't live with. Everything took a bit of time to setup once and then it is just started flowing.&lt;/p&gt;

&lt;h2&gt;Customer Feedback Experience&lt;/h2&gt;

&lt;p&gt;Recently, in order to enhance customer experience, yet another simple feature had been added to the client applications: integrated feedback reporting. Simply put, customer could click a button and send a message to the company. It will immediately show up in the customer support system. Additionally, all unhandled exceptions (should they happen) could be reported, too.&lt;/p&gt;

&lt;p&gt;&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/10/2009-10-19_103122.png" alt="Feedback button in Lokad"/&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Feedback reports  (if customers decide to) could include following anonymous information:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;system descriptor of the software (version, OS version);&lt;/li&gt;
&lt;li&gt;versions of the assemblies loaded into the AppDomain;&lt;/li&gt;
&lt;li&gt;latest portion of application log;&lt;/li&gt;
&lt;li&gt;statistics of some performance counters showing client-side information about interactions with our servers (number of communication failures, retries, amount of data transferred);&lt;/li&gt;
&lt;li&gt;exception counter statistics (information about unique exceptions handled by the application along with their counts).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/10/2009-10-19_103222.png" alt="Feedback reporting to Lokad Support"/&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Note, that sources for the &lt;em&gt;SystemDescriptor&lt;/em&gt;, &lt;em&gt;ExecutionCounter&lt;/em&gt; and &lt;em&gt;ExceptionCounter&lt;/em&gt; are available in &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt;. Actual feedback reporting shard is shared with the community in the &lt;a href="http://code.google.com/p/lokad-sdk/" target="_blank" class="offsite-link-inline"&gt;Lokad SDK&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Feedback system had been implemented as an infrastructure shard within the shared codebase. This implied IoC-friendly &lt;a href="http://abdullin.com/wiki/component-driven-development.html"&gt;component-driven design&lt;/a&gt; and allowed to efficiently reuse all components in multiple applications (even in these that didn't have any IoC infrastructure around). All improvements and fixes to the shared components, in such scenario, automatically benefit all applications that use them.&lt;/p&gt;

&lt;p&gt;Additionally, since the feedback system is implemented as an independent infrastructure shard, it can be used to trap and report possible exceptions that take place on the application startup (even before the &lt;a href="http://abdullin.com/wiki/inversion-of-control-ioc.html"&gt;Inversion of Control&lt;/a&gt; Container is setup). Later, when the application and composite UI elements are ready, we switch stand-alone feedback handler for integrated handler (that uses, application's Viewspace and action policies, for instance)&lt;/p&gt;

&lt;p&gt;This reduced feedback friction for the customers and made issue reports a lot more useful and helpful for the development team. Since all feedback reports get routed to the internal customer support system, we could feel the change really fast and resolve problems and provide solutions more efficiently.&lt;/p&gt;

&lt;h2&gt;New Challenge - Update Flood&lt;/h2&gt;

&lt;p&gt;This kind of automatic and tight integration between development, deployment and customer support spawns new possibilities and brings forth new challenges. First of all, it definitely affects the way we think about the development and plan future changes.&lt;/p&gt;

&lt;p&gt;Second, since it is too easy to deploy an update, we've got to start thinking about protecting customers from being flooded with a number of updates (software should solve the problems, not create new ones), since theoretically we could fire the deployment update after every single verified fix that is landed in the trunk.&lt;/p&gt;

&lt;p&gt;Here's how one of the implementation scenarios looks like right now.&lt;/p&gt;

&lt;p&gt;All software updates (packaged as a complete version, as usually) could be described with a:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;version;&lt;/li&gt;
&lt;li&gt;download url;&lt;/li&gt;
&lt;li&gt;tags (Critical, RC, Test, Major etc)&lt;/li&gt;
&lt;li&gt;optional description.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Primary download page is automatically updated with the links only when "Critical" and "Major" versions are released.&lt;/p&gt;

&lt;p&gt;Customers are unformed about the Major updates to the installed software with a usual manner (i.e.: toolbar notification). Less-important updates are not shown to them explicitly but could be pulled (i.e.: from the menu), if customer needs that.&lt;/p&gt;

&lt;p&gt;This scenario should work if we are facing scenario, when there is a minor fix affecting only a single customer. We could deploy an update via the normal procedure, but it does not make a lot of sense to push updates to every single customer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation should be rather straightforward:&lt;/strong&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Instead of updating simple txt on the server per every update, we could update an XML file in the RSS/Atom format with the build version, url, description and tags.&lt;/li&gt;
&lt;li&gt;By default every application filters out all non-Primary updates, displaying the rest on the toolbar. This way we deliver important functionality to customers, while saving them from the barrage of less important builds.&lt;/li&gt;
&lt;li&gt;Customers might explicitly look into the update stream, picking and firing the specific update they need (i.e. when informed about the fix by the customer support).&lt;/li&gt;
&lt;li&gt;Beta testers and partners might update application settings to be notified about RC and Minor deployments&lt;/li&gt;
&lt;li&gt;Developers and Testers might switch their filtering settings to include Beta and Minor updates.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Potential synergy effects:&lt;/strong&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Updates could be subscribed to via a mere RSS reader and mashed with a company news (automagically).&lt;/li&gt;
&lt;li&gt;Since we are already tracking Delivery-Build labels for issues, this information could be pasted to the description dialog, providing customers and testers with more context (could be available from the application and from the web/RSS).&lt;/li&gt;
&lt;li&gt;It is possible to push the idea even further and let customers set simple filter in their application ("inform me when ticket #X is fixed"). Then, whenever the next deployment is detected, a simple regex could scan the description for the ticket number, raising friendly alert, whenever it is mentioned there.&lt;/li&gt;
&lt;li&gt;If we have a critical update at hand (i.e.: breaking API change or an important security vulnerability) we can block the entire app and insist on updating.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Everything might get even more interesting as extensible and composable application architectures (with extensions being developed and delivered concurrently) get into the picture, allowing fine-grained and yet automated customer-company interactions.&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;In this short article we've walked over some development practices adopted in Lokad. These practices help the company to resolve customer problems and provide new solutions to their business challenges.&lt;/p&gt;

&lt;p&gt;In short the outlined practices include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;efficient software deployment and updates;&lt;/li&gt;
&lt;li&gt;efficient customer support and feedback collection;&lt;/li&gt;
&lt;li&gt;considering synergy effects and automation, whenever possible and feasible.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Of course, there's a lot more in efficient development, than these few practices. I'll address them eventually. You can &lt;a href="http://feeds.abdullin.com/RinatAbdullin"&gt;subscribe to this journal&lt;/a&gt; to get all the updates. &lt;a href="http://abdullin.uservoice.com/" target="_blank" class="offsite-link-inline"&gt;Voting for the next article to be written&lt;/a&gt; is also possible.&lt;/p&gt;

&lt;p&gt;As always, all feedback to the article is welcome and appreciated. Here are also a few questions, if you are willing to share your experience with the community around this Journal:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How much time does it takes for the customer to report a problem and get an update in your development environment?&lt;/li&gt;
&lt;li&gt;Does your company share the code with the community?&lt;/li&gt;
&lt;li&gt;Are you a customer of Lokad? What do you think about this development approach? How could it be improved?&lt;/li&gt;
&lt;li&gt;Are you a competitor of Lokad? What do you think? ))&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=KjlxWpZyack:zjUsaRmeCQ0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=KjlxWpZyack:zjUsaRmeCQ0:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=KjlxWpZyack:zjUsaRmeCQ0:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=KjlxWpZyack:zjUsaRmeCQ0:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=KjlxWpZyack:zjUsaRmeCQ0:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=KjlxWpZyack:zjUsaRmeCQ0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=KjlxWpZyack:zjUsaRmeCQ0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/KjlxWpZyack" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/10/19/efficient-development-deployment-and-customer-feedback-at-lo.html</feedburner:origLink></entry><entry><title>Zen Development Practices: C# Maybe Monad</title><category term="Articles" /><category term="C#" /><category term="Lifehacks" /><category term="Lokad" /><category term="Snippets" /><category term="Theory" /><category term="Tips" /><category term="xLim" /><id>http://abdullin.com/journal/2009/10/6/zen-development-practices-c-maybe-monad.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/CLAGosCD_ok/zen-development-practices-c-maybe-monad.html" /><author><name>Rinat Abdullin</name></author><published>2009-10-05T19:25:10Z</published><updated>2009-10-05T19:25:10Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;One of the things I like about software development is a simple fact, that &lt;em&gt;efficiently developed code, block or software, takes much more time to document, than to deliver&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;This efficiency could be based on certain practices, constraints and principles, followed by discipline. These items allow to take away small bits of complexity and development friction, allowing us to concentrate on the things that really matter and generate business value.&lt;/p&gt;

&lt;p&gt;Let's talk about one of this small things - a really simple construct in C# called Maybe (of the &lt;a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)" target="_blank" class="offsite-link-inline"&gt;monad fame&lt;/a&gt;) that had completely freed me from all cases of NullReferenceException in my code, while making it cleaner.&lt;/p&gt;

&lt;p&gt;Sounds interesting? Let's have a look at the C# code and .NET usage patterns.&lt;/p&gt;

&lt;h2&gt;Introduction&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Maybe&amp;lt;T&amp;gt;&lt;/strong&gt;, as the &lt;em&gt;simplest monad implementation in .NET&lt;/em&gt;, is a &lt;strong&gt;generic class that can either hold value of type T or be empty&lt;/strong&gt;. There is a little bit of &lt;strong&gt;helper syntax&lt;/strong&gt; and some &lt;strong&gt;usage guidelines and patterns&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;In this article we'll cover all of these; links for the sources in C# and binaries would be provided, too.&lt;/p&gt;

&lt;p&gt;Here's how the declaration of the Maybe class starts in C#:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Serializable, Immutable]
public sealed class Maybe&amp;lt;T&amp;gt; : IEquatable&amp;lt;Maybe&amp;lt;T&amp;gt;&amp;gt;
{
  readonly T _value;
  readonly bool _hasValue;

  Maybe(T item, bool hasValue)
  {
    _value = item;
    _hasValue = hasValue;
  }

  /// &amp;lt;summary&amp;gt; Gets the underlying value, if it is available &amp;lt;/summary&amp;gt;
  /// &amp;lt;value&amp;gt;The value.&amp;lt;/value&amp;gt;
  public T Value
  {
    get
    {
      if (!_hasValue)
        throw Errors.InvalidOperation(
          ResultResources.Dont_access_value_when_maybe_is_empty);

      return _value;
    }
  }

  internal Maybe(T value)
    : this(value, true)
  {
    // ReSharper disable CompareNonConstrainedGenericWithNull
    if (value == null) throw new ArgumentNullException("value");
    // ReSharper restore CompareNonConstrainedGenericWithNull
  }

  /// &amp;lt;summary&amp;gt; Gets a value indicating whether this instance 
  /// has value. &amp;lt;/summary&amp;gt;
  /// &amp;lt;value&amp;gt;&amp;lt;c&amp;gt;true&amp;lt;/c&amp;gt; if this instance has value; otherwise, 
  /// &amp;lt;c&amp;gt;false&amp;lt;/c&amp;gt;.&amp;lt;/value&amp;gt;
  public bool HasValue
  {
    get { return _hasValue; }
  }

  /// &amp;lt;summary&amp;gt;
  /// Default empty instance.
  /// &amp;lt;/summary&amp;gt;
  public static readonly Maybe&amp;lt;T&amp;gt; Empty = new Maybe&amp;lt;T&amp;gt;(default(T), false);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There are a few implicit operators and helpers methods that improve the usage experience (we'll talk about them later), but the simple code above is the core of the approach. Primary monad operations could be expressed in this simple snippet:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// function that MIGHT return a number
Maybe&amp;lt;int&amp;gt; DetectNumber(string number)
{
  switch (number)
  {
    case "Zero":
      // we are allowed an implicit conversion
      // so here we return a number directly
      return 0;
    case "One":
      return 1;
    case "Two":
      return 2;
    default:
      // empty singleton for missing value
      return Maybe&amp;lt;int&amp;gt;.Empty;
  }
}


// Actually getting a Monad in C#
var number = DetectNumber("Zero");

// prints "True"
Console.WriteLine(number.HasValue);
// prints "0"
Console.WriteLine(number.Value);


var number2 = DetectNumber("Hm..");
// prints "False"
Console.WriteLine(number2.HasValue);
// throws InvalidOperationException
Console.WriteLine(number2.Value);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So basically this &lt;em&gt;Maybe&lt;/em&gt; monad is extremely simple class that can either be empty or have value. If it is empty, and we attempt to access value, then the exception is thrown. In other words, that's a strongly-typed reference to an object that acts like null with some syntactic flavor.&lt;/p&gt;

&lt;p&gt;How is it even better than using nullable references and getting &lt;em&gt;NullReferenceException&lt;/em&gt; when you forget to check for &lt;em&gt;null&lt;/em&gt;?&lt;/p&gt;

&lt;p&gt;Here are the reasons justifying the usage of &lt;em&gt;Maybe{T}&lt;/em&gt; for me:&lt;/p&gt;

&lt;h2&gt;Reason 1: Good Citizenship&lt;/h2&gt;

&lt;p&gt;By using Maybe{T} in my code I promise that all the code will be following good citizenship principles and will keep &lt;strong&gt;all&lt;/strong&gt; object references non-null (initialized to some value from the default). This promise is to be uphold by a self-discipline and unit tests.&lt;/p&gt;

&lt;p&gt;This helps to avoid all null references completely.&lt;/p&gt;

&lt;h2&gt;Reason 2: Explicit behavior and clean code&lt;/h2&gt;

&lt;p&gt;If there is a potentially nullable reference, parameter or a function return result, then it should be explicitly marked with the &lt;em&gt;Maybe{T}&lt;/em&gt;, exposing its behaviour to the reader and forcing him to explicitly handle the states.&lt;/p&gt;

&lt;p&gt;Additionally, using &lt;em&gt;Maybe{T}&lt;/em&gt; allows us to avoid throwing weird exceptions or returning nulls in situations, where result could be undefined. &lt;/p&gt;

&lt;p&gt;Consider declaration of the method like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt; Parses an encoded string into
/// authentication information. &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="encodedString"&amp;gt;Encoded string.&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;authentication information&amp;lt;/returns&amp;gt;
/// &amp;lt;exception cref="ArgumentNullException"&amp;gt;when string is null&amp;lt;/exception&amp;gt;
/// &amp;lt;exception cref="InvalidOperationException"&amp;gt;when string is invalid&amp;lt;/exception&amp;gt;
AuthInfo ParseStringToAuthInfo(string encodedString);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method declaration is really similar to a lot of existing methods from the .NET BCL (i.e.: &lt;em&gt;int.Parse&lt;/em&gt; as the simplest one) and it shares a lot of excessive noise and inherent problems. Most importantly we are throwing some exceptions, when the input is not expected and could not be handled gracefully. This:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;blows the code execution and must be handled by a separate try-catch;&lt;/li&gt;
&lt;li&gt;requires code consumer to read the documentation instead of reading the method signature;&lt;/li&gt;
&lt;li&gt;does not prevent the code from potentially breaking in every single place, should we refactor and replace &lt;em&gt;InvalidOperationException&lt;/em&gt; by &lt;em&gt;InvalidAuthDataException&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's rewrite the method signature using the &lt;em&gt;Maybe&lt;/em&gt; monad style:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt; Attempts to parse an encoded string into 
/// authentication information. &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="encodedString"&amp;gt;Encoded string.&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;authentication information&amp;lt;/returns&amp;gt;
static Maybe&amp;lt;AuthInfo&amp;gt; ParseStringToAuthInfo(string encodedString)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this refactoring we:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;decoupled ourselves from the &lt;em&gt;ArgumentNullException&lt;/em&gt;, since we believe that input will never be null. Method body would live without the appropriate null check as well;&lt;/li&gt;
&lt;li&gt;decoupled ourselves from the &lt;em&gt;InvalidOperationException&lt;/em&gt; and use optional value, that would be valid only if the parsing succeeded;&lt;/li&gt;
&lt;li&gt;no longer require the developer using the method to look in the code documentation in order to understand what exactly the method works;&lt;/li&gt;
&lt;li&gt;do not need defensive and noisy try-catch programming around the calls to this method (or anywhere in the call stack).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Of course, there are other refactoring alternatives to the signature:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Option1 : use bool
static bool TryParseString(string encodedString, out AuthInfo);   
// Option 2: return value that could be null
static AuthInfo ParseString(string encodedString);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;First option&lt;/em&gt; uses the TryGetValue approach you can see on the IDictionary interface. This approach resorts to the &lt;em&gt;out&lt;/em&gt; keyword (which I always avoid), breaks the functional style of the programming (method should always have a single value being returned) and adds some noise to the using code.&lt;/p&gt;

&lt;p&gt;Also &lt;em&gt;AuthInfo&lt;/em&gt; is returned as undefined, if the parsing fails, violating the good citizenship.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Second option&lt;/em&gt; returns value that would be &lt;em&gt;null&lt;/em&gt; in case the parsing fails. Developer, in order to discover this, has to read the documentation. And he has to protect himself from the possible problems with null checks against the result.&lt;/p&gt;

&lt;p&gt;In my opinion, method using the &lt;em&gt;Maybe&lt;/em&gt; monad is the most clean approach of them all. &lt;/p&gt;

&lt;h2&gt;Reason 3: Chaining and pipeline syntax&lt;/h2&gt;

&lt;p&gt;Ok, so we have our Maybe-powered method signature:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static Maybe&amp;lt;AuthInfo&amp;gt; ParseStringToAuthInfo(string encodedString);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let's actually see the full power of the concept in C# on a sample taken fresh from the production code. Consider the method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// simple pipeline sequence
Maybe&amp;lt;AuthPrincipal&amp;gt; LoadPrincipal(string key)
{
  return ParseStringToAuthInfo(key)
    .Combine(u =&amp;gt; _service.BuildAccountSession(u))
    .Convert(sa =&amp;gt; new AuthPrincipal(sa));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this LINQ-style and purely functional sequence of 3 lines, we:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Attempt to parse the key into &lt;em&gt;AuthInfo&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;If the attempt was successful, we use some service to try to build an account session out of the parsed &lt;em&gt;AuthInfo&lt;/em&gt;. &lt;em&gt;BuildAccountSession&lt;/em&gt; operation might also fail, by the way. This is indicated in the method signature (by using Maybe) and would happen if the provided &lt;em&gt;AuthInfo&lt;/em&gt; didn't have a match in the repository.&lt;/li&gt;
&lt;li&gt;If we were successful in parsing the original string and in building the account session, then we create a new &lt;em&gt;AuthPrincipal&lt;/em&gt; class using this session; otherwise an empty Maybe{AuthPrincipal} is returned to indicate the composite failure.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;As you can see, detailed method description takes a bit more space, than the actual implementation. And the implementation itself is less fragile and smaller compared to traditional approach with nulls, throwing and handling various exceptions.&lt;/p&gt;

&lt;p&gt;After getting used to this benefit of Maybe, dealing with the code that has exceptions and nulls feels like working in Visual Studio without ReSharper installed. &lt;/p&gt;

&lt;p&gt;All the benefits listed above come from two classes (that contain less code, than this article) and some discipline. That's the way of &lt;a href="http://en.wikipedia.org/wiki/Zen" target="_blank" class="offsite-link-inline"&gt;Zen&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/07/2009-07-31-development-zen.jpg" alt="Zen image under Creative Commons Attribution ShareAlike 3.0 License from Wikipedia" /&gt;&lt;/p&gt;

&lt;p&gt;If you want to try &lt;em&gt;Maybe{T}&lt;/em&gt;, the code is available in &lt;em&gt;Lokad.Shared.dll&lt;/em&gt; from the &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt;. You can either copy this class to your solution (while &lt;a href="http://feeds.abdullin.com/Shared-Libraries"&gt;keeping an eye on the project&lt;/a&gt; for any improvements and changes in the guidelines) or grab the latest download.&lt;/p&gt;

&lt;p&gt;Let's continue our article by outlining common operations available for Maybe{T}.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating Maybe&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// implicit conversion is the most common way to create Maybe&amp;lt;T&amp;gt;
// mostly it happens when we return actual value from within a
// method that returns maybe.
// Or, when we pass value into the optional function parameter
Maybe&amp;lt;int&amp;gt; maybeInt = 10;

// creates a maybe object when implicit casting is not available 
// for some reason (i.e.: anonymous types or failing type inferrence)
var nonEmptyMaybe = Maybe.From(value);

// each type has only a single empty maybe instance that is
// cached via the type-caching
var emptyAuthInfo = Maybe&amp;lt;AuthInfo&amp;gt;.Empty;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Getting Value&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// tests if the Maybe has value
var hasValue = maybeInt.HasValue;

// returns value behind the Maybe, throwing exception if it is empty
// this approach is rarely used (because of the pipeline operators)
var value = maybeInt.Value

// get's value from maybe, using some default, if it is empty
var value = maybeUsername.GetValue("guest@abdullin.com");

// get's value from maybe, executing default generation if it is empty
// handy for scenarios, when generating default values is CPU expensive
var value = maybeUsername.GetValue(() =&amp;gt; ComposeName());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Pipeline Operations&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// get Maybe that either has value derived from the parent Maybe
// or is empty, if the parent is empty
var maybeUsername = maybeIdentity.Convert(i =&amp;gt; i.Username);

// gets actual value that is derived from the parent Maybe, if it is not
// empty, or uses a predefined default 
// equivalent of Convert.GetValue
var username = maybeIdentity.Convert(i =&amp;gt; i.Username,"guest@abdullin.com");
var username = maybeIdentity.Convert(i =&amp;gt; i.Username,() =&amp;gt; ComposeName());

// combines result of the two Maybe's, either of which could be empty
var maybeFullName = maybeUsername.Combine(k =&amp;gt; LookupFullName(k));

// executes the action against the value, if Maybe is not empty,
// returns the original Maybe to continue pipelining 
maybeFullName.Apply(fn =&amp;gt; Console.WriteLine(fn))

// executes the action, if maybe is Empty
// returns the original Maybe to continue pipelining
maybeFullName.Handle(() =&amp;gt; Application.Terminate());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In addition to the operators above, &lt;em&gt;Maybe{T}&lt;/em&gt; class also defines proper equality and hashing operations. It is debugger-friendly, too.&lt;/p&gt;

&lt;p&gt;However, this does not end the list of reasons of using Maybe for the efficient development.&lt;/p&gt;

&lt;h2&gt;Reason 4: Simplified unit testing&lt;/h2&gt;

&lt;p&gt;Using &lt;em&gt;Maybe&lt;/em&gt; monad in .NET also has the benefit of allowing to introduce simplified DSL syntax for &lt;a href="http://abdullin.com/wiki/unit-testing.html"&gt;unit-testing&lt;/a&gt; code leveraging the approach. &lt;/p&gt;

&lt;p&gt;Here are the core extensions you need (they are pipelined together for the brevity)&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// extensions checking different aspects of valid Maybe&amp;lt;T&amp;gt; monad
maybeValue
  .ShouldPass()
  .ShouldPassCheck(i =&amp;gt; i == 10)
  .ShouldPassWith(10)
  .ShouldBe(10)
  .ShouldBe(true);

// checking empty Maybe Moned
MaybeNot
  .ShouldFail()
  .ShouldBe(false);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each extension, basically throws a descriptive assertion exception, if the condition is not met.&lt;/p&gt;

&lt;p&gt;Here's how the unit test might look like with one of these extensions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Test]
public void System_info_is_disabled()
{
  WhenViewIsShown.SetResult(DialogResult.OK);
  Subject.BindModel(RandClientModels.NextFeedbackView());
  Implementation.CheckSystemInfo(false);
  Subject
    .GetModel()
    .ShouldPassCheck(m =&amp;gt; m.SystemInformation == "");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the check fails, because the maybe has a value but this value is invalid, then the failure would look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FailedAssertException: Expression should be true: '(m.SystemInformation = "")'.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These test extensions are located within &lt;em&gt;Lokad.Testing.dll&lt;/em&gt;, which is also a part of &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt; within a &lt;em&gt;Lokad.Testing&lt;/em&gt; namespace.&lt;/p&gt;

&lt;p&gt;This separation is done in order to prevent &lt;em&gt;IntelliSense&lt;/em&gt; from being polluted with all the &lt;em&gt;Should&lt;/em&gt; statements, while we are working in the production code. Testing code, on the contrary can have access to these routines (which is done by referencing the testing assembly and using the namespace).&lt;/p&gt;

&lt;h2&gt;Reason 5: Initialization of Immutable classes&lt;/h2&gt;

&lt;p&gt;All we know that in F# it is extremely easy to create an immutable object from another record by providing a few override values in the cloning process:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let conn2 = { conn1 with Service = MyService }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we are using only C#-style immutable classes as models in our application (which is beneficial for a number of reasons, but is a large topic on its own), then we are limited to the constructor initialization only, which could be rather messy:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// model definition
[Immutable, Serializable]
public sealed class ServiceConnection
{
  public readonly string Username;
  public readonly string Password;
  public readonly string AuthMode;
  public readonly Uri Service;

  public ServiceConnection(string username, string password, 
    string authMode, Uri service)
  {
    Username = username;
    Password = password;
    AuthMode = authMode;
    Service = service;
  }
}

// cloning with a custom service reference
var conn2 = new ServiceConnection(conn1.Username, conn2.Password, 
  conn2.AuthMode, MyService);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;More fields the model has, more messy cloning the process becomes. Fortunately, in the upcoming C# 4.0 we will be able to do everything more efficiently and with different combinations:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var conn2 = conn1.With(service: MyService);
var conn3 = conn1.With(username: Anonymous, AuthType: Plain);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This could be achieved with a single method by using C# 4.0 Optional Parameters and &lt;em&gt;Maybe{T}&lt;/em&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  public ServiceConnection With(
    string username = Maybe.String,
    string password = Maybe.String,
    string authType = Maybe.String,
    Uri service = Maybe.Uri)
  {
    return new ServiceConnection(
      username.GetValue(Username), 
      password.GetValue(Password),
      authType.GetValue(AuthType),
      service.GetValue(Service);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;where &lt;em&gt;Maybe.String&lt;/em&gt; (and its &lt;em&gt;Uri&lt;/em&gt; analogue) is just a short-cut for Maybe{string}.Empty that is already declared on the &lt;em&gt;Maybe&lt;/em&gt; non-generic helper class in &lt;em&gt;Lokad.Shared.dll&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;Caveats&lt;/h2&gt;

&lt;p&gt;This approach, as any other piece of knowledge from the &lt;a href="http://abdullin.com/xlim/"&gt;xLim body of knowledge&lt;/a&gt;, might be controversial and not applicable for you projects, development practices and beliefs.&lt;/p&gt;

&lt;p&gt;All that I can say - it works for me, allowing &lt;em&gt;slightly more efficient&lt;/em&gt; delivery, evolution and maintenance of .NET development projects ranging from business analytics servers, RESTful NoSql automation engines and up to Smart Client applications with reusable MVC infrastructure shards.&lt;/p&gt;

&lt;p&gt;This limited improvement in development efficiency sometimes requires using approaches and principles that may be somewhat incompatible with the traditional ones (MS .NET or Alt.NET), while continuously enforcing them across the codebases. But in the end, I think, it's worth it, just like &lt;a href="http://abdullin.com/wiki/continuous-integration.html"&gt;Continuous Integration&lt;/a&gt; or &lt;a href="http://abdullin.com/wiki/inversion-of-control-ioc.html"&gt;Inversion of Control&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;But again, that's the way of Zen - everybody has his own way to satori.&lt;/p&gt;

&lt;h2&gt;Questions and Answers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; &lt;em&gt;Why add another needless layer of complexity for such a simple task? Just learn how to use the null coalescing operator (??) and/or inline if-thens.&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Console.WriteLine(number != null ? "True" : "False");
Console.WriteLine(number ?? "Null Value");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Imagine a large real-world project that spawns multiple components and tiers, while facing problems slightly more challenging, than writing output to the console. If developers know that this project uses Maybe to declare potentially empty variables, then they are completely freed from checking for nulls and even thinking about that. That's one less thing to bother, making quite a difference in complex scenarios (and &lt;a href="http://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two" target="_blank" class="offsite-link-inline"&gt;human being can simultaneously bother only about 7 things max&lt;/a&gt;, anyway).&lt;/p&gt;

&lt;p&gt;This actual usage of &lt;em&gt;Maybe{T}&lt;/em&gt; might happen in just one or two methods of the project. However, when developers use them, they will know immediately (and not from the documentation) and will be forced to handle them because of the syntax.&lt;/p&gt;

&lt;p&gt;Things like that reduce development friction and allow complex project to be delivered efficiently and with really small teams.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; &lt;em&gt;How is this different from Nullable{T} in C#?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Only value types are supported by Nullable generic (or its shorthand syntax). So you can't use a class variable in a nullable type (which makes sense, since the reference itself can be &lt;em&gt;null&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; &lt;em&gt;Why do Lokad Shared Libraries feature null checks, although Maybe{T} is declared in the code?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Because &lt;em&gt;Lokad.Shared.dll&lt;/em&gt;, as a really lightweight library, might be used in various projects. Some of these projects might not have "no nulls returned and expected" policy. So it is logical to protect shared methods from the nulls explicitly. in order to avoid the unpredictable behavior.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; &lt;em&gt;How do I use Maybe{T} if method can fail because of the multiple reasons and I want to know them&lt;/em&gt;?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Maybe{T}&lt;/em&gt; on its own is not designed to handle such situations. These are the primary logically-complete solutions for this situation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You can return &lt;em&gt;Maybe{T}&lt;/em&gt; while printing multiple failure details to the &lt;em&gt;IScope&lt;/em&gt; passed as an argument. That's how &lt;a href="http://abdullin.com/journal/2008/11/23/net-application-block-for-validation-and-business-rules.html"&gt;Lokad Rules&lt;/a&gt; are working. It also works well in long-running complex (especially asynchronous) operations that require logging and detailed failure control.&lt;/li&gt;
&lt;li&gt;You can use &lt;em&gt;Result{TValue,TError}&lt;/em&gt; monad returning strongly-typed error result (i.e.: enumeration value) or it's generic counterpart Result{TValue} (if the strong-typing is not possible for some reason).&lt;/li&gt;
&lt;li&gt;You can always use good old exceptions, if the above options do not suite you for some reason and you are OK with try-cath and breaking the functional code flow.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; &lt;em&gt;Does Maybe work with validation rules?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Yes, &lt;em&gt;Maybe{T}&lt;/em&gt; works with &lt;a href="http://abdullin.com/journal/2008/11/23/net-application-block-for-validation-and-business-rules.html"&gt;Lokad validation and business rules&lt;/a&gt;. You can also use &lt;em&gt;MaybeIs&lt;/em&gt; helper class to compose strongly-typed rules on top of the &lt;em&gt;Maybe{T}&lt;/em&gt; monad. &lt;em&gt;MaybeIs&lt;/em&gt; has two static methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;MaybeIs.EmptyOr{T}(params Rule{T}[] rules)&lt;/em&gt; - composes validation rule that succeeds only if the &lt;em&gt;Maybe{T}&lt;/em&gt; is empty &lt;strong&gt;or&lt;/strong&gt; the underlying value passes additional rules.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;MaybeIs.ValidAnd{T}(params Rule{T}[] rules)&lt;/em&gt; - composes validation rule that succeeds if the &lt;em&gt;Maybe{T}&lt;/em&gt; is not empty &lt;strong&gt;and&lt;/strong&gt; the underlying value passes additional rules.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sample usage in composing more complex rule:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void ModelIsValid(FeedbackModel model, IScope scope)
{
  scope.Validate(() =&amp;gt; model.Sender, 
    MaybeIs.EmptyOr&amp;lt;string&amp;gt;(StringIs.ValidEmail));

  scope.Validate(() =&amp;gt; model.Model, ModelIsValid);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; &lt;em&gt;So essentially you are replacing "optional != null" with "optional.HasValue"&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Not exactly. HasValue is rarely checked against directly. Take a look at the piece of authentication code below. There are two possibly failing functions in it, that return &lt;em&gt;Maybe{T}&lt;/em&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Maybe&amp;lt;AuthPrincipal&amp;gt; LoadPrincipal(string key)
{
  return ParseStringToAuthInfo(key)
    .Combine(u =&amp;gt; _service.BuildAccountSession(u))
    .Convert(sa =&amp;gt; new AuthPrincipal(sa));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Signatures are like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static Maybe&amp;lt;AuthInfo&amp;gt; ParseStringToAuthInfo(string encodedString);
Maybe&amp;lt;AccountSession&amp;gt; BuildAccountSession(AuthInfo authInformation);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;HasValue&lt;/em&gt; and &lt;em&gt;Value&lt;/em&gt; aren't mentioned in this code. That's how it usually works.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question:&lt;/strong&gt; &lt;em&gt;What about operator overloading:&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static implicit operator T(Maybe&amp;lt;T&amp;gt; mayBe)
{
  return mayBe.Value; //or mayBe._value;
}

public static implicit operator bool(Maybe&amp;lt;T&amp;gt; mayBe)
{
  return mayBe.HasValue;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This kind of implicit conversion from Maybe directly to value/state is not advised for two reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It looses the intent of using &lt;em&gt;Maybe{T}&lt;/em&gt; to force explicit handling of nullable situations.&lt;/li&gt;
&lt;li&gt;Implicit conversion from Maybe to value is logically incorrect as it might return &lt;em&gt;default(T)&lt;/em&gt; value or result in exception (depending on implementation).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Basically such an implicit operation would feel somewhat similar to the old C++ joke from bash.org:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#define TRUE false
#define FALSE true
// and good luck with debugging))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Side note: Implicit conversion from value to &lt;em&gt;Maybe{T}&lt;/em&gt; or from error/value to &lt;em&gt;Result{TValue,TError}&lt;/em&gt;, as opposed to the case above, does not violate this logic. This is because we are not forcing collapse of possibility of multiple states into one known state (while have side effects if the state is not what we expect).&lt;/p&gt;

&lt;p&gt;This is why conversion from value to maybe is implicit, while the opposite has to be done either via the Value property or via the explicit conversion.&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;Let's wrap the things up.&lt;/p&gt;

&lt;p&gt;In this article we've talked about &lt;em&gt;Maybe{T}&lt;/em&gt; generic class that, as a simple monad concept, allows in .NET to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;promote &lt;strong&gt;Good citizenship&lt;/strong&gt; in the code avoiding nulls and exceptions;&lt;/li&gt;
&lt;li&gt;write &lt;strong&gt;clean code with explicit behavior&lt;/strong&gt;;&lt;/li&gt;
&lt;li&gt;use expressive LINQ-style syntax with &lt;strong&gt;chaining and pipeline operators&lt;/strong&gt;;&lt;/li&gt;
&lt;li&gt;benefit from the &lt;strong&gt;simplified unit testing&lt;/strong&gt; syntax;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;initialize immutable classes efficiently in C# 4.0&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;C# source files and compiled binaries featuring &lt;em&gt;Maybe&lt;/em&gt; monad and testing extensions could be downloaded from the &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt; Open Source project.&lt;/p&gt;

&lt;p&gt;It is important to note, that the current design of &lt;em&gt;Maybe{T}&lt;/em&gt; and development practices around it are based on the ongoing R&amp;amp;D process and production usage cases. As such, they might gradually evolve and improve further (this being reflected in Lokad Shared Libraries). &lt;/p&gt;

&lt;p&gt;This article is also considered to be an essential part of &lt;a href="http://abdullin.com/xlim/"&gt;xLim 3 development body of knowledge&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you are interested in more articles on Zen Development practices, you can stay tuned by &lt;a href="http://feeds.abdullin.com/RinatAbdullin"&gt;subscribing to this blog via RSS&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Next article I'm considering for these series is about &lt;em&gt;Result&lt;/em&gt; variations of the monads in C#, that allow handling more complex failure scenarios, than a simple Maybe (BTW, the previous Zen article was about &lt;a href="http://abdullin.com/journal/2009/7/31/zen-development-practices-method-level-ioc.html"&gt;Method-level IoC&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;All comments, thoughts and any other feedback are welcome and appreciated.&lt;/em&gt;&lt;/p&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=CLAGosCD_ok:xYm3dR0Yung:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=CLAGosCD_ok:xYm3dR0Yung:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=CLAGosCD_ok:xYm3dR0Yung:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=CLAGosCD_ok:xYm3dR0Yung:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=CLAGosCD_ok:xYm3dR0Yung:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=CLAGosCD_ok:xYm3dR0Yung:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=CLAGosCD_ok:xYm3dR0Yung:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/CLAGosCD_ok" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/10/6/zen-development-practices-c-maybe-monad.html</feedburner:origLink></entry><entry><title>Zen Development Practices: Method-level IoC</title><category term="Articles" /><category term="C#" /><category term="DSL" /><category term="How To" /><category term="IoC" /><category term="Lifehacks" /><category term="Lokad" /><category term="Snippets" /><category term="Theory" /><category term="Tips" /><category term="autofac" /><id>http://abdullin.com/journal/2009/7/31/zen-development-practices-method-level-ioc.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/9w-ThJkJGvw/zen-development-practices-method-level-ioc.html" /><author><name>Rinat Abdullin</name></author><published>2009-07-31T08:58:12Z</published><updated>2009-07-31T08:58:12Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;One of the things I really like about the software development is a simple fact that &lt;em&gt;having the right idea, tool or even just a proper state of mind could help you to avoid writing a lot of unnecessary code&lt;/em&gt;. As we all know, unnecessary code results in extra development friction and increased maintenance burden which come down to a higher TOC. This could scale from a few methods and up to the classes,  micro-frameworks and even sub-systems.&lt;/p&gt;

&lt;p&gt;All that matters in the end, is about the delivery of the unique business value within the budget, quality and time constraints.&lt;/p&gt;

&lt;p&gt;In this article I'll try to give you a brief overview overview of a few concepts (and a synergy between them) that have worked for me like this before. Most interesting of them I would refer to as a &lt;em&gt;Method-level Inversion of Control&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Let's have a closer look at a really short extension method that simplifies &lt;a href="http://abdullin.com/autofac/"&gt;Autofac&lt;/a&gt; usage for me in some specific scenarios:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Build(
  [NotNull] this IContainer container,
  [NotNull] Action&amp;lt;ContainerBuilder&amp;gt; registration)
{
  if (container == null) throw new ArgumentNullException("container");
  if (registration == null) throw new ArgumentNullException("registration");

  var builder = new ContainerBuilder();
  registration(builder);
  builder.Build(container);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, there are just a few lines of code here. Yet the amount of ideas and concepts related to them is slightly more diverse. Let's start walking over them.&lt;/p&gt;

&lt;p&gt;Basically this extension simplifies some in-line registrations for the existing container. You might need them from time to time, when defining some environment-based registrations, &lt;a href="http://abdullin.com/journal/2009/6/25/testing-mvc-elements-and-interactions-with-mock-container.html"&gt;using MockContainer&lt;/a&gt; for &lt;a href="http://abdullin.com/wiki/unit-testing.html"&gt;unit testing&lt;/a&gt; or simply starting a new prototype project. &lt;/p&gt;

&lt;p&gt;Here's how the code looks with and without this extension method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// old style registration
var builder = new ContainerBuilder();
builder.Register&amp;lt;MyComponent&amp;gt;().As&amp;lt;IMyService&amp;gt;();
builder.Build(container);

// Equivalent registration with the extension method
container.Build(b =&amp;gt; b.Register&amp;lt;MyComponent&amp;gt;().As&amp;lt;IMyService&amp;gt;());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Obviously, you could have multiple registrations and anything else that could be done with a &lt;em&gt;ContainerBuilder&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;By the way, this simple extension method is currently in the &lt;em&gt;Lokad.Stack.dll&lt;/em&gt;. If anybody actually wants to see it in &lt;em&gt;Autofac.dll&lt;/em&gt;, just drop a comment and I'll push it up to the Autofac codebase.&lt;/p&gt;

&lt;p&gt;The statement above might seem to be an overkill for "just a mere extension method", yet it highlights (once more) an extremely important rule of thumb that has helped me to develop and keep stable a few shared libraries so far. Here it is:&lt;/p&gt;

&lt;p&gt;You should never put some helper class or method into the shared codebase, just because it &lt;em&gt;looks&lt;/em&gt; cool or useful. It should stay in the original solution where it is used until &lt;strong&gt;two or more&lt;/strong&gt; external solutions show distinct need to reuse it and it is obvious that this code could be reused efficiently (&lt;em&gt;sometimes it is better not to reuse&lt;/em&gt;). Only then, we'll move that reusable code upstream (into the common shared project), while making sure that it fits perfectly all the use-cases.&lt;/p&gt;

&lt;p&gt;By the way, it is a good practice to have an automated &lt;a href="http://abdullin.com/wiki/continuous-integration.html"&gt;continuous integration&lt;/a&gt; project (or a couple of them) that regularly pulls together all the different solutions used in some projects (this includes 3rd party libraries available as open source), compiles them all and then runs tests. This kind of validation helps to detect possible dormant issues (i.e.: breaking API changes) as soon as possible, simplifying their resolution.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;What are these NotNull attributes?&lt;/em&gt; These are simple code hints for the ReSharper that are declared in Lokad.Quality.dll. They indicate that the method does not expect null values and explicitly enforces this principle of good citizenship by throwing ArgumentNullException. ReSharper will keep this in mind, while performing solution-wide analysis and highlighting warnings and suggestions (I think that's a decent benefit for just a few short attributes). &lt;/p&gt;

&lt;p&gt;Let's get back to the idea behind that extension method for Autofac IoC Container. You could consider it to be an example of method-level &lt;a href="http://abdullin.com/wiki/inversion-of-control-ioc.html"&gt;Inversion of Control&lt;/a&gt;. This pattern is really useful, when we want to capture or perform some operations against the underlying object, while enforcing some context and keeping the complex logic - clear of some implementation details.&lt;/p&gt;

&lt;p&gt;In the case of the Autofac builder extension we were capturing the component registrations, while enforcing their binding to the current &lt;em&gt;IContainer&lt;/em&gt; in the end (that's yet another solution to the &lt;em&gt;builder syntax&lt;/em&gt; problem, by the way).&lt;/p&gt;

&lt;p&gt;Here is another usage of this pattern, coming from a different domain - my &lt;a href="http://abdullin.com/journal/2009/7/24/couchdb-in-the-cloud-persisting-from-net-code.html"&gt;sandbox prototype for working with CouchDB&lt;/a&gt;. Check out the snippet bellow, paying attention to the lambda expressions with the &lt;em&gt;stream&lt;/em&gt; parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public DocumentInfo SaveDocument&amp;lt;T&amp;gt;(T item, Func&amp;lt;T, Guid&amp;gt; id)
{
  using (var r = _server.Do(id(item).ToString(), "PUT",
    stream =&amp;gt; Serializer.Serialize(stream, item)))
  {
    FailsUnless(r, CouchStatus.Code201);

    return r.ReadObject(stream =&amp;gt;
      Serializer.Deserialize&amp;lt;DocumentInfo&amp;gt;(stream));
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This snippet simply implements a wrapper for the RESTful &lt;a href="http://wiki.apache.org/couchdb/HTTP_Document_API" target="_blank" class="offsite-link-inline"&gt;document management API&lt;/a&gt; of CouchDB. &lt;/p&gt;

&lt;p&gt;As you can see, there are two places, where we need to access request and response streams. Yet, there is no explicit stream management and disposal. That's because we've implemented this logic already in the code that is actually responsible for that. This results in more compact and reliable code that frees the developer from remembering about stream management and other technical details that are not important at this layer. We also know that all the required extensibility points are already considered and enforced in the design (see &lt;a href="http://abdullin.com/journal/2009/7/24/couchdb-in-the-cloud-persisting-from-net-code.html"&gt;previous CouchDB article for details&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;span class="full-image ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/07/2009-07-31-development-zen.jpg" alt="Zen image under Creative Commons Attribution ShareAlike 3.0 License from Wikipedia"/&gt;&lt;/span&gt;&lt;/span&gt; &lt;/p&gt;

&lt;p&gt;Given that, implementing some sort of wrapper for a specific RESTful API becomes more peaceful and enjoyable experience. That's the way of &lt;a href="http://en.wikipedia.org/wiki/Zen" target="_blank" class="offsite-link-inline"&gt;Zen&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As you can guess, this pattern could be applied to other resource-management scenarios or situations as well.&lt;/p&gt;

&lt;p&gt;Another usage scenario of this pattern involved developing scheduling logic for a piece of concurrent data processing engine. We wanted to write and run complex queries against the complex domain model which was updated by a few asynchronous processes. Sometimes we even wanted to modify this model from within the query. Another obvious requirement was: query code (already complex) had to be atomic and without any code for managing transactions. All this resulted in a simple interfaces like the ones below (I'm extremely oversimplifying the domain, while keeping the primary idea):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;interface IQueryableDomainModel
{
  void RunQuery(Action&amp;lt;IQueryTarget&amp;gt; query);
}

interface IQueryTarget
{
  int NumberOfTasks { get; }
  int ScheduleSize { get; }
  Task[] GetTasks(int count);
  void EnqueueTasks(IEnumerable&amp;lt;Task&amp;gt; tasks);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;while the query was able to be declared in a manner:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static class SchedulingQueries
{
  void OptimisticScheduling(IQueryTarget target)
  {
    var tasks = target.GetTasks(target.NumberOfTasks);
    if (tasks.Length &amp;gt; 0)
    {
      target.EnqueueTasks(tasks);
    }
  }

  void SchedulingApproach2(IQueryTarget target)
  {
     if (target.ScheduleSize &amp;lt; 10)
     {
       OptimisticScheduling(target);
       return;
     }
     HistoricalScheduling(target); 
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to execute the query you just had to use the code like the one below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IQueryableDomainModel model = ...
model.RunQuery(OptimisticScheduling.SchedulingApproach2);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;IQueryableDomainModel model implementation takes the responsibility of ensuring concurrency by calling locks before executing the captured lambda argument and then releasing them after (similar to how we created &lt;em&gt;ContainerBuilder&lt;/em&gt; before running lambda against it and then applied it to the container after). &lt;/p&gt;

&lt;p&gt;If we were in need for some serious performance optimization, we could even start by inspecting the captured query statement and using fine-tuned locking scenarios (without even changing a single line in the original query).&lt;/p&gt;

&lt;p&gt;You may have already noticed that method-level IoC basically allows to create micro DSL in C#. That's precisely how this pattern has worked out in &lt;a href="http://abdullin.com/journal/2008/11/23/net-application-block-for-validation-and-business-rules.html"&gt;Lokad.Rules&lt;/a&gt; (yet another sample of the pattern), where each business rule is some compact code running against the &lt;em&gt;IScope&lt;/em&gt; interface. Core logic is encapsulated in the rules, but it is the &lt;em&gt;IScope&lt;/em&gt; (and the implementatios) that is to control the context and determine what to do with the rules.&lt;/p&gt;

&lt;p&gt;This results in rules that could be expressed and combined in a code like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// User name should have length within 6 and 256 characters 
/// and should be a valid email.
/// &amp;lt;/summary&amp;gt;
internal static readonly Rule&amp;lt;string&amp;gt;[] UserName = new[]
  {
    StringIs.Limited(6, 256),
    StringIs.ValidEmail
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can check out &lt;a href="http://abdullin.com/journal/2008/11/23/net-application-block-for-validation-and-business-rules.html"&gt;Lokad.Rules&lt;/a&gt; for more details, if interested. One thing worth of mentioning (if you decide to dive into the source code) is that the entire framework for business rules and validation is really small. We do not have anything classes like &lt;em&gt;IntGreaterThanValidator&lt;/em&gt; or &lt;em&gt;CompositeValidator&lt;/em&gt; simply because they are not really needed for this scenario.&lt;/p&gt;

&lt;p&gt;Well, this turned out to be quite some text about an extremely simple extension method. Yet, hopefully, the journal post hints that &lt;em&gt;software development is not about coding or size of the codebase&lt;/em&gt;. It is about the &lt;em&gt;ideas and concepts that help to leverage the technology in order to achieve some business goals&lt;/em&gt;. If used efficiently, they can result in a small codebase. There could even be no code at all (but that's a pure Zen).&lt;/p&gt;

&lt;p&gt;I know a few other interesting development concepts that are not so popular for some reason and yet helped a lot in complex projects by reducing the codebase, while making everything more simple and flexible. Eventually they might crystallize into more articles (like this one) with patterns, practices and theory. Although this is not going to happen any time soon, you might &lt;a href="http://feeds.abdullin.com/RinatAbdullin"&gt;subscribe to this journal to get the updates&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Meanwhile, I'd love to hear your thoughts and feedback on this article.&lt;/p&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=9w-ThJkJGvw:nkCU1jpy0L4:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=9w-ThJkJGvw:nkCU1jpy0L4:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=9w-ThJkJGvw:nkCU1jpy0L4:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=9w-ThJkJGvw:nkCU1jpy0L4:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=9w-ThJkJGvw:nkCU1jpy0L4:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=9w-ThJkJGvw:nkCU1jpy0L4:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=9w-ThJkJGvw:nkCU1jpy0L4:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/9w-ThJkJGvw" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/7/31/zen-development-practices-method-level-ioc.html</feedburner:origLink></entry><entry><title>Lokad Shared Libraries 1.5 and Autofac for Silverlight 3.0</title><category term="Lokad" /><category term="autofac" /><id>http://abdullin.com/journal/2009/7/17/lokad-shared-libraries-15-and-autofac-for-silverlight-30.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/axMoDTKbzrw/lokad-shared-libraries-15-and-autofac-for-silverlight-30.html" /><author><name>Rinat Abdullin</name></author><published>2009-07-17T13:16:58Z</published><updated>2009-07-17T13:16:58Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;Just a few announcements.&lt;/p&gt;

&lt;h1&gt;Lokad Shared Libraries 1.5 Release&lt;/h1&gt;

&lt;p&gt;&lt;br /&gt;
&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/07/favicon-64.png" alt="Lokad Shared Libraries"/&gt;&lt;/span&gt;&lt;/span&gt;
There have not been any major changes since the last official release. Some highlights include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Various tweaks and fixes coming from projects actively using Lokad Shared in production&lt;/li&gt;
&lt;li&gt;MockContainer implementation to simplify testing in &lt;a href="http://abdullin.com/wiki/component-driven-development.html"&gt;component-driven development&lt;/a&gt; scenarios such as MVC (described &lt;a href="http://abdullin.com/journal/2009/4/11/testing-mvc-controllers-with-mock-container.html"&gt;here&lt;/a&gt; and &lt;a href="http://abdullin.com/journal/2009/6/25/testing-mvc-elements-and-interactions-with-mock-container.html"&gt;here&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;WaitFor construct for executing fragile code with timeout options.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="http://code.google.com/p/lokad-shared-libraries/downloads/list" target="_blank" class="offsite-link-inline"&gt;Download options&lt;/a&gt; include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Merged libraries&lt;/strong&gt; as they are used in projects of &lt;a href="http://www.lokad.com/" target="_blank" class="offsite-link-inline"&gt;Lokad.com&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Separate assemblies for people that want to use only some bits.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;Autofac 1.4 for Silverlight 3.0&lt;/h1&gt;

&lt;p&gt;&lt;br /&gt;
&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/07/autofac-logo.png" alt="Autofac IoC COntainer for .NET"/&gt;&lt;/span&gt;&lt;/span&gt;
&lt;a href="http://abdullin.com/autofac/"&gt;Autofac IoC Container for .NET&lt;/a&gt; is now checked for compatibility with Silverlight 3.0 in a &lt;a href="http://abdullin.com/wiki/continuous-integration.html"&gt;continuous integration&lt;/a&gt; manner. Version 1.4 compiled for Silverlight 3.0 runtime is available within the &lt;a href="http://code.google.com/p/autofac/downloads/list" target="_blank" class="offsite-link-inline"&gt;download page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;People interested in checking out how the same code-base could be used to target various .NET runtime versions are welcome to check out the latest source code for the container.&lt;/p&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=axMoDTKbzrw:j6uUX_LCNGE:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=axMoDTKbzrw:j6uUX_LCNGE:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=axMoDTKbzrw:j6uUX_LCNGE:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=axMoDTKbzrw:j6uUX_LCNGE:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=axMoDTKbzrw:j6uUX_LCNGE:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=axMoDTKbzrw:j6uUX_LCNGE:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=axMoDTKbzrw:j6uUX_LCNGE:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/axMoDTKbzrw" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/7/17/lokad-shared-libraries-15-and-autofac-for-silverlight-30.html</feedburner:origLink></entry><entry><title>Testing MVC Elements and Interactions with Mock Container</title><category term="C#" /><category term="IoC" /><category term="Lokad" /><category term="Snippets" /><category term="autofac" /><category term="tdd" /><id>http://abdullin.com/journal/2009/6/25/testing-mvc-elements-and-interactions-with-mock-container.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/s-hQzanEuzU/testing-mvc-elements-and-interactions-with-mock-container.html" /><author><name>Rinat Abdullin</name></author><published>2009-06-24T21:38:38Z</published><updated>2009-06-24T21:38:38Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;&lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries project&lt;/a&gt; includes implementation of the MockContainer that significantly simplifies testing of Model-View-Controller elements in separation. It does this by &lt;em&gt;automatically generating and injecting mock objects&lt;/em&gt;, should the tested class ask for them in its constructor. &lt;/p&gt;

&lt;p&gt;These &lt;em&gt;mock objects are persisted in the local container&lt;/em&gt; instance as singleton, so that additional expectations could be recorded against them. Expectations are verified when the container is disposed.&lt;/p&gt;

&lt;p&gt;There is a little overhead of creating and disposing container and instances every test, since we are using &lt;a href="http://abdullin.com/autofac/"&gt;Autofac IoC Container&lt;/a&gt; internally here, which has a really good performance.&lt;/p&gt;

&lt;p&gt;Interface and internals of this MockContainer have been polished heavily since its &lt;a href="http://abdullin.com/journal/2009/4/11/testing-mvc-controllers-with-mock-container.html"&gt;introduction a few months ago&lt;/a&gt;. This (with the help from a base fixture class providing a nice syntax) has allowed to write tests like this one:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Test]
public void Display()
{
  View.SetTitle("Some title");

  // we expect the view to ask IViewspace to display itself
  WhenViewIsShown
     // you always set Form.CancelButton  for user's pleasure
    .CancelButtonShouldBeSet()
     // assert that title as as expected
    .TitleShouldBe("Some title");

    // create 0 to 20 random models and display them in view
    View.BindModel(RandClientModels.NextEvents(0, 20));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is an actual unit test against actual Windows.Forms.UserControl component. It does what it says. Ability to write unit tests like this brings following benefits for free:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In this unit test all calls are executed against the interface. So should we need add Silverlight or WPF view implementations to our library, we would already have tests for the first step of &lt;a href="http://abdullin.com/wiki/test-driven-development-tdd.html"&gt;Test Driven Development&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Ability to write simple unit tests really pays off in scenarios, where a single component is reused in multiple projects. Finding a bug in one of these projects, expressing it in a unit test and fixing, immediately makes all projects downstream more stable. &lt;/li&gt;
&lt;li&gt;Using randomly-generated Models allows to cover a wider range of the possible failure scenarios. Should some case go wrong, we'll be able to reproduce it by checking out rand seed used in the integration run (&lt;em&gt;Nondeterministic reproducible testing&lt;/em&gt; will be the subject of another article).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here's another type of unit test. It could be invoked explicitly just to see how our view looks alone (without launching an entire application and clicking our way to this View):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Test, Explicit]
public void Show_view_for_debugging()
{
  // when view asks to show itself, actually display it
  WhenViewIsShown.ShowAsDialog();
  // load random values and display
  View.BindModel(RandClientModels.NextEvent());
  // display view, while using ValidEvent rule 
  // to validate all input
  View.GetModel(EditEventController.ValidEvent);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;ExplicitAttribute&lt;/em&gt; in NUnit tells us that unit test is excluded from the usual unit testing run and has to be launched manually.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This kind of debugging unit test for the reusable View components speeds up all the testing and UI tweaking process. Do you need to check out how View validates data, scales or displays that recent UI tweak? This is just one click away:&lt;/p&gt;

&lt;p&gt;&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/06/2009-06-25_using_mockContainer_to_test_MVC_views.png" alt="Using MockContainer to test MVC Views"/&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Sometimes we may want to go deeper and check out how various components integrate together. This is not a normal unit test (in the sense of &lt;a href="http://abdullin.com/wiki/unit-testing.html"&gt;Unit Testing&lt;/a&gt;), so it is marked with ExplicitAttribute as well.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Test, Explicit]
public void Test_for_debugging_with_controller()
{
  // view is registered by test fixture
  WhenViewIsShown.ShowAsDialog();

  // simplified syntax for registering additional components
  // that we don't want to be replaced with mock objects.
  Container.Build(builder =&amp;gt;
  {
    builder.Register&amp;lt;ConnectionEditController&amp;gt;();
    builder.Register&amp;lt;WorkScopeView&amp;gt;().As&amp;lt;IWorkScopeView&amp;gt;();
  });

  // resolving controller and launching it with a random connection
  var controller = Container.Resolve&amp;lt;ConnectionEditController&amp;gt;();
  controller.Startup();
  controller.Edit(RandApiModels.NextServiceConnection());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Although code like this does not participate in the &lt;a href="http://abdullin.com/wiki/continuous-integration.html"&gt;Continuous Integration&lt;/a&gt; process, having it around speeds up the development and simplifies debugging, should something go wrong.&lt;/p&gt;

&lt;p&gt;This specific test creates UI elements like this:&lt;/p&gt;

&lt;p&gt;&lt;span class="full-image-block ssNonEditable"&gt;&lt;span&gt;&lt;img src="http://abdullin.com/storage/uploads/2009/06/2009-06-25_using_MockContainer_to_test_complex_component_interactions.png?__SQUARESPACE_CACHEVERSION=1245883585590" alt="Using MockContainer to test complex component interactions"/&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;Unit tests samples come from open source project &lt;a href="http://code.google.com/p/lokad-sdk/" class="offsite-link-inline"&gt;Lokad SDK&lt;/a&gt; that allows developers to introduce forecasting capabilities of &lt;a href="http://www.lokad.com/" target="_blank" class="offsite-link-inline"&gt;Lokad.com&lt;/a&gt; into their applications.&lt;/p&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=s-hQzanEuzU:ojRdmLpbTao:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=s-hQzanEuzU:ojRdmLpbTao:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=s-hQzanEuzU:ojRdmLpbTao:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=s-hQzanEuzU:ojRdmLpbTao:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=s-hQzanEuzU:ojRdmLpbTao:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=s-hQzanEuzU:ojRdmLpbTao:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=s-hQzanEuzU:ojRdmLpbTao:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/s-hQzanEuzU" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/6/25/testing-mvc-elements-and-interactions-with-mock-container.html</feedburner:origLink></entry><entry><title>Testing MVC Controllers with Mock Container</title><category term="C#" /><category term="How To" /><category term="IoC" /><category term="Lokad" /><category term="Snippets" /><category term="Theory" /><category term="autofac" /><id>http://abdullin.com/journal/2009/4/11/testing-mvc-controllers-with-mock-container.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/Ss0OCJ3cEmc/testing-mvc-controllers-with-mock-container.html" /><author><name>Rinat Abdullin</name></author><published>2009-04-11T14:57:03Z</published><updated>2009-04-11T14:57:03Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;While developing &lt;a href="http://abdullin.com/wiki/component-driven-development.html"&gt;components and services for the IoC environment&lt;/a&gt;, we end up with highly-specialized classes (which is good) that tend to consume a number of other lower-level classes, abstracted behind interfaces.&lt;/p&gt;

&lt;p&gt;While this increases flexibility and stability of the system, testing could become slightly more complicated.&lt;/p&gt;

&lt;p&gt;Let us consider following .NET controller class (of the &lt;a href="http://en.wikipedia.org/wiki/Model-view-controller" target="_blank" class="offsite-link-inline"&gt;Model-View-Controller&lt;/a&gt; pattern):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[UsedImplicitly]
[Guidelines.Controller]
public sealed class ExcelTaskEditController
{
  public ExcelTaskEditController(IExcelTaskEditView view,
                                 IExcelWorkbook workbook)
  {
    Enforce.Arguments(() =&amp;gt; view, () =&amp;gt; workbook);

    _view = view;
    _workbook = workbook;
  }

  public void Startup()
  {
    _view.EditRange += (range, message, action) =&amp;gt;
      _workbook.GetRange(range, message).Apply(action);
  }

  public Result&amp;lt;ExcelTask&amp;gt; Edit(Maybe&amp;lt;ExcelTask&amp;gt; request)
  {
    // Logic of binding Model to View is skipped here
    // for brevity
    return _view.GetModel(ExcelTaskIs.Valid);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you're interested in the logic behind &lt;em&gt;view.GetModel&lt;/em&gt; - check out the article on &lt;a href="http://abdullin.com/journal/2009/1/29/ddd-and-rule-driven-ui-validation-in-net.html"&gt;DDD and Rule-driven UI Validation in MVC&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Participation of this controller in the system composition is limited to a single line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;builder.RegisterEditor&amp;lt;ExcelTaskEditController, ExcelTask&amp;gt;(
  c =&amp;gt; c.Startup(), c =&amp;gt; c.Edit);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this line we simply tell the Autofac: "&lt;em&gt;When some view requests a capability to present user with UI to edit/create ExcelTask, pass it an edit delegate of the pre-configured controller&lt;/em&gt;". This does resemble MEF slightly.&lt;/p&gt;

&lt;p&gt;That's nice so far, but how do we unit test the actual controller? Here are some options:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;manually create mock classes for the View and Workbook interfaces it consumes and pass them to the constructor;&lt;/li&gt;
&lt;li&gt;be smart and use some mocking library to create each of these mocks/stubs for us.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, there is an easier approach:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Wire &lt;a href="http://abdullin.com/autofac/"&gt;IoC Container of our choice&lt;/a&gt; directly to  &lt;a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank" class="offsite-link-inline"&gt;mocking library of our choice&lt;/a&gt; and let them create mocks whenever needed by dependency injection.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With this approach unit test to check editing of a task could look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Test]
public void Editing_task()
{
  // action to test
  var result = Controller.Edit(Sample.ValidTask);
  // when task is edited, we should
  // bind it to a view
  // hide "Delete" button
  _container
    .AssertWasCalled&amp;lt;IExcelTaskEditView&amp;gt;(v =&amp;gt; v.BindModel(Sample.ValidTask))
    .AssertWasCalled&amp;lt;IExcelTaskEditView&amp;gt;(v =&amp;gt; v.SetDeleteVisible(true));
  // expected result
  Assert.AreEqual("my result", result.ErrorMessage);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And the setup code for the NUnit test fixture looks like this in C#:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[TestFixture]
public sealed class ExcelTaskEditControllerTests
{
  MockContainer&amp;lt;ExcelTaskEditController&amp;gt; _container;

  ExcelTaskEditController Controller
  {
    get { return _container.Subject; }
  }

  [SetUp]
  public void Setup()
  {
    // create new container, subject is registered automatically
    _container = MockContainer.For&amp;lt;ExcelTaskEditController&amp;gt;();
    // initialize the controller
    Controller.Startup();
    // tell mocking library:
    // when there is a specific call to a view interface, 
    // return predefined result
    _container
      .Resolve&amp;lt;IExcelTaskEditView&amp;gt;()
      .Stub(v =&amp;gt; v.GetModel(ExcelTaskIs.Valid))
      .Return(Result&amp;lt;ExcelTask&amp;gt;.Error("my result"));
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Implementation of &lt;em&gt;MockContainer&lt;/em&gt; class is rather straightforward in .NET. All it does is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;whenever an unknown service/component is requested - create a new stub for it with Rhino.Mocks library and register in the container as Singleton;&lt;/li&gt;
&lt;li&gt;provide a few shortcuts for frequently used mocking/assertion methods.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;MockContainer&lt;/em&gt; class could be found in Lokad.Testing.dll assembly that has been introduced to the &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt;. This new assembly includes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Rhino.Mocks.dll merged in for mocking purposes;&lt;/li&gt;
&lt;li&gt;Mocking Container implementation on top of Autofac IoC and Rhino Mocks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Lokad.Testing.dll&lt;/em&gt; depends on &lt;em&gt;Lokad.Shared.dll&lt;/em&gt; and &lt;em&gt;Lokad.Stack.dll&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;You can check out the &lt;a href="http://abdullin.com/shared-libraries/"&gt;project page&lt;/a&gt; for more details or simply &lt;a href="http://build.lokad.com/distrib/shared/" target="_blank" class="offsite-link-inline"&gt;download the latest binaries&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;MVC Controllers from this example are a specific case of using Component-Driven Development approach, that &lt;a href="http://abdullin.com/journal/2009/5/31/component-driven-development-and-ioc-containers.html"&gt;helps to build reliable software efficiently&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There is also another article on this topic: &lt;a href="http://abdullin.com/journal/2009/6/25/testing-mvc-elements-and-interactions-with-mock-container.html"&gt;Testing MVC Elements and Interactions with Mock Container&lt;/a&gt; that you might like.&lt;/p&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=Ss0OCJ3cEmc:bVczB78iDAM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=Ss0OCJ3cEmc:bVczB78iDAM:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=Ss0OCJ3cEmc:bVczB78iDAM:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=Ss0OCJ3cEmc:bVczB78iDAM:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=Ss0OCJ3cEmc:bVczB78iDAM:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=Ss0OCJ3cEmc:bVczB78iDAM:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=Ss0OCJ3cEmc:bVczB78iDAM:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/Ss0OCJ3cEmc" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/4/11/testing-mvc-controllers-with-mock-container.html</feedburner:origLink></entry><entry><title>Some OSS News on Lokad and Autofac</title><category term="Articles" /><category term="Integration" /><category term="Lokad" /><category term="autofac" /><category term="xLim" /><id>http://abdullin.com/journal/2009/3/10/some-oss-news-on-lokad-and-autofac.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/6WszwIwxrW4/some-oss-news-on-lokad-and-autofac.html" /><author><name>Rinat Abdullin</name></author><published>2009-03-10T06:43:46Z</published><updated>2009-03-10T06:43:46Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;Last weeks have been quite intense. So here are just some news and links.&lt;/p&gt;

&lt;h1&gt;Lokad Shared Libraries&lt;/h1&gt;

&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;SVN for repository for Lokad Shared Libraries has been moved away from the Source Forge and into the &lt;a href="http://code.google.com/p/lokad-shared-libraries/"&gt;Google Projects&lt;/a&gt;. That's where all documentation would eventually be migrated. &lt;/p&gt;

&lt;p&gt;Version of the library has been updated to 1.2 and there was a &lt;strong&gt;major release&lt;/strong&gt; (available for download at Google). Among other things it includes following changes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Rule messages have been cleaned up and moved into the resources. Thus, they are localizable now.&lt;/li&gt;
&lt;li&gt;Rule scopes have been got new extensions Lower() and Raise(). They create new child scopes (with the same path) that lower or boost the importance of rule messages being passed. This is useful for situations, when you want to reuse your existing rules in a slightly different context.&lt;/li&gt;
&lt;li&gt;There are some more predefined rules.&lt;/li&gt;
&lt;li&gt;Added a number of missing method overloads for composing and enforcing rules.&lt;/li&gt;
&lt;li&gt;Scope.Validate (which uses fast IL reflection) now also works on fields. This is for DDD/MVC scenarios where models are implemented as immutable classes.&lt;/li&gt;
&lt;li&gt;ILMerge process has been added to the integration. So Lokad.Stack.dll (in its current setup) now includes Autofac.dll and log4net.dll. &lt;/li&gt;
&lt;li&gt;Licenses for all 3rd party libraries are included in the ReadMe.txt, JIC.&lt;/li&gt;
&lt;li&gt;Library includes ReSharper 4.5 attributes for the code analysis (used in solution-wide analysis).&lt;/li&gt;
&lt;li&gt;More tests and a number of fixes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;Autofac&lt;/h1&gt;

&lt;p&gt;&lt;br /&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Autofac.Contrib is being merged with the Autofac (projects and solutions are still separate). This should simplify development of contributions (and has already simplified the integration process).&lt;/li&gt;
&lt;li&gt;Integration scripts (MSBuild now) and the solution structure have been upgraded to the latest version of the xLim template. &lt;/li&gt;
&lt;li&gt;&lt;p&gt;Discussion groups of Autofac have picked up quite a momentum recently. There are a few really interesting topics out there. If everything goes as it is, we might eventually see this kind of command-line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;msbuild Autofac.stack  /P:Include="mef,startable,nhibernate,log4net,rules"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The implementation sounds like an interesting challenge, but it should not be that hard with Mono.Cecil, ILMerge and some well-laid solution structures.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;Lokad SDK&lt;/h1&gt;

&lt;p&gt;&lt;br /&gt;
This new project might might be interesting, if you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;are interested in a different and efficient approach on building composite desktop applications with Autofac and Lokad Shared Libraries;&lt;/li&gt;
&lt;li&gt;want to learn about shared codebases, where MVC elements are reused in different application hosts;&lt;/li&gt;
&lt;li&gt;are potentially interested in integrating some business intelligence services (proprietary but smart, friendly and revenue sharing) in your projects;&lt;/li&gt;
&lt;li&gt;agree that SmartClient and CAB are too heavy and Autofac is better than Unity.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lokad SDK has been established at &lt;a href="http://code.google.com/p/lokad-sdk/"&gt;Google Code projects&lt;/a&gt; (moving away from SourceForge). It already includes an Add-in for Excel in beta stage and a foundation for composite UI library on top of Lokad Shared Libraries. &lt;/p&gt;

&lt;p&gt;Among the features it currently contains:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;functional-style MVC used for UI composition (models are immutable for the simplicity and better async in UI);&lt;/li&gt;
&lt;li&gt;UI-level validation with Lokad Rules;&lt;/li&gt;
&lt;li&gt;good citizenship code (supported by Result{T} and Maybe{T} classes);&lt;/li&gt;
&lt;li&gt;ClickOnce VSTO deployment in the build scripts (same xLim template);&lt;/li&gt;
&lt;li&gt;code quality checks (on top of Lokad.Quality) for enforcing design-level decisions (i.e. MVC models must be immutable or controller classes must have only 1 constructor);&lt;/li&gt;
&lt;li&gt;Autofac wiring in an add-in hosted in Excel 2007.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What do you think about all this?&lt;/p&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=6WszwIwxrW4:h_3V7KSAekk:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=6WszwIwxrW4:h_3V7KSAekk:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=6WszwIwxrW4:h_3V7KSAekk:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=6WszwIwxrW4:h_3V7KSAekk:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=6WszwIwxrW4:h_3V7KSAekk:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=6WszwIwxrW4:h_3V7KSAekk:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=6WszwIwxrW4:h_3V7KSAekk:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/6WszwIwxrW4" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/3/10/some-oss-news-on-lokad-and-autofac.html</feedburner:origLink></entry><entry><title>Logging with Lokad Shared Libraries for .NET</title><category term="Articles" /><category term="C#" /><category term="How To" /><category term="IoC" /><category term="Lokad" /><category term="Snippets" /><category term="autofac" /><id>http://abdullin.com/journal/2009/3/3/logging-with-lokad-shared-libraries-for-net.html</id><link rel="alternate" type="text/html" href="http://feeds.abdullin.com/~r/Shared-Libraries/~3/c_Sr3rRRLWw/logging-with-lokad-shared-libraries-for-net.html" /><author><name>Rinat Abdullin</name></author><published>2009-03-03T18:38:41Z</published><updated>2009-03-03T18:38:41Z</updated><content type="html" xml:lang="en-US">&lt;p&gt;Let's get back to the topic of using &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt; and &lt;a href="http://abdullin.com/autofac/"&gt;Autofac .NET IoC Container&lt;/a&gt; to structure and configure your applications.&lt;/p&gt;

&lt;p&gt;In the first article we've talked about &lt;a href="http://abdullin.com/journal/2009/2/12/structuring-net-applications-with-autofac-ioc.html"&gt;Structuring .NET Applications with Autofac&lt;/a&gt;. There was a stub for sample Module class for strongly-typed configuration. &lt;/p&gt;

&lt;p&gt;Let's go on to explore the contents of the &lt;em&gt;Module.Configure&lt;/em&gt; method that performs the actual work. We'll focus on logging in this article. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public sealed class Module : IModule
{
  public string ConnectionOptions { get; set; }
  public bool UseMockDataLayer { get; set; }
  public Mode Mode { get; set; }

  public Module()
  {
    Mode = Mode.Release;
  }

  public void Configure(IContainer container)
  {
    // if module is reused in Windows Azure:
    // if (RoleManager.IsRoleManagerRunning)
    //   ApplyOverridesFromRuntime();    

    var builder = new ContainerBuilder();

    // configure logging
    var logger = GetLoggerForWindows(Mode);
    builder.Register(logger);
    builder.Register(logger.Get("DefaultLog"));

    // configure exception capturing
    builder.Register(exceptionCounter);
    var exceptionCounter = ExceptionCounters.Default;   

    RegisterPolicy(builder);
    RegisterDal(builder);
    RegisterRuleBehavior(builder);
  }
  // more
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, the first step is about configuring logging and making it available for any component resolved through the Autofac IoC. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;GetLoggerForWindows&lt;/em&gt; method (we'll look into the implementation later) returns an instance of generic interface &lt;em&gt;INamedProvider{ILog}&lt;/em&gt;. This interface essentially allows us to get a named logger (name of a logger is a category that could be used to filter messages later on):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;INamedProvider&amp;lt;ILog&amp;gt; logger = ...;
ILog namedLog = logger.Get("DAL Log");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Both &lt;em&gt;ILog&lt;/em&gt; and &lt;em&gt;INamedProvider{T}&lt;/em&gt; interfaces are defined in the &lt;em&gt;Lokad.Shared.dll&lt;/em&gt; and, thus, are not bound to any logging framework. Any component, that is resolved via the IoC Container, could get an instance of either of these to do its logging chores.&lt;/p&gt;

&lt;p&gt;Here's how the ILog interface is defined in C#:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface ILog
{
  void Log(LogLevel level, object message);
  void Log(LogLevel level, Exception ex, object message);
  bool IsEnabled(LogLevel level);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, it is extremely easy to write your own implementation of this interface. Here's, actually, how the implementation of &lt;em&gt;DebugLog&lt;/em&gt; could look like in C#:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void Log(LogLevel level, object message)
{
  Debug.WriteLine(message, level.ToString());
}

public void Log(LogLevel level, Exception ex, object message)
{
  Debug.WriteLine(message, level.ToString());
  Debug.WriteLine(ex, level.ToString());
}

public bool IsEnabled(LogLevel level)
{
  return true;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And any such implementation will (thanks to the extension methods defined in Lokad.Shared.dll) provide out-of-the box rich functionality like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;log.Debug("Message");
log.Debug(ex, "Message with exception");
log.DebugFormat("Message #{0}", id);
log.DebugFormat(ex, "Message #{0}", id);

if (log.IsDebugEnabled())
{
    // some extensive logging
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These helper methods are defined for following logging levels:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Debug&lt;/strong&gt; - message is intended for debugging;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Warn&lt;/strong&gt; - informatory message;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Info&lt;/strong&gt; - the message is about potential problem in the system;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Error&lt;/strong&gt; - some error has occurred;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fatal&lt;/strong&gt; - message is associated with the critical problem.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Additionally, Lokad.Shared.dll provides simple implementations of these simple loggers (in System.Diagnostics namespace):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;TraceLog&lt;/strong&gt; - prints messages to the &lt;em&gt;Trace.Listeners&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DebugLog&lt;/strong&gt; - prints messages to the &lt;em&gt;Debug.Listeners&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;NullLog&lt;/strong&gt; - does not do anything.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Obviously, a production system would need more diverse logging capabilities, than these three interfaces. That's why Logging.Stack.dll allows to seamlessly plug powerful &lt;a href="http://logging.apache.org/log4net/index.html" target="_blank" class="offsite-link-inline"&gt;Apache log4net&lt;/a&gt; logging library into these interfaces. &lt;/p&gt;

&lt;p&gt;Note, that this plugging will happen only in the configuration sections. So your business code would stay completely detached from the logging implementation details.&lt;/p&gt;

&lt;p&gt;Apache log4net, is quite powerful, but configuring it could be quite complex. That's why Lokad.Stack.dll also provides a simplified fluent API to hide the complexity of configuring common usage scenarios.&lt;/p&gt;

&lt;p&gt;Given all these details, here's finally how our GetLoggerForWindows implementation might look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static INamedProvider&amp;lt;ILog&amp;gt; GetLoggerForWindows(Mode mode)
{
  // configuring different logging based on our mode
  switch (mode)
  {
    case Mode.Release:
      // write all informational and higher events to
      // windows event log
      LoggingStack.UseEventLog(EventLogName, EventLogSource)
        .Filter(LogLevel.Info, LogLevel.Max);

      // dump all warning and higher messages to rolling text log
      LoggingStack.UseRollingLog("logs/errorlog.txt", 100.Kb(), 10)
        .Filter(LogLevel.Warn, LogLevel.Fatal);
      break;
    case Mode.Diagnostics:
      // dump all messages to daily log
      LoggingStack.UseDailyLog("logs/log.txt");
      break;
    case Mode.Debug:
      // Visual studio would get these messages
      return TraceLog.Provider;
    default:
      throw new ArgumentOutOfRangeException("mode");
  }
  return LoggingStack.GetLogProvider();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the sample above we configure our logging infrastructure to write to (based on the configuration):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Windows Event log&lt;/li&gt;
&lt;li&gt;Rolling textual log&lt;/li&gt;
&lt;li&gt;Daily log&lt;/li&gt;
&lt;li&gt;Trace&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If that's not enough for you, you can load raw log4net settings from your config:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;LoggingStack.UseConfig();
return LoggingStack.GetLogProvider();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By the way, thanks to the power of &lt;a href="http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx" target="_blank" class="offsite-link-inline"&gt;ILMerge&lt;/a&gt; and for your convenience, Lokad.Stack.dll already contains a version of log4net.dll inside. So you don't have to bother about getting it (neither you have to bother about looking for its open-source license for redistribution purposes, since it is already included in common &lt;em&gt;ReadMe.txt&lt;/em&gt; distributed with the libraries). &lt;/p&gt;

&lt;p&gt;Latest Autofac is packaged in there also.&lt;/p&gt;

&lt;p&gt;That's it for the second article about configuring logging in your .NET applications that use &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In the third article in the series we'll talk about configuring lightweight exception and performance counters to capture essential execution information about our application. &lt;/p&gt;

&lt;p&gt;Meanwhile you can: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;stay tuned to &lt;a href="http://feeds.abdullin.com/RinatAbdullin"&gt;RSS feed&lt;/a&gt; for the updates;&lt;/li&gt;
&lt;li&gt;explore &lt;a href="http://abdullin.com/shared-libraries/"&gt;Lokad Shared Libraries&lt;/a&gt;;&lt;/li&gt;
&lt;li&gt;Share you thoughts about the logging integration capabilities provided by the libraries. Are they simple and powerful enough for you to use them (or pieces of the code) in your projects?&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=c_Sr3rRRLWw:Vv6814Msg6Q:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=c_Sr3rRRLWw:Vv6814Msg6Q:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=c_Sr3rRRLWw:Vv6814Msg6Q:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=c_Sr3rRRLWw:Vv6814Msg6Q:gIN9vFwOqvQ"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=c_Sr3rRRLWw:Vv6814Msg6Q:gIN9vFwOqvQ" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.abdullin.com/~ff/Shared-Libraries?a=c_Sr3rRRLWw:Vv6814Msg6Q:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/Shared-Libraries?i=c_Sr3rRRLWw:Vv6814Msg6Q:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/Shared-Libraries/~4/c_Sr3rRRLWw" height="1" width="1"/&gt;</content><feedburner:origLink>http://abdullin.com/journal/2009/3/3/logging-with-lokad-shared-libraries-for-net.html</feedburner:origLink></entry></feed>
