<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>db@net blog site</title>
	<atom:link href="http://www.dbnet.co.il/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dbnet.co.il/blog</link>
	<description>db@net corporate blog</description>
	<lastBuildDate>Sun, 04 Jul 2010 12:26:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Availability &#8211; like an insurance &#8211; only worse</title>
		<link>http://www.dbnet.co.il/blog/2010/07/availability-like-an-insurance-only-worse/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=availability-like-an-insurance-only-worse</link>
		<comments>http://www.dbnet.co.il/blog/2010/07/availability-like-an-insurance-only-worse/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 13:57:24 +0000</pubDate>
		<dc:creator>Ariel Rauch</dc:creator>
				<category><![CDATA[Business Continuity]]></category>

		<guid isPermaLink="false">http://www.dbnet.co.il/blog/?p=24</guid>
		<description><![CDATA[A few years ago, a customer asked us to improve the availability of his Oracle database. The customer ran an internet shop of sorts, and while his revenues were steadily increasing he became aware of the bad impact a system outage might have on his reputation and directly on his pocket&#8230;   A few months after [...]]]></description>
			<content:encoded><![CDATA[<p>A few years ago, a customer asked us to improve the availability of his Oracle database. The customer ran an internet shop of sorts, and while his revenues were steadily increasing he became aware of the bad impact a system outage might have on his reputation and directly on his pocket&#8230; </p>
<p> A few months after the installation and a successful implementation of our solution, an SOS emergency phone call reached our service center at 1 am: </p>
<p> &#8221;<em> &#8230; Our central storage system crashed and although we switched to the standby-database, the database did not start. Could you please help us &#8230;&#8221;</em> </p>
<p>I think the fact that catastrophes in the IT sector always happen at night should be officially added to the Murphy law book. On the other hand, in times of globalization this phenomenon will probably die out. </p>
<p> In addition it is interesting to note that although this customer did not buy our SLA service he knew whom to call&#8230; Never mind! </p>
<p>Anyway, our professionals quickly found out that the synchronization process which was supposed to keep the standby database up-to-date stopped working two weeks ago. Although this database could be opened it would not have presented the actual data. </p>
<p>The customer was lucky in this case, as we were able to recover the data from the crashed central storage and after an all-in-all outage of six hours the site was up and running again. </p>
<p>Almost every technological solution aimed at increasing the availability of a system will automatically also increase the complexity of the underlying infrastructure, as well as the daily maintenance effort. </p>
<p>I am aware that it is quite difficult to explain to a finance department of a company why they should spend more money on addtional hardware, which is solely used to ensure the availability of some applications without gaining any additional benefit in terms of functionality or performance. One way to convince a CFO might be to compare it to buying insurance. An insurance policy will only be useful when something unexpected happens. This comparison unfortunately does not give any reasonable explanation for the higher daily maintenance cost. Let me be very clear: The higher the complexity of an infrastructure, the higher the maintenance cost. This additional cost is not used for the activation of a solution in case of a crash but is aimed to cover the additional effort necessary to keep the normal operation up and running. </p>
<p>In conclusion, and perhaps a bit provocatively I would like to state: </p>
<p>IT infrastructure that was expanded to comply with a certain higher availability will be more liable to outages than before the expansion, without the appropriate daily maintenance. </p>
<p>Yours </p>
<p>Ariel Rauch</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbnet.co.il/blog/2010/07/availability-like-an-insurance-only-worse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OLAP Case Study</title>
		<link>http://www.dbnet.co.il/blog/2010/06/olap-case-study/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=olap-case-study</link>
		<comments>http://www.dbnet.co.il/blog/2010/06/olap-case-study/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 10:02:22 +0000</pubDate>
		<dc:creator>Ben Beres</dc:creator>
				<category><![CDATA[Microsoft SQL Server]]></category>
		<category><![CDATA[Dimensions]]></category>
		<category><![CDATA[Olap case study]]></category>

		<guid isPermaLink="false">http://www.dbnet.co.il/blog/?p=158</guid>
		<description><![CDATA[The best way to learn about <strong>OLAP</strong> is to take look at an example of where it would be useful. You can use this case study as a way to think about your own project. Just instead of trips we could be talking about sales, atmospheric changes, astronomical phenomena, or practically anything.]]></description>
			<content:encoded><![CDATA[<p>The best way to learn about <strong>OLAP</strong> is to take look at an example of where it would be useful. You can use this case study as a way to think about your own project. Just instead of trips we could be talking about sales, atmospheric changes, astronomical phenomena, or practically anything.</p>
<p><em><strong>Case Study:</strong></em> </p>
<p>A company exists that is in charge of keeping track of vehicles via satellite sensors installed in their machine. The purpose is to be able to track all different sorts of statistics about the car and the drivers. When they turn their engines on a unit called a “trip” is started. When they turn their engine off, the “trip” is ended. These trips and all the data associated with them are sent via the sensors into a central SQL Server database.</p>
<p>The company would like to glean from this “sensor data”, information regarding the trip. For example they expect to view the following information:</p>
<ul>
<li>Who the driver was</li>
<li>How much fuel was consumed</li>
<li>Where they drove</li>
<li>How well the driver drove</li>
<li>In the case of a transport vehicle carrying refrigerated items, what the temperature was in the storage compartment</li>
</ul>
<p>Depending on how sophisticated the sensors are, this data, as well as a myriad of other information, can be tracked and stored in the database. To simplify, we will take a few simple points of interest.</p>
<p><em>Database Overview:</em><em>tblVehicles</em> – Has a primary key called VehicleID</p>
<p><em>tblDrivers</em> – Has a primary key called DriverID</p>
<p><em>tblTrips</em> – Has a primary key called TripID.  tblTrips is has many field that pertain to the upkeep and maintentance of the vehicle for a particular trip. For example: Fuel used, engine temperature, clutch movement, distance traveled, etc., Also the trip table stores which vehicle and driver is associated with the trip.</p>
<p><em>tblEvents</em> – Has a primary key called EventID. tblEvents stores different types of events that can occur when driving a car. For example: Speeding, Passing, Wide turns etc.,</p>
<p><em>tblTripEvents</em> – Has a duplicate key TripID, EventID. This table tblEvents stores the occurrences of these particular events that occurred during a trip.</p>
<p><em>tblTripsGrades</em> – Has a triplicate key TripID, GradeType, GradeID. This table stores grades that are determined by computing the number of event occurrences for a certain trip. For example, Grade Type: Fuel Consumption, GradeType: Driver Safety</p>
<p><em><strong>Specification:</strong></em><br />
The sensor company has many customers that own and operate many cars, transport vehicles. Every day the database fills with tremendous amounts of data regarding all the trips that each customer’s vehicles have travelled. They want to allow their customers to log on to a website and be able to view every detail about the vehicles, drivers and trips at lightning speed.  They want to generate reports based on time periods so that can view how well a driver is doing, how many trips happened and grade the efficiency of the vehicles and drivers.</p>
<p><em><strong>Attack:</strong></em><br />
We have all the information the customer needs stored in the database. The issue is that there may be hundreds of thousands if not millions of trips accumulated over a relatively short period of time. We need speedy access to this data. The first obvious approach is to define indexes on important fields in these tables and to write some scripts that join these fields to reveal the information. </p>
<p><strong>The bottom line is</strong>: <em>Regular indexes and “joins” in SQL Server scripts will not be fast enough. We need a way to view the information almost instantaneously. OLAP will allow you to create different views of this information from the perspective of <strong>dimensions</strong> and access them directly. </em></p>
<p>The next step is to define what the <strong>dimensions</strong> should be and how to use them.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbnet.co.il/blog/2010/06/olap-case-study/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning Cubes – For Beginners</title>
		<link>http://www.dbnet.co.il/blog/2010/06/learning-cubes-%e2%80%93-for-beginners/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=learning-cubes-%25e2%2580%2593-for-beginners</link>
		<comments>http://www.dbnet.co.il/blog/2010/06/learning-cubes-%e2%80%93-for-beginners/#comments</comments>
		<pubDate>Thu, 03 Jun 2010 07:06:53 +0000</pubDate>
		<dc:creator>Ben Beres</dc:creator>
				<category><![CDATA[Microsoft SQL Server]]></category>
		<category><![CDATA[Cubes]]></category>
		<category><![CDATA[Dimensions]]></category>
		<category><![CDATA[Hierarchies]]></category>
		<category><![CDATA[Members]]></category>
		<category><![CDATA[OLAP]]></category>

		<guid isPermaLink="false">http://www.dbnet.co.il/blog/2010/06/learning-cubes-%e2%80%93-for-beginners/</guid>
		<description><![CDATA[The more information stored in a well-designed relational database, there are more ways a user may want to gather data. A user may want to implement queries to glean different patterns or produce specialized reports. This is where OLAP and Cubes enter the picture. ]]></description>
			<content:encoded><![CDATA[<p>The basic problem with relational databases is that there are times when <strong>Data Mining</strong> is not scalable or time efficient. For example, there may be a database which is perfectly normalized and well suited for applications where data is constantly being inserted or updated. </p>
<p>A database design should be intuitive; thus allowing for queries that are easy to implement. <strong>Normalized Databases </strong>often store information in dozens or even hundreds of tables. This optimizes the performance for inserting and updating data. This is because a marginal amount of actual data is stored in each of those tables. Only a few tables are affected each time a SQL transaction is processed.</p>
<p>While all this may be true, once the database reaches a certain magnitude, querying the database becomes un-scalable. At that point, applications are developed to reduce the size of these databases which in turn combats retrieval times. As these relational databases grow in size, select queries take longer to execute. This is why <strong>indexing </strong>is an integral component of database design.</p>
<p>The more information stored in a well-designed relational database, there are more ways a user may want to gather data. A user may want to implement queries to glean different patterns or produce specialized reports. This is where <strong>OLAP </strong>and <strong>Cubes </strong>enter the picture. </p>
<p>Question: What is the difference between a cube and a square or rectangle?<br />
Answer: Multidimensionality.</p>
<p>That is a long and confusing word. It reminds me of my favorite movie growing up – “Back To The Future”:<br />
Doc:&#8221;Marty! You&#8217;re not thinking fourth-dimensionally!&#8221;<br />
Marty:&#8221;Yeah, right, I have a real problem with that.&#8221; </p>
<p>Even programmers have that problem as well.  That makes cubism seem daunting. It is for that reason cubism can be explained using good old fashioned 3-dimensionality. A Relational Database, like excel spreadsheets, consists of 2 dimensions, <strong>rows </strong>and <strong>columns</strong>. A cube is a square drawn 3-dimensionally. Thus, it is a good starting point to move beyond the scope of the conventional 2-dimensions.</p>
<p>Data mining architectures, on the other hand, are utilized for speed of data analysis. In order to pull off this task, data is stored in a Data Warehouse where data is de-normalized via a dimension-based model, a Cube.<br />
To enhance the speed data retrieval, data is stored in a number of different ways in their most granular forms. These storage mechanisms are called <strong>Aggregates</strong>.  </p>
<p>A cube is a data structure whose design allows for speedy analysis of information. Besides speed, cubes are capable of manipulating and analyzing data from many different perspectives, or Pivots. The way cubes can organize data overcomes the limitations of relational databases. </p>
<p>In this blog I plan on describing cubes in the context of <strong>OLAP </strong>(On Line Analytical Programming) databases; as well as how and when to use them. I will define all the terms needed to understand cubes by explaining:<br />
•	Dimensions<br />
•	Measures<br />
•	Members<br />
•	Hierarchies<br />
•	Data sources<br />
•	Pivots<br />
•	MDX</p>
<p>Once we have an OLAP Cube Database up and running, we will learn a pseudo-SQL like language designed to glean data from multiple pivots, called <strong>MDX</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbnet.co.il/blog/2010/06/learning-cubes-%e2%80%93-for-beginners/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Trust is good, control is better &#8211; Effective Unit Testing in .Net</title>
		<link>http://www.dbnet.co.il/blog/2010/05/trust-is-good-control-is-better-effective-unit-testing-in-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=trust-is-good-control-is-better-effective-unit-testing-in-net</link>
		<comments>http://www.dbnet.co.il/blog/2010/05/trust-is-good-control-is-better-effective-unit-testing-in-net/#comments</comments>
		<pubDate>Thu, 06 May 2010 16:48:22 +0000</pubDate>
		<dc:creator>manuelk</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Mocks]]></category>
		<category><![CDATA[Unit Tests]]></category>

		<guid isPermaLink="false">http://www.dbnet.co.il/blog/?p=118</guid>
		<description><![CDATA[The first time I heard about Unit testing was during my undergraduate degree in 1999 while learning about Extreme Programming. Since then, it always fell into the category of &#8220;There is never enough time to do it right, but always enough time to do it over&#8220;. The big question is wether the effort it takes [...]]]></description>
			<content:encoded><![CDATA[<p>The first time I heard about Unit testing was during my undergraduate degree in 1999 while learning about <a href="http://www.extremeprogramming.org/" target="_blank">Extreme Programming</a>. Since then, it always fell into the category of &#8220;<em>There is never enough time to do it right, but always enough time to do it over</em>&#8220;.</p>
<p>The big question is wether the effort it takes to write tests is balanced out by the benefits they provide. It has been shown in a number of cases that for medium to large projects with non-trivial codebases, Unit tests do improve both development productivity and product quality. See Steve Sanderson&#8217;s <a href="http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/" target="_blank">blog post</a> for a good costs/benefit analysis.</p>
<p>The main benefits offered by Unit tests are that they help you to:</p>
<ul>
<li>design code while you’re writing it</li>
<li>verify that your implementation actually does what you intended it to do</li>
</ul>
<p>As a consequence Unit testss make it possible to refactor safely and add a layer of documentation to your code, showing how it is intended to be used.</p>
<p>Before delving deeper into the topic, let&#8217;s define what a Unit Test is. Roy Osherove provides the following definition:</p>
<blockquote><p>A unit test is an automated piece of code that invokes the <strong>method or class</strong> being tested and then checks some assumptions about the logical behavior of that method or class.</p></blockquote>
<p><strong>Unit Test Frameworks</strong></p>
<p>There are a number of frameworks which facilitate Unit Testing capabilities for .Net. One of the most popular ones is <a href="www.nunit.org" target="_blank">NUnit</a>, an open source project ported from Java&#8217;s JUnit.</p>
<p>In NUnit, tests are written as functions which are decorated with attributes to mark them as tests.<br />
A typical test suite would look like this:</p>
<pre class="brush: csharp;">
using System;
using NUnit.Framework;

namespace MyProject.Tests
{
    [TestFixture]
    public class CalculatorTests
    {
        private MyProject.ICalculator myCalculator;

        [SetUp]
        public void Init()
        {
            // code that will be called before each Test case.
            myCalculator = new MyProject.Calculator();
        }

        [TearDown]
        public void Clean()
        {
            // code that will be called after each Test case
            myCalculator = null;
        }

        [Test]
        public void Add_TwoIntegers_ReturnsSum()
        {
            int num1 = 3;
            int num2 = 4;
            int sum = myCalculater.Add(3,4);
            Assert.AreEqual(7, sum);
        }
    }
}
</pre>
<p>The NUnit client can detect these functions, run the tests and show the results:</p>
<p><img src="http://www.altervisitor.com/software/images/nunit1.gif" alt="" height="400" /></p>
<p>Alternatively, you can use <a href="http://www.testdriven.net" target="_blank">Testdriven.net</a> &#8211; a unit testing add-in for Visual Studio which allows running tests from within Visual Studio with a single-click:</p>
<p><img src="http://i.msdn.microsoft.com/cc300778.fig01(en-us).gif" alt="" height="331" /></p>
<p><strong>Unit Test Guidelines</strong><br />
An important aspect is the naming convention for test objects. Roy Osherove suggests the following rules dependent on the object under test:</p>
<ul>
<li><strong>Project</strong>: [ProjectUnderTest].Tests</li>
<li><strong>Class</strong>: [ClassName]Tests</li>
<li><strong>Method</strong>: [MethodName]_[StateUnderTest]_[ExpectedBehavior]</li>
</ul>
<p>As there are guidelines for writing good code, there are criterias for good unit tests:</p>
<ul>
<li><strong>Repeatable</strong>: You must be able to measure an expected outcome reliably for known inputs.</li>
<li><strong>Independent of other tests</strong>: Any subset of tests should be able to run in any order w/o affecting the outcome.</li>
<li><strong>Easy to write</strong>: If it takes a lot of work to set up the inputs to a test, you aren&#8217;t going to recoup your investment in writing that test. Difficulty in writing a test usually points to a flaw in design: time to refactor.</li>
<li><strong>Easy to understand</strong>: Ideally, the automated tests that you write should also serve as a useful form of design and requirements documentation.</li>
<li><strong>Fast</strong>: Slow-running tests will retard productivity.</li>
</ul>
<p>In order to avoid interdependencies between tests, it is important that no state is shared between tests.</p>
<p><strong>Design for Testability</strong><br />
According to Jeremy Miller, &#8220;<em>Testability is the quality of a software design that allows for automated testing in a cost-effective manner</em>&#8220;.</p>
<p>The two biggest problem with writing testable code are:</p>
<ul>
<li><strong>Side effects:</strong> a method which, in addition to producing a value, also modifies some state</li>
<li><strong>Dependencies:</strong> objects in your system that your code interacts with. These can be other business objects or external dependencies s.a. filesystems, threads, memory, time, etc.</li>
</ul>
<p><strong>Side-Effect free functions<br />
</strong>It is almost trivial to test a function when all you have to do is inspect it&#8217;s return value.<br />
Side-effect free functions are the cornerstone of functional programming, where side effects are not allowed (unless through monads).<br />
In classic OOP though, we are encouraged to write methods which modify the internal state of an object. Writing OO code while avoiding side effects is a very <a href="http://domaindrivendesign.org/node/127" target="_blank">important concept</a> in Domain Driven Design.</p>
<p>There are several patterns on how to avoid side effects, one of which is making objects immutable &#8211; meaning that once initialized, the object cannot be changed. This may sound strange, but consider the String class in .Net, which is immutable. Eric Lippert, a leading designer and implementor of the C# language and .NET Framework wrote, that in his opinion:</p>
<blockquote><p>&#8220;Immutable data structures are the way of the future in C#. It is much easier to reason about a data structure if you know that it will never change.&#8221;</p></blockquote>
<p>In fact, he wrote an entire <a href="http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx" target="_blank">series of posts</a> on immutability.</p>
<p><strong>Dependencies</strong><br />
While side effects make unit testing harder, because you have to think about changes in your object&#8217;s state after you call a method, an even uglier problem are external dependencies.</p>
<p>If a method accesses the database or a configuration file, then your tests are not repeatable, unless you initialize the state of the DB or the file on every test run.</p>
<p>A much better approach is to &#8220;fake&#8221; your dependency so it behaves in a predictable manner which is under your control. In order to fake a dependency, the test routine must be able to switch the original object with a fake implementation.</p>
<p>Consider the following implementations of class House:</p>
<pre class="brush: csharp;">
//Implementation 1: Impossible to access the variable
class House
{
    private Bedroom bedroom;

    public House()
    {
        bedroom = new Bedroom();
    }
    //more methods...
}

//Implementation 2: Possible to access the variable on object creation (via the constructor) but difficult to provide an alternative implementation
class House
{
    private Bedroom bedroom;

    public House(Bedroom b)
    {
        bedroom = b;
    }
    //more methods...
}

//Implementation 3: Possible to exchange the variable's implementation, since it is exposed by an Interface
class House
{
    private IBedroom bedroom;

    public House(IBedroom b)
    {
        bedroom = b;
    }
    //more methods...
}
</pre>
<p>In order to test House no. 3 we could create a fake object FakeBedroom which implements the interface IBedroom and lets us test the House w/o it&#8217;s dependency on Bedroom&#8217;s implementation. Instead of passing the dependency in via the constructor, we could expose it as a public Property and set it after the object is initialized. Both methods are ways to perform <a href="http://martinfowler.com/articles/injection.html" target="_blank">Dependency Injection</a>. Ideally all of your important dependencies should be made injectable and managed via a Dependency Injection (DI) Framework s.a. <a href="http://www.springframework.net/" target="_blank">Spring.Net</a> or <a href="http://www.castleproject.org/container/" target="_blank">Castle Windsor</a>.</p>
<p>Coming back to fake objects, we usually distinguish between two types:</p>
<ul>
<li><strong>Stubs</strong>: A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.</li>
<li><strong>Mocks</strong>: A mock is a fake object which verifies whether the object under test interacted as expected with the fake object. A mock is much like a stub, except that a mock additionally saves the history of communication, which will later be verified.</li>
</ul>
<p><strong>RhinoMocks<br />
</strong>Before we will look at an example, I want to address an important point: While it is possible to create Stubs and Mocks manually, it is very tedious to do so and is generally not worth the effort. Instead there are a number of frameworks available which let you create Mocks and Stubs on the fly. The most widely used mocking framework in .Net is <a href="http://www.ayende.com/projects/rhino-mocks.aspx" target="_blank">RhinoMocks</a> by Oren Eini otherwise known as Ayende Rahien (Besides being the author of RhinoMocks, Oren is an active contributor of the NHibernate and Castle projects and the author of one of the most popular .Net blogs: <a href="http://ayende.com/Blog/" target="_blank">http://ayende.com/Blog/</a>).</p>
<p>In RhinoMocks fake objects can be used the following way:</p>
<ol>
<li>The framework creates the fake object which impelements a given interface</li>
<li>The expected behavior of the fake object is &#8220;recorded&#8221;</li>
<li>The fake object is injected into the object-to-test</li>
<li>The method-to-test is called</li>
<li>During the call the recorded behvior of the fake object is &#8220;played back&#8221; according to the interaction with the object-to-test</li>
<li>The framework verifies that the all the expectations are fulfilled</li>
</ol>
<p><em>Example</em>: The following example (borrowed from Roy Osherove) shows a LogAnalyzer which depends on a WebService for error logging and on an Email Service for Notification. The Analyze() method checks if the filename is too short and if so, logs the error by calling the WebService. If that call fails, an email-notification is sent via the EmailService:</p>
<pre class="brush: csharp;">
public class LogAnalyzer
{
    public IWebService Service { get; set; }
    public IEmailService Email { get; set; }

    public void Analyze(string fileName)
    {
        if ( fileName.Length &lt; 8 )
        {
            try
            {
                service.LogError(&quot;Filename too short:&quot; + fileName);
            }
            catch (Exception e)
            {
                email.SendEmail(&quot;a&quot;, &quot;subject&quot;, e.Message);
            }
        }
    }
}
</pre>
<p>A test of the Analyze method using NUnit and RhinoMocks could look something like this:</p>
<pre class="brush: csharp;">
[Test]
public void Analyze_WebServiceThrows_SendsEmail()
{
    MockRepository mocks = new MockRepository();
    IWebService stubService = mocks.Stub();
    IEmailService mockEmail = mocks.StrictMock();

    using(mocks.Record())
    {
        //Set up stub behavior:
        // if LogError is called...
        stubService.LogError(&quot;whatever&quot;);
        // ...then regardless of the input...
        LastCall.Constraints(Is.Anything());
        // ...throw an ecxeption!
        LastCall.Throw(new Exception(&quot;fake exception&quot;));

        //Set up expected mock behavior:
        mockEmail.SendEmail(&quot;a&quot;,&quot;subject&quot;,&quot;fake exception&quot;);
    }

    //initialize LogAnalyzer
    LogAnalyzer log = new LogAnalyzer();

    //inject fake WebService and EmailService objects
    log.Service = stubService;
    log.Email = mockEmail;

    //call the method we want to test
    string tooShortFileName = &quot;abc.ext&quot;;
    log.Analyze(tooShortFileName);

    //verify that all expectations on the mock object are fulfilled
    mocks.VerifyAll();
}
</pre>
<p>A thorough coverage of RhinoMocks is beyond the scope of this article, the aim of which was to briefly present a current approach to Unit Testing in .Net.</p>
<p>There are many excellent .Net frameworks (e.g. the built-in testing framework of Visual Studio 2010), patterns and principles (e.g. Test Driven Design) regarding unit testing in particular and software testing in general, which can greatly contribute to the quality of your code and the efficiency of your development process.</p>
<p><strong>Conclusion</strong></p>
<ul>
<li>In most cases Unit Tests improve code quality and productivity</li>
<li>Design Unit Tests to be repeatable, fast and independent from each other</li>
<li>Design code for testability by reducing side-effects and managing your dependencies via a dependency injection framework</li>
<li>Make use of testing frameworks, s.a. NUnit, Testdriven.Net and RhinoMocks to make writing unit tests feasible</li>
</ul>
<p><strong>Resources</strong></p>
<ul>
<li>Roy Osherove&#8217;s book: <a href="http://www.amazon.com/exec/obidos/ASIN/1933988274" target="_blank">&#8220;The Art of Unit Testing with Examples in .NET&#8221;</a></li>
<li>Jeremy Miller&#8217;s article <a href="http://msdn.microsoft.com/en-us/magazine/dd263069.aspx" target="_blank">&#8220;Design for Testability&#8221;</a></li>
<li>Misko Hevery has published <a href="http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf" target="_blank">an excellent Guide</a> about how the folks at Google design their code for testability</li>
</ul>
<p>Manuel Korn</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbnet.co.il/blog/2010/05/trust-is-good-control-is-better-effective-unit-testing-in-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Domain Events &#8211; Don&#8217;t observe us, we&#8217;ll observe you</title>
		<link>http://www.dbnet.co.il/blog/2010/04/domain-events-dont-observe-us-well-observe-you/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=domain-events-dont-observe-us-well-observe-you</link>
		<comments>http://www.dbnet.co.il/blog/2010/04/domain-events-dont-observe-us-well-observe-you/#comments</comments>
		<pubDate>Sun, 11 Apr 2010 16:07:37 +0000</pubDate>
		<dc:creator>manuelk</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Domain Events]]></category>
		<category><![CDATA[Publisher Subscriber]]></category>

		<guid isPermaLink="false">http://www.dbnet.co.il/blog/?p=66</guid>
		<description><![CDATA[A few days ago I listened to a presentation by Eric Evans about the lessons learned since the publication of his hugely successful book &#8220;Domain Driven Design&#8221; in 2004. For starters, here is the punchline of what Wikipedia has to say about Domain Driven Design:   Domain-driven design (DDD) is an approach to developing software for complex [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago I listened to a <a href="http://domaindrivendesign.org/library/evans_2009_1" target="_blank">presentation by Eric Evans</a> about the lessons learned since the publication of his hugely successful <a href="http://books.google.co.il/books?id=7dlaMs0SECsC&amp;dq=eric+evans+domain+driven+design&amp;printsec=frontcover&amp;source=bn&amp;hl=iw&amp;ei=RDbDS9WkC8eC_QbtqKHkBg&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=4&amp;ved=0CCcQ6AEwAw#v=onepage&amp;q&amp;f=false" target="_blank">book &#8220;Domain Driven Design&#8221;</a> in 2004.</p>
<div>For starters, here is the punchline of what Wikipedia has to say about <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">Domain Driven Design</a>:</div>
<div> </div>
<blockquote>
<div><span>Domain-driven design (DDD) is an approach to developing software for complex needs by deeply connecting the implementation to an evolving model of the core business concepts. </span></div>
</blockquote>
<p>A thorough presentation of the principles, tenets and practices of DDD are outside the scope of this article. Instead, I would like to focus on one specific concept that Evans forgot to include when he wrote the book five years ago and which he today presents as one of the fundamental building blocks for successful DDD: Domain Events.</p>
<div>The pattern was originally formulated by <a href="http://martinfowler.com/eaaDev/DomainEvent.html">Martin Fowler</a> in early 2005:</div>
<div> </div>
<blockquote><p>Captures the memory of something interesting which affects the domain</p></blockquote>
<div>The pattern combines two ideas:</div>
<div> </div>
<ol>
<li><strong>Publisher / Subscriber instead of RPC<br />
</strong>Instead of directly invoking all the consequences of a change in the system, an event is raised which can be handled by whomever is interested in it.</li>
<li><strong>Event Sourcing instead of mutable state</strong><br />
Instead of altering the state of the system directly as soon as something happens, the change is reflected in the history (or log) of events. You can think of it as an incremental backup: Only the most recent changes must be saved because we rely on an existing record of all previous changes.  This is known as <a href="http://codebetter.com/blogs/gregyoung/archive/2010/02/20/why-use-event-sourcing.aspx" target="_blank">Event Sourcing</a> and I do not want to go into it further.</li>
</ol>
<p>Now, event-driven programming is hardly new &#8211; most UI Frameworks s.a. ASP.Net and Winforms are based on exposing events on controls. The crux of the Domain-Event pattern is that not only do you use events in UI scenarios but in your core business model. An example should shed light on the differences in approach:</p>
<p>Given an Ecommerce application, the following functional requirements are given:</p>
<p>When a user wires money into his account:</p>
<ul>
<li>his credit card must be validated and charged</li>
<li>his balance must be updated</li>
<li>his status must be updated (maybe he became a preferred customer)</li>
<li>he needs to be notified via email</li>
<li>the event needs to be logged</li>
</ul>
<p>In a traditional programming model, we would end up writing something like this:</p>
<pre class="brush: csharp;">
DepositMoney(User u, double amount, currency curr)
{
    ccInfo cc = Repository.GetCcInfo(u.UserID);

    if( CreditCard.Authorize(cc, amount, curr) )
    {
        CreditCard.Settle(cc, amount, curr);
        Payment.Add(u.UserID, amount, curr);
        Notification.SendPaymentConfirmationMsg(u.UserID, amount, curr);
        Log.PlayerPayment(u.UserID, amount, curr);

        if( Account.IsEligibleForUpgrade(u.UserID) )
        {
            UpgradeInfo upg = Account.Upgrade(u.UserID);
            Notification.SendCustomerUpgradeMsg(upg);
            Log.CustomerUpgrade(u.UserID, upg);
        }
    }
    else
    {
        Notification.SendCcRefusedMsg(u, cc);
        Log.CcRefusal(u.UserID, cc, amount, curr);
    }
}
</pre>
<p>The above example is obviously incomplete but it shows how fast we can find ourselves in a dependency hell, i.e. within a single method we reference six different modules (Repository, CreditCard, Payment, Notification, Log, Account) which ideally should not have any knowledge of each other.</p>
<p>Also the above design raises all kinds of inconvenient dilemmas, for example: the Log is always called after we send a Notification. Maybe we should include logging in the Notification methods? This would definitely reduce the chances of forgetting to log an event, but it would also create a direct dependency between the two unrelated modules and thus negate the principles of maximizing cohesion and separation of concerns.</p>
<p>It seems that either way, we&#8217;ll end up with messy code which will be hard to maintain &#8211; the first step towards the dreaded <a href="http://en.wikipedia.org/wiki/Big_ball_of_mud" target="_blank">Big Ball of Mud</a> architecture. </p>
<p><strong>How can Domain Events help?</strong></p>
<p>With Domain Events the above method simply raises a DepositRequestedEvent, which includes the references to the user, amount and currency. Other modules subscribe to this type of event. In our case, a PaymentService subscribes to the DepositRequestedEvent, and upon observing such an event authorizes and settles the credit card, updates the balance and raises in turn a PaymentAddedEvent or a CcRefusedEvent. These events are handled independently by an AccountService, a NotificationService and an LogService. The AccountService may raise a CustomerUpgradedEvent which is handled by NotificationService and LogService. Whenever something important happens in the system another event is raised. </p>
<p>This way we can drastically reduce the amount of interdependencies because modules do not call each other directly. Since this is an asynchronous messaging model our system becomes more scalable and may even deliver better performance because tasks can be processed in parallel.</p>
<p>Obviously this kind of architecture demands a sophisticated subscriber/publisher infrastructure for managing the message streams and event subscriptions. In this article I want to briefly present two such frameworks: </p>
<ul>
<li>Udi Dahan&#8217;s NServiceBus</li>
<li>.Net 4.0 Reactive Framework (RxFramework)</li>
</ul>
<div> </div>
<div><strong>NServiceBus</strong></div>
<div> </div>
<p>NServiceBus is a one-way asynchronous queued messaging platform which was developed with the following focus in mind:</p>
<ul>
<li>
<div>Inherent Publisher / Subscriber support (each message sent can be viewed as an event raised)</div>
</li>
<li>
<div>Developer friendly (Painless installation and usage)</div>
</li>
<li>
<div>Reliability and Scalability (NServiceBus is built upon MSMQ which facilitates persisted and thus reliable messaging)</div>
</li>
<li>
<div>Support for long-running workflows (or &#8220;Sagas&#8221; as they are called in NServiceBus terminology)</div>
</li>
<li>
<div>Extensibility</div>
</li>
</ul>
<div> </div>
<div>For an overview of NServiceBus, look here: <a href="http://www.nservicebus.com/Overview.aspx" target="_blank">http://www.nservicebus.com/Overview.aspx</a></div>
<div> </div>
<p>One of the great features of NServiceBus is that events are defined as classes which implement one or more interfaces. A subscriber subscribes to an Event via its Interface. That means that different events can be handled by the same subscription as long as they implement a common interface (e.g. IEmailNotification or ILoggable).</p>
<div> </div>
<p>As a consequence, the decision whether an event is handled or not depends neither on the subscriber (who handles all events which implement a certain interface) nor on the publisher (who only knows the type of the event, not all the implemented interfaces) but on the event itself. This adds a level of cohesion to all the components involved which is very difficult to achieve in the classic approach above. To quote Udi Dahan:</p>
<blockquote><p>[Domain Events based architecture] complies with the Single Responsibility Principle, so the business requirement which states that when a customer becomes preferred, they should be sent an email belongs somewhere else.</p>
<p>Notice that the key word in the requirement – “when”.</p>
<p>Any time you see that word in relation to your domain, consider modeling it as a domain event.</p></blockquote>
<div> </div>
<p>For an excellent discussion of how NServiceBus can assist in developing a domain events based application, read <a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/" target="_blank">Udi Dahan&#8217;s article</a>. In case you want to listen to a one-hour talk of Udi about NServiceBus architecture, check out <a href="http://deepfriedbytes.com/deepfriedbytes/podcast/episode-49-getting-the-right-message-about-nservicebus-with-udi-dahan/" target="_blank">this podcast</a>.</p>
<div> </div>
<div><strong>RxFramework</strong></div>
<div> </div>
<p>As opposed to NServiceBus the RxFramework does not provide a reliable messaging solution. Instead it attempts to change the way we as programmers deal with sequentially arriving input. Until now the dominating pattern regarding sequential input was the IEnumerable interface and the <a href="http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html" target="_blank">&#8220;yield&#8221; keyword in C#</a>. Since the advent of LINQ and the deferred execution mechanism, this Design Pattern has received a lot of attention. The idea is very simple: Instead of looking at the complete sequence of inputs up front, we only retrieve one member at a time.</p>
<p>The RxFramework takes this idea one step further and postulates: Instead of &#8220;pulling&#8221; each member of the sequence by explicitly asking for it, let&#8217;s subscribe to the sequence and whenever the next member &#8220;appears&#8221;, we will be notified. In this model, a stream of events is treated as data which can be filtered and processed very similarly (in fact identically) to the way we are used to processing any list or sequence of regular objects. Wes Dyer has written an excellent <a href="http://blogs.msdn.com/wesdyer/archive/2009/11/18/a-brief-introduction-to-the-reactive-extensions-for-net-rx.aspx" target="_blank">introduction to the RXFramework</a>, which clarifies this point and shows how it makes .Net Events more manageable.</p>
<p>We can utilize this ability to implement the event-domain pattern. In fact, Mike Chaliy presents a nice example of how to implement a money transfer scenario (very similar to the one above) as <a href="http://chaliy.name/blog/2010/1/business_logic_rx_example" target="_blank">domain events via the RxFramework</a>.</p>
<p><strong>Conclusion</strong></p>
<p>Domain Events are a recognized architectural pattern which is gaining more and more popularity among the designers of highly scalable and robust systems. The reasons for its rising popularity are threefold:</p>
<ul>
<li>As Applications become more complex, the need for better code organization increases</li>
<li>The need for highly scalable applications grows steadily</li>
<li>The availability of supporting Frameworks enable developers to implement a Domain Events architecture without having to develop their own messaging solutions</li>
</ul>
<p>Two frameworks were presented which facilitate two radically different approaches to Domain Event based architecture:</p>
<ul>
<li><strong>NServiceBus</strong>: a platform for reliable, asynchronous, one-way messaging and long running workflows</li>
<li><strong>RxFramework</strong>: treats a stream of events like data which can be filtered and manipulated easily</li>
</ul>
<p> </p>
<p>Manuel Korn</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbnet.co.il/blog/2010/04/domain-events-dont-observe-us-well-observe-you/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Console.WriteLine(&#8220;Hello World&#8221;) &#8211; The .Net Programming Blog Is Born</title>
		<link>http://www.dbnet.co.il/blog/2010/03/console-writelinehello-world-the-net-programming-blog-is-born/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=console-writelinehello-world-the-net-programming-blog-is-born</link>
		<comments>http://www.dbnet.co.il/blog/2010/03/console-writelinehello-world-the-net-programming-blog-is-born/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 16:14:11 +0000</pubDate>
		<dc:creator>manuelk</dc:creator>
				<category><![CDATA[.Net]]></category>

		<guid isPermaLink="false">http://www.dbnet.co.il/blog/?p=21</guid>
		<description><![CDATA[Welcome to the db@net .Net Programming Blog! After working at db@net  for over two and a half years, I feel that something very exciting is happening these days: the shift towards collaborative knowledge reuse! Until now, I&#8217;ve had the opportunity to learn tons of new and cool stuff at db@net, but I wasn&#8217;t able to share [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Welcome to the db@net .Net Programming Blog!</strong></p>
<p>After working at db@net  for over two and a half years, I feel that something very exciting is happening these days: the shift towards <em>collaborative knowledge reuse</em>!</p>
<p>Until now, I&#8217;ve had the opportunity to learn tons of new and cool stuff at db@net, but I wasn&#8217;t able to share these experiences and receive constructive feedback in a structured manner from all the other smart people around.</p>
<p>This is about to change with the opening of this and other technical blogs which constitute a platform for the exchange of questions, ideas and experiences of our corporate programming community.</p>
<p>I am particularly excited about the .Net blog because of db@net&#8217;s proven track record designing and implementing great .Net apps.</p>
<p>The articles presented and discussed here shall cover a very wide range of topics as long as they are remotely connected to .Net programming:</p>
<ul>
<li>Insights gathered while designing, developing, deploying or maintaining .Net apps</li>
<li>Your latest brilliant piece of code you want everyone to be jealous of</li>
<li>New and cool technologies and frameworks</li>
<li>Design and architectural patterns</li>
<li>Book and article reviews</li>
<li>Coding puzzles</li>
</ul>
<p>I am absolutely convinced that this blog has great potential to contribute to every member of our team and I am looking forward to being a part of it.</p>
<p>Manuel Korn</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbnet.co.il/blog/2010/03/console-writelinehello-world-the-net-programming-blog-is-born/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Business Continuity &#8211; Not only another cluster</title>
		<link>http://www.dbnet.co.il/blog/2010/03/business-continuity-not-only-another-cluster/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=business-continuity-not-only-another-cluster</link>
		<comments>http://www.dbnet.co.il/blog/2010/03/business-continuity-not-only-another-cluster/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 09:29:32 +0000</pubDate>
		<dc:creator>Ariel Rauch</dc:creator>
				<category><![CDATA[Business Continuity]]></category>

		<guid isPermaLink="false">http://www.dbnet.co.il/blog/?p=9</guid>
		<description><![CDATA[First I would like to welcome you all to this new blog site. It is a blog site which should give to all the professionals of db@net an opportunity to share their wealthy experience with eachothers and with all the rest of you &#8211; readers who are not necessarily part of the db@net family but [...]]]></description>
			<content:encoded><![CDATA[<p>First I would like to welcome you all to this new blog site. It is a blog site which should give to all the professionals of db@net an opportunity to share their wealthy experience with eachothers and with all the rest of <strong>you</strong> &#8211; readers who are not necessarily part of the db@net family but are fascinated by the topics and the openess those are discussed here.</p>
<p>This site is not an advertisment site although in nowerdays everything that is published over the net may be seen and even measured as part of advertisment campaigns. So let me state that this was not our intention &#8211; at least.</p>
<p>Although I actively experienced the break-through of the internet generation &#8211; yes, indeed I am that old &#8211; and had probably a certain impact on my near professional environment I have the feeling as if I would sit in a new car, nylon still on the seats and a fresh smell of &#8220;new&#8221; in the air &#8230;</p>
<p>This is my first blog &#8211; This is what I meant to say <img src='http://www.dbnet.co.il/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>My main intention with this blog is to analyse and discuss all aspects related to business continuity and eventually propose some to-do&#8217;s or not to-do&#8217;s. Important to note that business continuity is only partially a technological topic. Respectively I would claim that the goal of business continuity &#8211; as it&#8217;s name suggests &#8211; is solely business-oriented. Having said that it is definitely true that many of the implementations to seek business continuity are mainly based on mostly complex technological solutions. This fact &#8211; although &#8211; should not irritate us: <strong>Technology is only the way to achieve the business goal!</strong></p>
<p>Let us make a fast search in the net to find a definition for business continuity. The &#8220;great thing&#8221; about the net is that you can probably always find a definition that fits your personal view &#8211; and so I did (<a title="Wikipedia: Business Continuity" href="http://en.wikipedia.org/wiki/Business_continuity" target="_blank">Wikipedia: Business Continuity</a>):</p>
<p><em>„Business continuity is the activity performed by an organization to ensure that critical business functions will be available to customers, suppliers, regulators, and other entities that must have access to those functions. These activities include many daily chores such as project management, system backups, change control, and help desk. Business Continuity is not something implemented at the time of a disaster; Business Continuity refers to those activities performed daily to maintain service, consistency, and recoverability.”</em></p>
<p>In the coming articles we will explain several components of business continuity. We definitely will discuss some &#8220;real world&#8221; examples to better illustrate concepts. Important for a fruitful discussion is of course <strong>your</strong> <strong>participation</strong> in it. We will take seriously every of your comments, being constructively, critically or only questioning.</p>
<p>I am sure that this topic is as important as interesting to all of us and I am looking forward to discussing it with you.</p>
<p>Yours</p>
<p>Ariel</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbnet.co.il/blog/2010/03/business-continuity-not-only-another-cluster/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

