<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6595360840585786394</id><updated>2011-12-07T23:02:15.113-08:00</updated><category term='Globalization'/><category term='ELMAH'/><category term='design patterns'/><category term='TDD'/><category term='javascript'/><category term='log4net'/><category term='AJAX'/><category term='NHibernate'/><category term='Hudson'/><category term='SQLite'/><category term='ASP.NET MVC'/><category term='Entity Framework'/><category term='ASP.NET'/><category term='ADO.NET'/><title type='text'>Atanas Hristov</title><subtitle type='html'>my adventures in programming</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>15</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-8351296234889066206</id><published>2011-08-26T19:06:00.000-07:00</published><updated>2011-08-26T20:35:29.630-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Hudson'/><category scheme='http://www.blogger.com/atom/ns#' term='TDD'/><title type='text'>Hudson: Installation and Configuration for Dot.NET Projects</title><content type='html'>&lt;b&gt;Hudson&lt;/b&gt; is a tool for continuous build, integration and deployment widely used in the Java world. Hudson can be used also with other platforms and programming languages and on many operating systems. A lot of plug-ins are available for Hudson.&lt;br /&gt;&lt;br /&gt;For the &lt;b&gt;Dot.NET&lt;/b&gt; world Hudson provides complete environment for continuous integration. The tool compile code with  MSBuild, can run NAnt scripts, can run NUnit tests, check for code rules with FxCop or Gendarme,  create documentation with Sandcastle.&lt;br /&gt;&lt;br /&gt;The Hudson server by default provides integration with Subversion. It can be installed on Windows to run as a windows service.&lt;br /&gt;&lt;br /&gt;The configuration of the jobs to run on the Hudson server is done completely from the web-based console of the tool. Also from there we install plug-ins.  &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Installing Hudson: Prerequisites&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Installing Hudson on Windows is easy task. Following are the steps we needed in our case.&lt;br /&gt;&lt;br /&gt;In this scenario we'll be using Hudson for Dot.NET development in conunction with the following tools: MSBuild, NUnit, FxCop, Gendarme, Sandcastle, so that we'll build, run unit tests, check code styles and create API documentation for our projects. &lt;br /&gt;&lt;br /&gt;I will demonstrate using Subversion for source control system. But with Hudson you can easily use other version control systems too.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install &lt;b&gt;Java&lt;/b&gt;. Hudson is a Java application.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Download Link: http://www.java.com/en/download/ie_manual.jsp&lt;br /&gt;&lt;br /&gt;Add to the system environment variable %PATH% the directory name where the java.exe is:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;"C:\Program Files (x86)\Java\jre6\bin"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Open new command window and try to check the version of Java installed:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\&amp;gt;java -version&lt;br /&gt;java version "1.6.0_26"&lt;br /&gt;Java(TM) SE Runtime Environment (build 1.6.0_26-b03)&lt;br /&gt;Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install the &lt;b&gt;Dot.NET SDKs&lt;/b&gt; you need.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;You can install all together 2.0, 3.5, 4.0 and use one or another as needed. Check if the MSBuild is installed:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Users\Administrator&amp;gt;"C:\Windows\Microsoft.NET\Framework\v2.0.50727\MSBuild"&lt;br /&gt;Microsoft (R) Build Engine Version 2.0.50727.4016&lt;br /&gt;&lt;br /&gt;C:\Users\Administrator&amp;gt;"C:\Windows\Microsoft.NET\Framework\v3.5\MSBuild"&lt;br /&gt;Microsoft (R) Build Engine Version 3.5.30729.1&lt;br /&gt;&lt;br /&gt;C:\&amp;gt;"C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild"&lt;br /&gt;Microsoft (R) Build Engine Version 4.0.30319.1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;You can even leverage this on that MSBuild version depending on the different projects you integrate in Hudson.&lt;br /&gt;&lt;br /&gt;Add though the directory where the 4th version of Dot.NET is to the system PATH variable:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;"%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;then test if you can run the MSBuild from new command prompt:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\&gt;msbuild&lt;br /&gt;Microsoft (R) Build Engine Version 4.0.30319.1&lt;br /&gt;...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install the &lt;b&gt;NUnit&lt;/b&gt; framework.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;NUnit is a unit-testing (xUnit) framework. It comes with GUI tests runner and command line test runner. &lt;br /&gt;&lt;br /&gt;Download Link: http://www.nunit.org/&lt;br /&gt;In our case it is the version 2.5.10 from the URL:&lt;br /&gt;http://launchpad.net/nunitv2/2.5/2.5.10/+download/NUnit-2.5.10.11092.msi&lt;br /&gt;&lt;br /&gt;Once the NUnit is installed, configure a version of the runner for the Dot.NET 4.0 framework. Copy directory:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\NUnit 2.5.10\bin\net-2.0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;to:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\NUnit 2.5.10\bin\net-4.0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Edit the nunit.exe.config file from the new directory and add at the end of that file: &lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;&amp;lt;startup&amp;gt;&lt;br /&gt;  &amp;lt;requiredRuntime version="v4.0.30319" /&amp;gt;&lt;br /&gt;&amp;lt;/startup&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;just before the closing "configuration" tag. Please note the version number, make the same as you've got installed. &lt;br /&gt;&lt;br /&gt;Add to the system environment variable %PATH% the directory name:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;"C:\Program Files (x86)\NUnit 2.5.10\bin\net-4.0"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Open new console window and check to see if the command line test runner is in the %PATH%:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\&gt;nunit-console-x86.exe&lt;br /&gt;NUnit version 2.5.10.11092&lt;br /&gt;Copyright (C) 2002-2009 Charlie Poole.&lt;br /&gt;...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install &lt;b&gt;FxCop&lt;/b&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;FxCop is a tool from Microsoft that analyzes managed code assemblies and reports information about design, localization, performance and security improvements.&lt;br /&gt;&lt;br /&gt;The tool comes a part of the Windows SDK for Windows 7 and Dot.NET 4.&lt;br /&gt;All other installers of the FxCop are outdated, that's why we have to get  the SDK on the machine.&lt;br /&gt;&lt;br /&gt;Download the SDK from URL:&lt;br /&gt;http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=6b6c21d2-2006-4afa-9702-529fa782d63b&lt;br /&gt;&lt;br /&gt;Install with the default options.&lt;br /&gt;&lt;br /&gt;The SDK was in our case installed into:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files\Microsoft SDKs\Windows\v7.1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The Samples into:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;A part of the SDK is the help library manager that gives you a chance to download locally on your computer part of the SDK documentation. The help library will be installed into:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\ProgramData\Microsoft\HelpLibrary\&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;and you (optionally) can install help content in there.&lt;br /&gt;&lt;br /&gt;After this install finished, there is yet another installer now to run. The FxCop installer will be into directory:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\FXCop&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Run the FxCopSetup.exe file from there.&lt;br /&gt;&lt;br /&gt;The installer suggested in our case the following install folder:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;c:\Program Files (x86)\Microsoft Fxcop 10.0\&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;After this installation finished, add to the system environment variable %PATH% the directory name:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;"C:\Program Files (x86)\Microsoft Fxcop 10.0"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Open new console window and test if you can run the application:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\&gt;FxCopCmd.exe&lt;br /&gt;Microsoft (R) FxCop Command-Line Tool, Version 10.0 (10.0.30319.1) X86&lt;br /&gt;Copyright (C) Microsoft Corporation, All Rights Reserved.&lt;br /&gt;...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install &lt;b&gt;Gendarme&lt;/b&gt;.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Gendarme is part of the mono-tools. It a rule based tool for finding problems in .NET applications and libraries much like the FxCop is.  &lt;br /&gt;&lt;br /&gt;Download and install the tool from the following URL:&lt;br /&gt;https://github.com/downloads/spouliot/gendarme/gendarme-2.10-win32-setup.zip&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The installer suggested to following target folder:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\Gendarme\&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;After this installation finished, add to the system environment variable %PATH% the directory name:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;"C:\Program Files (x86)\Gendarme"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Open new console window and test if you can run this application:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\&gt;gendarme.exe&lt;br /&gt;Gendarme v2.10.0.0&lt;br /&gt;Copyright (C) 2005-2011 Novell, Inc. and contributors&lt;br /&gt;...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install &lt;b&gt;Sandcastle&lt;/b&gt;, htmlhelp and SHFB.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Sandcastle produces MSDN style documetation  from the source assemblies integrating the XML documentation from the source code.&lt;br /&gt;&lt;br /&gt;Download and install Sandcastle from:&lt;br /&gt;http://sandcastle.codeplex.com/&lt;br /&gt;&lt;br /&gt;In our case the installer suggested by default the following install directory:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\Sandcastle\&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Download and install the Microsoft HTML Help Workshop from:&lt;br /&gt;http://go.microsoft.com/fwlink/?LinkId=14188&lt;br /&gt;&lt;br /&gt;Run the downloaded file htmlhelp.exe  and follow the instructions.&lt;br /&gt;&lt;br /&gt;The default installation path was in our case:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\HTML Help Workshop&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Download and install the Sandcastle Help File Builder from:&lt;br /&gt;http://shfb.codeplex.com/&lt;br /&gt;&lt;br /&gt;Unpack the downloaded zip file and run the SandcastleInstaller.exe installer application. It comes with nice wizard GUI. Follow the instructions. The installer will ask you to download and install for you all the additional applications it will need in order to work. Just answer with "Yes" on those questions. &lt;br /&gt;&lt;br /&gt;You will skip the installation of Microsoft Help 2, this is not a necessary part to have.&lt;br /&gt;&lt;br /&gt;It also will ask you to apply a patch to Sandcastle. Answer with "Apply Patch" on this screen. &lt;br /&gt;&lt;br /&gt;If you wish you can install also language pack for German language. &lt;br /&gt;&lt;br /&gt;Optionally it will download for you the MAML guide - the guide from Microsoft for the documentation markup language, web project custom providers - a package with information for producing XML documents for web applications and website projects, a HTML to MAML converter.&lt;br /&gt;&lt;br /&gt;If you don't have Visual Studio installed skip the section :MAML Schema InteliSense"&lt;br /&gt;&lt;br /&gt;After this step it will suggest to install for you the SHFB - Sancastle Help File Builder. Cilck on "Install SHFB" on this screen.&lt;br /&gt;&lt;br /&gt;The SHFB in our case was installed into:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\EWSoftware\Sandcastle Help File Builder\&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;On the last screen of the wizard click on the 'Reboot' in order all the changes to take effect on your system. &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;b&gt;Visual Studio Templates&lt;/b&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;If on the machine where Hudson will be running the visual studio is not installed you may need to come some Visual template files from developer's machine. For example copy to the machine the complete directory:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;as for Visual Studio 2010 Express Edition with default installation path.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Installing Hudson: Prepare Visual Studio Project Structure for Hudson&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;To easily integrate a Visual Studio Project into Hudson, I would suggest the following project structure and files to be created.&lt;br /&gt;&lt;br /&gt;Suppose we've got a project named "&lt;b&gt;WebAPI&lt;/b&gt;"&lt;br /&gt;&lt;br /&gt;In my project directories in Subversion I would prefer having structure like:&lt;br /&gt;&lt;br /&gt;directory &lt;b&gt;.\References&lt;/b&gt; - copy here all the third party DLLs you'll be referencing from the project&lt;br /&gt;&lt;br /&gt;directory &lt;b&gt;.\WebAPI&lt;/b&gt; - here is the project with the production code: a Visual Studio project named like the directory - WebAPI.csproj&lt;br /&gt;&lt;br /&gt;From project properties in the Visual Studio, in section "Build" go to sub-section "Output" and enable check the box "XML documentation file". The name of the output file in "Debug" target build configuration should be the same as the specified in the Sandcastle project (below).  &lt;br /&gt;&lt;br /&gt;directory &lt;b&gt;.\WebAPITests&lt;/b&gt; - contains  the project with the unit tests for the WebAPI project: another Visual Studio project with Visual Studio project file named WebAPITests.csproj&lt;br /&gt;&lt;br /&gt;The project with the unit tests references the project with the production code.&lt;br /&gt;&lt;br /&gt;file &lt;b&gt;WebAPI.sln&lt;/b&gt; - the Visual Studio solution file.&lt;br /&gt;&lt;br /&gt;file &lt;b&gt;WebAPI.shfbproj&lt;/b&gt; - the Sandcaslte project file&lt;br /&gt;&lt;br /&gt;To create the Sandcastle project file run the "Sandcastle Help File Builder GUI" application. From the project properties the make the HelpFileFormat to be "HtmlHeml 1, Website".&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-R9l0JoJoyyw/TlhePHifOII/AAAAAAAAAHk/_tr5wDve08g/s1600/Image.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="46" width="400" src="http://2.bp.blogspot.com/-R9l0JoJoyyw/TlhePHifOII/AAAAAAAAAHk/_tr5wDve08g/s400/Image.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Documentation sources are:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;WebAPI\bin\Debug\WebAPI.dll&lt;br /&gt;WebAPI\bin\Debug\WebAPI.XML&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-68OkbC-6Lm0/TlhesV5CjoI/AAAAAAAAAHs/juJDBlwiGZk/s1600/Image%2B%255B1%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="117" width="198" src="http://2.bp.blogspot.com/-68OkbC-6Lm0/TlhesV5CjoI/AAAAAAAAAHs/juJDBlwiGZk/s400/Image%2B%255B1%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;which is the output after compiling the WebAPI.csproj with target build configuration "Debug".&lt;br /&gt;&lt;br /&gt;note the OutputPath from the "Project Properties" panel. The output goes to:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;.\Help\&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This is the directory to which we'll make link in Hudson for the API documentation of our project once the documentation is generated. That way we'll publish the generated from the continuous integration API documentation as a web-site.&lt;br /&gt;&lt;br /&gt;file &lt;b&gt;run-fxcop.bat&lt;/b&gt; - a batch command to run FxCop from Hudson. Example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;FxCopCmd.exe /file:WebAPI\bin\Debug\WebAPI.dll  /rule:DesignRules.dll /out:fxcop-result.xml&lt;br /&gt;&lt;br /&gt;exit 0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;note it takes the Debug output from the the WebAPI project and the output of running the FxCop application goes to file fxcop-result.xml. &lt;br /&gt;&lt;br /&gt;file &lt;b&gt;run-gendarme.bat&lt;/b&gt; - a batch command to run Gendarme from Hudson. Example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;gendarme.exe --xml gendarme-result.xml WebAPI\bin\Debug\WebAPI.dll&lt;br /&gt;&lt;br /&gt;exit 0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;note it takes the Debug output from the the WebAPI project and the output of running the Gendarme application goes to file gendarme-result.xml&lt;br /&gt;&lt;br /&gt;file &lt;b&gt;run-nunit.bat&lt;/b&gt; - a batch command to run NUnit tests from Hudson.&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;nunit-console-x86.exe WebAPITests\bin\WebAPITests.exe /xml=nunit-result.xml&lt;br /&gt;&lt;br /&gt;exit 0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;note it takes the Debug output from the the WebAPI project and the output of running the NUnit console goes to file nunit-result.xml&lt;br /&gt;&lt;br /&gt;file &lt;b&gt;run-sandcastle.bat&lt;/b&gt; - a batch command to generate documentation&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;MSBuild.exe /p:CopyrightText="Copyright Company" /p:FeedbackEMailAdress="address@company.com" WebAPI.shfbproj&lt;br /&gt;&lt;br /&gt;exit 0&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;note we specify the MSBuild from the version 4.0 of Dot.NET and as a project file for the build project we point to the file WebAPI.shfbproj&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;And here we've got structure similar to this:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-EIe4SiYjoSg/TlhfPrz7VaI/AAAAAAAAAH0/MR3O6j1Af2Q/s1600/Image%2B%255B2%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="400" width="371" src="http://4.bp.blogspot.com/-EIe4SiYjoSg/TlhfPrz7VaI/AAAAAAAAAH0/MR3O6j1Af2Q/s400/Image%2B%255B2%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;All the output xml files from the batch commands will be used by Hudson to show us results of running unit tests, checking code style, etc.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Installing Hudson: Installation&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;At this point we are ready to install the Hudson. We'll install Hudson as a Windows service on Windows.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Prepare working directory&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Create directory &lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Hudson&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In this directory Hudson will be installed. From the Windows control panel set up system environment variable:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;HUDSON_HOME=C:\Hudson&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Open new command prompt and test the new variable:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\&gt;echo %HUDSON_HOME%&lt;br /&gt;C:\Hudson&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In this directory Hudson will check out from Subversion our code and will run the jobs to compile and run unit tests. So, this will be the Hudson's working directory. There Hudson will accumulate files with historical information.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install Hudson&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Create directory where to install the Hudson server:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Program Files (x86)\Hudson&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Download into this directory the latest version of Hudson from:&lt;br /&gt;http://java.net/projects/hudson/downloads/download/war/hudson-2.1.0.war&lt;br /&gt;&lt;br /&gt;Note: you can always upgrade Hudson automatically to the latest version directly from the Hudson's web console - after the Hudson installed as windows service.&lt;br /&gt;&lt;br /&gt;Rename the file as removing the version information from the file name. Check the install directory of the Hudson server:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;C:\Users\Administrator&gt;dir "C:\Program Files (x86)\Hudson"&lt;br /&gt;08/20/2011  09:24 AM    &amp;lt;DIR&amp;gt;          .&lt;br /&gt;08/20/2011  09:24 AM    &amp;lt;DIR&amp;gt;          ..&lt;br /&gt;08/20/2011  09:23 AM        38,948,136 hudson.war&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Run Hudson&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Now open a command prompt and go to this directory, run the Hudson server from there:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;java -jar hudson.war&lt;br /&gt;C:\Program Files (x86)\Hudson&gt;java -jar hudson.war&lt;br /&gt;Running from: C:\Program Files (x86)\Hudson\hudson.war&lt;br /&gt;[Winstone 2011/08/20 14:11:50] - Beginning extraction from war file&lt;br /&gt;Aug 20, 2011 2:11:52 PM hudson.WebAppMain contextInitialized&lt;br /&gt;It will start doing  thinks, just wait until it says: "Completed initialization".&lt;br /&gt;...&lt;br /&gt;INFO: Home directory: C:\Hudson&lt;br /&gt;...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;note: look on the log messages, somewhere at the beginning it should say:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;hudson home directory: C:\Hudson&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Hudson will start by default HTTP web server on port 8080, open the following URL into your web browser, this is the Hudson's console there:&lt;br /&gt;http://localhost:8080&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install as windows service&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Click on Hudson/Manage Hudson, then on “Install as Windows Service”. It will take time to finish.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-o4Rrd_CFu6Q/TlhgsfUs3SI/AAAAAAAAAH8/Ca4i3PK7PDM/s1600/Image%2B%255B3%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="170" width="400" src="http://4.bp.blogspot.com/-o4Rrd_CFu6Q/TlhgsfUs3SI/AAAAAAAAAH8/Ca4i3PK7PDM/s400/Image%2B%255B3%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;Watch the application on the command prompt, it will restart as windows service. After the installation complete confirm to restart.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-GldSn3h7Q0Y/TlhgyBcTTgI/AAAAAAAAAIE/wx-eCRwXqAM/s1600/Image%2B%255B4%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="178" width="400" src="http://2.bp.blogspot.com/-GldSn3h7Q0Y/TlhgyBcTTgI/AAAAAAAAAIE/wx-eCRwXqAM/s400/Image%2B%255B4%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;You can close the window with the command prompt. From here on only work happens on the web interface of Hudson!&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Note: You can delete the service using this command:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;sc delete hudson&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note: Later you can always upgrade to the latest version your copy of Hudson.&lt;br /&gt;&lt;br /&gt;From the web console of Hudson go to Hudson\Manage Hudson and click on "Upgrade Automatically".&lt;br /&gt;Wait for Hudson to finish the installation.&lt;br /&gt;Click on "Restart when no jobs are running".&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Install Plug-Ins&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Go to Hudson\Manage Hudson and click on Manage Plugins. Click on "Available" and select:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;MSBuild Plugin&lt;br /&gt;NAnt Plugin&lt;br /&gt;NUnit Plugin&lt;br /&gt;Analysis Collector Plugin&lt;br /&gt;Static Code Analysis Plug-ins&lt;br /&gt;Task Scanner Plugin&lt;br /&gt;Violations&lt;br /&gt;Warnings Plugin&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Scroll down the page and click on "Install". After Hudson installed all those plugins, click on "Restart when no jobs are running".&lt;br /&gt;&lt;br /&gt;Go to Hudson\Manage Hudson\Pugin Manager, open tab Installed and check if all these Plugins are installed:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-lKUbGBVI_bI/TlhhFai--DI/AAAAAAAAAIM/lSYXgEuD6TI/s1600/Image%2B%255B5%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="400" width="374" src="http://2.bp.blogspot.com/-lKUbGBVI_bI/TlhhFai--DI/AAAAAAAAAIM/lSYXgEuD6TI/s400/Image%2B%255B5%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Go to Hudson\Manage Hudson and click on "Configure System".&lt;br /&gt;Scroll down to "MSBuild Builder" and click on "Add".&lt;br /&gt;&lt;br /&gt;Write for name "MSBuild Dot.NET 4.0".&lt;br /&gt;Write for path the full path name of the msbuild.exe file for Dot.NET 4.0, in our case it was &lt;br /&gt;&lt;pre class="javascript" name="code"&gt;"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;You can add for other Dot.NET frameworks if you need. Later from the concrete jobs you'll use them as appropriate in your case.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-bYnfNmSFOi4/TlhheGYPLOI/AAAAAAAAAIU/wJsdWEcxQc8/s1600/Image%2B%255B6%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="274" width="400" src="http://2.bp.blogspot.com/-bYnfNmSFOi4/TlhheGYPLOI/AAAAAAAAAIU/wJsdWEcxQc8/s400/Image%2B%255B6%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Scroll down, click "Save".&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Configure Hudson: Add Jobs&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Now we can add our project for continuous integration as a job on the Hudson server.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Continuous build&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;This is a build which will be checking every minute for changes in the Subversion repository, if they are some changes will check out the latest changes, build our project and run the unit tests.&lt;br /&gt;&lt;br /&gt;Click on Hudson\New job. Set the name of the job, in this example "WebAPI continuous build" and select the option "Build a free-style software project". Click on "OK".&lt;br /&gt;&lt;br /&gt;In section "&lt;b&gt;Source Code Management&lt;/b&gt;" select "Subversion". Set the Repository URL as appropriate.  &lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-QDSkakmdD8o/Tlhhzo1i6YI/AAAAAAAAAIc/fgbRfouoj-Q/s1600/Image%2B%255B7%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="261" width="400" src="http://3.bp.blogspot.com/-QDSkakmdD8o/Tlhhzo1i6YI/AAAAAAAAAIc/fgbRfouoj-Q/s400/Image%2B%255B7%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;Move the focus to another field. Hudson will try to access your Subversion server and if the authentication failed will show red colored message next to the text box with the repositiry URL. The message should contain an html link "enter credentials". Click the link and follow the instructions. Eventually you'll be able to give your user name and password if you choose this form of authentication. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-67A4A8Tm__s/Tlhh7LL5MNI/AAAAAAAAAIk/okcl3YVzmMo/s1600/Image%2B%255B8%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="174" width="400" src="http://4.bp.blogspot.com/-67A4A8Tm__s/Tlhh7LL5MNI/AAAAAAAAAIk/okcl3YVzmMo/s400/Image%2B%255B8%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;Once you successfully finish this, you'll come back to the previous page.&lt;br /&gt;&lt;br /&gt;In section "&lt;b&gt;Build Triggers&lt;/b&gt;" select "Poll SCM" and specify "*/1 * * * *" to check every minute for changes in the source repository.&lt;br /&gt;&lt;br /&gt;In section "&lt;b&gt;Buld&lt;/b&gt;" click on "Add build step", then "Build a Visual Studio project or solution using MSBuild". Select/write (we are following the example file and VS project names from above):&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;MsBuild Version   : MS Buld Dot.NET 4.0&lt;br /&gt;MsBuild Build File :  WebAPI.sln&lt;br /&gt;Command line arguments :  /p:Configuration=DEBUG&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Click on "Add build step", then on "Execute Windows batch command". Write:&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;run-nunit.bat&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-li1I1YRpodk/TlhiQTn2BtI/AAAAAAAAAIs/b_1tlwSmN-o/s1600/Image%2B%255B9%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="271" width="400" src="http://2.bp.blogspot.com/-li1I1YRpodk/TlhiQTn2BtI/AAAAAAAAAIs/b_1tlwSmN-o/s400/Image%2B%255B9%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;In section "&lt;b&gt;Post-build Actions&lt;/b&gt;" select "Publish NUnit test result report and enter for "Test report XMLs:&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;nunit-result.xml&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-KmtLPSq-p4g/TlhiihCRGAI/AAAAAAAAAI0/B4RA3horI6Y/s1600/Image%2B%255B10%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="209" width="400" src="http://2.bp.blogspot.com/-KmtLPSq-p4g/TlhiihCRGAI/AAAAAAAAAI0/B4RA3horI6Y/s400/Image%2B%255B10%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;Click on Save to save the job. In short time Hudson should start a build for this job. If the build failed, check the "Console Output" from the job menus.&lt;br /&gt;&lt;br /&gt;Note: you can at any time schedule run for a job. Go to the home page of the tool, click on the link to the job "WebAPI continuous build", from the left-side menus click on "Build now".&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-Q9A5IRQ711A/TlhiomW31OI/AAAAAAAAAI8/5_DXThigWS0/s1600/Image%2B%255B11%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="276" width="400" src="http://4.bp.blogspot.com/-Q9A5IRQ711A/TlhiomW31OI/AAAAAAAAAI8/5_DXThigWS0/s400/Image%2B%255B11%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;You can check the result of your unit tests from the link "Latest Test Result". Also you can browse your source code tree from the "Workspace" link and check for latest changes from the link "Resent Changes".&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now that we added a build project we've got nice dashboard on the home page of our Hudson server:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-Bif6-sJGHEE/TlhiyVuVZRI/AAAAAAAAAJE/5G1V23JQgb8/s1600/Image%2B%255B12%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="145" width="400" src="http://1.bp.blogspot.com/-Bif6-sJGHEE/TlhiyVuVZRI/AAAAAAAAAJE/5G1V23JQgb8/s400/Image%2B%255B12%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;b&gt;Extended build&lt;/b&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;This is a build which will run once in a day and will run code-style checks and will create documentation for the API.&lt;br /&gt;&lt;br /&gt;Click on Hudson\New job. Set the name of the job, in this example "WebAPI extended build" and select the option "Build a free-style software project". Click on "OK".&lt;br /&gt;&lt;br /&gt;In section "&lt;b&gt;Source Code Management&lt;/b&gt;" select "Subversion". Set the Repository URL as appropriate.  &lt;br /&gt;&lt;br /&gt;Move the focus to another field. Hudson will try to access your Subversion server and if the authentication failed will show red colored message next to the text box with the repositiry URL. The message should contain an html link "enter credentials". Click the link and follow the instructions. Eventually you'll be able to give your user name and password if you choose this form of authentication. Once you successfully finish this, you'll come back to the previous page.&lt;br /&gt;&lt;br /&gt;In section "&lt;b&gt;Build Triggers&lt;/b&gt;" select "Build periodically" and specify "40 02 * * *" - just an example - to run the job once a day at 02:40 PM.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;In section "&lt;b&gt;Buld&lt;/b&gt;" click on "Add build step", then "Build a Visual Studio project or solution using MSBuild". Select/write (we are following the example file and VS project names from above):&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;MsBuild Version   : MS Buld Dot.NET 4.0&lt;br /&gt;MsBuild Build File :  WebAPI\WebAPI.csproj&lt;br /&gt;Command line arguments :  /p:Configuration=DEBUG&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note: this only is going to build the project with production code, we don't need to build the complete Visual Studio solution, but won't be wrong as well.&lt;br /&gt;&lt;br /&gt;Add one after other the following Windows batch commands clicking on the button "Add build steps" as "Execute Windows batch command":&lt;br /&gt;&lt;br /&gt;&lt;pre class="javascript" name="code"&gt;run-fxcop.bat&lt;br /&gt;&lt;br /&gt;run-gendarme.bat&lt;br /&gt;&lt;br /&gt;run-sandcastle.bat&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-_d5R75q8AGU/TlhjO9Z1IMI/AAAAAAAAAJM/ss5LBCbPsSU/s1600/Image%2B%255B13%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="302" width="400" src="http://3.bp.blogspot.com/-_d5R75q8AGU/TlhjO9Z1IMI/AAAAAAAAAJM/ss5LBCbPsSU/s400/Image%2B%255B13%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;From the "&lt;b&gt;Post-build Actions&lt;/b&gt;" section  select "&lt;i&gt;Publish Javadoc&lt;/i&gt;" and enter "help" as "Javadoc directory".&lt;br /&gt;&lt;br /&gt;Then select "&lt;i&gt;Report Violations&lt;/i&gt;" and configure the rows for fxcop and gendarme reports as appropriate. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-lxnrDeEvIa0/Tlhje-0ry0I/AAAAAAAAAJU/Cl1_tZMJseo/s1600/Image%2B%255B14%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="384" width="400" src="http://1.bp.blogspot.com/-lxnrDeEvIa0/Tlhje-0ry0I/AAAAAAAAAJU/Cl1_tZMJseo/s400/Image%2B%255B14%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;Click on "Save" button down the page.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Click on "Build now" from the left-side menus of the project. &lt;br /&gt;&lt;br /&gt;Once the build finished you can check for the generated documentation and the code violations.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-zUtYlaPopr0/TlhjlPo8GxI/AAAAAAAAAJc/-r6uWGO_Jc8/s1600/Image%2B%255B15%255D.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="252" width="400" src="http://3.bp.blogspot.com/-zUtYlaPopr0/TlhjlPo8GxI/AAAAAAAAAJc/-r6uWGO_Jc8/s400/Image%2B%255B15%255D.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;Take some time to explore both of them, you'll find very useful suggestions in there.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Hudson: Links&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Hudson CI Server: http://hudson-ci.org/&lt;br /&gt;FxCop: http://msdn.microsoft.com/en-us/library/bb429476%28v=vs.80%29.aspx&lt;br /&gt;NUnit: http://www.nunit.org/&lt;br /&gt;&lt;br /&gt;Links to some of the Plugins we mentioned:&lt;br /&gt;MSBuild Plugin: http://wiki.hudson-ci.org/display/HUDSON/MSBuild+Plugin&lt;br /&gt;NAnt Plugin: http://wiki.hudson-ci.org//display/HUDSON/NAnt+Plugin&lt;br /&gt;NUnit Plugin: http://wiki.hudson-ci.org//display/HUDSON/NUnit+Plugin&lt;br /&gt;Analysis Collector: http://wiki.hudson-ci.org//display/HUDSON/Analysis+Collector+Plugin&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-Hudson-Installation-and-Configuration-for-DotNET-Projects-blog-about-programming"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2011%2F08%2Fhudson-installation-and-configuration.html" style="border:0px"/&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-8351296234889066206?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/8351296234889066206/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2011/08/hudson-installation-and-configuration.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/8351296234889066206'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/8351296234889066206'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2011/08/hudson-installation-and-configuration.html' title='Hudson: Installation and Configuration for Dot.NET Projects'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-R9l0JoJoyyw/TlhePHifOII/AAAAAAAAAHk/_tr5wDve08g/s72-c/Image.png' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-5089133458482156847</id><published>2011-02-03T18:00:00.000-08:00</published><updated>2011-08-29T07:03:03.183-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='TDD'/><title type='text'>TDD with jsTestDriver - find image size with Java Script</title><content type='html'>In my &lt;a href="http://atanashristov.blogspot.com/2011/02/tdd-with-yui-3-find-image-size-with.html"&gt;last post&lt;/a&gt; I created small java script function that finds the size of image by URL. I used &lt;span style="font-weight:bold;"&gt;YUI 3 test framework&lt;/span&gt; for doing unit tests while I worked on that function.&lt;br /&gt;&lt;br /&gt;Because YUI 3 test framework is in-browser framework we are facing the challenge how to automate our unit tests and how to apply &lt;span style="font-weight:bold;"&gt;TDD&lt;/span&gt; with &lt;span style="font-weight:bold;"&gt;automated continuous build&lt;/span&gt; and &lt;span style="font-weight:bold;"&gt;automated continuous integration&lt;/span&gt;. As we  have to manually re-run tests it is a challenge to keep testing our java script on several web browsers on different platforms.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;jsTestDriver&lt;/span&gt; is automation tool for unit testing for java script. It is a server written in Java. From several several browsers you open URL hosted on the jsTestDriver server. The jsTestDriver can then automatically re-run the unit tests whenever they are some changes in the source code and thereof shows if the unit tests failed or passed on the currently connected web browsers. That way you can test as many as you like &lt;span style="font-weight:bold;"&gt;combinations of browsers and platforms&lt;/span&gt; in an automated way. &lt;br /&gt;&lt;br /&gt;I'll be working on Linux for the examples, but the jsTestDriver works on Windows too. Also, it is always a good idea to develop your java script libraries outside your web projects and ideally to use in your web projects already tested, optimized and minified java script file.&lt;br /&gt;&lt;br /&gt;The installation of jsTestDriver is very simple. Download the jar file from the project's web site:&lt;br /&gt;http://js-test-driver.googlecode.com/files/JsTestDriver-1.2.2.jar&lt;br /&gt;&lt;br /&gt;Just copy the jar file on directory where it is convenient for you.  Here is a snipped from my directory structure:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/bin$ ls&lt;br /&gt;compiler.jar  JsTestDriver-1.2.2.jar  SoyToJsSrcCompiler.jar&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;You should export environment variable &lt;span style="font-weight:bold;"&gt;$JSTESTDRIVER_HOME&lt;/span&gt; (%JSTESTDRIVER_HOME% on Windows, go to My Computer -&gt; Properties -&gt; System -&gt; Advanced and change the Environment Variables to make the changes permanent).&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/bin$ cat ~/.bashrc | tail -n 7&lt;br /&gt;&lt;br /&gt;export PATH=".:$HOME/bin:$PATH:/var/lib/gems/1.9.1/bin"&lt;br /&gt;export JSBIN="$HOME/Desktop/Projects/js/bin"&lt;br /&gt;export JSTESTDRIVER_HOME="$JSBIN"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The directory structure for our small project looks like this:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/proj/play$ ls&lt;br /&gt;build  deps  jsTestDriver.conf  src  test&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As I mentioned in my &lt;a href="http://atanashristov.blogspot.com/2011/02/tdd-with-yui-3-find-image-size-with.html"&gt;last post&lt;/a&gt; &lt;span style="font-style:italic;"&gt;build&lt;/span&gt; you can ignore, I normally have &lt;span style="font-style:italic;"&gt;build&lt;/span&gt; directory where I would generate minified, tested java script - the stuff that I'll be using in my web project. We don't need the &lt;span style="font-style:italic;"&gt;deps&lt;/span&gt; folder this time, as we will not have any dependencies on 3rd party java script.&lt;br /&gt;&lt;br /&gt;The file &lt;span style="font-weight:bold;"&gt;jsTestDriver.conf&lt;/span&gt; is a configuration file for the jsTestDriver with the following content:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/proj/play$ cat jsTestDriver.conf&lt;br /&gt;server: http://localhost:4224&lt;br /&gt;&lt;br /&gt;load:&lt;br /&gt;- src/*.js&lt;br /&gt;- test/*.js&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It states, we'll run the jsTestDriver on port 4224, the server will load all the java script files from directories src and test. All the load paths are relative to the directory where the jsTestDriver.conf  file is. Please note that the order the directories and file names are important.  In our case the jsTestDriver will first load the source code java script files, then the unit test java script files. More information for the jsTestDriver configuration file you can find on the projects wiki page:&lt;br /&gt;&lt;br /&gt;http://code.google.com/p/js-test-driver/wiki/ConfigurationFile&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;src&lt;/span&gt; - this directory holds just one java script file in which is the source code of function &lt;span style="font-weight:bold;"&gt;ImgSize()&lt;/span&gt; &lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/proj/play$ cat src/ImgSize.js&lt;br /&gt;/**&lt;br /&gt;* Calculate the size of image.&lt;br /&gt;* @param {string} url Url of the image which size to find&lt;br /&gt;* @param {function(number, number)} onSizeCalculated Callback function to run once&lt;br /&gt;*   the size of the image calculated&lt;br /&gt;*/&lt;br /&gt;function ImgSize(url, onSizeCalculated) {&lt;br /&gt;&lt;br /&gt;// Once the image is loaded, the calls the callback function onSizeCalculated&lt;br /&gt;function setDimensions() {&lt;br /&gt;// scope changed: this = Image object&lt;br /&gt;if (onSizeCalculated) {&lt;br /&gt;onSizeCalculated(this.width, this.height);&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Initialization:&lt;br /&gt;// - sets callback on image loaded - setDimensions;&lt;br /&gt;// - loads the image.&lt;br /&gt;function init() {&lt;br /&gt;var img = new Image();&lt;br /&gt;img.name = url;&lt;br /&gt;img.onload = setDimensions;&lt;br /&gt;img.src = url;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Run initialization&lt;br /&gt;init();&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This is the same function that we developed and tested with the &lt;span style="font-weight:bold;"&gt;YUI 3 test framework&lt;/span&gt; in my &lt;a href="http://atanashristov.blogspot.com/2011/02/tdd-with-yui-3-find-image-size-with.html"&gt;last post&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;test&lt;/span&gt; is the directory where the java script files with the unit tests are&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/proj/play$ ls test/&lt;br /&gt;ImgSize  ImgSize.html  ImgSize-test.js&lt;br /&gt;ahristov@medion:~/Desktop/Projects/js/proj/play$ ls test/ImgSize&lt;br /&gt;137x38.gif&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;File ImgSize.html is from my last post, you can ignore it for now. The file 137x38.gif is an image with the size 137px / 38px which I'll use for the purpose of the unit testing.&lt;br /&gt;&lt;br /&gt;If we were about to test synchronous java script we would use the traditional &lt;span style="font-weight:bold;"&gt;TestCase&lt;/span&gt; runner. Our ImgSize-test.js would look like:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;// holds tests for the ImgSize() function&lt;br /&gt;//&lt;br /&gt;TestCase("ImgSizeTest", {&lt;br /&gt;"test image size should be 137x38": function() {&lt;br /&gt;new ImgSize('http://192.168.1.4:8080/js/proj/play/test/ImgSize/137x38.gif',&lt;br /&gt;function assertOnSizeCalculated(width, height) {&lt;br /&gt;assertEquals(137, width);&lt;br /&gt;assertEquals( 38, height);&lt;br /&gt;})&lt;br /&gt;}&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;How that we are going to test asynchronous calls we should use the &lt;span style="font-weight:bold;"&gt;AsyncTestCase&lt;/span&gt; runner, so that our ImgSize-test.js contains:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;var ImgSizeTest = AsyncTestCase('ImgSizeTest');&lt;br /&gt;&lt;br /&gt;ImgSizeTest.prototype.testImgSizeFunction = function(queue) {&lt;br /&gt;&lt;br /&gt;expectAsserts(2);&lt;br /&gt;&lt;br /&gt;var onSizeCalculated = queue.add(function() {&lt;br /&gt;assertEquals(137, arguments[0][0]);&lt;br /&gt;assertEquals( 38, arguments[0][1]);&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;new ImgSize('http://192.168.1.4:8080/js/proj/play/test/ImgSize/137x38.gif',&lt;br /&gt;onSizeCalculated);&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The queue parameter accepts inline function via method add(), the function will run whenever the browser downloaded the image and calculated the size of the image.&lt;br /&gt;&lt;br /&gt;As you can see, the image file should be accessible from URL from the testing browsers, so I just put the gif image on web server on the following URL above. Keep in mind, you have to adjust that the way you need it.&lt;br /&gt;&lt;br /&gt;The syntax is very similar to &lt;span style="font-weight:bold;"&gt;YUI 3 test&lt;/span&gt; and even simpler. Whenever the browser loaded the image, we are going to check if the ImgSize() function gets the proper image size information. Please note that we are not dealing with DOM and UI. If you want to test DOM operations you can add HTML to the unit test files, for more information check the wiki pages of the &lt;span style="font-weight:bold;"&gt;jsTestDriver&lt;/span&gt; project:&lt;br /&gt;&lt;br /&gt;http://code.google.com/p/js-test-driver/wiki/HtmlDoc&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The page containing documentation for asynchronous unit tests with jsTestDriver is:&lt;br /&gt;http://code.google.com/p/js-test-driver/wiki/AsyncTestCase &lt;br /&gt;&lt;br /&gt;How it is time to start the jsTestDriver server:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~$ java -jar $JSTESTDRIVER_HOME/JsTestDriver-1.2.2.jar --port 4224&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Next step is to open the URL where the jsTestDriver server is listening:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_pNNYA7XMbCI/TUtg4NXub9I/AAAAAAAAAEw/DOj8JOt7dzk/s1600/jsTestDriver01.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 352px; height: 224px;" src="http://4.bp.blogspot.com/_pNNYA7XMbCI/TUtg4NXub9I/AAAAAAAAAEw/DOj8JOt7dzk/s400/jsTestDriver01.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5569651882951864274" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Enter the URL to the server in the web browser and click in "Capture This Browser"&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_pNNYA7XMbCI/TUthDXvYarI/AAAAAAAAAE4/xhJQCruMRLo/s1600/jsTestDriver02.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 183px;" src="http://3.bp.blogspot.com/_pNNYA7XMbCI/TUthDXvYarI/AAAAAAAAAE4/xhJQCruMRLo/s400/jsTestDriver02.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5569652074714000050" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;This browser started waiting for automation from the server to run unit tests. Let's add another browser to the testing:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_pNNYA7XMbCI/TUthON9mSYI/AAAAAAAAAFA/ULpo8SYJsGI/s1600/jsTestDriver03.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 363px; height: 400px;" src="http://4.bp.blogspot.com/_pNNYA7XMbCI/TUthON9mSYI/AAAAAAAAAFA/ULpo8SYJsGI/s400/jsTestDriver03.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5569652261067835778" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Clicking on "Capture This Browser":&lt;br /&gt;&lt;br /&gt;Connect several web browsers to the jsTestDriver server. &lt;br /&gt;&lt;br /&gt;As we are ready to start our unit tests, we have to first run the jsTestDriver server. From the directory where the configuration file jsTestDriver.conf is we run:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/proj/play$ java -jar $JSTESTDRIVER_HOME/JsTestDriver-1.2.2.jar --tests all&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Which gets the following output:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_pNNYA7XMbCI/TUthi3YtaOI/AAAAAAAAAFI/5NcEHVccm48/s1600/jsTestDriver04.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 58px;" src="http://2.bp.blogspot.com/_pNNYA7XMbCI/TUthi3YtaOI/AAAAAAAAAFI/5NcEHVccm48/s400/jsTestDriver04.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5569652615784786146" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The test passed on 3 different browsers.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now, how to repeat the tests automatically whenever the source code of our java script changed? &lt;br /&gt;&lt;br /&gt;If you have Ruby installed on your system, you can install the &lt;span style="font-weight:bold;"&gt;jstdutil&lt;/span&gt; package:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;gem install jstdutil&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It provides a wrapper to jsTestDriver so instead of writing every time this long command lines on the shell, you just - from the directory where the jsTestDriver.conf file is run:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;ahristov@medion:~/Desktop/Projects/js/proj/play$ jsautotest&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Every time we do changes on our java script source code the jsTestDriver will automatically start doing the unit tests and then will report the result:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_pNNYA7XMbCI/TUth6h-8jxI/AAAAAAAAAFQ/Jub4CAmMZ7s/s1600/jsTestDriver05.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 314px;" src="http://4.bp.blogspot.com/_pNNYA7XMbCI/TUth6h-8jxI/AAAAAAAAAFQ/Jub4CAmMZ7s/s400/jsTestDriver05.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5569653022356442898" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Let's change the test, make the test fail, change the following line:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;assertEquals( 38, arguments[0][1]);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;to&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;assertEquals( 39, arguments[0][1]);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;as the jsautotest is running. At the moment we save the javascript file, jsautotest automatically re-runs the tests sending the appropriate command to the jsTestDriver server and all currently captured browsers start running the tests. We get error in our tests and the jsautotest console explains this with output similar to:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_pNNYA7XMbCI/TUtiQy-5wnI/AAAAAAAAAFY/kOf1ihX-jWE/s1600/jsTestDriver06.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 84px;" src="http://2.bp.blogspot.com/_pNNYA7XMbCI/TUtiQy-5wnI/AAAAAAAAAFY/kOf1ihX-jWE/s400/jsTestDriver06.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5569653404876784242" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Changing the assert back from 39 to 38 in the ImgSize-test.js makes jsautotest again to re-run the tests on the jsTestDr4iver server, and this time they successfully pass.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The &lt;span style="font-weight:bold;"&gt;jsTestDriver&lt;/span&gt; project has the following URL:&lt;br /&gt;http://code.google.com/p/js-test-driver/&lt;br /&gt;&lt;br /&gt;The home page of the &lt;span style="font-weight:bold;"&gt;jstdutil&lt;/span&gt; Ruby package:&lt;br /&gt;http://cjohansen.no/en/javascript/jstdutil_a_ruby_wrapper_over_jstestdriver &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2011%2f02%2ftdd-with-jstestdriver-find-image-size.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url%3Dhttp%253a%252f%252fatanashristov.blogspot.com%252f2011%252f02%252ftdd-with-jstestdriver-find-image-size.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-TDD-with-jsTestDriver-find-image-size-with-Java-Script-blog-about-programming"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2011%2F02%2Ftdd-with-jstestdriver-find-image-size.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-5089133458482156847?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/5089133458482156847/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2011/02/tdd-with-jstestdriver-find-image-size.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/5089133458482156847'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/5089133458482156847'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2011/02/tdd-with-jstestdriver-find-image-size.html' title='TDD with jsTestDriver - find image size with Java Script'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_pNNYA7XMbCI/TUtg4NXub9I/AAAAAAAAAEw/DOj8JOt7dzk/s72-c/jsTestDriver01.png' height='72' width='72'/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-2232385676076098987</id><published>2011-02-02T18:10:00.000-08:00</published><updated>2011-02-03T15:11:08.582-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='TDD'/><title type='text'>TDD with YUI 3 - find image size with Java Script</title><content type='html'>&lt;span style="font-weight: bold;"&gt;Finding size of image using java script&lt;/span&gt; involves asynchronous techniques and callback functions. I'm showing  how the in-browser &lt;span style="font-weight: bold;"&gt;YUI 3 test framework&lt;/span&gt; can be used for &lt;span style="font-weight: bold;"&gt;TDD&lt;/span&gt;.  They are other options for in-browser test frameworks like QUnit and JsUnit, the techniques here should be equally usable.&lt;br /&gt;&lt;br /&gt;I came across the need to find the size of image given by URL and using java script. The task was about scaling the width and the height of html  elements proportionally for the needs of the UI and accordingly to the size of the image.&lt;br /&gt;&lt;br /&gt;To find the size of image you have to first wait until the image downloaded - unless the image is in the browser's cache. Once the image downloaded and loaded into Image object in java script you can check for the size.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Let's first specify the desired java script function. Let's name it &lt;span style="font-style: italic;"&gt;ImgSize()&lt;/span&gt; with the following signature:&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;  function ImgSize(url, onSizeCalculated)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Parameter &lt;span style="font-style: italic;"&gt;url&lt;/span&gt; is the url to the image to look for&lt;br /&gt;Parameter &lt;span style="font-style: italic;"&gt;onSizeCalculated &lt;/span&gt;is a reference to callback function to call once the image downloaded and we have calculated the size of the image. The callback function - once the size of the image is calculated - will receive two numeric arguments: the width and height - the size of the image.&lt;br /&gt;&lt;br /&gt;For the directory structure of this project I'll suggest working directory with the following &lt;span style="font-style: italic;"&gt;subdirectories&lt;/span&gt;:&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;    ahristov@medion:~/Desktop/Projects/js/proj/play$ ls&lt;br /&gt;    build  deps  src  test&lt;br /&gt;&lt;/pre&gt;I usually start with similar directory structure (well, not to mention for things like tags, branches, revisions, etc.  but that's another theme :-).&lt;br /&gt;The subdirectory &lt;span style="font-style: italic;"&gt;build&lt;/span&gt; I use to save the output of my work. In our example you can just ignore it.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;deps/yui&lt;/span&gt; - contains the complete YUI3 library. Again, we'll be using only the test framework from the YUI. The test framework you'll find in the following subdirectory:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;  ahristov@medion:~/Desktop/Projects/js/proj/play$ ls deps/yui/build/test/&lt;br /&gt;  assets  test-debug.js  test.js  test-min.js&lt;br /&gt;&lt;/pre&gt;&lt;span style="font-weight: bold;"&gt;test&lt;/span&gt; - this directory contains the HTML test fixture for the &lt;span style="font-style: italic;"&gt;ImgSize()&lt;/span&gt; function. It is a html file that hosts the java script unit tests. Also there is a gif image with the size of 137px / 38px in subdirectory test/ImgSize the size of which will be calculated from the unit tests and against this we'll be checking how the &lt;span style="font-style: italic;"&gt;ImgSize()&lt;/span&gt; function works.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;  ahristov@medion:~/Desktop/Projects/js/proj/play$ ls test&lt;br /&gt;  ImgSize  ImgSize.html&lt;br /&gt;  ahristov@medion:~/Desktop/Projects/js/proj/play$ ls test/ImgSize&lt;br /&gt;  137x38.gif&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;src&lt;/span&gt; - this directory holds just one java script file in which is the source code of function &lt;span style="font-style: italic;"&gt;ImgSize()&lt;/span&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;  ahristov@medion:~/Desktop/Projects/js/proj/play$ ls src&lt;br /&gt;  ImgSize.js&lt;br /&gt;&lt;/pre&gt;I'll show you first the content of the test fixture - the html document  &lt;span style="font-style: italic;"&gt;ImgSize.html&lt;/span&gt; from my test suite:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;  ahristov@medion:~/Desktop/Projects/js/proj/play$ cat test/ImgSize.html&lt;br /&gt;  &amp;lt;html&amp;gt;&lt;br /&gt;  &amp;lt;head&amp;gt;&lt;br /&gt;    &amp;lt;script type="text/javascript" charset="utf-8" src="../deps/yui/build/yui/yui-min.js"&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;    &amp;lt;script type="text/javascript" charset="utf-8" src="../src/ImgSize.js"&amp;gt;&amp;lt;/script&amp;gt;&lt;br /&gt;  &amp;lt;/head&amp;gt;&lt;br /&gt;  &amp;lt;body&amp;gt;&lt;br /&gt;    &amp;lt;script type="text/javascript"&amp;gt;&lt;br /&gt;    &lt;br /&gt;      // Create new YUI instance, and populate it with the required modules&lt;br /&gt;      YUI().use('console', 'test', function(Y) {&lt;br /&gt;      &lt;br /&gt;        Y.namespace("ImgSize.Test");&lt;br /&gt;        &lt;br /&gt;        Y.ImgSize.Test.ImgSizeTestCase = new Y.Test.Case({&lt;br /&gt;        &lt;br /&gt;          name: "Test image size",&lt;br /&gt;          &lt;br /&gt;          test137x98 : function () {&lt;br /&gt;              new ImgSize('./ImgSize/137x38.gif',&lt;br /&gt;                function assertOnSizeCalculated(width, height) {&lt;br /&gt;                  Y.Assert.areEqual(137, width, "Width should be same");&lt;br /&gt;                  Y.Assert.areEqual( 38, height, "Height should be same");&lt;br /&gt;                });&lt;br /&gt;              }&lt;br /&gt;          });&lt;br /&gt;&lt;br /&gt;        Y.Test.Runner.add(Y.ImgSize.Test.ImgSizeTestCase);&lt;br /&gt;        &lt;br /&gt;        //run the tests&lt;br /&gt;        Y.Test.Runner.run();&lt;br /&gt;        &lt;br /&gt;      });&lt;br /&gt;  &amp;lt;/script&amp;gt;&lt;br /&gt;  &amp;lt;/body&amp;gt;&lt;br /&gt;  &amp;lt;/html&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Into the head section I added script link to the YUI library &lt;span style="font-weight: bold;"&gt;yui-min.js&lt;/span&gt; and another script link to the &lt;span style="font-weight: bold;"&gt;ImgSize.js&lt;/span&gt; - the file where the source code of the function under test - ImgSize() - will be.&lt;br /&gt;&lt;br /&gt;As you can see, the html markup is very basic. The only content of the &lt;span style="font-weight: bold;"&gt;body &lt;/span&gt;tag - just &lt;span style="font-weight: bold;"&gt;before closing&lt;/span&gt; it - is a script tag where the unit tests are.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;YUI.use('console', 'test'&lt;/span&gt; -  The YUI has a very powerful modular structure. The use() function fetches for us only the functionality we'll need without downloading for us complete framework . So we only include the test runner console and the test framework. That is the only we'll fetch out of the whole YUI framework whenever the browser opens the html page with the unit tests. I really like the modularity of frameworks like &lt;span style="font-weight: bold;"&gt;YUI &lt;/span&gt;or &lt;span style="font-weight: bold;"&gt;Closure&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Y.namespace()&lt;/span&gt; - this is very useful feature of the YUI library that helps you to organize your code into namespaces. We are not going into more details concerning the YUI namespaces in this example.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;new Y.Test.Case()&lt;/span&gt; creates an instance of test case. The test case will be named "Test image size". After the name of the test case we define one or more unit tests - functions as named properties.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;test137x98&lt;/span&gt; -  this is the only test  in this test case - we ask the ImgSize() function to calculate the size of the image 137x38.gif giving as a callback function assertion function. Whenever the image downloaded and the size of the image calculated, the assertion function will be invoked and will run as YUI test.&lt;br /&gt;&lt;br /&gt;You probably will recognize many similarities between YUI test and frameworks like nUnit of Junit. You can for example also specify "setUp" or "tearDown" functions. Besides this the YUI test framework also gives you &lt;span style="font-weight: bold;"&gt;mocking&lt;/span&gt;, &lt;span style="font-weight: bold;"&gt;asynchronous tests&lt;/span&gt;, etc. It is a very nice library.&lt;br /&gt;&lt;br /&gt;In case we were testing DOM manipulations and more UI stuff, then we would add HTML markup for that. In this case we are dealing with pure java script function and the abilities of the Image java script object.&lt;br /&gt;&lt;br /&gt;The YUI test won't be so good in case we want to automate and run our tests frequently on rich set of browsers. In such cases we would be using automated testing frameworks like &lt;span style="font-weight: bold;"&gt;jsTestDriver &lt;/span&gt;for example.&lt;br /&gt;&lt;br /&gt;Finally here is the source code of the &lt;span style="font-weight: bold;"&gt;ImgSize()&lt;/span&gt; function:&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;  ahristov@medion:~/Desktop/Projects/js/proj/play$ cat src/ImgSize.js&lt;br /&gt;  /**&lt;br /&gt;  * Calculate the size of image.&lt;br /&gt;  * @param {string} url Url of the image which size to find&lt;br /&gt;  * @param {function(number, number)} onSizeCalculated Callback function to run once&lt;br /&gt;  *   the size of the image calculated&lt;br /&gt;  */&lt;br /&gt;  function ImgSize(url, onSizeCalculated) {&lt;br /&gt;  &lt;br /&gt;    // Once the image is loaded, the calls the callback function onSizeCalculated&lt;br /&gt;    function setDimensions() {&lt;br /&gt;      // scope changed: this = Image object&lt;br /&gt;      if (onSizeCalculated) {&lt;br /&gt;       onSizeCalculated(this.width, this.height);&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    // Initialization:&lt;br /&gt;    // - sets callback on image loaded - setDimensions;&lt;br /&gt;    // - loads the image.&lt;br /&gt;    function init() {&lt;br /&gt;      var img = new Image();&lt;br /&gt;      img.name = url;&lt;br /&gt;      img.onload = setDimensions;&lt;br /&gt;      img.src = url;&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    // Run initialization&lt;br /&gt;    init();&lt;br /&gt;  };&lt;br /&gt;&lt;/pre&gt;The first action that happens inside ImgSize() is into the &lt;span style="font-style: italic;"&gt;Init()&lt;/span&gt; function. We create object of type Image and before the assignment to property src we make sure we have assigned &lt;span style="font-weight: bold;"&gt;Image.onload&lt;/span&gt; event handler. Once the image is loaded, we check if onSizeCalculated callback was sent and call the callback function - see function &lt;span style="font-style: italic;"&gt;setDimensions()&lt;/span&gt;. In our case is will be unit test assertion.&lt;br /&gt;&lt;br /&gt;We just have to open the html test fixture file into our web browser. Here's how the test report looks in Chrome's Developer Tools. You should watch the results of the unit test execution into the console window:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_pNNYA7XMbCI/TUoRrYcl6aI/AAAAAAAAAEc/cIu5X6z96x4/s1600/YUI3-image-size.png"&gt;&lt;br /&gt;  &lt;img style="display: block; margin: 0px auto 10px; text-align: center; cursor: pointer; width: 400px; height: 215px;" src="http://3.bp.blogspot.com/_pNNYA7XMbCI/TUoRrYcl6aI/AAAAAAAAAEc/cIu5X6z96x4/s400/YUI3-image-size.png" alt="" id="BLOGGER_PHOTO_ID_5569283326191462818" border="0" /&gt;&lt;br /&gt;&lt;/a&gt;&lt;br /&gt;More information for the YUI test framework you'll find here:&lt;br /&gt;&lt;br /&gt;http://developer.yahoo.com/yui/3/test/&lt;br /&gt;&lt;br /&gt;The YUI Test is part of the Yahoo! User Interface Library and I'll be using version 3 of the YUI. To download the YUI 3 go to the following URL:&lt;br /&gt;&lt;br /&gt;http://developer.yahoo.com/yui/3/&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2011%2f02%2ftdd-with-yui-3-find-image-size-with.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url%3Dhttp%253a%252f%252fatanashristov.blogspot.com%252f2011%252f02%252ftdd-with-yui-3-find-image-size-with.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-TDD-with-YUI-3-find-image-size-with-Java-Script-blog-about-programming"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2011%2F02%2Ftdd-with-yui-3-find-image-size-with.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-2232385676076098987?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/2232385676076098987/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2011/02/tdd-with-yui-3-find-image-size-with.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/2232385676076098987'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/2232385676076098987'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2011/02/tdd-with-yui-3-find-image-size-with.html' title='TDD with YUI 3 - find image size with Java Script'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_pNNYA7XMbCI/TUoRrYcl6aI/AAAAAAAAAEc/cIu5X6z96x4/s72-c/YUI3-image-size.png' height='72' width='72'/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-4790674631724765743</id><published>2010-03-15T10:05:00.000-07:00</published><updated>2010-03-15T10:29:58.879-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>Design Patterns – State Pattern</title><content type='html'>The &lt;a href="http://en.wikipedia.org/wiki/State_pattern"&gt;&lt;b&gt;State design pattern&lt;/b&gt;&lt;/a&gt; is a behavioural pattern. The behaviour of object changes accordingly to its internal state. Instead of implementing if-then-else like structure inside the object to switch the behaviour, we move the logic to property "State" which has method Handle() and call this method. We change the behaviour of the object as we just switch the value of the "State" property.&lt;br /&gt;&lt;br /&gt;The class which behaviour will change accordingly to its state is named &lt;b&gt;Context&lt;/b&gt;. The Context class contains property &lt;b&gt;State&lt;/b&gt; which is of type that implements common &lt;b&gt;IState&lt;/b&gt; interface. &lt;br /&gt;&lt;br /&gt;We have different implementations of IState - StateOne, StateTwo etc. We assign new IState object to the property "State" of the Context object and the behaviour of the Context object changes.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Traffic Light&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Imagine we are going to implement traffic light. Accordingly to &lt;a href="http://en.wikipedia.org/wiki/Traffic_light"&gt;Wikipedia&lt;/a&gt; we have three possible lights: red; amber and green. The traffic light cycle may vary, but we are going to implement 3-way traffic light cycle. &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;u&gt;Red light&lt;/u&gt; - Means prohibits the traffic from proceeding.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;u&gt;Green light&lt;/u&gt; - Then follows the green light that allows to proceed.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;u&gt;Yellow light&lt;/u&gt; - Next is yellow light denoting if safe to, prepare to stop.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;We will use the State pattern to implement a traffic light. The traffic light (TrafficLight) object is the context object. The traffic light has public properties for the color of the light currently turned on, it knows for how long this light should stay, and knows light of which color will follow after that. But setting these properties is done by State object.&lt;br /&gt;&lt;br /&gt;We have 3 different states for the three traffic light colors. All they have method Handle() which is invoked by the TrafficLight object.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;IState interface&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;All the concrete State classes have to implement interface ITrafficLightState. The concrete traffic light state handles request from the Context object and thereof the behaviour of the Context object changes.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;        interface ITrafficLightState&lt;br /&gt;        {&lt;br /&gt;            void Handle(TrafficLight trafficLight);&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;State implementations&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;For the different traffic light colors we implement three different State objects. All they implement interface ITrafficLightState:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;        // State "Red Light"&lt;br /&gt;        class RedLightState : ITrafficLightState&lt;br /&gt;        {&lt;br /&gt;            public void Handle(TrafficLight trafficLight)&lt;br /&gt;            {&lt;br /&gt;                trafficLight.Color = "Red"; // Switch the traffic light color&lt;br /&gt;                trafficLight.Pause = 5; // For 5 seconds&lt;br /&gt;                trafficLight.NextState = new GreenLightState(); // Then green light follows&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // State "Amber Light"&lt;br /&gt;        class AmberLightState : ITrafficLightState&lt;br /&gt;        {&lt;br /&gt;            public void Handle(TrafficLight trafficLight)&lt;br /&gt;            {&lt;br /&gt;                trafficLight.Color = "Amber"; // Switch the traffic light color&lt;br /&gt;                trafficLight.Pause = 2; // For 2 seconds&lt;br /&gt;                trafficLight.NextState = new RedLightState(); // Then red light follows&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // State "Green Light"&lt;br /&gt;        class GreenLightState : ITrafficLightState&lt;br /&gt;        {&lt;br /&gt;            public void Handle(TrafficLight trafficLight)&lt;br /&gt;            {&lt;br /&gt;                trafficLight.Color = "Green"; // Switch the traffic light color&lt;br /&gt;                trafficLight.Pause = 5; // For 5 seconds&lt;br /&gt;                trafficLight.NextState = new AmberLightState(); // Then Amber light follows&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;TrafficLight context object&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;How we are ready to implement the TrafficLight context object:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;        // Context - "Traffic Light", has internal state - one of the above.&lt;br /&gt;        // The behaviour changes accordingly to the current state&lt;br /&gt;        class TrafficLight&lt;br /&gt;        {&lt;br /&gt;            // Has properties that define it's behaviour&lt;br /&gt;            public int Pause { get; set; }&lt;br /&gt;            public string Color { get; set; }&lt;br /&gt;&lt;br /&gt;            // Has internal State&lt;br /&gt;            public ITrafficLightState NextState { get; set; }&lt;br /&gt;&lt;br /&gt;            // Sets the default state&lt;br /&gt;            public TrafficLight()&lt;br /&gt;            {&lt;br /&gt;                this.NextState = new RedLightState();&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            // Receives request ...&lt;br /&gt;            public void Request()&lt;br /&gt;            {&lt;br /&gt;                // ... then:&lt;br /&gt;                // Delegates to the internal State to handle.&lt;br /&gt;                NextState.Handle(this);&lt;br /&gt;&lt;br /&gt;                // The behaviour has changed, color, time of light, etc.&lt;br /&gt;                Console.WriteLine(Color);&lt;br /&gt;                System.Threading.Thread.Sleep(Pause * 1000);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And with this we are ready to give a try of our implementation, which looks like this now:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_pNNYA7XMbCI/S55rutUwfJI/AAAAAAAAAEI/ebf0-C5-qH8/s1600-h/State.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 201px;" src="http://3.bp.blogspot.com/_pNNYA7XMbCI/S55rutUwfJI/AAAAAAAAAEI/ebf0-C5-qH8/s400/State.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5448911049349692562" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;To demonstrate the traffic light we run an infinite loop and call the method Request() on instance of TrafficLight:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            // Demonstrate how TrafficLight works&lt;br /&gt;            TrafficLight trafficLight = new TrafficLight();&lt;br /&gt;            while (true)&lt;br /&gt;                trafficLight.Request();&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Usage of State pattern&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;In our example the state of the Context object was changed from the state object itself. But it is not necessarily to be done this way. We can implement a Coffee Machine to run Short, Tall, Grand coffee.  Then the state would be changed pressing a button on the Machine. Or we could use State pattern to switch between simple and advanced preview on a form. Then probably the Handle() function will just change the preview but not the user preferences.&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2010%2f03%2fdesign-patterns-state-pattern.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fatanashristov.blogspot.com%2f2010%2f03%2fdesign-patterns-state-pattern.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-Design-Patterns-State-Pattern"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2010%2F03%2Fdesign-patterns-state-pattern.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-4790674631724765743?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/4790674631724765743/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2010/03/design-patterns-state-pattern.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4790674631724765743'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4790674631724765743'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2010/03/design-patterns-state-pattern.html' title='Design Patterns – State Pattern'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_pNNYA7XMbCI/S55rutUwfJI/AAAAAAAAAEI/ebf0-C5-qH8/s72-c/State.png' height='72' width='72'/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-7537595785779039358</id><published>2010-01-04T10:17:00.000-08:00</published><updated>2010-01-21T00:34:13.804-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='SQLite'/><category scheme='http://www.blogger.com/atom/ns#' term='NHibernate'/><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>Implementing and Using Repositories with NHibernate</title><content type='html'>Following the podcasts of the &lt;a href=”http://blog.wekeroad.com/mvc-storefront”&gt;MVC Storefront Project &lt;/a&gt; at the time learning the ASP.NET MVC framework was for me really good introduction to the ideas of the Domain Driven Design (&lt;a href=”http://en.wikipedia.org/wiki/Domain_driven_design”&gt;DDD&lt;/a&gt;). &lt;br /&gt;&lt;br /&gt;Now, months later and still new to the DDD, but very enthusiastic, I’ll try to sketch some ideas I learned so far and in practice to implement a complete example. In particular I’ll be utilizing the Repository pattern and implement it with NHibernate as data access framework. I’m using NHibernate but I keep in mind to provide a layer of abstraction and to make it possible to switch to another data access provider (Entity Framework for example).&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Repository Pattern&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Accordingly to &lt;a href=”http://martinfowler.com/eaaCatalog/repository.html”&gt;Martin Fowler&lt;/a&gt;:&lt;br /&gt;&lt;br /&gt;“A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers“.&lt;br /&gt;&lt;br /&gt;The Repository encapsulates the actual storage and querying and keeps the client to focus on the model. We can use dependency injection and inversion of control to switch real and fake repositories for the needs of testing. We have also all the querying logic in centralized part of the application and it makes the support easier. Our application depends on simple in-memory collections, etc.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Business Model&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;We have pretty simple bookstore model. We have only two kinds of objects: &lt;b&gt;Books&lt;/b&gt; and &lt;b&gt;Authors&lt;/b&gt;. A book can be written by one or many authors. One author can take part of writing one or more books. So, the relation between them is many-to-many.&lt;br /&gt;&lt;br /&gt;The final database model could be similar to this:&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_pNNYA7XMbCI/S0IxHMlEFrI/AAAAAAAAACo/vRY3DcXUT7U/s1600-h/ERD1.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 385px; height: 259px;" src="http://1.bp.blogspot.com/_pNNYA7XMbCI/S0IxHMlEFrI/AAAAAAAAACo/vRY3DcXUT7U/s400/ERD1.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5422950901013026482" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Domain Entity Objects and Approval Services&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;In DDD &lt;b&gt;Entity&lt;/b&gt; is an object fundamentally defined by &lt;a href=”http://domaindrivendesign.org/node/109”&gt;thread of continuity and identity&lt;/a&gt;. &lt;br /&gt;&lt;br /&gt;&lt;b&gt;Value object&lt;/b&gt; is then an object that has properties (shapes) and does not have identity. Usually these are read-only object we use as data transfer object (DTO).&lt;br /&gt;&lt;br /&gt;In an “ideal” world the entity objects does not have properties, but exposes operations (methods). To change the internal state of entity object we call its methods and send there value objects as parameters.&lt;br /&gt;&lt;br /&gt;In this example our entity objects will have properties and we directly will access them to change the information contained in our entities.&lt;br /&gt;&lt;br /&gt;When changing the properties of the entity objects we’ll need a possibility to validate the state of the entity object. We use the &lt;u&gt;validation&lt;/u&gt; for example to show the end user an error message and prevent storing object to the database if it does not have valid state. The book object for example should have a title. We need a way the entity does validation of itself. Also, same entity object can be valid in one context, but in another context with same containing data to be invalid. We’ll inject a &lt;u&gt;validator&lt;/u&gt; object that will implement the rules of the validation.&lt;br /&gt;&lt;br /&gt;The validator object is kind of a &lt;b&gt;Service&lt;/b&gt; object and is an operation. It does not belong to any object, but just checks if the properties of the entity object pass some rules. The dependency injection will be exposed via property which we name “&lt;b&gt;Approval&lt;/b&gt;”.&lt;br /&gt;&lt;br /&gt;The &lt;b&gt;EntityBase&lt;/b&gt; class is from where all our entities will inherit:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    /// &amp;lt;summary&amp;gt;&lt;br /&gt;    /// EntityBase represents objects primary defined by it's identity (Id).&lt;br /&gt;    /// The type of the identity, usually but not necessariily is of &lt;br /&gt;    /// type integer and is automatically assigned primary key.&lt;br /&gt;    /// &lt;br /&gt;    /// All of the domain entities inherit this base class.&lt;br /&gt;    /// All of the domain entities have an identity and are able&lt;br /&gt;    /// to state if the data they contain is valid.&lt;br /&gt;    /// &lt;br /&gt;    /// To check if the entity object contains valid data, they expose &lt;br /&gt;    /// property named Approval which is a concrete implementation of&lt;br /&gt;    /// ApprovalBase. The entity's Validate() method just wraps&lt;br /&gt;    /// the Approval.Validate(). The validation of entity returns list &lt;br /&gt;    /// of error messages and there is also a shortcut methnod IsValid()&lt;br /&gt;    /// which just gives back true if the validation was successful &lt;br /&gt;    /// or false if the validation has failed.&lt;br /&gt;    /// &lt;br /&gt;    /// The entity objects implement IComparable interface and equality tests.&lt;br /&gt;    /// The have Equals() method to check if two variables point to same instance &lt;br /&gt;    /// of the same entity class and also they have equality operators that check&lt;br /&gt;    /// if the IDs are same.&lt;br /&gt;    /// &amp;lt;/summary&amp;gt;&lt;br /&gt;    public abstract class EntityBase&amp;lt;TIdentity&amp;gt; where TIdentity : IComparable&lt;br /&gt;    {&lt;br /&gt;        // Gets or sets the identity.&lt;br /&gt;        public virtual TIdentity Id { get; set; }&lt;br /&gt;&lt;br /&gt;        protected EntityBase(TIdentity Id) { this.Id = Id; }&lt;br /&gt;&lt;br /&gt;        protected EntityBase() { }&lt;br /&gt;&lt;br /&gt;        // Approval object that does the validation.&lt;br /&gt;        public abstract ApprovalBase Approval { get; set; }&lt;br /&gt;&lt;br /&gt;        // Validation&lt;br /&gt;        public virtual IList&amp;lt;String&amp;gt; Validate()&lt;br /&gt;        {&lt;br /&gt;            if (Approval != null)&lt;br /&gt;                return Approval.Validate(this);&lt;br /&gt;            else&lt;br /&gt;                return new List&amp;lt;String&amp;gt;();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Validation shortcut&lt;br /&gt;        public virtual bool IsValid()&lt;br /&gt;        {&lt;br /&gt;            return (Validate().Count == 0);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        // Equality tests /////////////&lt;br /&gt;&lt;br /&gt;        // Determines whether the specified entity parameter&lt;br /&gt;        /// is equal to the current object (is the same reference)&lt;br /&gt;        public override bool Equals(object entity)&lt;br /&gt;        {&lt;br /&gt;            if (entity == null || !(entity is EntityBase&amp;lt;TIdentity&amp;gt;))&lt;br /&gt;                return false;&lt;br /&gt;&lt;br /&gt;            return (this == (EntityBase&amp;lt;TIdentity&amp;gt;)entity);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Check if two entities have same ID&lt;br /&gt;        public static bool operator ==(EntityBase&amp;lt;TIdentity&amp;gt; entity1, EntityBase&amp;lt;TIdentity&amp;gt; entity2)&lt;br /&gt;        {&lt;br /&gt;            object obj1 = entity1 as object;&lt;br /&gt;            object obj2 = entity2 as object;&lt;br /&gt;&lt;br /&gt;            if ((obj1 == null) &amp;&amp; (obj2 == null))&lt;br /&gt;                return true;&lt;br /&gt;&lt;br /&gt;            if ((obj1 == null) || (obj2 == null))&lt;br /&gt;                return false;&lt;br /&gt;&lt;br /&gt;            if (entity1.GetType() != entity2.GetType())&lt;br /&gt;                return false;&lt;br /&gt;&lt;br /&gt;            if (entity1.Id.CompareTo(entity2.Id) != 0)&lt;br /&gt;                return false;&lt;br /&gt;&lt;br /&gt;            return true;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Check if two entities have different ID&lt;br /&gt;        public static bool operator !=(EntityBase&amp;lt;TIdentity&amp;gt; entity1, EntityBase&amp;lt;TIdentity&amp;gt; entity2)&lt;br /&gt;        {&lt;br /&gt;            return (!(entity1 == entity2));&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // GetHashCode() if the Id.&lt;br /&gt;        public override int GetHashCode() { return this.Id.GetHashCode(); }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Then we inject an approval object to our entities and the approval objects inherit from &lt;b&gt;ApprovalBase&lt;/b&gt;:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    /// &amp;lt;summary&amp;gt;&lt;br /&gt;    /// The entity objects have property based&lt;br /&gt;    /// dependency injection with approval object.&lt;br /&gt;    /// &lt;br /&gt;    /// If the entity has approval object,&lt;br /&gt;    /// the entity can be validated to prevent saving&lt;br /&gt;    /// entities with incorrect values, or to inform the &lt;br /&gt;    /// end user that the data he has entered is invalid.&lt;br /&gt;    /// &lt;br /&gt;    /// The validation can be changed according to the context&lt;br /&gt;    /// the entity is in. In one situation the entity may be valid, but&lt;br /&gt;    /// in other situation the same entity with same properties&lt;br /&gt;    /// may not be valid.&lt;br /&gt;    /// &lt;br /&gt;    /// The ApprovalBase is an abstract class from wich the concrete approval&lt;br /&gt;    /// classes will inherit. The ApprovalBase has method Validate wich returns &lt;br /&gt;    /// List of ApprovalErrorMessage error messages.&lt;br /&gt;    /// &amp;lt;/summary&amp;gt;&lt;br /&gt;    public abstract class ApprovalBase&lt;br /&gt;    {&lt;br /&gt;        public abstract IList&amp;lt;String&amp;gt; Validate&amp;lt;TEntity&amp;gt;(TEntity entity);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Finder Objects&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;I found the ideas from Russell East’s blog &lt;a href="http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/"&gt;"Implementing the Repository and Finder patterns"&lt;/a&gt; to be very promising and I think it is a very advanced way of implementing repositories.&lt;br /&gt; &lt;br /&gt;For the original idea, please refer to:&lt;br /&gt;&lt;br /&gt;http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/&lt;br /&gt;&lt;br /&gt;I'm just following the same pattern here. The querying repositories depend on finder and persistence repositories.&lt;br /&gt;&lt;br /&gt;One goals of Russell's idea is to keep independent from concrete Object Relational Mapper (ORM). Other goal is to have typed repositories - one per entity - and thereof make it possible to inject finder objects to the repositories. Also, he makes possible to inject the concrete persistance layer via inversion of control and provides fully testable implementation of repository.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;All the entity finders extend a base &lt;b&gt;IEntityFinder&lt;/b&gt; interface. The generic type is constrained by the EntityBase type.&lt;br /&gt;The IEntityFinder interface is not to be used directly, but to be extended by typed Repository interfaces.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public interface IFinder&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;        where TEntity : EntityBase&amp;lt;TIdentity&amp;gt;&lt;br /&gt;        where TIdentity : IComparable&lt;br /&gt;    {&lt;br /&gt;        // Has a DataSource property of IQueryable on which &lt;br /&gt;        // we use LINQ for quering.&lt;br /&gt;        IQueryable&amp;lt;TEntity&amp;gt; DataSource { get; set; }&lt;br /&gt;&lt;br /&gt;        /// Get count of objects/records.&lt;br /&gt;        int Count();&lt;br /&gt;&lt;br /&gt;        /// Find by id. We have entityConcrete = repositoryConcrete.Find.ById(123) like usage.&lt;br /&gt;        TEntity ById(TIdentity id);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;All the finder object inherit from &lt;b&gt;FinderBase&lt;/b&gt; class. The Finder objects implement search logic/functions using LINQ. The classes inherited from RepositoryBase (see below) have then object Find, which method names by convention look like "ById", "ByName", etc.  The concrete finders have to implement at least ById method.&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    public abstract class FinderBase&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;        : IFinder&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;        where TEntity : EntityBase&amp;lt;TIdentity&amp;gt;&lt;br /&gt;        where TIdentity : IComparable&lt;br /&gt;    {&lt;br /&gt;        public IQueryable&amp;lt;TEntity&amp;gt; DataSource { get; set; }&lt;br /&gt;&lt;br /&gt;        /// Gets count of records.&lt;br /&gt;        public int Count()&lt;br /&gt;        {&lt;br /&gt;            return DataSource.Count();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        /// Find one entity by ID.&lt;br /&gt;        public abstract TEntity ById(TIdentity id);&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Base Repository Class&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Let’s first define how the concrete persistence layer should look like.&lt;br /&gt; &lt;br /&gt;The concrete ORM specific implementation is abstracted with interface &lt;b&gt;IPersistor&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;The repository takes care for querying; the persistence repository takes care for persistence and depends on ORM specific implementation.&lt;br /&gt;&lt;br /&gt;The basic operations in the contract declared by this interface are: get entity by id; save entity to persist; delete entity from persist repository; get the query object on top of which to implement concrete LINQ queries.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public interface IPersistor&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        TEntity Get(TIdentity id);&lt;br /&gt;        void Save(TEntity entity);&lt;br /&gt;        void Delete(TEntity entity);&lt;br /&gt;        IQueryable&amp;lt;TEntity&amp;gt; Query();&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now we are about to finish the base repository class.&lt;br /&gt;&lt;br /&gt;All the repositories extend a base &lt;b&gt;IRepository&lt;/b&gt; interface. The generic type is restricted to be EntityBase type.&lt;br /&gt;The basic operations in the contract are much the same like the defined in IPersistor, but we don't expose IQueryable to public, as we implement all the querying logic into the concrete repositories.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public interface IRepository&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;        where TEntity : EntityBase&amp;lt;TIdentity&amp;gt;&lt;br /&gt;        where TIdentity : IComparable&lt;br /&gt;    {&lt;br /&gt;        TEntity Get(TIdentity id);&lt;br /&gt;        IList&amp;lt;String&amp;gt; Save(TEntity entity);&lt;br /&gt;        void Delete(TEntity entity);&lt;br /&gt;        // hidden // IQueryable&amp;lt;TEntity&amp;gt; Query();&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The &lt;b&gt;RepositoryBase&lt;/b&gt; is an abstract class from which all concrete repositories inherit from.&lt;br /&gt;The repositories are injected with concrete entity types using the typed interface, so we have one repository per entity.&lt;br /&gt;The repository class must be supplied an instance of IPersistor and an instance of IFinder.&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public abstract class RepositoryBase&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;        : IRepository&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;        where TEntity : EntityBase&amp;lt;TIdentity&amp;gt;&lt;br /&gt;        where TIdentity : IComparable&lt;br /&gt;    {&lt;br /&gt;        private readonly IPersistor&amp;lt;TEntity, TIdentity&amp;gt; persistor;&lt;br /&gt;        public IPersistor&amp;lt;TEntity, TIdentity&amp;gt; Persistor { get { return persistor; } }&lt;br /&gt;&lt;br /&gt;        private readonly IFinder&amp;lt;TEntity, TIdentity&amp;gt; finder;&lt;br /&gt;        public IFinder&amp;lt;TEntity, TIdentity&amp;gt; Finder { get { return finder; } }&lt;br /&gt;&lt;br /&gt;        private RepositoryBase() { }&lt;br /&gt;&lt;br /&gt;        public RepositoryBase(&lt;br /&gt;            IPersistor&amp;lt;TEntity, TIdentity&amp;gt; persistor,&lt;br /&gt;            IFinder&amp;lt;TEntity, TIdentity&amp;gt; finder)&lt;br /&gt;        {&lt;br /&gt;            this.persistor = persistor;&lt;br /&gt;            this.finder = finder;&lt;br /&gt;            this.finder.DataSource = Query();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Get entity by ID&lt;br /&gt;        public virtual TEntity Get(TIdentity id)&lt;br /&gt;        {&lt;br /&gt;            return persistor.Get(id);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        /// &amp;lt;summary&amp;gt;&lt;br /&gt;        /// Validate and Save the entity. If the validation failed, will not save the entity,&lt;br /&gt;        /// but returns back list of error messages.&lt;br /&gt;        /// &amp;lt;/summary&amp;gt;&lt;br /&gt;        public virtual IList&amp;lt;String&amp;gt; Save(TEntity entity)&lt;br /&gt;        {&lt;br /&gt;            if (entity == null)&lt;br /&gt;                throw new ArgumentNullException("entity");&lt;br /&gt;&lt;br /&gt;            IList&amp;lt;String&amp;gt; errors = entity.Validate();&lt;br /&gt;&lt;br /&gt;            if (errors.Count == 0)&lt;br /&gt;                persistor.Save(entity);&lt;br /&gt;&lt;br /&gt;            return errors;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Delete entity from persistance repository&lt;br /&gt;        public virtual void Delete(TEntity entity)&lt;br /&gt;        {&lt;br /&gt;            if (entity == null)&lt;br /&gt;                throw new ArgumentNullException("entity");&lt;br /&gt;&lt;br /&gt;            persistor.Delete(entity);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        /// Gets IQueryable which we use from the concrete&lt;br /&gt;        /// implementation of repository to implement our &lt;br /&gt;        /// query methods (FindBy).&lt;br /&gt;        protected IQueryable&amp;lt;TEntity&amp;gt; Query()&lt;br /&gt;        {&lt;br /&gt;            return persistor.Query();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;The Book Store Model –Entities and Approvals&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;At this point I’ll define the book store model, its entities, and approval objects.&lt;br /&gt;&lt;br /&gt;The &lt;b&gt;Book&lt;/b&gt; object has along with title, publisher info, ISBN also a list of one or many authors.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public class Book : EntityBase&amp;lt;int&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        public Book() : base() &lt;br /&gt;        {&lt;br /&gt;            this.Authors = new List&amp;lt;Author&amp;gt;();&lt;br /&gt;        }&lt;br /&gt;        public Book(int id) : this() { Id = id; }&lt;br /&gt;        public override ApprovalBase Approval { get; set; }&lt;br /&gt;&lt;br /&gt;        public virtual string Title { get; set; }&lt;br /&gt;        public virtual string Publisher { get; set; }&lt;br /&gt;        public virtual string ISBN { get; set; }&lt;br /&gt;&lt;br /&gt;        public virtual IList&amp;lt;Author&amp;gt; Authors { get; private set; }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;An &lt;b&gt;Author&lt;/b&gt; have a name and also eventually takes part on writing several books.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public class Author : EntityBase&amp;lt;int&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        public Author() : base() &lt;br /&gt;        {&lt;br /&gt;            this.Books = new List&amp;lt;Book&amp;gt;();&lt;br /&gt;        }&lt;br /&gt;        public Author(int id) : this() { Id = id; }&lt;br /&gt;        public override ApprovalBase Approval { get; set; }&lt;br /&gt;&lt;br /&gt;        public virtual string Name { get; set; }&lt;br /&gt;        public virtual IList&amp;lt;Book&amp;gt; Books { get; private set; }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Please note that the properties of the entities are marked as “&lt;b&gt;virtual&lt;/b&gt;” as it is required by NHibernate.&lt;br /&gt;&lt;br /&gt;How let’s create some approval services. Again – we can switch the approval the entity has even at run time as we have property injection implemented in our entities and they don’t depend on concrete approval services. If we set the approval of the entity to null, the validation will be successful regardless the data the entity contains.&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;To check if Book object contains valid data we implement &lt;b&gt;BookApproval&lt;/b&gt;. A Book should have title and at least one author.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public class BookApproval : ApprovalBase&lt;br /&gt;    {&lt;br /&gt;        public override IList&amp;lt;String&amp;gt; Validate&amp;lt;TEntity&amp;gt;(TEntity entity)&lt;br /&gt;        {&lt;br /&gt;            List&amp;lt;String&amp;gt; errors = new List&amp;lt;String&amp;gt;();&lt;br /&gt;            Book book = entity as Book;&lt;br /&gt;&lt;br /&gt;            if (book == null)&lt;br /&gt;                throw new ArgumentException("Entity not a book");&lt;br /&gt;&lt;br /&gt;            if (String.IsNullOrEmpty(book.Title))&lt;br /&gt;                errors.Add("Title can not be empty");&lt;br /&gt;&lt;br /&gt;            if ((book.Authors == null) || (book.Authors.Count == 0))&lt;br /&gt;                errors.Add("A book should have at least one author");&lt;br /&gt;&lt;br /&gt;            return errors;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To check if Author object contains valid data we implement &lt;b&gt;AuthorApproval&lt;/b&gt;. An Author should have name.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public class AuthorApproval : ApprovalBase&lt;br /&gt;    {&lt;br /&gt;        public override IList&amp;lt;String&amp;gt; Validate&amp;lt;TEntity&amp;gt;(TEntity entity)&lt;br /&gt;        {&lt;br /&gt;            List&amp;lt;String&amp;gt; errors = new List&amp;lt;String&amp;gt;();&lt;br /&gt;            Author author = entity as Author;&lt;br /&gt;&lt;br /&gt;            if (author == null)&lt;br /&gt;                throw new ArgumentException("Entity is not an author");&lt;br /&gt;&lt;br /&gt;            if (String.IsNullOrEmpty(author.Name))&lt;br /&gt;                errors.Add("Name can not be empty");&lt;br /&gt;&lt;br /&gt;            return errors;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Okay, sometimes they are some “no name” authors. If you think so, you still can create your own implementation of AuthorApproval service :-)&lt;br /&gt;&lt;h3&gt;The Book Store Model – Repositories and Finders&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;First we define interfaces which the client code will use when talking to the book store repositories.&lt;br /&gt;&lt;br /&gt;The &lt;b&gt;IBookFinder&lt;/b&gt; states that we should have one new method, not required by IFinder, and this is ByISBN(). &lt;br /&gt;The &lt;b&gt;IBookRepository&lt;/b&gt; exposes Find property of type IBookRepository.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public interface IBookFinder : IFinder&amp;lt;Book, int&amp;gt; &lt;br /&gt;    {&lt;br /&gt;        Book ByISBN(string ISBN); // adds new find methiod&lt;br /&gt;    }&lt;br /&gt;    public interface IBookRepository : IRepository&amp;lt;Book, int&amp;gt; &lt;br /&gt;    { &lt;br /&gt;        IBookFinder Find { get; }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Similarly the same way for the Author:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public interface IAuthorFinder : IFinder&amp;lt;Author, int&amp;gt; &lt;br /&gt;    {&lt;br /&gt;        Author ByName(string name);&lt;br /&gt;    }&lt;br /&gt;    public interface IAuthorRepository : IRepository&amp;lt;Author, int&amp;gt;&lt;br /&gt;    { &lt;br /&gt;        IAuthorFinder Find { get; } &lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Then we create concrete &lt;b&gt;BookFinder&lt;/b&gt; and &lt;b&gt;BookRepository&lt;/b&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public class BookFinder : FinderBase&amp;lt;Book, int&amp;gt;, IBookFinder&lt;br /&gt;    {&lt;br /&gt;        public override Book ById(int id)&lt;br /&gt;        {&lt;br /&gt;            return DataSource.Where(b =&amp;gt; b.Id == id).FirstOrDefault();&lt;br /&gt;        }&lt;br /&gt;        public Book ByISBN(string ISBN)&lt;br /&gt;        {&lt;br /&gt;            return DataSource.Where(b =&amp;gt; b.ISBN == ISBN).FirstOrDefault();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public class BookRepository : RepositoryBase&amp;lt;Book, int&amp;gt;, IBookRepository&lt;br /&gt;    {&lt;br /&gt;        public BookRepository(&lt;br /&gt;            IPersistor&amp;lt;Book, int&amp;gt; persistor,&lt;br /&gt;            IBookFinder entityFinder)&lt;br /&gt;            : base(persistor, entityFinder) { }&lt;br /&gt;&lt;br /&gt;        public IBookFinder Find&lt;br /&gt;        {&lt;br /&gt;            get { return (IBookFinder)Finder; }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;and also concrete &lt;b&gt;AuthorFinder&lt;/b&gt; and &lt;b&gt;AuthorRepository&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public class AuthorFinder : FinderBase&amp;lt;Author, int&amp;gt;, IAuthorFinder&lt;br /&gt;    {&lt;br /&gt;        public override Author ById(int id)&lt;br /&gt;        {&lt;br /&gt;            return DataSource.Where(a =&amp;gt; a.Id == id).FirstOrDefault();&lt;br /&gt;        }&lt;br /&gt;        public Author ByName(string name)&lt;br /&gt;        {&lt;br /&gt;            return DataSource.Where(a =&amp;gt; a.Name == name).FirstOrDefault();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public class AuthorRepository : RepositoryBase&amp;lt;Author, int&amp;gt;, IAuthorRepository&lt;br /&gt;    {&lt;br /&gt;        public AuthorRepository(&lt;br /&gt;            IPersistor&amp;lt;Author, int&amp;gt; persistor,&lt;br /&gt;            IAuthorFinder finder)&lt;br /&gt;            : base(persistor, finder) { }&lt;br /&gt;&lt;br /&gt;        public IAuthorFinder Find&lt;br /&gt;        {&lt;br /&gt;            get { return (IAuthorFinder)Finder; }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Book Store Model – External Dependencies&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Until now we have a model for our book store. This model is fully testable and we can test how it works and inject some stubs for finders, approvals, etc. if it is needed. Here we go further and finish our work as we implement the rest of the book store with some dependencies to external projects. We will use NHibernate as ORM and furthermore FluentNHibernate. We will use StructureMap for inversion of control. We will need few ADO.NET drivers for different databases, as we will be able to switch between them on demand. At the end we will create in memory SQLite database and test our book store..&lt;br /&gt;&lt;br /&gt;Download and unpack these files and add references from the solution explorer:&lt;br /&gt; &lt;br /&gt;Download: fluentnhibernate-binary-1.0.0.595.zip from http://fluentnhibernate.org/&lt;br /&gt;Referenced assemblies: Antlr3.Runtime.dll, Castle.Core.dll, Castle.DynamicProxy2.dll, FluentNHibernate.dll, Iesi.Collections.dll, NHibernate.dll, NHibernate.ByteCode.Castle.dll&lt;br /&gt;&lt;br /&gt;Download: NHibernate.Linq-1.0.0.GA-bin.zip from http://sourceforge.net/projects/nhibernate/files/&lt;br /&gt;Referenced assemblies: NHibernate.Linq.dll&lt;br /&gt;&lt;br /&gt;Download: SQLite-1.0.65.0-binaries.zip from http://sqlite.phxsoftware.com&lt;br /&gt;Referenced assemblies: System.Data.SQLite.DLL, System.Data.SQLite.Linq.dll&lt;br /&gt;&lt;br /&gt;Download: Npgsql2.0.7-bin-ms.net3.5sp1.zip from http://npgsql.projects.postgresql.org/&lt;br /&gt;Referenced assemblies: Npgsql.dll, Mono.Security.dll&lt;br /&gt;&lt;br /&gt;Download: StructureMap_2.5.3.zip from http://structuremap.sourceforge.net/Default.htm&lt;br /&gt;Referenced assemblies: StructureMap.dll&lt;br /&gt;&lt;br /&gt;Download: xunit-1.5.zip from http://www.codeplex.com/xunit&lt;br /&gt;Referenced assemblies: xunit.dll, xunit.extensions.dll&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Place the following “using” directives at the beginning of the code file:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;using NHibernate;&lt;br /&gt;using NHibernate.Cfg;&lt;br /&gt;using NHibernate.Linq;&lt;br /&gt;using NHibernate.Tool.hbm2ddl;&lt;br /&gt;using FluentNHibernate.Mapping;&lt;br /&gt;using FluentNHibernate.Cfg;&lt;br /&gt;using FluentNHibernate.Cfg.Db;&lt;br /&gt;using StructureMap;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Book Store Model – FluentNHibernate mappings&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;From the “Getting started” &lt;a href=”http://wiki.fluentnhibernate.org/Getting_started”&gt;wiki&lt;/a&gt; page of the of the Fluent NHibernate project:&lt;br /&gt;“Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents (.hbm.xml files), Fluent NHibernate lets you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code“.&lt;br /&gt;&lt;br /&gt;We create dedicated classes to map the book store entity objects to tables into the database. For the entity’s identity NHibernate will automatically create automatically generated (auto incremented) values. The mapper class derive from FluentNHibernate.Mapping .ClassMap&lt;T&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public sealed class BooksMap : ClassMap&amp;lt;Book&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        public BooksMap()&lt;br /&gt;        {&lt;br /&gt;            Id(x =&amp;gt; x.Id);&lt;br /&gt;            Map(x =&amp;gt; x.Title).Length(256).Default("").Not.Nullable();&lt;br /&gt;            Map(x =&amp;gt; x.Publisher).Length(256).Default("").Nullable();&lt;br /&gt;            Map(x =&amp;gt; x.ISBN).Length(16).Default("").Not.Nullable();&lt;br /&gt;            HasManyToMany(x =&amp;gt; x.Authors).LazyLoad();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    public sealed class AuthorsMap : ClassMap&amp;lt;Author&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        public AuthorsMap()&lt;br /&gt;        {&lt;br /&gt;            Id(x =&amp;gt; x.Id);&lt;br /&gt;            Map(x =&amp;gt; x.Name).Length(128).Default("").Not.Nullable();&lt;br /&gt;            HasManyToMany(x =&amp;gt; x.Books).LazyLoad();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Book Store Model –NHibernate Persistors&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;As we defined concrete repositories and finders for the book and author entities, still we don’t have concrete persistors. First we define base persistor which &lt;b&gt;depends on NHibernate&lt;/b&gt; (uses NHibernate.ISession, etc). Then we define the persistors for our entities.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    // Concrete NHibernate based persistance repository.&lt;br /&gt;    public abstract class PersistorBase&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;        : IPersistor&amp;lt;TEntity, TIdentity&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        protected ISession Session { get; set; }&lt;br /&gt;&lt;br /&gt;        public PersistorBase(ISession session)&lt;br /&gt;        {&lt;br /&gt;            Session = session;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public TEntity Get(TIdentity id)&lt;br /&gt;        {&lt;br /&gt;            return (TEntity)Session.Get(typeof(TEntity), id);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Save(TEntity entity)&lt;br /&gt;        {&lt;br /&gt;            Session.SaveOrUpdate(entity);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Delete(TEntity entity)&lt;br /&gt;        {&lt;br /&gt;            Session.Delete(entity);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public IQueryable&amp;lt;TEntity&amp;gt; Query()&lt;br /&gt;        {&lt;br /&gt;            var qry = from t in Session.Linq&amp;lt;TEntity&amp;gt;()&lt;br /&gt;                      select t;&lt;br /&gt;&lt;br /&gt;            return qry.AsQueryable();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Persistance repository for books.&lt;br /&gt;    public class BookPersistor : PersistorBase&amp;lt;Book, int&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        public BookPersistor(ISession session) : base(session) { }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Persistance repository for authors.&lt;br /&gt;    public class AuthorPersistor : PersistorBase&amp;lt;Author, int&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        public AuthorPersistor(ISession session) : base(session) { }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Book Store Model –NHibernate initialization&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;How comes stuff completely related to NHibernate and not directly to the book store model.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;BaseDatabase&lt;/b&gt; is wrapper class for NHibernate initialization - a class from which concrete per database driver/server implementations will be created.&lt;br /&gt;&lt;br /&gt;From this one we create implementation for Postgres, for MySQL, for SQLite, etc.&lt;br /&gt;Into the concrete implementations we switch drivers, connection string, etc.&lt;br /&gt;&lt;br /&gt;In Init() we open connection to the database.&lt;br /&gt;The BuildSchema() method creates the database tables, relations, etc.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public abstract class BaseDatabase : IDisposable&lt;br /&gt;    {&lt;br /&gt;        protected static Configuration configuration;&lt;br /&gt;        protected static ISessionFactory sessionFactory;&lt;br /&gt;&lt;br /&gt;        public ISession Session { get; protected set; }&lt;br /&gt;&lt;br /&gt;        /// Does initialization, run from the constructors of the inherited classes.&lt;br /&gt;        protected void Init()&lt;br /&gt;        {&lt;br /&gt;            sessionFactory = CreateSessionFactory();&lt;br /&gt;            Session = sessionFactory.OpenSession();&lt;br /&gt;            BuildSchema(Session);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected abstract ISessionFactory CreateSessionFactory();&lt;br /&gt;&lt;br /&gt;        private static void BuildSchema(ISession session)&lt;br /&gt;        {&lt;br /&gt;            SchemaExport schemaExport = new SchemaExport(configuration);&lt;br /&gt;            schemaExport.Execute(true, true, false, session.Connection, null);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void Dispose()&lt;br /&gt;        {&lt;br /&gt;            Session.Dispose();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And now I implement some concrete initializations per database driver/server:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    /// Database configured as in file SQLite database.&lt;br /&gt;    public class SQLiteInFileDatabase : BaseDatabase&lt;br /&gt;    {&lt;br /&gt;        public string FileName { get; private set; }&lt;br /&gt;&lt;br /&gt;        /// Create SQLite database with specified file name.&lt;br /&gt;        public SQLiteInFileDatabase(string fileName)&lt;br /&gt;        {&lt;br /&gt;            // file name to store the database, "database.db" for example.&lt;br /&gt;            FileName = fileName;&lt;br /&gt;&lt;br /&gt;            // does not run the base constructor, but calls Init() by itself.&lt;br /&gt;            Init(); &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected override ISessionFactory CreateSessionFactory()&lt;br /&gt;        {&lt;br /&gt;            return Fluently.Configure()&lt;br /&gt;                .Database(SQLiteConfiguration.Standard.UsingFile(FileName).ShowSql())&lt;br /&gt;                .Mappings(m =&amp;gt; m.FluentMappings.AddFromAssemblyOf&amp;lt;BooksMap&amp;gt;())&lt;br /&gt;                .ExposeConfiguration(Cfg =&amp;gt; configuration = Cfg)&lt;br /&gt;                .BuildSessionFactory();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    /// Database configured as in memory SQLite database.&lt;br /&gt;    public class SQLiteInMemoryDatabase : BaseDatabase&lt;br /&gt;    {&lt;br /&gt;        /// Create in memory SQLite database.&lt;br /&gt;        public SQLiteInMemoryDatabase()&lt;br /&gt;        {&lt;br /&gt;            Init();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected override ISessionFactory CreateSessionFactory()&lt;br /&gt;        {&lt;br /&gt;            return Fluently.Configure()&lt;br /&gt;                .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())&lt;br /&gt;                .Mappings(m =&amp;gt; m.FluentMappings.AddFromAssemblyOf&amp;lt;BooksMap&amp;gt;())&lt;br /&gt;                .ExposeConfiguration(Cfg =&amp;gt; configuration = Cfg)&lt;br /&gt;                .BuildSessionFactory();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    /// Database configured as in memory SQLite database.&lt;br /&gt;    public class PostgresDatabase : BaseDatabase&lt;br /&gt;    {&lt;br /&gt;        public string ConnectionString { get; private set; }&lt;br /&gt;&lt;br /&gt;        /// Create in memory SQLite database.&lt;br /&gt;        public PostgresDatabase(string connectionString)&lt;br /&gt;        {&lt;br /&gt;            ConnectionString = connectionString;&lt;br /&gt;            Init();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        protected override ISessionFactory CreateSessionFactory()&lt;br /&gt;        {&lt;br /&gt;            return Fluently.Configure()&lt;br /&gt;                .Database(PostgreSQLConfiguration.PostgreSQL81&lt;br /&gt;                    .ConnectionString(ConnectionString).ShowSql())&lt;br /&gt;                .Mappings(m =&amp;gt; m.FluentMappings.AddFromAssemblyOf&amp;lt;BooksMap&amp;gt;())&lt;br /&gt;                .ExposeConfiguration(Cfg =&amp;gt; configuration = Cfg)&lt;br /&gt;                .BuildSessionFactory();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Book Store Model – the BookStore database class&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;It is time for the book store class. The &lt;b&gt;BookStore&lt;/b&gt; class contains book and author repository and does the necessary initialization of those. Also contains concrete instance of BaseDatabase. We inject concrete instance of BaseDatabase from the parameterized constructor. We also have parameter less constructor which leans upon StructureMap to init this singleton class with concrete instance and implementation of BaseDatabase.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    /// Is a singleton, use GetInstance()&lt;br /&gt;    public class BookStore&lt;br /&gt;    {&lt;br /&gt;        private static BookStore bookStore;&lt;br /&gt;&lt;br /&gt;        public static BookStore GetInstance()&lt;br /&gt;        {&lt;br /&gt;            if (bookStore == null)&lt;br /&gt;                bookStore = new BookStore();&lt;br /&gt;            return bookStore;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private BaseDatabase db;&lt;br /&gt;        public IBookRepository BookRepository { get; private set; }&lt;br /&gt;        public IAuthorRepository AuthorRepository { get; private set; }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        /// Inject concrete instance of BaseDatabase.&lt;br /&gt;        public BookStore()&lt;br /&gt;            : this(ObjectFactory.GetInstance&amp;lt;BaseDatabase&amp;gt;())&lt;br /&gt;        { }&lt;br /&gt;&lt;br /&gt;        public BookStore(BaseDatabase db)&lt;br /&gt;        {&lt;br /&gt;            this.db = db;&lt;br /&gt;            Init();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        private void Init()&lt;br /&gt;        {&lt;br /&gt;            IBookFinder bookFinder = new BookFinder();&lt;br /&gt;            BookPersistor bookPersistor = new BookPersistor(db.Session);&lt;br /&gt;            BookRepository = new BookRepository(bookPersistor, bookFinder);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            IAuthorFinder authorFinder = new AuthorFinder();&lt;br /&gt;            AuthorPersistor authorPersistor = new AuthorPersistor(db.Session);&lt;br /&gt;            AuthorRepository = new AuthorRepository(authorPersistor, authorFinder);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // can be used to implement the Unit of Work Pattern.&lt;br /&gt;        public void Flush()&lt;br /&gt;        {&lt;br /&gt;            db.Session.Flush();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Book Store Model – Usage&lt;/h3&gt;&lt;br /&gt;For the usage and to run the final example I’ll put the rest into the Program.cs file.&lt;br /&gt;&lt;br /&gt;First I create two concrete implementation of BaseDatabase: SQLite where we have specified file name for our SQLite database and Postgres where we have specified the concrete connection string.&lt;br /&gt;&lt;br /&gt;Then we have method ConfigureDependencies() to initialize StructureMap. We say which concrete class to be created whenever we create instance of BaseDatabase using the default parameter less constructor. Please note that we have such situation in class BookStore in GetInstance() where it creates an instance of itself. BookStore depends only on BaseDatabase class, but not on the concrete implementations of BaseDatabase. Then StructureMap will decide for the concrete implementation of BaseDatabase.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    public class Program&lt;br /&gt;    {&lt;br /&gt;        public class SQLiteInFileConcreteDatabase : SQLiteInFileDatabase&lt;br /&gt;        {&lt;br /&gt;            public SQLiteInFileConcreteDatabase() : base("test.db") { }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public class PostgresConcreteDatabase : PostgresDatabase&lt;br /&gt;        {&lt;br /&gt;            public PostgresConcreteDatabase()&lt;br /&gt;                : base("Server=127.0.0.1;Port=5432;Database=bookstore;User Id=postgres;Password=;")&lt;br /&gt;            { }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        /// &amp;lt;summary&amp;gt;&lt;br /&gt;        /// Configure StructureMap dependencies.&lt;br /&gt;        /// &amp;lt;/summary&amp;gt;&lt;br /&gt;        private static void ConfigureDependencies()&lt;br /&gt;        {&lt;br /&gt;            ObjectFactory.Initialize(x =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                x.ForRequestedType&amp;lt;BaseDatabase&amp;gt;()&lt;br /&gt;                    .TheDefaultIsConcreteType&amp;lt;SQLiteInMemoryDatabase&amp;gt;();&lt;br /&gt;                    // .TheDefaultIsConcreteType&amp;lt;SQLiteInFileDatabaseConcrete&amp;gt;();&lt;br /&gt;                    // .TheDefaultIsConcreteType&amp;lt;PostgresConcreteDatabase&amp;gt;();&lt;br /&gt;                    // whatever concrete database and settings&lt;br /&gt;            });&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            ConfigureDependencies();&lt;br /&gt;&lt;br /&gt;            BookStore bookStore = BookStore.GetInstance();&lt;br /&gt;&lt;br /&gt;            Author JohnDoe = new Author() { Name = "John Doe" };&lt;br /&gt;            bookStore.AuthorRepository.Save(JohnDoe);&lt;br /&gt;&lt;br /&gt;            Author JaneDoe = new Author() { Name = "Jane Doe" };&lt;br /&gt;            bookStore.AuthorRepository.Save(JaneDoe);&lt;br /&gt;&lt;br /&gt;            Book book;&lt;br /&gt;&lt;br /&gt;            // test approval:&lt;br /&gt;            book = new Book() { };&lt;br /&gt;            book.Approval = new BookApproval();&lt;br /&gt;            Console.WriteLine("Approval of book: {0}", String.Join(System.Environment.NewLine, book.Validate().ToArray()));&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            // test saving to database&lt;br /&gt;            book = new Book() { Title = "Meet John Doe", ISBN = "1234567890123" };&lt;br /&gt;            book.Authors.Add(JohnDoe);&lt;br /&gt;            book.Authors.Add(JaneDoe);&lt;br /&gt;            bookStore.BookRepository.Save(book); &lt;br /&gt;            bookStore.Flush(); // moan on error&lt;br /&gt;&lt;br /&gt;            Book selected = bookStore.BookRepository.Find.ByISBN("1234567890123");&lt;br /&gt;            Console.WriteLine(String.Format("Author one: {0}", selected.Authors[0].Name));&lt;br /&gt;            Console.WriteLine(String.Format("Author two: {0}", selected.Authors[1].Name));&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;When I ran the program, I’ve got the following output:&lt;br /&gt;&lt;br /&gt; &lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_pNNYA7XMbCI/S0IxQAW1E9I/AAAAAAAAACw/PnYeTleseic/s1600-h/EXAMPLE1.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 390px; height: 353px;" src="http://2.bp.blogspot.com/_pNNYA7XMbCI/S0IxQAW1E9I/AAAAAAAAACw/PnYeTleseic/s400/EXAMPLE1.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5422951052350919634" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;I also gave a try of the BookApproval. The validation has failed with two error messages. Saving that book definition – with bookStore.BookRepository.Save(book); - wouldn’t be possible as the validation did not pass.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;At the end I place some links related to the theme.&lt;br /&gt;&lt;br /&gt;An excellent blog on implementing repository and finder pattern:&lt;br /&gt;http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/&lt;br /&gt;&lt;br /&gt;Part 2 from the Blog attending the MVC Storefront Project where the Repository Pattern is used:&lt;br /&gt;http://blog.wekeroad.com/mvc-storefront/asp-net-mvc-mvc-storefront-part-2/&lt;br /&gt;&lt;br /&gt;Fluent mapping for NHibernate&lt;br /&gt;http://fluentnhibernate.org/&lt;br /&gt;&lt;br /&gt;To download NHibernate.Linq&lt;br /&gt;http://sourceforge.net/projects/nhibernate/files/&lt;br /&gt;&lt;br /&gt;ADO.NET SQLite Data Provider:&lt;br /&gt;http://sqlite.phxsoftware.com&lt;br /&gt;&lt;br /&gt;ADO.NET Postgresql Data Provider:&lt;br /&gt;http://npgsql.projects.postgresql.org/&lt;br /&gt;&lt;br /&gt;StructureMap Inversion of Control Framework:&lt;br /&gt;http://structuremap.sourceforge.net/Default.htm&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2010%2f01%2fimplementing-and-using-repositories.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fatanashristov.blogspot.com%2f2010%2f01%2fimplementing-and-using-repositories.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-Implementing-and-Using-Repositories-with-NHibernate"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2010%2F01%2Fimplementing-and-using-repositories.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-7537595785779039358?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/7537595785779039358/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2010/01/implementing-and-using-repositories.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/7537595785779039358'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/7537595785779039358'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2010/01/implementing-and-using-repositories.html' title='Implementing and Using Repositories with NHibernate'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_pNNYA7XMbCI/S0IxHMlEFrI/AAAAAAAAACo/vRY3DcXUT7U/s72-c/ERD1.png' height='72' width='72'/><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-1112786262870154093</id><published>2009-12-01T08:08:00.000-08:00</published><updated>2009-12-01T10:56:33.691-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>Design Patterns – Memento Pattern</title><content type='html'>The &lt;a href="http://en.wikipedia.org/wiki/Memento_pattern"&gt;&lt;b&gt;Memento Pattern&lt;/b&gt;&lt;/a&gt; is useful to remember the state of object without keeping copy of the whole object. Copying of the entire object is sometimes inefficient as the copy eventually contains much more information that we need to restore back.&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_pNNYA7XMbCI/SxVANvO_1YI/AAAAAAAAACY/I1yoEf9mHvg/s1600/Memento.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 151px;" src="http://1.bp.blogspot.com/_pNNYA7XMbCI/SxVANvO_1YI/AAAAAAAAACY/I1yoEf9mHvg/s400/Memento.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5410301132117366146" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Memento&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Memento&lt;/b&gt; is the object that can remember the internal state of another object.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;// Memento. Uses deep copy and serialization&lt;br /&gt;// to save/restore the state of type TState.&lt;br /&gt;public class Memento&amp;lt;TState&amp;gt;&lt;br /&gt;{&lt;br /&gt;  MemoryStream stream = new MemoryStream();&lt;br /&gt;  BinaryFormatter formatter = new BinaryFormatter();&lt;br /&gt;&lt;br /&gt;  public Memento&amp;lt;TState&amp;gt; Save(TState state)&lt;br /&gt;  {&lt;br /&gt;    formatter.Serialize(stream, state);&lt;br /&gt;    return this;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public TState Restore()&lt;br /&gt;  {&lt;br /&gt;    stream.Seek(0, SeekOrigin.Begin);&lt;br /&gt;    TState state = (TState)formatter.Deserialize(stream);&lt;br /&gt;    stream.Close();&lt;br /&gt;    return state;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The Memento in this example uses generics to ensure type consistence and prevent using type conversion.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Originator&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Originator&lt;/b&gt; is the object which state to remember and restore back if needed. The Originator has two methods for that:&lt;br /&gt;- GetMemento() that returns the state of the object &lt;br /&gt;- and SetMemento() receives back state to restore from&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;// The Originator has one property that returns &lt;br /&gt;// the complete state of the object.&lt;br /&gt;public interface IOriginator&amp;lt;TState&amp;gt;&lt;br /&gt;{&lt;br /&gt;  TState State { get; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Holds the state of the Originator&lt;br /&gt;[Serializable]&lt;br /&gt;public class ProductState&lt;br /&gt;{&lt;br /&gt;  public string Name { get; set; }&lt;br /&gt;  public float Price { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Originator&lt;br /&gt;// The complete state is moved to one property &lt;br /&gt;// to generalize the memento pattern.&lt;br /&gt;[Serializable]&lt;br /&gt;public class Product : IOriginator&amp;lt;ProductState&amp;gt;&lt;br /&gt;{&lt;br /&gt;  public Product()&lt;br /&gt;  {&lt;br /&gt;    this.State = new ProductState();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public Product(string name, float price)&lt;br /&gt;    : this()&lt;br /&gt;  {&lt;br /&gt;    this.State.Name = name;&lt;br /&gt;    this.State.Price = price;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public ProductState State { get; private set; }&lt;br /&gt;&lt;br /&gt;  public Memento&amp;lt;ProductState&amp;gt; GetMemento()&lt;br /&gt;  {&lt;br /&gt;    return new Memento&amp;lt;ProductState&amp;gt;().Save(State);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public void SetMemento(Memento&amp;lt;ProductState&amp;gt; memento)&lt;br /&gt;  {&lt;br /&gt;    State = memento.Restore();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public override string ToString()&lt;br /&gt;  {&lt;br /&gt;    return String.Format(System.Globalization.CultureInfo.InvariantCulture,&lt;br /&gt;      "{0} {1:f2}", State.Name, State.Price);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Caretaker&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Caretaker&lt;/b&gt; is the object that controls when to create Memento but the Originator will use the stored into the Caretaker state to restore from.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;// Usage example and Caretaker as the same time.&lt;br /&gt;static void Main(string[] args)&lt;br /&gt;{&lt;br /&gt;  // Caretaker is in this example the class that holds the Main() void&lt;br /&gt;  // or the Main() void itself of you want.&lt;br /&gt;  Memento&amp;lt;ProductState&amp;gt; memento = new Memento&amp;lt;ProductState&amp;gt;();&lt;br /&gt;&lt;br /&gt;  Product product = new Product("Name one", 100f);&lt;br /&gt;  Console.WriteLine("Initial state: " + product.ToString());&lt;br /&gt;&lt;br /&gt;  memento = product.GetMemento();&lt;br /&gt;  Console.WriteLine("The state was saved to memento");&lt;br /&gt;&lt;br /&gt;  // Change the state of the Originator&lt;br /&gt;  product.State.Name = "Name two";&lt;br /&gt;  product.State.Price = 200f;&lt;br /&gt;  Console.WriteLine("State changed: " + product.ToString());&lt;br /&gt;&lt;br /&gt;  // Change the state of the Originator&lt;br /&gt;  product.State.Name = "Name three";&lt;br /&gt;  product.State.Price = 300f;&lt;br /&gt;  Console.WriteLine("State changed: " + product.ToString());&lt;br /&gt;&lt;br /&gt;  product.SetMemento(memento);&lt;br /&gt;  Console.WriteLine("The state restored from memento");&lt;br /&gt;&lt;br /&gt;  Console.WriteLine("Reverted state: " + product.ToString());&lt;br /&gt;&lt;br /&gt;  Console.ReadLine();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;which gives after running the following output:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_pNNYA7XMbCI/SxVC8WcqkUI/AAAAAAAAACg/hPCLZjkkVBg/s1600/MementoRunningExample.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 311px; height: 102px;" src="http://3.bp.blogspot.com/_pNNYA7XMbCI/SxVC8WcqkUI/AAAAAAAAACg/hPCLZjkkVBg/s400/MementoRunningExample.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5410304131940913474" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The Memento is save-state undo command, where the captured is a backup. In this example the Memento object used in-memory storage to keep backup of state, but the Memento object could also even persist state into a database.&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f12%2fdesign-patterns-memento-pattern.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f12%2fdesign-patterns-memento-pattern.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-Design-Patterns-Memento-Pattern-blog-about-programming"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2009%2F12%2Fdesign-patterns-memento-pattern.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-1112786262870154093?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/1112786262870154093/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/12/design-patterns-memento-pattern.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/1112786262870154093'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/1112786262870154093'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/12/design-patterns-memento-pattern.html' title='Design Patterns – Memento Pattern'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_pNNYA7XMbCI/SxVANvO_1YI/AAAAAAAAACY/I1yoEf9mHvg/s72-c/Memento.png' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-4129280759333092913</id><published>2009-10-31T09:40:00.000-07:00</published><updated>2009-10-31T14:11:24.911-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='AJAX'/><category scheme='http://www.blogger.com/atom/ns#' term='ASP.NET MVC'/><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>AJAX publish/subscribe</title><content type='html'>Calling long running web server process and locking the user for a while in web applications with the typical for the HTTP &lt;b&gt;request/replay&lt;/b&gt; way can be critical for the user expirience. Even more, possibly we don't get back the data due to problems with the network connection or browser timeouts.&lt;br /&gt;&lt;br /&gt;Even if on top of unreliable protocol like HTTP we can provide some abstraction level to ensure we'll get the result from the web server. We could simulate the &lt;a hreh="http://en.wikipedia.org/wiki/Publish/subscribe"&gt;&lt;b&gt;publish/subscribe&lt;/b&gt; pattern&lt;/a&gt; in ajax. Furthermore our communication with the web server is asynchronous and allows our application to respond better to the user interactions.&lt;br /&gt;&lt;br /&gt;On the web server we could implement multithreading and open working threads which get the calculations done.&lt;br /&gt;&lt;br /&gt;With javascript we send request to the web server and then in some interval of time we again and again ask if the server has prepared the result. When the web server has collected the information we need, we take the data from the web server, display on the page and stop the repetative calls to the web server.&lt;br /&gt;&lt;br /&gt;I will implement publish/subscribe with &lt;b&gt;ASP.NET MVC&lt;/b&gt; and &lt;b&gt;jQuery&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The CityWeather model&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;First i'll create model class CityWeather. The only public properties of CityWeather object are "City" and "Temperature".&lt;br /&gt;&lt;br /&gt;After CityWeather class created, the constructor calls Measure() in thread. The Measure() function simulates long running process used to collect the weather information for that city.&lt;br /&gt;&lt;br /&gt;We store all the requests for measurements in static collection _measurements. The keys of this collection are the city names. &lt;br /&gt;&lt;br /&gt;The only public function of the model class is the static function GetCityWeather() which when called will check if in _measurements exists object CityWeather for this city. If not will create one. The function returns back the corresponding CityWeather object from the _measurements collection.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt; namespace PublishSubscribe.Models&lt;br /&gt; {&lt;br /&gt;  // Measurements per city.&lt;br /&gt;  // Call class method CityWeather.GetCityWeather(city) &lt;br /&gt;  // to get CityWeather object with measurements &lt;br /&gt;  // for that city. &lt;br /&gt;  // Repead calling CityWeather.GetCityWeather(city) &lt;br /&gt;  // until city.Temperature is not null.&lt;br /&gt;  public class CityWeather&lt;br /&gt;  {&lt;br /&gt;   // Holds all requested measurements.&lt;br /&gt;   // Used from class method GetCityWeather()&lt;br /&gt;   // The keys are city names.&lt;br /&gt;   // The values are CityWeather objects.&lt;br /&gt;   private static Dictionary&amp;lt;string, CityWeather&amp;gt; _measurements = &lt;br /&gt;    new Dictionary&amp;lt;string, CityWeather&amp;gt;();&lt;br /&gt;&lt;br /&gt;   // public properties of CityWeather object:&lt;br /&gt;   public string City { get; private set; }&lt;br /&gt;   public int? Temperature { get; private set; }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   // The constructor itself starts measurement &lt;br /&gt;   // in an asynchronous thread.&lt;br /&gt;   private CityWeather(string city) &lt;br /&gt;   {&lt;br /&gt;    this.City = city;&lt;br /&gt;&lt;br /&gt;    // after the object is constructed will start &lt;br /&gt;    // doing measurement in a thread, which respectively &lt;br /&gt;    // takes some time&lt;br /&gt;    ThreadStart ts = new ThreadStart(Measure);&lt;br /&gt;    Thread th = new Thread(ts);&lt;br /&gt;    th.Priority = ThreadPriority.Lowest;&lt;br /&gt;    th.Start();&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   // Worker method started in separate thread from &lt;br /&gt;   // the constructor&lt;br /&gt;   private void Measure()&lt;br /&gt;   { &lt;br /&gt;    // measurement takes some time - up to a minute&lt;br /&gt;    Thread.Sleep(new Random().Next(1,6) * 10000);&lt;br /&gt;&lt;br /&gt;    // lock the object alowing concurent access&lt;br /&gt;    // to the object properties&lt;br /&gt;    lock (this)&lt;br /&gt;     // degrees Celsius between 10 and 20&lt;br /&gt;     Temperature = new Random().Next(10, 20);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   // The only public method that capsulates all the logic &lt;br /&gt;   // of keeping single instances - one per city - &lt;br /&gt;   // just as static memory for the purpose of the&lt;br /&gt;   // demonstration.&lt;br /&gt;   //&lt;br /&gt;   // Keep calling CityWeather.GetCityWeather(city) until &lt;br /&gt;   // you get back an CityWeather object with &lt;br /&gt;   // property Temperature which is not null.&lt;br /&gt;   public static CityWeather GetCityWeather(string city)&lt;br /&gt;   {&lt;br /&gt;    lock (_measurements)&lt;br /&gt;    {&lt;br /&gt;     if (! _measurements.ContainsKey(city))&lt;br /&gt;     {&lt;br /&gt;      CityWeather cw = new CityWeather(city);&lt;br /&gt;      _measurements.Add(city, cw);&lt;br /&gt;     }&lt;br /&gt;&lt;br /&gt;     return _measurements[city]; // check &lt;br /&gt;    }&lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The usage of this class is pretty simple. We call the static function CityWeather.GetCityWeather() with the name of a city to get weather measurements for that city. We repeat the call again and again until we get back CityWeather object where Temperature property is set - is not null, but contains value.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Weather controller&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Then I'll create the controller class:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt; namespace PublishSubscribe.Controllers&lt;br /&gt; {&lt;br /&gt;  public class WeatherController : Controller&lt;br /&gt;  {&lt;br /&gt;   public JsonResult Measure(string city)&lt;br /&gt;   {&lt;br /&gt;    return Json(Models.CityWeather.GetCityWeather(city));&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public ActionResult Index()&lt;br /&gt;   {&lt;br /&gt;    return View();&lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The controller has two methods. Measure gets weather measurements for one given city. We send back JSON result. &lt;br /&gt;&lt;br /&gt;The Index method we will use to create page where we will demonstrate how the &lt;span&gt;AJAX publish/subscribe&lt;/span&gt; calls will work.&lt;br /&gt;&lt;br /&gt;We are ready to try how the Measure JSON handler will respond and to see the how the CityWeather model will work. We run the application and navigate to /weather/measure where we request measurements for a city and repetative hit repoad on the browser until we receive back the Temperature calculated.&lt;br /&gt;&lt;br /&gt;Here is how example session with repetative calls looks like:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt; URL: http://localhost:3284/weather/measure/?city=berlin&lt;br /&gt; Response: {"City":"berlin","Temperature":null}&lt;br /&gt; ...&lt;br /&gt; URL: http://localhost:3284/weather/measure/?city=berlin&lt;br /&gt; Response: {"City":"berlin","Temperature":null}&lt;br /&gt; ...&lt;br /&gt; URL: http://localhost:3284/weather/measure/?city=berlin&lt;br /&gt; Response: {"City":"berlin","Temperature":12}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;AJAX publish/subscribe with jQuery&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Now I'm going to implement the web page to demonstrate the idea behind the AJAX publish/subscribe.&lt;br /&gt;&lt;br /&gt;The html body tag is very simple.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;body&amp;gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;label for="city"&amp;gt;City:&amp;lt;/label&amp;gt;&lt;br /&gt; &amp;lt;input type="text" id="txtCity" /&amp;gt;&lt;br /&gt; &amp;lt;input type="button" value="measure" id="btnMeasure" /&amp;gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;table id="cites"&amp;gt;&lt;br /&gt;  &amp;lt;thead&amp;gt;&lt;br /&gt;   &amp;lt;tr&amp;gt;&amp;lt;td style="width:200px"&amp;gt;City&amp;lt;/td&amp;gt;&amp;lt;td&amp;gt;Temperature&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;&lt;br /&gt;  &amp;lt;/thead&amp;gt;&lt;br /&gt;  &amp;lt;tbody&amp;gt;&lt;br /&gt;  &amp;lt;/tbody&amp;gt;&lt;br /&gt; &amp;lt;/table&amp;gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;/body&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We write city name into the input box and click the "measure" button. We repeat that several times with other city names. We expect whenever the server has measured the weather for a city we asked for, the result will be added to the table as new row. The order of the cities we ask for measurements is not necessarily the order we'll get back calculated measurements. The time the server will spend to take weather measurements may vary from city to city and is not presumable.&lt;br /&gt;&lt;br /&gt;This way we will have asynchronious communication with the server and the user will appreciate the better respond from the application.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Last, I'll put some javascript after the closing body task and will automate the html page with jQuery.&lt;br /&gt;&lt;br /&gt;As we don't have multithreading in javascript we simulate it with setInterval and clearInterval. We start repetative calls as we run sendMeasureRequest(city) every second and ask the web server if the measurements for that city are calculated. Once the server gives back calculated results we stop the repetative calls.&lt;br /&gt;&lt;br /&gt;The setInterval() function gives us interval ID which we later use at calling clearInterval() to stop repetative tasks. Then we also need to map somewhere interval ID to city name, thereof we create array measurements which keys are city names. The values of the measurements dictionary are data structures wich hold interval ID, city name and the temperature as measured from the web server.&lt;br /&gt;&lt;br /&gt;Once the web server respond calculated measurement we stop the corresponding repetative calls to the web server and call the function cityMeasured(). We add new row into the table with the measurements.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt; &amp;lt;script type="text/javascript"&amp;gt;&lt;br /&gt;&lt;br /&gt;  /* Hash array of all collected measurememts */&lt;br /&gt;  var measurements = new Array();&lt;br /&gt;&lt;br /&gt;  /* Does weather measurement for a city */&lt;br /&gt;  function measureCity(city) {&lt;br /&gt;   if (measurements[city] == undefined) {&lt;br /&gt;    // send request to the server every one second&lt;br /&gt;    var intervalID = setInterval(sendMeasureRequest, 1000, city);&lt;br /&gt;    measurements[city] = {&lt;br /&gt;     IntervalID: intervalID,&lt;br /&gt;     City: city,&lt;br /&gt;     Temperature: null&lt;br /&gt;    };&lt;br /&gt;    sendMeasureRequest(city);&lt;br /&gt;   }&lt;br /&gt;   cityMeasured(city);&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  /* Send GET request to the server to collect weather measurements for a city */&lt;br /&gt;  function sendMeasureRequest(city) {&lt;br /&gt;   $.ajax({&lt;br /&gt;    'url': '&amp;lt;%= Url.Action("Measure") %&amp;gt;',&lt;br /&gt;    'type': 'GET',&lt;br /&gt;    'dataType': 'json',&lt;br /&gt;    'data': { 'city': city },&lt;br /&gt;    'success': function(data) {&lt;br /&gt;     if (data.Temperature != null) {&lt;br /&gt;      clearInterval(measurements[data.City].IntervalID);&lt;br /&gt;      measurements[data.City].Temperature = data.Temperature;&lt;br /&gt;      cityMeasured(data.City);&lt;br /&gt;     }&lt;br /&gt;    }&lt;br /&gt;   });&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  /* Does weather measurement for a city */&lt;br /&gt;  function cityMeasured(city) {&lt;br /&gt;   if (measurements[city].Temperature != null) {&lt;br /&gt;    if ($('#tr_' + city).length == 0) {&lt;br /&gt;     $("#cites &amp;gt; tbody").append('&amp;lt;tr id="tr_' + city + '"&amp;gt;&amp;lt;td&amp;gt;'&lt;br /&gt;      + measurements[city].City&lt;br /&gt;      + '&amp;lt;/td&amp;gt;&amp;lt;td&amp;gt;'&lt;br /&gt;      + measurements[city].Temperature + '&amp;nbsp;grad'&lt;br /&gt;      + '&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;');&lt;br /&gt;    }&lt;br /&gt;   }&lt;br /&gt;   $('#tr_' + city).fadeOut();&lt;br /&gt;   $('#tr_' + city).fadeIn();&lt;br /&gt;  }&lt;br /&gt;   &lt;br /&gt;  /* SetUp click handler */&lt;br /&gt;  $(document).ready(function() {&lt;br /&gt;   $("#btnMeasure").click(function() {&lt;br /&gt;    var city = $("#txtCity").val();&lt;br /&gt;    measureCity(city);&lt;br /&gt;   });&lt;br /&gt;  });&lt;br /&gt; &amp;lt;/script&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;After I ran the application and navigated to /weather/ I asked for weather measurements for the following cities in the exact order: Paris, Boston, Rom, Hamburg&lt;br /&gt;&lt;br /&gt;Then I waited few seconds and the weather measurements were displayed to the page one after other:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_pNNYA7XMbCI/SuxpGUUhLNI/AAAAAAAAABw/Mqy29j9AQm0/s1600-h/PublishSubscribeAjax-result.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 335px; height: 175px;" src="http://1.bp.blogspot.com/_pNNYA7XMbCI/SuxpGUUhLNI/AAAAAAAAABw/Mqy29j9AQm0/s400/PublishSubscribeAjax-result.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5398805610565283026" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Well, we may consider as next to be done, once the weather in city from the table has charnged, we refresh the information on the table.&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f10%2fajax-publishsubscribe.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f10%2fajax-publishsubscribe.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-AJAX-publishsubscribe-with-ASPNET-MVC-and-jQuery"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2009%2F10%2Fajax-publishsubscribe.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-4129280759333092913?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/4129280759333092913/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/10/ajax-publishsubscribe.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4129280759333092913'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4129280759333092913'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/10/ajax-publishsubscribe.html' title='AJAX publish/subscribe'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_pNNYA7XMbCI/SuxpGUUhLNI/AAAAAAAAABw/Mqy29j9AQm0/s72-c/PublishSubscribeAjax-result.png' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-4554736015119078364</id><published>2009-10-13T05:39:00.000-07:00</published><updated>2009-12-31T03:37:13.249-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>Design Patterns – Abstract Factory Pattern</title><content type='html'>Factories are objects that encapsulate the logic for creating other objects. &lt;br /&gt;&lt;br /&gt;Factory object could create one or another object based on some configuration parameters. Or the factory could decide what kind of concrete object to create based on a parameter to some object creational method. For example if the method received post-code the factory creates City object and when the parameter is an email address the factory creates Customer object. In that way one might create factory to select one or another kind of object from database based on the user input.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Abstract Factory&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;The &lt;b&gt;Abstract Factory&lt;/b&gt; is that encapsulates the way of creating concrete objects that have lot of common.&lt;br /&gt;&lt;br /&gt;Often the created from abstract factory objects derive from same &lt;b&gt;base class&lt;/b&gt; or share some interface. Abstract factory object for example could be used to create fake objects for the purpose of testing the software, and create regular objects otherwise in production mode. The fake object and the regular object derive from same base class or share same interface. The client code deals only with instances of the base type and has no knowledge of the concrete implementation.&lt;br /&gt;&lt;br /&gt;I will give an example of abstract factory created with C#.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Reflection based abstract factory&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;The central feature of our abstract factory is to create concrete objects based on key/value pairs.&lt;br /&gt;&lt;br /&gt;We register the types the factory is able to create into a dictionary. For registration of the types the factory may create we expose method &lt;b&gt;Register()&lt;/b&gt;. &lt;br /&gt;&lt;br /&gt;Our base abstract factory class uses reflection to call the object constructors of the concrete type. That is done in method &lt;b&gt;CreateInstance()&lt;/b&gt;. We invoke CreateInstance() with:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;&lt;b&gt;key&lt;/b&gt; - that will be used to create one concrete object or another as it is registered already via Register().&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;&lt;b&gt;typeParams&lt;/b&gt; - if the concrete object has parameterized constructor which we want to use, then we specify the parameter types in an array.&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;&lt;b&gt;valParams&lt;/b&gt; - if the concrete object has parameterized constructor which we want to use, then we specify the parameter values in an array.&lt;br /&gt;&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Following is a implementation of reflection based abstract factory:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    // T1 is the appropriate key type.&lt;br /&gt;    // T2 is the base type from which derive all the types the factory can create.&lt;br /&gt;    public abstract class AbstractFactory&amp;lt;T1, T2&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        // Creates the factory.&lt;br /&gt;        // T1 is the appropriate type. &lt;br /&gt;        // T2 is the base type from which derive all the types the factory can create.&lt;br /&gt;        public static AbstractFactory&amp;lt;T1, T2&amp;gt; CreateFactory()&lt;br /&gt;        {&lt;br /&gt;            throw new Exception("Override FactoryReflected.CreateFactory()!");&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Register for types the factory can create.&lt;br /&gt;        protected Dictionary&amp;lt;T1, Type&amp;gt; _registered = new Dictionary&amp;lt;T1, Type&amp;gt;();&lt;br /&gt;&lt;br /&gt;        // Registers the specified factory types.&lt;br /&gt;        protected void Register(T1 key, Type type)&lt;br /&gt;        {&lt;br /&gt;            _registered.Add(key, type);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;        // Creates new instance of type by enumeration key. &lt;br /&gt;        public T2 CreateInstance(T1 key, Type[] typeParams, object[] valParams)&lt;br /&gt;        {&lt;br /&gt;            Type type = _registered[key];&lt;br /&gt;&lt;br /&gt;            System.Reflection.ConstructorInfo cInfo =&lt;br /&gt;                type.GetConstructor(typeParams);&lt;br /&gt;&lt;br /&gt;            return (T2)cInfo.Invoke(valParams);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We also have used generics to make the implementation of reflection based abstract factory more generalized.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Personal name&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Let's face the problem and how we are going to find a solution. The different societies have different &lt;a href="http://en.wikipedia.org/wiki/Full_name#Naming_convention"&gt;conventions for personal full name&lt;/a&gt;. In Russia the common order is "family-name given-name". In some situations the family-name is capitalized. In west Europe the usual convention is "given-name family-name", etc.&lt;br /&gt;&lt;br /&gt;Our problem is - we are going to use the appropriate form of address when we communicate with people from different regions. For simplicity assume we have the family and the given name. We need a way to compose appropriate full name.&lt;br /&gt;&lt;br /&gt;First we have the base class &lt;b&gt;Name&lt;/b&gt;. The Name class has first and last name properties. We also have an abstract method &lt;b&gt;GetFullName()&lt;/b&gt; which should give different result for different society. Furthermore, the concrete implementation will be done in derived classes:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    // Base abstract class from which concrete implementations derive&lt;br /&gt;    public abstract class Name&lt;br /&gt;    { // see http://en.wikipedia.org/wiki/Full_name#Naming_convention&lt;br /&gt;&lt;br /&gt;        protected string firstName;&lt;br /&gt;        protected string lastName;&lt;br /&gt;        protected Name() { }&lt;br /&gt;        public Name(string first, string last)&lt;br /&gt;        {&lt;br /&gt;            this.firstName = first;&lt;br /&gt;            this.lastName = last;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Full name can be composed differently &lt;br /&gt;        // as the different societies have they different &lt;br /&gt;        // naming conventions&lt;br /&gt;        public abstract string GetFullName();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // composing Western full name&lt;br /&gt;    public class WesternName : Name&lt;br /&gt;    {&lt;br /&gt;        public WesternName(string first, string last) : base(first, last) { }&lt;br /&gt;        public override string GetFullName() { return firstName + " " + lastName; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // composing Eastern full name&lt;br /&gt;    public class EasternName : Name&lt;br /&gt;    {&lt;br /&gt;        public EasternName(string first, string last) : base(first, last) { }&lt;br /&gt;        public override string GetFullName() { return lastName + " " + firstName; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // another Eastern full name convention&lt;br /&gt;    public class EasternOfficialName : Name&lt;br /&gt;    {&lt;br /&gt;        public EasternOfficialName(string first, string last) : base(first, last) { }&lt;br /&gt;        public override string GetFullName() { return lastName.ToUpper() + " " + firstName; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Concrete factory&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Having the abstract factory from above we create &lt;b&gt;concrete factory&lt;/b&gt; used for creation of objects of classes derived from the Name class. The &lt;b&gt;NameFactory&lt;/b&gt; contains the initialization of itself in method &lt;b&gt;CreateFactory()&lt;/b&gt;. If we create new concrete class derived from class Name to fit another convention for  personal full name then we also have to register that new class in CreateFactory() method.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    public class NameFactory : AbstractFactory&amp;lt;string, Name&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        private NameFactory() { }&lt;br /&gt;&lt;br /&gt;        public static new NameFactory CreateFactory()&lt;br /&gt;        {&lt;br /&gt;            NameFactory factory = new NameFactory();&lt;br /&gt;&lt;br /&gt;            // Register which concrete type to create for which key&lt;br /&gt;            factory.Register("WesternOrder", typeof(WesternName));&lt;br /&gt;            factory.Register("EasternOrder", typeof(EasternName));&lt;br /&gt;            factory.Register("EasternOfficialOrder", typeof(EasternOfficialName));&lt;br /&gt;&lt;br /&gt;            return factory;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We will create instances of NameFactory only via the static method CreateFactory() and thereof we have specified the default constructor to be private.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Using the concrete factory&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;We create nameFactory object and then call one after another GetFullName() of all possible derived from class Name objects. These derived from Name objects we create as we call method &lt;b&gt;CreateInstance()&lt;/b&gt; of nameFactory.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            NameFactory nameFactory = NameFactory.CreateFactory();&lt;br /&gt;&lt;br /&gt;            foreach (string convention in new string[] { &lt;br /&gt;                "WesternOrder", "EasternOrder", "EasternOfficialOrder", })&lt;br /&gt;            {&lt;br /&gt;                Name name = nameFactory.CreateInstance(convention,&lt;br /&gt;                    new Type[] { typeof(string), typeof(string) },&lt;br /&gt;                    new object[] { "Atanas", "Hristov" });&lt;br /&gt;&lt;br /&gt;                Console.WriteLine(name.GetFullName());&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;            Console.Read();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And finally the output to the console:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_pNNYA7XMbCI/StR1qDMXRDI/AAAAAAAAABo/ZcieGu2RvJc/s1600-h/abstract-pattern-example.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 164px; height: 79px;" src="http://2.bp.blogspot.com/_pNNYA7XMbCI/StR1qDMXRDI/AAAAAAAAABo/ZcieGu2RvJc/s400/abstract-pattern-example.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5392064019141444658" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f10%2fdesign-patterns-abstract-factory.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f10%2fdesign-patterns-abstract-factory.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-Design-Patterns-Abstract-Factory-Pattern-blog-about-programming"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2009%2F10%2Fdesign-patterns-abstract-factory.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-4554736015119078364?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/4554736015119078364/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/10/design-patterns-abstract-factory.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4554736015119078364'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4554736015119078364'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/10/design-patterns-abstract-factory.html' title='Design Patterns – Abstract Factory Pattern'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_pNNYA7XMbCI/StR1qDMXRDI/AAAAAAAAABo/ZcieGu2RvJc/s72-c/abstract-pattern-example.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-6964953872381170717</id><published>2009-09-25T05:24:00.000-07:00</published><updated>2009-12-02T00:07:39.931-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>Design Patterns – Singleton Pattern</title><content type='html'>The &lt;a href="http://en.wikipedia.org/wiki/Singleton_pattern"&gt;Singleton pattern&lt;/a&gt; gives us a way to restrict the instantiation of objects of given class to certain number, in the common usage to one only.&lt;br /&gt;&lt;br /&gt;The Singleton class instantiates itself and works as a global repository for an instance of itself. For example we share a database connection or log writer across all threads in one process.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Implementation of Singleton pattern&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Here i'm going to implement Singleton class in C#. The class should hide its constructor. It has also &lt;b&gt;GetInstance()&lt;/b&gt; method that gives back the only concrete instance. We embed the concrete instance of the class into the static variable "obj". &lt;br /&gt;&lt;br /&gt;For the purpose of the demonstration we have one public method Add() used to add some number to the class and Total() which gives back the total of the added numbers.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    public class Singleton&lt;br /&gt;    {&lt;br /&gt;        private static Singleton obj = new Singleton(); // holds a reference to the only concrete instance&lt;br /&gt;&lt;br /&gt;        private static int total = 0; // we add numbers up to this via Add()&lt;br /&gt;&lt;br /&gt;        private Singleton() { } // hiden constructor&lt;br /&gt;&lt;br /&gt;        public static Singleton GetInstance() { return obj; } // returns the only concrete instance&lt;br /&gt;&lt;br /&gt;        public void Add(int number)&lt;br /&gt;        { // add up to the total&lt;br /&gt;            lock (obj) // synchronize in concurrency&lt;br /&gt;            {&lt;br /&gt;                Thread.Sleep(new Random().Next(1000)); // randomly wait up to a second&lt;br /&gt;                total += number;&lt;br /&gt;                Console.WriteLine(String.Format("Add {0} to total", number));&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public int Total()&lt;br /&gt;        { // gets the total&lt;br /&gt;            lock (obj)&lt;br /&gt;                return total;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;In Add() method we have a timeout up to a second to randomize the time to run the method.&lt;br /&gt;&lt;br /&gt;We also locked the access to the class variables for concurrency. We are going to test the Singletion class in multithreaded environment.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Usage of Singleton pattern&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;First we create three static helper methods which will make calls to Add() with different number from one to three.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        // add&lt;br /&gt;        static void HelperOne() { Singleton.GetInstance().Add(1); }&lt;br /&gt;        static void HelperTwo() { Singleton.GetInstance().Add(2); }&lt;br /&gt;        static void HelperThree() { Singleton.GetInstance().Add(3); }&lt;br /&gt;...&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Then in Main() we run three threads and run concurrently the three static helper methods.&lt;br /&gt;&lt;br /&gt;We wait for the threads to finish and show the total of all additions to the singleton class.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;        static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Thread[] threads = new Thread[]&lt;br /&gt;            {&lt;br /&gt;                new Thread(new ThreadStart(HelperOne)),&lt;br /&gt;                new Thread(new ThreadStart(HelperTwo)),&lt;br /&gt;                new Thread(new ThreadStart(HelperThree))&lt;br /&gt;            };&lt;br /&gt;&lt;br /&gt;            foreach (Thread thread in threads) { thread.Start(); }&lt;br /&gt;            foreach (Thread thread in threads) { thread.Join(); }&lt;br /&gt;&lt;br /&gt;            Console.WriteLine(String.Format("The total is {0}",&lt;br /&gt;                Singleton.GetInstance().Total()));&lt;br /&gt;&lt;br /&gt;            Console.Read();&lt;br /&gt;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Run the example&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Running that I've got the following output:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_pNNYA7XMbCI/Sry4YTRWiYI/AAAAAAAAABg/0xDXcdHW7yo/s1600-h/singleton-pattern-output.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 129px; height: 60px;" src="http://2.bp.blogspot.com/_pNNYA7XMbCI/Sry4YTRWiYI/AAAAAAAAABg/0xDXcdHW7yo/s400/singleton-pattern-output.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5385381982057695618" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Happy codding!&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-Design-Patterns-Singleton-Pattern-blog-about-programming"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2009%2F09%2Fdesign-patterns-singleton-pattern.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-6964953872381170717?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/6964953872381170717/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/09/design-patterns-singleton-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/6964953872381170717'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/6964953872381170717'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/09/design-patterns-singleton-pattern.html' title='Design Patterns – Singleton Pattern'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_pNNYA7XMbCI/Sry4YTRWiYI/AAAAAAAAABg/0xDXcdHW7yo/s72-c/singleton-pattern-output.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-4202771426746542566</id><published>2009-09-11T09:16:00.001-07:00</published><updated>2009-12-02T00:10:24.060-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>Design Patterns – Chain of Responsibility Pattern</title><content type='html'>Imagine you have complicated decision logic and you’ve got a big if-then-else like structure in your code which you want to simplify. &lt;br /&gt;The &lt;b&gt;Chain of Responsibility Pattern&lt;/b&gt; is a good way for code refactoring in such situation. It will make the code more flexible and easy to support and modify in the future.&lt;br /&gt;&lt;br /&gt;You prepare a set of interdependent &lt;b&gt;chain handler classes&lt;/b&gt; linked in a chain. Every chain handler class implements part of the decision logic and has a link to next chain handler object. A &lt;b&gt;request data object&lt;/b&gt; is passed thru the chain. Eventually one of the handlers on the chain matches some decision criteria, does data processing and ends up the run flow. This would be the handler objects in the chain that takes the responsibility and does data processing having received the request data object.&lt;br /&gt;&lt;br /&gt;In this example we will try to programmatically come up with a conclusion based on passed in to the chain two boolean parameters. For every possible combination of those parameters we are going give a conclusion back, so we have four different possible results. Otherwise we could do things using conditional structures like:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;If Param1 is true&lt;br /&gt;        If Param2 is true&lt;br /&gt;                Conclusion1&lt;br /&gt;        Else&lt;br /&gt;                Conclusion2&lt;br /&gt;Else&lt;br /&gt;        If Param2 is true&lt;br /&gt;                Conclusion3&lt;br /&gt;        Else&lt;br /&gt;                Conclusion4&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Based on that conditional structure we will create chain of responsibility with four different chain handler classes covering all decision making combinations.&lt;br /&gt;&lt;br /&gt;We will use &lt;b&gt;C#&lt;/b&gt; as a programming language for the examples.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Chain Handler Interface and Base Class&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;We start with the definition of the chain handler interface. The chain handler object stores internally a request data object. We have a way to set if there is a handler next on the chain. The handler has Run() void where the decision making and eventually data processing will be done.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    // All handler objects implement common interface.&lt;br /&gt;    // T: request object- holds data to process &lt;br /&gt;    // and the result of the processing&lt;br /&gt;    public interface IChainHandler&amp;lt;TRequest&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        IChainHandler&amp;lt;TRequest&amp;gt; SetNextLink(IChainHandler&amp;lt;TRequest&amp;gt; next); // set link to next handler&lt;br /&gt;        void Run(); // does processing&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As we will have four chain handler classes and they all have a lot in common, we create parent abstract base class for chain handler.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    // base class for all concrete chain handler objects&lt;br /&gt;    public abstract class ChainHandlerBase : IChainHandler&amp;lt;RequestData&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        // the request data object&lt;br /&gt;        protected RequestData _requestData;&lt;br /&gt;&lt;br /&gt;        // a reference to next chain handler object&lt;br /&gt;        private IChainHandler&amp;lt;RequestData&amp;gt; _nextHandler;&lt;br /&gt;&lt;br /&gt;        // hide parameterless constructor&lt;br /&gt;        private ChainHandlerBase() { }&lt;br /&gt;&lt;br /&gt;        // expose constructor with parameters&lt;br /&gt;        public ChainHandlerBase(RequestData requestData)&lt;br /&gt;        {&lt;br /&gt;            _requestData = requestData;&lt;br /&gt;        }&lt;br /&gt;        // set the reference to the next chain handler object&lt;br /&gt;        public IChainHandler&amp;lt;RequestData&amp;gt; SetNextLink(IChainHandler&amp;lt;RequestData&amp;gt; nextHandler)&lt;br /&gt;        {&lt;br /&gt;            _nextHandler = nextHandler;&lt;br /&gt;            return _nextHandler;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // let the concrete implementation make processing decision &lt;br /&gt;        public abstract void Run();&lt;br /&gt;&lt;br /&gt;        // run next handler in the chain if defined or end up the processing&lt;br /&gt;        protected void RunNext()&lt;br /&gt;        {&lt;br /&gt;            if (_nextHandler != null)&lt;br /&gt;                _nextHandler.Run();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Request Data Object&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;A step back – we need to define the request data object which we’ll pass thru the chain. This object holds two input boolean parameters and a holder where we write the conclusion message back.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    // Data to pass thru the chain.&lt;br /&gt;    // Based on this data the chain &lt;br /&gt;    public class RequestData&lt;br /&gt;    {&lt;br /&gt;        // pass in parameters&lt;br /&gt;        public bool HaveLotOfMoney { get; set; }&lt;br /&gt;        public bool HaveBrilliantIdea { get; set; }&lt;br /&gt;&lt;br /&gt;        // a message to send back&lt;br /&gt;        public string MessageBack { get; set; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Concrete Chain Handler Implementations&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Now we are ready to define concrete chain handler classes and cover all possible combinations of the input parameters.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;    // concrete chain handler object&lt;br /&gt;    public class ChainHandlerOne : ChainHandlerBase&lt;br /&gt;    {&lt;br /&gt;        public ChainHandlerOne(RequestData requestData) : base(requestData) { }&lt;br /&gt;        public override void Run()&lt;br /&gt;        {&lt;br /&gt;            if ((_requestData.HaveLotOfMoney) &amp;&amp; (_requestData.HaveBrilliantIdea))&lt;br /&gt;            {&lt;br /&gt;                _requestData.MessageBack = "I am with you.";&lt;br /&gt;                return;&lt;br /&gt;            }&lt;br /&gt;            RunNext();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // concrete chain handler object&lt;br /&gt;    public class ChainHandlerTwo : ChainHandlerBase&lt;br /&gt;    {&lt;br /&gt;        public ChainHandlerTwo(RequestData requestData) : base(requestData) { }&lt;br /&gt;        public override void Run()&lt;br /&gt;        {&lt;br /&gt;            if ((_requestData.HaveLotOfMoney) &amp;&amp; (!_requestData.HaveBrilliantIdea))&lt;br /&gt;            {&lt;br /&gt;                _requestData.MessageBack = "Well done. Go on pension.";&lt;br /&gt;                return;&lt;br /&gt;            }&lt;br /&gt;            RunNext();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // concrete chain handler object&lt;br /&gt;    public class ChainHandlerThree : ChainHandlerBase&lt;br /&gt;    {&lt;br /&gt;        public ChainHandlerThree(RequestData requestData) : base(requestData) { }&lt;br /&gt;        public override void Run()&lt;br /&gt;        {&lt;br /&gt;            if ((!_requestData.HaveLotOfMoney) &amp;&amp; (_requestData.HaveBrilliantIdea))&lt;br /&gt;            {&lt;br /&gt;                _requestData.MessageBack = "What a nice idea.";&lt;br /&gt;                return;&lt;br /&gt;            }&lt;br /&gt;            RunNext();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // concrete chain handler object&lt;br /&gt;    public class ChainHandlerFour : ChainHandlerBase&lt;br /&gt;    {&lt;br /&gt;        public ChainHandlerFour(RequestData requestData) : base(requestData) { }&lt;br /&gt;        public override void Run()&lt;br /&gt;        {&lt;br /&gt;            if ((!_requestData.HaveLotOfMoney) &amp;&amp; (!_requestData.HaveBrilliantIdea))&lt;br /&gt;            {&lt;br /&gt;                _requestData.MessageBack = "Don't give up.";&lt;br /&gt;                return;&lt;br /&gt;            }&lt;br /&gt;            RunNext();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Set Up the Chain&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;We are ready at this point to put in order the chain. We create chain handler objects and link them in a appropriate order. We send to the first handler in the chain a request data object and hit the Run() method to get the result calculated.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;        // wraps the chain initialization and processing code&lt;br /&gt;        static RequestData WhatAboutMe(RequestData requestData)&lt;br /&gt;        {&lt;br /&gt;            // construct the first chain handler.&lt;br /&gt;            ChainHandlerBase firstHandler = new ChainHandlerOne(requestData);&lt;br /&gt;&lt;br /&gt;            // arrange chain of responsibility as list of chain handker objects&lt;br /&gt;            firstHandler&lt;br /&gt;                .SetNextLink(new ChainHandlerTwo(requestData))&lt;br /&gt;                .SetNextLink(new ChainHandlerThree(requestData))&lt;br /&gt;                .SetNextLink(new ChainHandlerFour(requestData));&lt;br /&gt;&lt;br /&gt;            // start processing of the request data&lt;br /&gt;            firstHandler.Run();&lt;br /&gt;&lt;br /&gt;            // return back the request data with the message created&lt;br /&gt;            return requestData;&lt;br /&gt;        }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Run the Chain&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;The win of utilizing chain responsibility pattern is the extensibility of our code in future. If we need additional logic we have to implement new chain handler class. We also may construct the chains in one or another way, we can order the chain handler object based on concrete needs. We absolutely take care of single responsibility principle and we divide a long and complicated to maintain code into well testable small classes.&lt;br /&gt;&lt;br /&gt;Finally let’s run our chain of responsibility implementation. We’ll send every possible combination of input to the chain and see what’ll happen.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;static void Main(string[] args)&lt;br /&gt;{&lt;br /&gt;  Console.WriteLine(WhatAboutMe(new RequestData {&lt;br /&gt;    HaveLotOfMoney = true, HaveBrilliantIdea = true }).MessageBack);&lt;br /&gt;&lt;br /&gt;  Console.WriteLine(WhatAboutMe(new RequestData {&lt;br /&gt;    HaveLotOfMoney = true, HaveBrilliantIdea = false }).MessageBack);&lt;br /&gt;&lt;br /&gt;  Console.WriteLine(WhatAboutMe(new RequestData { &lt;br /&gt;    HaveLotOfMoney = false, HaveBrilliantIdea = true }).MessageBack);&lt;br /&gt;&lt;br /&gt;  Console.WriteLine(WhatAboutMe(new RequestData { &lt;br /&gt;    HaveLotOfMoney = false, HaveBrilliantIdea = false }).MessageBack);&lt;br /&gt;&lt;br /&gt;  Console.Write("Hit Enter to finish.");&lt;br /&gt;  Console.ReadLine();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Running that we get on the console like:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_pNNYA7XMbCI/Sqp4Dg_voBI/AAAAAAAAABY/eeJF8BqXe6w/s1600-h/chain-of-resp-result.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 230px; height: 82px;" src="http://2.bp.blogspot.com/_pNNYA7XMbCI/Sqp4Dg_voBI/AAAAAAAAABY/eeJF8BqXe6w/s400/chain-of-resp-result.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5380244706639716370" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f09%2fdesign-patterns-chain-of-responsibility.html"&gt;&lt;img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fatanashristov.blogspot.com%2f2009%2f09%2fdesign-patterns-chain-of-responsibility.html" border="0" alt="kick it on DotNetKicks.com" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a rev="vote-for" href="http://dotnetshoutout.com/Atanas-Hristov-Design-Patterns-Chain-of-Responsibility-Pattern-blog-about-programming"&gt;&lt;img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fatanashristov.blogspot.com%2F2009%2F09%2Fdesign-patterns-chain-of-responsibility.html" style="border:0px"/&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-4202771426746542566?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/4202771426746542566/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/09/design-patterns-chain-of-responsibility.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4202771426746542566'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4202771426746542566'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/09/design-patterns-chain-of-responsibility.html' title='Design Patterns – Chain of Responsibility Pattern'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_pNNYA7XMbCI/Sqp4Dg_voBI/AAAAAAAAABY/eeJF8BqXe6w/s72-c/chain-of-resp-result.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-4332117611278368787</id><published>2009-09-07T04:02:00.001-07:00</published><updated>2009-09-07T04:13:07.156-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ASP.NET MVC'/><title type='text'>Upload file to database with ASP.NET MVC and Castle Active Record</title><content type='html'>A file upload function to web application raises the question where to store the uploaded data. One possibility is to just store into the file system. This is inexpensive and easy to implement, but you have to think for file backups. If you don’t have huge amount of data you can also upload files directly into a database using binary format for table column to store the content of the file.&lt;br /&gt;&lt;br /&gt;In this post I’m going to give a try of the second option and create simple application to store uploaded files directly into the database.&lt;br /&gt;&lt;br /&gt;I will use &lt;a href="http://www.postgresql.org/"&gt;Postgres&lt;/a&gt; database to store the file uploads and as ORM I will use &lt;a href="http://www.castleproject.org/activerecord/"&gt;Active Record&lt;/a&gt; from the Castle project. Then I need a driver for .NET to connect to the database, we will use the &lt;a href="http://npgsql.projects.postgresql.org/"&gt;Npgsql&lt;/a&gt; driver.&lt;br /&gt;&lt;br /&gt;With Castle Active Record you can easy switch to another database server; it’s just matter of switching the referenced driver and replace appropriately the configuration into Web.config file.&lt;br /&gt;&lt;br /&gt;Assume we have PostgreSQL Server on localhost up and running and we will connect to the database "postgres" as user "postgres".&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Create the project and set the configuration&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;We start with creating new ASP.MVC Application in Visual Studio and give it the name of "UploadToDb".&lt;br /&gt;&lt;br /&gt;We then add references to the following assemblies from our project:&lt;br /&gt;&lt;br /&gt;NHibernate.dll&lt;br /&gt;Castle.ActiveRecord.dll&lt;br /&gt;Castle.Components.Validator.dll&lt;br /&gt;Castle.Core.dll&lt;br /&gt;Castle.DynamicProxy.dll&lt;br /&gt;Iesi.Collections.dll&lt;br /&gt;Npgsql.dll&lt;br /&gt;&lt;br /&gt;We change the Web.config file and add the appropriate settings for Active Record.&lt;br /&gt;&lt;br /&gt;In "configSections" we add new section sub element for the Active Record. Next to "configSections" we add "activerecord" element where we specify the connection parameters and the database driver we are going to use.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;   &amp;lt;configSections&amp;gt;&lt;br /&gt;      &amp;lt;section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" /&amp;gt;&lt;br /&gt;            ….&lt;br /&gt;   &amp;lt;/configSections&amp;gt;&lt;br /&gt;   &amp;lt;activerecord isWeb="false" isDebug="true"&amp;gt;&lt;br /&gt;      &amp;lt;config&amp;gt;&lt;br /&gt;         &amp;lt;add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/&amp;gt;&lt;br /&gt;         &amp;lt;add key="hibernate.dialect" value="NHibernate.Dialect.PostgreSQL81Dialect"/&amp;gt;&lt;br /&gt;         &amp;lt;add key="hibernate.connection.driver_class" value="NHibernate.Driver.NpgsqlDriver"/&amp;gt;&lt;br /&gt;         &amp;lt;add key="hibernate.connection.connection_string" value="Server=localhost;Port=5432;Database=postgres;User ID=postgres;Password=;"/&amp;gt;&lt;br /&gt; &amp;lt;/config&amp;gt;&lt;br /&gt;   &amp;lt;/activerecord&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Database table and domain model&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;First we'll create Active Record class for the domain object "Upload" into Models directory. This is an entity object and has property Id which is a primary key into the database. We’ve got also data property which holds the binary data from the file we upload. There is also mimetype property which holds the MIME type of the uploaded file.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Web;&lt;br /&gt;using Castle.ActiveRecord;&lt;br /&gt;using Castle.ActiveRecord.Framework.Scopes;&lt;br /&gt;using NHibernate.Expression;&lt;br /&gt;using System.Data;&lt;br /&gt;using System.Collections;&lt;br /&gt;&lt;br /&gt;namespace UploadToDb.Models&lt;br /&gt;{&lt;br /&gt;    [ActiveRecord("uploads")]&lt;br /&gt;    public class Upload : ActiveRecordBase&amp;lt;Upload&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        private int id = 0;&lt;br /&gt;        [PrimaryKey(PrimaryKeyType.Sequence, SequenceName = "uploads_seq")]&lt;br /&gt;        public int Id&lt;br /&gt;        {&lt;br /&gt;            get { return id; }&lt;br /&gt;            set { id = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private byte[] data = new byte[] { };&lt;br /&gt;        [Property]&lt;br /&gt;        public byte[] Data&lt;br /&gt;        {&lt;br /&gt;            get { return data; }&lt;br /&gt;            set { data = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private string mimetype = "";&lt;br /&gt;        [Property]&lt;br /&gt;        public string Mimetype&lt;br /&gt;        {&lt;br /&gt;            get { return mimetype; }&lt;br /&gt;            set { mimetype = value; }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public static Upload FindById(int id)&lt;br /&gt;        {&lt;br /&gt;            return FindOne(Expression.Eq("Id", id));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;To search uploaded files into the database we use the above implemented method FindById(int) which is just used to enclose and wrap that extra Actie Record syntax with the expressions. Otherwise we have a lot of search capabilities coming with Active Record, for example to get list of all file uploads we use Models.Upload.FindAll() as the class Models.Upload inherits from ActiveRecordBase class.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;We create table to store the uploaded files&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;CREATE TABLE "uploads" (&lt;br /&gt; "id" int DEFAULT 0 NOT NULL,&lt;br /&gt; "mimetype" Varchar NOT NULL,&lt;br /&gt; "data" Bytea&lt;br /&gt;);&lt;br /&gt;&lt;br /&gt;ALTER TABLE "uploads" ADD CONSTRAINT "uploads_pk" PRIMARY KEY ("id");&lt;br /&gt;&lt;br /&gt;CREATE SEQUENCE uploads_seq START 1;&lt;br /&gt;ALTER TABLE uploads ALTER COLUMN id SET DEFAULT nextval('uploads_seq'::text);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Set up the application&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;At application start we will initialize Active Record. Open Global.asax.cs file and edit method Application_Start(). After RegisterRoutes we add the initialization piece of code:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;protected void Application_Start()&lt;br /&gt;{&lt;br /&gt;  RegisterRoutes(RouteTable.Routes);&lt;br /&gt;&lt;br /&gt;  // load configuration from Web.config&lt;br /&gt;  Castle.ActiveRecord.Framework.IConfigurationSource source =&lt;br /&gt;    System.Configuration.ConfigurationManager.GetSection("activerecord")&lt;br /&gt;    as Castle.ActiveRecord.Framework.IConfigurationSource;&lt;br /&gt;&lt;br /&gt;  // Initialize and mention which types define our model&lt;br /&gt;  Castle.ActiveRecord.ActiveRecordStarter.Initialize(source,&lt;br /&gt;    typeof(Models.Upload));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The UploadController class&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Basically we’d need three different URLs: Add – to upload new file; Get- to get uploaded file and finally Index which gives us list of all uploads.&lt;br /&gt; &lt;br /&gt;We’ll create UploadController class in Controllers directory.  Then we implement the three methods.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Collections.Generic;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Web;&lt;br /&gt;using System.Web.Mvc;&lt;br /&gt;using System.Web.Mvc.Ajax;&lt;br /&gt;&lt;br /&gt;namespace UploadToDb.Controllers&lt;br /&gt;{&lt;br /&gt;    public class UploadController : Controller&lt;br /&gt;    {&lt;br /&gt;        [AcceptVerbs(HttpVerbs.Post)]&lt;br /&gt;        public ActionResult Add(HttpPostedFileBase file)&lt;br /&gt;        {&lt;br /&gt;            if (file != null)&lt;br /&gt;            {&lt;br /&gt;                Models.Upload upload = new UploadToDb.Models.Upload();&lt;br /&gt;                upload.Mimetype = file.ContentType;&lt;br /&gt;                upload.Data = new byte[file.ContentLength];&lt;br /&gt;                file.InputStream.Read(upload.Data, 0, file.ContentLength);&lt;br /&gt;                upload.Save();&lt;br /&gt;            }&lt;br /&gt;            return Index();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public FileContentResult Get(int id)&lt;br /&gt;        {&lt;br /&gt;            Models.Upload upload = Models.Upload.FindById(id);&lt;br /&gt;            return File(upload.Data, upload.Mimetype);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public ActionResult Index()&lt;br /&gt;        {&lt;br /&gt;            this.ViewData["uploads"] = Models.Upload.FindAll();&lt;br /&gt;            return this.View("Index");&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Method Add() calls Index() after the file upload finished, those way we get the list of the uploads after we upload new file.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The HTML view&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Created directory Views\Upload and add there view Index. I won’t select a master page for the purpose of the presentation. I also won’t use strongly-typed view, but just will thread the ViewData as a dictionary.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;html xmlns="http://www.w3.org/1999/xhtml" &amp;gt;&lt;br /&gt;&amp;lt;head runat="server"&amp;gt;&lt;br /&gt;    &amp;lt;title&amp;gt;File uploads&amp;lt;/title&amp;gt;&lt;br /&gt;&amp;lt;/head&amp;gt;&lt;br /&gt;&amp;lt;body&amp;gt;&lt;br /&gt;&lt;br /&gt;    &amp;lt;h3&amp;gt;1.List of uploads&amp;lt;/h3&amp;gt;&lt;br /&gt;    &amp;lt;%&lt;br /&gt;        UploadToDb.Models.Upload[] uploads = (UploadToDb.Models.Upload[])this.ViewData["uploads"];&lt;br /&gt;        foreach (UploadToDb.Models.Upload upload in uploads.OrderBy(x=&amp;gt; x.Id))&lt;br /&gt;        {&lt;br /&gt;    %&amp;gt;&lt;br /&gt;            &amp;lt;div&amp;gt;&amp;lt;%= Html.ActionLink(upload.Id.ToString(), "Get", new { upload.Id })%&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;    &amp;lt;%&lt;br /&gt;        }&lt;br /&gt;    %&amp;gt;&lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;    &amp;lt;h3&amp;gt;2.Upload new file&amp;lt;/h3&amp;gt;&lt;br /&gt;    &amp;lt;% using (Html.BeginForm("Add", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) &lt;br /&gt;       { %&amp;gt;&lt;br /&gt;        Choose file: &amp;lt;input type="file" name="file" /&amp;gt;&lt;br /&gt;        &amp;lt;input type="submit" /&amp;gt;       &lt;br /&gt;    &amp;lt;% } %&amp;gt;&lt;br /&gt;    &lt;br /&gt;    &lt;br /&gt;&amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Basically we have two parts here.&lt;br /&gt;&lt;br /&gt;Part one is a list of all the uploaded files. It creates list of links to open the uploaded files via the "Get" method.&lt;br /&gt;&lt;br /&gt;Part two is an html multipart form used to upload new file. After the file upload finished, we invoke again the Index controller method to list all the files uploaded to the database.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;To upload file to database run the application and navigate the browser to ~/Upload/ directory.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I've got that screen after two files uploaded:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_pNNYA7XMbCI/SqTp2ofChKI/AAAAAAAAABQ/5KuWClXzwuY/s1600-h/uploaded-two-files.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 175px;" src="http://3.bp.blogspot.com/_pNNYA7XMbCI/SqTp2ofChKI/AAAAAAAAABQ/5KuWClXzwuY/s400/uploaded-two-files.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5378680979777029282" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Enjoy!&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-4332117611278368787?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/4332117611278368787/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/09/upload-file-to-database-with-aspnet-mvc.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4332117611278368787'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/4332117611278368787'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/09/upload-file-to-database-with-aspnet-mvc.html' title='Upload file to database with ASP.NET MVC and Castle Active Record'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_pNNYA7XMbCI/SqTp2ofChKI/AAAAAAAAABQ/5KuWClXzwuY/s72-c/uploaded-two-files.png' height='72' width='72'/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-1732617251713000930</id><published>2009-09-04T09:21:00.001-07:00</published><updated>2009-09-04T09:23:36.829-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='log4net'/><title type='text'>Logging with log4net</title><content type='html'>Log4net is a very powerful tool to get information from running application. After deployment your code has to deal with environment that is more or less different than on your development machine. Log4net not only provides your application with powerful logging where you can specify a lot of options and levels, but you can even dynamically  turn on and off logging for different classes while the application is running at the same time.&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;The homepage of the project is:&lt;br /&gt;http://logging.apache.org/log4net/index.html&lt;br /&gt;&lt;br /&gt;I’m about to show you the way I’m usually using log4net in my projects.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Step one&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;The very first step is to add reference to log4net.dll to the project.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Initialization of log4net&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;It has to be done once in your application. You can prepare and run static initializer in the manner of:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt; &lt;br /&gt;public class Initializer&lt;br /&gt;{&lt;br /&gt;    private static object _locked = new object();&lt;br /&gt;    protected static bool initialized = false;&lt;br /&gt;&lt;br /&gt;    public static Initializer() { Init(); }&lt;br /&gt;    &lt;br /&gt;    public static void Init()&lt;br /&gt;    {&lt;br /&gt;        lock (_locked)&lt;br /&gt;        {&lt;br /&gt;            if (initialized)&lt;br /&gt;                return;&lt;br /&gt;&lt;br /&gt;            log4net.Config.XmlConfigurator.Configure(); // run once at app startup&lt;br /&gt;    ...&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Then call Initializer.Init() at application start-up from your Global.aspx or Main() for example.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Add logger for one class&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;One possibility to use log4net is to create separate logger for one class only. Thereof you can:&lt;br /&gt;&lt;br /&gt;a/ write to separate and dedicated for that class only log file, &lt;br /&gt;b/ or you can have different formating for logging messages from that class, &lt;br /&gt;c/ or you can set different log level for the log messages from that class, &lt;br /&gt;d/ or just because the class name could be written along with the logging messages so it will be easy to localize the part of the code from where the message comes.&lt;br /&gt;&lt;br /&gt;Here is part of declaration of class named "McChannel" for which class we will define class logger.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt; &lt;br /&gt;&lt;br /&gt;// (1) add using directives:&lt;br /&gt;...&lt;br /&gt;using log4net;&lt;br /&gt;using log4net.Config;&lt;br /&gt;&lt;br /&gt;[ActiveRecord("mc_channels")]&lt;br /&gt;public class McChannel : ActiveRecordBase&lt;McChannel&gt;&lt;br /&gt;{&lt;br /&gt;    // (2) declare and initialize static per class logger&lt;br /&gt;    private static readonly ILog log = LogManager.GetLogger(typeof(McChannel));&lt;br /&gt;...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;From inside the body of that class you can use the logger "log" like:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt; &lt;br /&gt;&lt;br /&gt;  log.Debug("Selecting channel names at.");&lt;br /&gt;  log.DebugFormat("Addiding channel {0}", one.Channel_name_official);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;You have log.Debug(), log.Info(), log.Warn(), log.Error(), log.Fatal() methods you use for logging and they all have the corresponding extended with string formatting methods: log.DebugFormat(), log.InfoFormat(), log.WarnFormat(), log.ErrorFormat(), log.FatalFormat(). In the exact priority order as listed here the Debug() has the lowermost priority. &lt;br /&gt;&lt;br /&gt;In your configuration (see below) you have to set which level of logging you want to log. The logging levels as they are defined in order of decreasing priority are:&lt;br /&gt;&lt;br /&gt;OFF: no logging at all.&lt;br /&gt;FATAL: only log.Fatal() messages will be logged&lt;br /&gt;ERROR: log.Error()and higher will be logged&lt;br /&gt;WARN: log.Warn() and higher will be logged&lt;br /&gt;INFO: log.Info()and higher will be logged&lt;br /&gt;DEBUG: log.Fatal()and higher will be logged&lt;br /&gt;ALL: all logging methods will be logged.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Configuration of log4net in App.config or Web.config&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Let's prepare simple configuration for log4net.&lt;br /&gt;&lt;br /&gt;First in configSections we add element section with attribute name="log4net".&lt;br /&gt;Then we add sub element "log4net"  to element "configuration". &lt;br /&gt;&lt;br /&gt;We create appender "RollingFileAppender" which defines where we write logging messages and what the pattern for formatting the log messages is. Furthermore the files will be rotated.&lt;br /&gt;&lt;br /&gt;We can have more than one appender in your configuration.&lt;br /&gt;&lt;br /&gt;Then we default set priority levels for the whole application to "ERROR" - see element "root" - but we define for class "McChannel" priority level of "DEBUG".&lt;br /&gt;&lt;br /&gt;Here is the complete example:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt; &lt;br /&gt;&lt;br /&gt;&amp;lt;?xml version="1.0"?&amp;gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;  &amp;lt;configSections&amp;gt;&lt;br /&gt;    &amp;lt;section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /&amp;gt;&lt;br /&gt;  &amp;lt;/configSections&amp;gt;&lt;br /&gt;  &amp;lt;log4net&amp;gt;&lt;br /&gt;    &amp;lt;appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"&amp;gt;&lt;br /&gt;      &amp;lt;file value="D:\Logfile.txt" /&amp;gt;&lt;br /&gt;      &amp;lt;appendToFile value="true" /&amp;gt;&lt;br /&gt;      &amp;lt;rollingStyle value="Size" /&amp;gt;&lt;br /&gt;      &amp;lt;maxSizeRollBackups value="100" /&amp;gt;&lt;br /&gt;      &amp;lt;maximumFileSize value="1024KB" /&amp;gt;&lt;br /&gt;      &amp;lt;staticLogFileName value="true" /&amp;gt;&lt;br /&gt;      &amp;lt;layout type="log4net.Layout.PatternLayout"&amp;gt;&lt;br /&gt;        &amp;lt;conversionPattern value="%date %-5level %logger - %message%newline" /&amp;gt;&lt;br /&gt;      &amp;lt;/layout&amp;gt;&lt;br /&gt;    &amp;lt;/appender&amp;gt;&lt;br /&gt;    &amp;lt;root&amp;gt;&lt;br /&gt;      &amp;lt;!-- ALL DEBUG INFO WARN ERROR FATAL OFF --&amp;gt;&lt;br /&gt;      &amp;lt;!-- Setup the root category, add the appenders and set the default level to ERROR --&amp;gt;&lt;br /&gt;      &amp;lt;priority value="ERROR" /&amp;gt;&lt;br /&gt;      &amp;lt;!-- Set the default logger  --&amp;gt;&lt;br /&gt;      &amp;lt;appender-ref ref="RollingFileAppender" /&amp;gt;&lt;br /&gt;    &amp;lt;/root&amp;gt;&lt;br /&gt;    &amp;lt;logger name="McChannel"&amp;gt;&lt;br /&gt;      &amp;lt;!-- Only for the logger for class McChannel we set level to DEBUG --&amp;gt;&lt;br /&gt;      &amp;lt;level value="DEBUG" /&amp;gt;&lt;br /&gt;    &amp;lt;/logger&amp;gt;&lt;br /&gt;  &amp;lt;/log4net&amp;gt;&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The output of logging messages from class McChannel goes to D:\Logfile.txt after we run the application.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;this.Dispose()&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Log4net is very flexible. You can add the logging messages into a database table, you can use the TraceContext of ASP.NET, the console appender can produce colorized output, you can append to the Application event log in Windows, address Windows Messenger Service, send emails with logging messages and many more.&lt;br /&gt;&lt;br /&gt;Have a nice weekend!&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-1732617251713000930?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/1732617251713000930/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/09/logging-with-log4net.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/1732617251713000930'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/1732617251713000930'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/09/logging-with-log4net.html' title='Logging with log4net'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-188283006359152284</id><published>2009-08-07T07:06:00.000-07:00</published><updated>2009-08-07T09:03:48.154-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ELMAH'/><category scheme='http://www.blogger.com/atom/ns#' term='ASP.NET'/><title type='text'>ASP.NET Error Logging with ELMAH</title><content type='html'>Debugging production code is always a challenge. From my experience I have used the &lt;a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx"&gt;Windows event logs&lt;/a&gt; and the Apache &lt;a href="http://logging.apache.org/log4net/index.html"&gt;log4net&lt;/a&gt; so far.&lt;br /&gt;&lt;br /&gt;Most of the time log4net is the solution for all my needs and I like how flexible it is. But they were situations where the logging solution was not enough. The real problem occurs if in your application you get unhandled exceptions. You know - database connection broken, network downtime, system software updates - it's in many ways possible to throw the application into confusion without having even the near idea where to look for. And this is where &lt;a href="http://code.google.com/p/elmah/"&gt;ELMAH&lt;/a&gt; comes to the rescue.&lt;br /&gt;&lt;br /&gt;You can include ELMAH in your projects with a little effort and even with the default configuration you take benefits. ELMAH can log errors for you to different places - from xml files to database servers but the easiest way is to just store error messages into memory. ELMAH will give you a way to check for unhandled exceptions from special URL on your ASP.NET site.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Addiding ELMAH to a project&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Having heard for ELMAH from Hanselminutes I decided to give a try.&lt;br /&gt;There was a project under active development where new versions uploaded on the staging server very frequently, even many times a day. &lt;br /&gt;&lt;br /&gt;After the download of the binaries I just added a reference to &lt;b&gt;Elmah.dll&lt;/b&gt; into the project. Then following the instructions on the ELMAH &lt;a href="http://code.google.com/p/elmah/wiki/MVC"&gt;documentation&lt;/a&gt; I made few additions to the &lt;b&gt;Web.config&lt;/b&gt; file.&lt;br /&gt;&lt;br /&gt;a/ I added to "configSections":&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;    &amp;lt;sectionGroup name="elmah"&amp;gt;&lt;br /&gt;      &amp;lt;section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" /&amp;gt;&lt;br /&gt;      &amp;lt;section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" /&amp;gt;&lt;br /&gt;      &amp;lt;section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" /&amp;gt;&lt;br /&gt;      &amp;lt;section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" /&amp;gt;&lt;br /&gt;    &amp;lt;/sectionGroup&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;b/ Then added into "httpHandlers":&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;  &amp;lt;add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" /&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;c/ and at the end into "httpModules":&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;  &amp;lt;add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;I also added another configuration option to enable opening the ELMAH views from remote connection, not only on the server, into section "configuration" I added:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;  &amp;lt;elmah&amp;gt;&lt;br /&gt;    &amp;lt;security allowRemoteAccess="yes" /&amp;gt;&lt;br /&gt;  &amp;lt;/elmah&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That was everything necessary to include ELMAH to the project.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Did I say - ELMAH is wonderful!&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Having ELMAH included to the web application with this configuration, we have got the error logging information accessible at http://APPHOME/elmah.axd.&lt;br /&gt;&lt;br /&gt;We put into the staging server only well unit-tested code. Once as we did changes on the database schema we have forgotten to patch the database where the staging server connects.&lt;br /&gt;&lt;br /&gt;During the integration tests the application raised an exception. On the browser the exception information was not very helpful (see: &lt;a href="http://en.wikipedia.org/wiki/Yellow_Screen_of_Death#ASP.NET"&gt;yellow screen of dead&lt;/a&gt;). Into the log files generated by log4net there was nothing mentioned. Then we opened the ELMAH page and we saw the reason for the exception:&lt;br /&gt;&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_pNNYA7XMbCI/SnxQN8_BFCI/AAAAAAAAAAk/lnxkqnkXq-0/s1600-h/ELMAH01a.png"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 204px;" src="http://3.bp.blogspot.com/_pNNYA7XMbCI/SnxQN8_BFCI/AAAAAAAAAAk/lnxkqnkXq-0/s400/ELMAH01a.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5367253056557749282" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;ELMAH is a tool to help you with any ASP.NET project. Use it &lt;b&gt;right now&lt;/b&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-188283006359152284?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/188283006359152284/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/08/aspnet-error-logging-with-elmah.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/188283006359152284'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/188283006359152284'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/08/aspnet-error-logging-with-elmah.html' title='ASP.NET Error Logging with ELMAH'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_pNNYA7XMbCI/SnxQN8_BFCI/AAAAAAAAAAk/lnxkqnkXq-0/s72-c/ELMAH01a.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-5227158523885170978</id><published>2009-08-03T03:58:00.000-07:00</published><updated>2009-08-05T02:15:47.943-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Globalization'/><category scheme='http://www.blogger.com/atom/ns#' term='ASP.NET'/><title type='text'>ASP.NET Globalization</title><content type='html'>I just finished a project where one of the requirements was to localize completely the input the user gave and the output of values (numbers, date) sent back to the user.&lt;br /&gt;&lt;br /&gt;There is a nice way in dot.NET to set current culture information on a thread. You can for example examine the Request.UserLanguages - which is an array of strings and shows you which locales and languages the browser accepted - and then prepare CultureInfo object and assign that object to CurrentThread.&lt;br /&gt;&lt;br /&gt;That way you set culture info for every request on the webserver. You use later the culture info information from CurrentThread to parse the user input and to write back localized values to the user.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Set CultureInfo for CurrentThread&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;The very first step is to set the culture information on CurrentThread on per page request basis. To do so edit function Application_BeginRequest from file Global.aspx.cs.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;      protected void Application_BeginRequest(object sender, EventArgs e)&lt;br /&gt;      {&lt;br /&gt;          // you could use Request.UserLanguages&lt;br /&gt;          // to set appropriate culture information&lt;br /&gt;          System.Globalization.CultureInfo ci = …;          &lt;br /&gt;          System.Threading.Thread.CurrentThread.CurrentCulture = ci;&lt;br /&gt;      }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Set ASP.NET AJAX in your Master Page or View Page&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Edit file Site.Master (or the MasterPage or ViewPage where the ScriptManager is.&lt;br /&gt;Set EnableScriptGlobalization attribute to "true". Insert bug-fix for Number.parseLocal&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&amp;lt;form id="frm" runat="server"&amp;gt;&lt;br /&gt;    &amp;lt;asp:ScriptManager&lt;br /&gt;ID="ScriptManager1"&lt;br /&gt;runat="server"&lt;br /&gt;EnableScriptGlobalization="true"&amp;gt;&lt;br /&gt;        &amp;lt;Services&amp;gt;&lt;br /&gt;            &amp;lt;asp:ServiceReference Path="~/WebServices/Service.asmx" /&amp;gt;&lt;br /&gt;            ...&lt;br /&gt;        &amp;lt;/Services&amp;gt;&lt;br /&gt;    &amp;lt;/asp:ScriptManager&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;script type="text/javascript"&amp;gt;&lt;br /&gt;    Number.parseLocaleFixed = function(value) {&lt;br /&gt;        return Number.parseLocale(value.replace(' ', ' '));&lt;br /&gt;    }&lt;br /&gt;&amp;lt;/script&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Parse User Input in ASP.NET Ajax&lt;/h3&gt;&lt;br /&gt;To parse user input of numbers use Number.parseLocaleFixed() javascript function. To parse user input of date use Date.parseLocale() javascript function.&lt;br /&gt;Example:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt; Var numb = Number.parseLocaleFixed(&lt;br /&gt;     document.getELementById(‘txtNumb’).value);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Parse user input in ASPX page&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;Use the Parse() functions of the expected type. Specify the culture info in Parse(). Take the culture info from CurrentThread.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt; DateTime dt = DateTime.Parse(s,&lt;br /&gt;         System.Threading.Thread&lt;br /&gt;            .CurrentThread.CurrentCulture);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Write localized Information to the page&lt;/h3&gt;&lt;br /&gt;&lt;br /&gt;To write localized values to the page use the culture information from CurrentThread:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt; &amp;lt;%= dt.ToString(“d”, System.Threading.Thread&lt;br /&gt;           .CurrentThread.CurrentCulture) %&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To write localized pattern for validation of date input field you can use something like:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;&lt;br /&gt;   CultureInfo ci = System.Threading.Thread&lt;br /&gt;            .CurrentThread.CurrentCulture;&lt;br /&gt;&lt;br /&gt;   // validation of date input&lt;br /&gt; string dSeparator = ci.DateTimeFormat.DateSeparator;&lt;br /&gt; if (dSeparator == ".") dSeparator = @"\.";&lt;br /&gt; string dPatternExpr = String.Format(@"^(|[0-9]{{1,4}}{0}[0-9]{{1,4}}{0}[0-9]{{1,4}})$",&lt;br /&gt;     dSeparator);&lt;br /&gt;&lt;br /&gt; valSigningDate.ValidationExpression = dPatternExpr;&lt;br /&gt;&lt;br /&gt; // validation of number input&lt;br /&gt; string nDecimalSeparator = ci.NumberFormat.CurrencyDecimalSeparator;&lt;br /&gt; if (nDecimalSeparator == ".") nDecimalSeparator = @"\.";&lt;br /&gt; string nPatternExpr = String.Format(@"^[-+]?[0-9]*{0}?[0-9]*$",&lt;br /&gt;     nDecimalSeparator);&lt;br /&gt;&lt;br /&gt; valSinglePayment.ValidationExpression = nPatternExpr;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-5227158523885170978?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/5227158523885170978/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/08/aspnet-globalisation.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/5227158523885170978'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/5227158523885170978'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/08/aspnet-globalisation.html' title='ASP.NET Globalization'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6595360840585786394.post-2009645972331752479</id><published>2009-08-01T07:56:00.000-07:00</published><updated>2009-08-05T02:15:32.691-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='SQLite'/><category scheme='http://www.blogger.com/atom/ns#' term='ADO.NET'/><category scheme='http://www.blogger.com/atom/ns#' term='Entity Framework'/><title type='text'>Using Entity Framework with  SQLite - Installation</title><content type='html'>&lt;strong&gt;&lt;a href="http://www.sqlite.org/"&gt;SQLite&lt;/a&gt;&lt;/strong&gt; is a simple but powerful open source database engine which you can use among everything else at development time and later connect your application to database server at run time.&lt;br /&gt;&lt;br /&gt;Tools I have found to be pretty helpful to administer SQLite databases are:  &lt;strong&gt;&lt;a href="http://www.sqliteexpert.com/download.html"&gt;SQLite Expert Personal&lt;/a&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;a href="http://sqliteadmin.orbmu2k.de/"&gt;sqliteadmin&lt;/a&gt;&lt;/strong&gt;.&lt;br /&gt;&lt;br /&gt;To use SQLite with the Entity Framework you need ADO.NET Provider. A complete provider is &lt;strong&gt;&lt;a href="http://sqlite.phxsoftware.com/"&gt;System.Data.SQLite&lt;/a&gt;&lt;/strong&gt;.&lt;br /&gt;&lt;br /&gt;Download file &lt;b&gt;SQLite-1.0.65.0-setup.exe&lt;/b&gt; and install to appropriate location. I used directory C:\Programme\SQLite.NET as installation directory. In subdirectory bin into the installation directory you'll find two libraries - "System.Data.SQLite.Linq.dll", "System.Data.SQLite.dll" -  which you optionally can register into the global assembly cache (gacutil -I ). To connect the Entity Framework to SQLite database you'll need to add references to these two assemblies.&lt;br /&gt;&lt;br /&gt;Now, there is a nice dot.NET project on MSDN - &lt;strong&gt;&lt;a href="http://code.msdn.microsoft.com/EFQuerySamples"&gt;EFQuerySamples&lt;/a&gt;&lt;/strong&gt; - which demonstrates the Entity Framework with the well known Northwind database. You can use that application to learn the syntax of the Entity Framework queries and even to see the generated SQL. Download the project and unzip the file.&lt;br /&gt;&lt;br /&gt;To get the EFQuerySamples running against SQLite database, there is a supplement to the MSDN project - &lt;strong&gt;&lt;a href="http://sqlite.phxsoftware.com/forums/p/1377/5921.aspx#5921"&gt;EFQuerySamples_SQLite&lt;/a&gt;&lt;/strong&gt;. You need to copy from this over the original project the following files. &lt;br /&gt;&lt;br /&gt;Having the two projects unzipped next to each other copy:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;file EFQuerySamples_SQLite\App.config to EFQuerySamples\App.config&lt;br /&gt;file EFQuerySamples_SQLite\Entity Framework Query Samples.csproj to EFQuerySamples\Entity Framework Query Samples.csproj&lt;br /&gt;file EFQuerySamples_SQLite\DB\northwindEF.db to EFQuerySamples\DB\northwindEF.db&lt;br /&gt;file EFQuerySamples_SQLite\Schemas\NorthwindEFModel.SQLite.ssdl to EFQuerySamples\Schemas\NorthwindEFModel.SQLite.ssdl&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Open the Visual Studio solution from EFQuerySamples.&lt;br /&gt;&lt;br /&gt;Add references to the assemblies System.Data.SQLite and System.Data.SQLite.Linq.&lt;br /&gt;&lt;br /&gt;Open file App.config and add  new &lt;b&gt;DbProviderFactory&lt;/b&gt;:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;  &lt;br /&gt;  &amp;lt;system.data&amp;gt;&lt;br /&gt;    &amp;lt;DbProviderFactories&amp;gt;&lt;br /&gt;      &amp;lt;remove invariant="System.Data.SQLite"/&amp;gt;&lt;br /&gt;      &amp;lt;add name="SQLite Data Provider" invariant="System.Data.SQLite" &lt;br /&gt;           description=".Net Framework Data Provider for SQLite" &lt;br /&gt;           type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"/&amp;gt;&lt;br /&gt;   &amp;lt;/DbProviderFactories&amp;gt;&lt;br /&gt;    &amp;lt;/system.data&amp;gt;&lt;br /&gt;   &lt;br /&gt; &lt;/pre&gt;&lt;br /&gt;    &lt;br /&gt; Take care of the &lt;b&gt;Version&lt;/b&gt; in attribute type, make sure equals the version of the System.Data.SQLite.dll you downloaded.&lt;br /&gt;&lt;br /&gt;Also in App.config there should be addition to section &lt;b&gt;connectionStrings&lt;/b&gt; coming with the supplement project:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="cpp"&gt;&lt;br /&gt;  &lt;br /&gt;  &amp;lt;connectionStrings&amp;gt;&lt;br /&gt;    &amp;lt;add name="NorthwindEF (SQLite)" connectionString="provider=System.Data.SQLite;metadata=Schemas\NorthwindEFModel.csdl|Schemas\NorthwindEFModel.msl|Schemas\NorthwindEFModel.SQLite.ssdl;Provider Connection String='Data Source=DB\northwindEF.db'"&lt;br /&gt;      providerName="System.Data.EntityClient" /&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now you can run the EFQuerySamples application, choose the SQLite connection and run the various examples.&lt;br /&gt;&lt;br /&gt;Enjoy!&lt;br /&gt;&lt;br /&gt;Atanas Hristov&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6595360840585786394-2009645972331752479?l=atanashristov.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://atanashristov.blogspot.com/feeds/2009645972331752479/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://atanashristov.blogspot.com/2009/08/using-entity-framework-with-sqlite.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/2009645972331752479'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6595360840585786394/posts/default/2009645972331752479'/><link rel='alternate' type='text/html' href='http://atanashristov.blogspot.com/2009/08/using-entity-framework-with-sqlite.html' title='Using Entity Framework with  SQLite - Installation'/><author><name>Atanas Hristov</name><uri>http://www.blogger.com/profile/09356647829628439069</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='http://1.bp.blogspot.com/_pNNYA7XMbCI/SqAv0wzzpxI/AAAAAAAAAAw/C5Onu1Q3aes/S220/Untitled.jpg'/></author><thr:total>0</thr:total></entry></feed>
