<?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>TiMoch</title>
	<atom:link href="https://timoch.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>https://timoch.com/blog</link>
	<description>on edge</description>
	<lastBuildDate>Tue, 29 Apr 2014 15:02:50 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=3.9.40</generator>
	<item>
		<title>Annoyed with INotifyPropertyChanged?</title>
		<link>https://timoch.com/blog/2013/08/annoyed-with-inotifypropertychange/</link>
		<comments>https://timoch.com/blog/2013/08/annoyed-with-inotifypropertychange/#comments</comments>
		<pubDate>Wed, 14 Aug 2013 08:53:13 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=347</guid>
		<description><![CDATA[Have you ever been annoyed with having to implement the cumbersome plumbing required for INotifyPropertyChanged ? Well, I have. So I tried to find a way to make authoring bindable objects better. The typical example: [crayon-69d57b8960753666978853/] As you can see, it is quite verbose. The event and OnPropertyChanged() method need to be implemented for each [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Have you ever been annoyed with having to implement the cumbersome plumbing required for INotifyPropertyChanged ? Well, I have. So I tried to find a way to make authoring bindable objects better.</p>
<p>The typical example:</p><pre class="crayon-plain-tag">public class Contact : INotifyPropertyChanged {
    private string _firstName;

    public string FirstName {
        get { return _firstName; }
        set {
            if (!Equals(_firstName, value)) {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}</pre><p>As you can see, it is quite verbose. The event and OnPropertyChanged() method need to be implemented for each class and it&#8217;s easy to get the implementation of OnPropertyChanged() wrong (typically introducing a race condition). Moreover, it&#8217;s 10 lines of code for each property. I hate that. The more you have to write, the bigger a surface for bugs to appear. A property should just boil down to  <pre class="crayon-plain-tag">public string FirstName { get; set; }</pre> .</p>
<p>That won&#8217;t be possible of course. The default setters and getters just handle the assignment and loading of a compiler-generated backing field. So we somehow need to add the code for each property.</p>
<h1>Enter Bindable objects</h1>
<p>Similar to class <a href="http://msdn.microsoft.com/en-us/library/microsoft.practices.prism.viewmodel.notificationobject(v=pandp.40).aspx">NotificationObject</a>, Bindable is here to help implementing INotifyPropertyChanged. The NotificationObject class only implements <a href="http://msdn.microsoft.com/en-us/library/gg419029(v=pandp.40).aspx">RaisePropertyChanged()</a> but does not help with the implementation of the properties. Here is what you can do with Bindable:</p><pre class="crayon-plain-tag">public class Contact : Bindable {
    public string FirstName {
        get { return Get&lt;string&gt;(); }
        set { Set(value); }
    }
}</pre><p>Noticeably shorter, isn&#8217;t it ?</p>
<p>Behind the scene, Bindable uses a dictionary to store the property values. You probably have noticed that the property name is not given to Bindable.Get() or Bindable.Set(). Bindable leverages the compiler to provide the value automatically:</p><pre class="crayon-plain-tag">protected T Get&lt;T&gt;([CallerMemberName] string name = null) { }
protected void Set&lt;T&gt;(T value, [CallerMemberName] string name = null) { }</pre><p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx"><pre class="crayon-plain-tag">CallerMemberNameAttribute</pre></a> when applied on an optional parameter instructs the compiler to pass a string whose value is the name of the calling member. So when property FirstName calls <pre class="crayon-plain-tag">Get&lt;string&gt;()</pre> , the compiler generates code for <pre class="crayon-plain-tag">Get&lt;string&gt;("FirstName")</pre> .</p>
<p>Here is the actual code for class Bindable:</p><pre class="crayon-plain-tag">using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace TiMoch.Framework {
    /// &lt;summary&gt;
    /// Base class to implement object that can be bound to
    /// &lt;/summary&gt;
    public class Bindable : INotifyPropertyChanged {
        private Dictionary&lt;string, object&gt; _properties = new Dictionary&lt;string, object&gt;();

        /// &lt;summary&gt;
        /// Gets the value of a property
        /// &lt;/summary&gt;
        /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
        /// &lt;param name="name"&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        protected T Get&lt;T&gt;([CallerMemberName] string name = null) {
            Debug.Assert(name != null, "name != null");
            object value = null;
            if (_properties.TryGetValue(name, out value))
                return value == null ? default(T) : (T)value;
            return default(T);
        }

        /// &lt;summary&gt;
        /// Sets the value of a property
        /// &lt;/summary&gt;
        /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
        /// &lt;param name="value"&gt;&lt;/param&gt;
        /// &lt;param name="name"&gt;&lt;/param&gt;
        protected void Set&lt;T&gt;(T value, [CallerMemberName] string name = null) {
            Debug.Assert(name != null, "name != null");
            if (Equals(value, Get&lt;T&gt;(name)))
                return;
            _properties[name] = value;
            OnPropertyChanged(name);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}</pre><p>Some aspects can be improved. For example, enabling subclasses to provide their own backing field. This is left as an exercise to the reader <img src="https://timoch.com/blog/wp-includes/images/smilies/icon_wink.gif" alt=";-)" class="wp-smiley" /> </p>
<p>I use this class a lot when implementing MVVM either in Wpf or Winforms.</p>
<p>What do you think ?</p>
<p>Edit: fixed code snippets as per Krumelur&#8217;s comments. Thanks Krumelur.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/08/annoyed-with-inotifypropertychange/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Unit testing model validation with MVC&#8217;s DataAnnotations</title>
		<link>https://timoch.com/blog/2013/06/unit-testing-model-validation-with-mvcs-dataannotations/</link>
		<comments>https://timoch.com/blog/2013/06/unit-testing-model-validation-with-mvcs-dataannotations/#comments</comments>
		<pubDate>Fri, 21 Jun 2013 08:55:04 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[unit-test]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=338</guid>
		<description><![CDATA[In a previous post, I mentioned that model validation should be tested separately from controller logic. I will demonstrate a way of unit testing the validation of models implemented with System.ComponentModel.DataAnnotations. It is actually quire easy to unit test model validation. Models are inherently easy to test separately due to their POD (Plain Old Data) nature. [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In a previous post, I mentioned that model validation should be tested separately from controller logic. I will demonstrate a way of unit testing the validation of models implemented with <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx">System.ComponentModel.DataAnnotations</a>.</p>
<p>It is actually quire easy to unit test model validation. Models are inherently easy to test separately due to their POD (Plain Old Data) nature. We can instantiate them directly. Moreover, DataAnnotations provides us with the necessary <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.aspx">interface</a> to run the validation against a model object completely separately from the rest of the application.</p>
<h2>A first model validation test class</h2>
<p>Here is a basic model that we will unit test for the demonstration:</p><pre class="crayon-plain-tag">using System;
using System.ComponentModel.DataAnnotations;

namespace DataAnnotationsUnitTesting
{
    public class CreatePersonModel
    {
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Range(typeof (DateTime), "1900/01/01", "2000/01/01")]
        public DateTime BirthDate { get; set; }
        [RegularExpression(@"\+?\d+")]
        public string PhoneNumber { get; set; }
    }
}</pre><p>As you can see, it is quite simple. We&#8217;ll go directly to the unit test implementation.</p>
<p>The strategy we are going to use consists in basing each test case on a valid model instance, then modifying it in such a way that it triggers one single validation error. We end up with a skeleton unit test class like this:</p><pre class="crayon-plain-tag">using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using NUnit.Framework;

namespace DataAnnotationsUnitTesting {
    [TestFixture]
    public class CreatePersonModelValidationTests : AssertionHelper {
        private CreatePersonModel CreateValidPersonModel() {
            return new CreatePersonModel() {
                FirstName = "Some Name",
                LastName = "Some Last Name",
                BirthDate = new DateTime(1982, 07, 28),
                PhoneNumber = "+112233445566"
            };
        }

        public IEnumerable&lt;ValidateRuleSpec&gt; ValidationRule_Source() {
            yield break;
        }

        [Test]
        [TestCaseSource("ValidationRule_Source")]
        public void ValidationRule(ValidateRuleSpec spec) {
            // Arrange
            var model = CreateValidPersonModel();
            // Apply bad valud
            model.GetType().GetProperty(spec.MemberName).SetValue(model, spec.BadValue);

            // Act
            var validationResults = new List&lt;ValidationResult&gt;();
            var success = Validator.TryValidateObject(model, new ValidationContext(model), validationResults, true);

            // Assert
            Expect(success, False);
            Expect(validationResults.Count, EqualTo(1));
            Expect(validationResults.SingleOrDefault(r =&gt; r.MemberNames.Contains(spec.MemberName)), Not.Null);
        }

        public class ValidateRuleSpec {
            public object BadValue;
            public string MemberName;

            public override string ToString() {
                return MemberName + " - " + (BadValue ?? "&lt;null&gt;");
            }
        }
    }
}</pre><p>Some explanation:</p>
<ul>
<li><span style="line-height: 13px;">ValidateRule() implements the test itself. However, it gets the specifications for each test via an argument. </span></li>
<li>ValidateRule_Source() provides the specs for our test.</li>
<li>class ValidateRuleSpec holds the specifications. Its ToString() uses the spec values to render a distinct string per test. This makes unit test reports easy to read. In case of failure, you know exactly which spec failed.</li>
</ul>
<p>And now the implementation of our ValidateRule_Source():</p><pre class="crayon-plain-tag">public IEnumerable&lt;ValidateRuleSpec&gt; ValidationRule_Source() {
    yield return new ValidateRuleSpec() {
        BadValue = null,
        MemberName = "FirstName"
    };
    yield return new ValidateRuleSpec() {
        BadValue = string.Empty,
        MemberName = "FirstName"
    };
    yield return new ValidateRuleSpec() {
        BadValue = null,
        MemberName = "LastName"
    };
    yield return new ValidateRuleSpec() {
        BadValue = string.Empty,
        MemberName = "LastName"
    };
    yield return new ValidateRuleSpec() {
        BadValue = new DateTime(),
        MemberName = "BirthDate"
    };
    yield return new ValidateRuleSpec() {
        BadValue = DateTime.Today,
        MemberName = "BirthDate"
    };
    yield return new ValidateRuleSpec() {
        BadValue = "-65623",
        MemberName = "PhoneNumber"
    };
    yield return new ValidateRuleSpec() {
        BadValue = "abc",
        MemberName = "PhoneNumber"
    };
}</pre><p></p>
<h2>Refining the solution</h2>
<p>This works but can be improved. Most of the functionality can be abstracted. The actual test need only provide the valid model object and the specifications. A bit of refactoring yields a nicer design for our test:</p><pre class="crayon-plain-tag">using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using NUnit.Framework;

namespace DataAnnotationsUnitTesting {
    [TestFixture]
    public abstract class ModelValidationTestsBase : AssertionHelper {
        protected abstract CreatePersonModel CreateValidModel();

        public abstract IEnumerable&lt;ValidateRuleSpec&gt; ValidationRule_Source();

        [Test]
        [TestCaseSource("ValidationRule_Source")]
        public void ValidationRule(ValidateRuleSpec spec) {
            // Arrange
            var model = CreateValidModel();
            // Apply bad valud
            model.GetType().GetProperty(spec.MemberName).SetValue(model, spec.BadValue);

            // Act
            var validationResults = new List&lt;ValidationResult&gt;();
            var success = Validator.TryValidateObject(model, new ValidationContext(model), validationResults, true);

            // Assert
            Expect(success, False);
            Expect(validationResults.Count, EqualTo(1));
            Expect(validationResults.SingleOrDefault(r =&gt; r.MemberNames.Contains(spec.MemberName)), Not.Null);
        }

        protected ValidateRuleSpec Spec(string memberName, object badValue) {
            return new ValidateRuleSpec() {MemberName = memberName, BadValue = badValue};
        }

        public class ValidateRuleSpec {
            public object BadValue;
            public string MemberName;

            public override string ToString() {
                return MemberName + " - " + (BadValue ?? "&lt;null&gt;");
            }
        }
    }

    public class CreatePersonModelValidationTests : ModelValidationTestsBase {
        protected override CreatePersonModel CreateValidModel() {
            return new CreatePersonModel() {
                FirstName = "Some Name",
                LastName = "Some Last Name",
                BirthDate = new DateTime(1982, 07, 28),
                PhoneNumber = "+112233445566"
            };
        }

        public override IEnumerable&lt;ValidateRuleSpec&gt; ValidationRule_Source() {
            yield return Spec("FirstName", null);
            yield return Spec("FirstName", string.Empty);
            yield return Spec("LastName", null);
            yield return Spec("LastName", string.Empty);
            yield return Spec("BirthDate", new DateTime());
            yield return Spec("BirthDate", DateTime.Today);
            yield return Spec("PhoneNumber", "-65623");
            yield return Spec("PhoneNumber", "abc");
        }
    }
}</pre><p>Notice how we trimmed CreatePersonModelValidationTests to a minimum. The class ModelValidationTestsBase can now be used for most of our model validation unit tests.</p>
<p>What do you think?</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/06/unit-testing-model-validation-with-mvcs-dataannotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit test equality is not domain equality</title>
		<link>https://timoch.com/blog/2013/06/unit-test-equality-is-not-domain-equality/</link>
		<comments>https://timoch.com/blog/2013/06/unit-test-equality-is-not-domain-equality/#comments</comments>
		<pubDate>Tue, 11 Jun 2013 09:19:08 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[stackoverflow]]></category>
		<category><![CDATA[unit-test]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=329</guid>
		<description><![CDATA[I came across a question on stackoverflow concerning comparing object for equality in unit test. The poster basically wants to get rid of series of assertions like this: [crayon-69d57b8962bc4136363752/] I agree, this is ugly. The more so if you have multiple tests that assert on the equality of these properties. You can always factor it [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I came across a <a href="http://stackoverflow.com/questions/318210/compare-equality-between-two-objects-in-nunit">question on stackoverflow</a> concerning comparing object for equality in unit test. The poster basically wants to get rid of series of assertions like this:</p><pre class="crayon-plain-tag">Assert.AreEqual(LeftObject.Property1, RightObject.Property1);
Assert.AreEqual(LeftObject.Property2, RightObject.Property2);
Assert.AreEqual(LeftObject.Property3, RightObject.Property3);
...
Assert.AreEqual(LeftObject.PropertyN, RightObject.PropertyN);</pre><p>I agree, this is ugly. The more so if you have multiple tests that assert on the equality of these properties. You can always factor it out into a helper function but you still end up actually writing the comparisons yourself.</p>
<p>The selected answer doesn&#8217;t feel right. The proposal is to implement Equals() in the class for your tested object. This is not always desirable or even possible. Consider the case where your use case actually makes use of Equals() in its logic. There may already exist an implementation of Equals() that satisfies different needs than those of your test. Moreover, when overriding Equals(), there is more to it than just this single function. GetHashCode() must be implemented too &#8230; and correctly ! If you don&#8217;t implement GetHashCode(), you may end up with subtle or not-so-subtle bugs if your object gets stored as a dictionary key. In most cases, it will not be an issue because only a very few classes are actually used a dictionary keys. However, if you get into the habit of overriding Equals() without GetHashCode(), you can be bitten hard !!</p>
<p>One of the most favored answer is to use reflection to discover the distinct properties. This is the way to go. Code that solely exists for testing purposes should be kept away from the classes you test. However, I find the proposed solution sub-optimal. For one thing, the method is solely dedicated to testing and directly calls Assert.AreEqual(). For another, I don&#8217;t like that it automatically recurse into IList properties, but this is a question of style.</p>
<p>I would propose a general purpose utility method like this.</p><pre class="crayon-plain-tag">/// &lt;summary&gt;
/// Returns the names of the properties that are not equal on a and b.
/// &lt;/summary&gt;
/// &lt;param name="a"&gt;&lt;/param&gt;
/// &lt;param name="b"&gt;&lt;/param&gt;
/// &lt;returns&gt;An array of names of properties with distinct values or null if a and b are null or not of the same type&lt;/returns&gt;
public static string[] GetDistinctProperties(object a, object b) {
    if (object.ReferenceEquals(a, b))
        return null;
    if (a == null)
        return null;
    if (b == null)
        return null;

    var aType = a.GetType();
    var bType = b.GetType();

    if (aType != bType)
        return null;

    var props = aType.GetProperties();

    if (props.Any(prop =&gt; prop.GetIndexParameters().Length != 0))
        throw new ArgumentException("Types with index properties not supported");

    return props
        .Where(prop =&gt; !Equals(prop.GetValue(a, null), prop.GetValue(b, null)))
        .Select(prop =&gt; prop.Name).ToArray();
}</pre><p>and of course, the unit test that goes along with it:</p><pre class="crayon-plain-tag">[Test]
public void GetDistinctProperties() {
    Expect(ReflectionUtils.GetDistinctProperties(null, null), Null);
    Expect(ReflectionUtils.GetDistinctProperties(new TestClass1(), null), Null);
    Expect(ReflectionUtils.GetDistinctProperties(null, new TestClass1()), Null);
    Expect(ReflectionUtils.GetDistinctProperties(new TestClass1(), new TestClass2()), Null);
    Expect(ReflectionUtils.GetDistinctProperties(new TestClass1(), new TestClass1()),
            EquivalentTo(new string[] {}));
    Expect(ReflectionUtils.GetDistinctProperties(new TestClass1() {Foo = "haha"}, new TestClass1()),
            EquivalentTo(new string[] {"Foo"}));
    Expect(ReflectionUtils.GetDistinctProperties(new TestClass1(), new TestClass1() {Bar = 10}),
            EquivalentTo(new string[] {"Bar"}));
}

[Test, ExpectedException(typeof(ArgumentException))]
public void GetDistinctProperties_ThrowsWithIndexedProperty() {
    ReflectionUtils.GetDistinctProperties("haha", "jeje");
}</pre><p>It can then be used in a unit test like this:</p><pre class="crayon-plain-tag">[Test]
public void BasicOperations() {
    RegionParameters parameters = new RegionParameters(5, 5, 5, 5);
    var tilemap = new BasicTileMap(parameters);

    var tile = new Tile() {
        MagmaLevel = 0,
        WaterLevel = 0,
        RockType = 1,
        State = TileState.HasFloor
    };

    tilemap.Update(new Location(0, 0, 0), tile);

    var got = tilemap.Get(new Location(0, 0, 0));
    Expect(ReflectionUtils.GetDistinctProperties(tile, got), Empty);
}</pre><p>You can wrap the method via a unit-test friendly static assert method or any way you like. The above test would fail in a quite explicit way. An error message looks like this:</p><pre class="crayon-plain-tag">Expected: &lt;empty&gt;
  But was:  &lt; "MagmaLevel" &gt;

   at NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression, String message, Object[] args)
   at Undermine.Engine.Tests.TileMaps.BasicTileMapTests.BasicOperations() in BasicTileMapTests.cs: line 29</pre><p>What do you think ?</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/06/unit-test-equality-is-not-domain-equality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asp.Net MVC: Testing your controller actions</title>
		<link>https://timoch.com/blog/2013/06/asp-net-mvc-testing-your-controller-actions/</link>
		<comments>https://timoch.com/blog/2013/06/asp-net-mvc-testing-your-controller-actions/#comments</comments>
		<pubDate>Mon, 10 Jun 2013 08:53:40 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[unit-test]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=318</guid>
		<description><![CDATA[I can&#8217;t say I like all the aspects of Microsoft ASP.Net MVC. But there is one aspect that I like though is the ability to unit test most of the components of your application. Standard ASP.Net did not prevent you from testing your application. However, the framework and documentation did not encourage you to organize [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I can&#8217;t say I like all the aspects of Microsoft ASP.Net MVC. But there is one aspect that I like though is the ability to unit test most of the components of your application. Standard ASP.Net did not prevent you from testing your application. However, the framework and documentation did not encourage you to organize your application in a way that is testable.</p>
<p>ASP.Net MVC really pushes for loosely coupled components and as such, encourages unit testing. Your controllers are not much more than plain methods taking some input, executing some logic and returning an output. Your controller is not responsible for much in the end. Even though it is a central part of any functionality, its responsibility is reduced to implementing the logic for responding to a certain type of request. It relies on the framework configuration and conventions to call its methods in an appropriate way.</p>
<p>Understanding the extend of a controller&#8217;s responsibility is a key to writing good, concise unit tests. Sometimes, it&#8217;s easier to remember what it is <strong>not responsible for</strong>:</p>
<ul>
<li><span style="line-height: 13px;"><strong>Model binding</strong>: turning the encoded form data or routing information into .Net object. A controller action does not need to know and does not care that the id of the object your are updating is a part of your action&#8217;s path (eg. <pre class="crayon-plain-tag">/admin/tags/edit/my-tag</pre> ) or if it is provided in the form of an encoded form field (eg. <pre class="crayon-plain-tag">&lt;input type="text" name="tagSlug" /&gt;</pre> )</span></li>
<li><strong>Model validation</strong>: it may seem surprising but in most cases, your controller should not implement the validation logic. From a controller&#8217;s action point of view, is there really a difference between a person&#8217;s last name missing or an unknown phone number format ? As far as your hypothetical EditPerson action is concerned, there is a validation error. Model validation should be tested separately.</li>
<li><strong>Pure business logic</strong>: a controller action is meant to handle requests. Even though it does not directly cope with http intricacies, it still very close to the http request/response life cycle. For example, an action ComputeLoanSchedule that needs to return a loan amortization schedule should probably delegate the actual computation to a business service class (ILoanService.GetAmortizationSchedule()) whose sole purpose is to handle such computation. In the future, if you need to expose the amortization schedule feature as a web api, you will only need to implement another controller and call the same business service.</li>
</ul>
<p>In the end, your controller is<strong> only responsible for:</strong></p>
<ul>
<li><span style="line-height: 13px;"><strong>Delegating work to domain services</strong>: as stated above, the domain logic of your application should be logically separated from your UI layer. It also gives you the flexibility to scale your web application and business domain services. </span></li>
<li><strong>Returning an appropriate response</strong>: a controller&#8217;s action responds to a request by returning a response. The standard MVC Controller class expects your actions provide a result that will drive the way the response if created. eg. Returning a ViewResult will trigger view rendering and a RedirectToRouteResult may respond with an HTTP 302.</li>
</ul>
<h1>Unit testing a controller action</h1>
<p>When it comes to unit testing, the less to test, the better. As such, the limited responsibility of controller actions is a boon when writing unit tests. As an example, I will be using a very simple controller<pre class="crayon-plain-tag">TagsController</pre> . It is part of a blog-like website. Its role is to allow for the management of tags to be applied to other components of the application like articles etc.</p>
<p><pre class="crayon-plain-tag">TagsController</pre> exposes a CRUD-like set of functionality:</p>
<ul>
<li><span style="line-height: 13px;">Index: provides the user with a list of existing tags</span></li>
<li>Create: enables the creation of new tags</li>
<li>Edit: enables editing existing tags</li>
</ul>
<h2>The simple case</h2>
<p>We will focus on the index functionality for now. It is implemented as a single action on our TagsController:</p><pre class="crayon-plain-tag">public class TagsController : Controller {
    private ITagService tagService;

    public TagsController(ITagService tagService) {
        this.tagService = tagService;
    }

    public ActionResult Index() {
        var tags = this.tagService.GetAll().OrderBy(tag =&gt; tag.Name);
        return View("Index", tags);
    }

    /* ... */
}</pre><p>The TagsController constructor takes a ITagService. It provides our constructor access to the tags in our database. As you can see, the <pre class="crayon-plain-tag">Index()</pre> action method does only 2 distinct operations. First, it asks for the tags to display. Then, it tells the framework to render the &#8220;Index&#8221; view using the retrieved tags as a model.</p>
<p>With such a simple implementation, the unit test will be quite simple also. I&#8217;ll follow the usual AAA (Arrange-Act-Assert) pattern.</p><pre class="crayon-plain-tag">[Test]
public void Index_RetrievesAllTags() {
    // Arrange
    var mockService = new Mock&lt;ITagService&gt;();
    var controller = new TagsController(mockService.Object);
    mockService
        .Setup(s =&gt; s.GetAll())
        .Returns(new[] {
            new Tag {Slug = "tag1", Name = "Tag1"},
            new Tag {Slug = "tag7", Name = "Tag7"},
            new Tag {Slug = "tag4", Name = "Tag4"}
        });

    // Act
    var result = controller.Index() as ViewResult;

    // Assert
    Expect(result, Not.Null);
    Expect(result.ViewName, EqualTo("Index"));

    // ensure service was used
    mockService.Verify(s =&gt; s.GetAll(), Times.Once());

    // check view's model
    var tags = result.Model as IEnumerable&lt;Tag&gt;;
    Expect(tags, Not.Null);
    Expect(tags.Count(), EqualTo(3));
    // tags should be sorted
    Expect(tags.ToArray()[0].Slug, EqualTo("tag1"));
    Expect(tags.ToArray()[1].Slug, EqualTo("tag4"));
    Expect(tags.ToArray()[2].Slug, EqualTo("tag7"));
}</pre><p>The first part sets up an ITagService mock for TagsController to consume. We then simply call method <pre class="crayon-plain-tag">Index()</pre> .</p>
<p>The assertions start with making sure we got a non-null result of the ViewResult type. <pre class="crayon-plain-tag">Index()</pre>  should ask for the &#8220;Index&#8221; view to be rendered. I prefer explicitly specifying the view name to render in my controller action. I believe this reduces the mental gymnastic necessary when debugging action-view interactions.</p>
<p><pre class="crayon-plain-tag">mockService.Verify()</pre>  ensures<pre class="crayon-plain-tag">ITagService.GetAll()</pre>  was called.</p>
<p>I then proceed with checking the model provided to the view is consistent with the data from the mock service object. One of the requirements is that the tags are sorted by name.</p>
<p>As you can see in the Index unit test, there is a lot more code than the method being tested. This is also one of the reason why you should reduce the scope of your tests as much as you can.</p>
<h2>A more complex test case</h2>
<p>I&#8217;ll cover the &#8220;create a new tag&#8221; functionality. In this case, the functionality is implemented by a pair of actions. A parameter-less <pre class="crayon-plain-tag">Create()</pre>  action simply triggers the rendering of an empty tag editor (implemented by a view names &#8220;Save&#8221;. The other <pre class="crayon-plain-tag">Create()</pre>  action takes a <pre class="crayon-plain-tag">SaveTagModel</pre>  parameter and responds to form submissions. As such, it behaves differently in case there is a validation error or the tag already exists in the tag db.</p><pre class="crayon-plain-tag">public class TagsController : Controller
{
    /* ... */

    [HttpGet]
    public ActionResult Create() {
        return View("Save", new SaveTagModel() {IsNew = true});
    }

    [HttpPost]
    public ActionResult Create(SaveTagModel saveTagModel) {
        var existingTag = tagService.GetBySlug(saveTagModel.Slug);
        if (existingTag != null) {
            ModelState.AddModelError("TagExists", "A tag with that slug already exists");
        }

        if (!ModelState.IsValid) {
            saveTagModel.IsNew = true;
            return View("Save", saveTagModel);
        }

        tagService.Save(new Tag() { Name = saveTagModel.Name, Slug = saveTagModel.Slug });
        return RedirectToAction("Index");
    }

    /* ... */
}</pre><p>I&#8217;ll show the tests I put together to cover the functionality of <pre class="crayon-plain-tag">TagsController.Create()</pre> . The first of those test is ensuring the initial to Create() triggers the rendering of an empty tag editor. The tag editor is implemented by a view called &#8220;Save&#8221; shared between the <pre class="crayon-plain-tag">Create()</pre>  and <pre class="crayon-plain-tag">Edit()</pre>  operations. As you can see, I make sure the view is specified by name. I also make sure the model is in a state consistent with an empty<pre class="crayon-plain-tag">SaveTagModel</pre> .</p><pre class="crayon-plain-tag">[Test]
public void Create_ShowsEmptySaveEditor() {
    // Arrange
    var mockService = new Mock&lt;ITagService&gt;();
    var controller = new TagsController(mockService.Object);

    // Act
    var result = controller.Create() as ViewResult;

    //Assert
    Expect(result, Not.Null);
    Expect(result.ViewName, EqualTo("Save"));
    var saveTagModel = result.Model as SaveTagModel;
    Expect(saveTagModel, Not.Null);
    Expect(saveTagModel.IsNew, True);
    Expect(saveTagModel.Name, Null.Or.Empty);
    Expect(saveTagModel.Slug, Null.Or.Empty);
}</pre><p>The next 2 tests cover the behavior of the<pre class="crayon-plain-tag">Create(SaveTagModel tag)</pre>  action. That is the action that responds to form submission from the tag editor.  These tests need to cover the following</p>
<ul>
<li><span style="line-height: 13px;">What happens when invalid input is provided?</span></li>
<li>What happens when a tag exists with the same &#8216;slug&#8217;?</li>
<li>What happens upon success?</li>
</ul>
<p>It will not come as a surprise that I wrote 3 tests, one for each of the points. The first test ensure <pre class="crayon-plain-tag">Create()</pre>  behaves when provided with invalid data. This test demonstrates an important point. The controller is not aware and does not care what the actual model errors are. Its &#8216;invalid input&#8217; behavior is triggered by any model error. We want to reduce our controller logic as much as possible. There may be some cases where the controller&#8217;s action behave differently based on specific errors. If you can avoid it, do so. It is against the separation of concern. A controller is not responsible for validation.</p><pre class="crayon-plain-tag">[Test]
public void Create_ShowsEditorAgainOnInvalidInput() {
    // Arrange
    var mockService = new Mock&lt;ITagService&gt;();
    var controller = new TagsController(mockService.Object);

    // Act
    var saveTagModelArg = new SaveTagModel() {Slug = string.Empty, Name = "somename"};
    controller.ModelState.AddModelError("testerror", "test message");
    var result = controller.Create(saveTagModelArg) as ViewResult;

    //Assert
    Expect(result, Not.Null);
    Expect(result.ViewName, EqualTo("Save"));
    var saveTagModel = result.Model as SaveTagModel;
    Expect(saveTagModel, Not.Null);
    Expect(saveTagModel.IsNew, True);
    Expect(saveTagModel.Name, EqualTo("somename"));
    Expect(saveTagModel.Slug, Null.Or.Empty);
    Expect(result.ViewData.ModelState.IsValid, False);
}</pre><p>Considering what I have just said, there is an issue with the current implementation of <pre class="crayon-plain-tag">Create()</pre> . It checks that a tag does not exist. This is a form of validation and should probably be moved either to model validation (implemented by a custom validation attribute) or to the service (by adding a specific <pre class="crayon-plain-tag">ITagService.Create()</pre>  method). On the other hand, since the validation relies on a service component one could argue that it is part of the orchestration the controller is responsible for. I will leave it here because it is such a trivial validation. Anything more complex I would extract it and test it separately. My rule of thumb is: if it takes more than one unit test to cover a piece of validation in the controller, the validation should be moved to its own class.</p>
<p>Here is the test that covers that part.</p><pre class="crayon-plain-tag">[Test]
public void Create_ShowsEditorAgainOnDuplicateSlug() {
    // Arrange
    var mockService = new Mock&lt;ITagService&gt;();
    var controller = new TagsController(mockService.Object);
    mockService.Setup(s =&gt; s.GetBySlug("tag"))
        .Returns(new Tag("tag", "Tag"));

    // Act
    var saveTagModelArg = new SaveTagModel() {Slug = "tag", Name = "somename"};
    var result = controller.Create(saveTagModelArg) as ViewResult;

    //Assert
    Expect(result, Not.Null);
    Expect(result.ViewName, EqualTo("Save"));
    var saveTagModel = result.Model as SaveTagModel;
    Expect(saveTagModel, Not.Null);
    Expect(saveTagModel.IsNew, True);
    Expect(saveTagModel.Name, EqualTo("somename"));
    Expect(saveTagModel.Slug, EqualTo("tag"));
    Expect(result.ViewData.ModelState.IsValid, False);
}</pre><p>Last but not least, here is the test that covers the success path. Out action should have called <pre class="crayon-plain-tag">ITagService.Save()</pre>  with an appropriate argument and it should redirect us to the index page for our tags. As you can see, the redirection is tested against route values, not against an actual URI. The routing configuration is covered by another set of tests. This will be the subject of another post in the next few days.</p><pre class="crayon-plain-tag">[Test]
public void Create_SavesTagAndRedirectsOnSuccess() {
    // Arrange
    var mockService = new Mock&lt;ITagService&gt;();
    var controller = new TagsController(mockService.Object);
    var saveTagModelArg = new SaveTagModel() {Slug = "tag", Name = "somename"};
    mockService.Setup(s =&gt; s.Save(It.Is&lt;Tag&gt;(tag =&gt; tag.Slug == "tag" &amp;&amp; tag.Name == "somename")));

    // Act
    var result = controller.Create(saveTagModelArg) as RedirectToRouteResult;

    //Assert
    Expect(result, Not.Null);
    Expect(result.Permanent, False);
    Expect(result.RouteName, Null.Or.Empty);
    Expect(result.RouteValues["controller"], Null.Or.Empty.Or.EqualTo("Tags"));
    Expect(result.RouteValues["action"], EqualTo("Index"));
    mockService.VerifyAll();
}</pre><p></p>
<h1>Conclusion</h1>
<p>As you can see, even though our controller is quite simple (3 methods only and simple at that), we had to write quite a few lines of unit test code to cover all the code paths. If you want to keep your unit tests to a minimum, make sure you respect the separation of concern principle. Test each of the involved components separately and reduce to a minimum the contract between them. The less they know about the other, the easier it is to change one component without your change to ripple through your whole application.</p>
<p>In the next few posts, I will cover testing model binding and validation as well as routes.</p>
<p>Don&#8217;t hesitate to hail me in the comments or on <a href="https://twitter.com/TiMochOnEdge">Twitter</a></p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/06/asp-net-mvc-testing-your-controller-actions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing XPathNavigator</title>
		<link>https://timoch.com/blog/2013/06/testing-xpathnavigator/</link>
		<comments>https://timoch.com/blog/2013/06/testing-xpathnavigator/#comments</comments>
		<pubDate>Mon, 03 Jun 2013 09:11:47 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xpath]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=304</guid>
		<description><![CDATA[In my previous post about XPathNavigator, I explained in what circumstances the default implementation of XPathNavigator is troublesome. I went over the design of the class and highlighted how that design helps us re-implement XPathNavigator to address the issue. Testing XPathNavigator First things first, before attacking the new implementation proper, we want to make sure [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In my <a title="So what’s wrong with XPathDocument ?" href="http://timoch.com/blog/2013/05/so-whats-wrong-with-xpathdocument/">previous post about XPathNavigator</a>, I explained in what circumstances the default implementation of XPathNavigator is troublesome. I went over the design of the class and highlighted how that design helps us re-implement XPathNavigator to address the issue.</p>
<h2>Testing XPathNavigator</h2>
<p>First things first, before attacking the new implementation proper, we want to make sure our implementation is compatible with the default implementation. To do so, we will write tests that will be run both against the Microsoft implementation as well as our implementation once it exists. Our goal here is really twofold. On the one hand, we want to ensure the existing implementation actually works as documented. On the other hand, we want to check our own implementation against the specification tests.</p>
<h3>What should we test ?</h3>
<p>XPathNavigator is a complex class. So we want to limit my tests to what actually matters for the new implementation. Otherwise, we may be writing literally hundreds of tests.</p>
<p>It is obviously not necessary to test methods that will not be re-implemented. In the previous post, we identified a subset of methods that we will need to re-implement. All other methods are somehow using this basic subset to implement their functionality. The subset is the list of abstract members:</p><pre class="crayon-plain-tag">public abstract string BaseURI { get; }
    public abstract bool IsEmptyElement { get; }
    public abstract string LocalName { get; }
    public abstract string Name { get; }
    public abstract string NamespaceURI { get; }
    public abstract XmlNameTable NameTable { get; }
    public abstract XPathNodeType NodeType { get; }
    public abstract string Prefix { get; }

    public abstract bool MoveTo(XPathNavigator other);
    public abstract bool MoveToFirstAttribute();
    public abstract bool MoveToFirstChild();
    public abstract bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope);
    public abstract bool MoveToId(string id);
    public abstract bool MoveToNext();
    public abstract bool MoveToNextAttribute();
    public abstract bool MoveToNextNamespace(XPathNamespaceScope namespaceScope);
    public abstract bool MoveToParent();
    public abstract bool MoveToPrevious();</pre><p>As you can see, we have two distinct groups:</p>
<ul>
<li><span style="line-height: 13px;">The abstract properties expose information about the current node. Our tests will ensure that we get consistent information for all types of node.<br />
</span></li>
<li>The abstract methods are all concerned about moving the navigator to another node. The tests need to check that the move operations result in the navigator pointing to the right node given a known starting position.</li>
</ul>
<h3>How should we test it ?</h3>
<p>We will test the properties by setting up a XPathNavigator that points to specific nodes of an xml document. Once setup, we simply check the properties expose consistent values. We will test the Move() operations in a very similar way. We will setup the XPathNavigator instance on a specific node, execute the Move() operation we want to test and then check that the XPathNavigator yields values through its properties that are consistent with the navigator&#8217;s new position.</p>
<p>This is actually very similar. The only difference is the Move() operation. The similarity will let us factor our most of the test code into a few utility functions.</p><pre class="crayon-plain-tag">private void CanMoveImpl(MoveTestArgs args, Func&lt;XPathNavigator, bool&gt; moveOperation) {
    CheckInconclusive(args);

    // Arrange - get a navigator on requested node
    var nav = CreateNavigatorOnSelected(args.Xml, args.InitialPosition);

    // Act - move thenode
    var success = moveOperation(nav);

    // Assert -- check if success consistent with ShouldSucceed
    Expect(success, args.ShouldSucceed ? (Constraint)True : False, "inconsistent success state");
    // Assert -- check node properties 
    ExpectNodeProperties(nav, args);
}</pre><p>CanMoveImpl() acts as a parametrized test. It takes 2 arguments:</p>
<ul>
<li><span style="line-height: 13px;">args: a MoveTestArgs instance. This argument describes the test&#8217;s original state and the resulting state we should test against.</span></li>
<li>moveOperation: A delegate to the Move() operation to test. Passing the operation to test as a parameter let us also write non-Move() tests by simply passing a no-op callback.</li>
</ul>
<p><em>NUnit: I am using NUnit to write the unit tests. It is only a matter of preference. You can adapt the tests to work against another testing framework such as <a href="http://msdn.microsoft.com/en-us/library/ms243147.aspx">Microsoft Unit Testing Framework</a>. I find NUnit to be simple to use, non-obstrusive and very flexible. </em></p>
<p>CanMoveImpl() is called by actual test methods like the following:</p><pre class="crayon-plain-tag">[TestCaseSource("CanMoveToNext_Source")]
public void CanMoveToNext(MoveTestArgs args) {
    CanMoveImpl(args, n =&gt; n.MoveToNext());
}</pre><p>It is a parametrized test. The TestCaseSource attribute tells NUnit which method to call to get the MoveTestArgs instance for each test.</p><pre class="crayon-plain-tag">public IEnumerable&lt;MoveTestArgs&gt; CanMoveToNext_Source() {
    yield return new MoveTestArgs() {
        Xml = @"&lt;root&gt;&lt;/root&gt;",
        InitialPosition = "/", // selects root
        ShouldSucceed = false
    };

    yield return new MoveTestArgs() {
        Xml = @"&lt;root&gt;&lt;child/&gt;&lt;/root&gt;",
        InitialPosition = "/root/child",
        ShouldSucceed = false
    };

    yield return new MoveTestArgs() {
        Xml = @"&lt;root&gt;&lt;child/&gt;&lt;child2/&gt;&lt;/root&gt;",
        InitialPosition = "/root/child",
        NodeType = XPathNodeType.Element,
        LocalName = "child2",
    };

    /* ... */
}</pre><p>Method CanmoveToNext_Source() returns each test case for a given operation. In the above example, we have the test cases for &#8220;when position on document root, MoveToNext() should fail&#8221;, &#8220;When positioned on element whith no next sibling, MoveToNext() should fail&#8221; and &#8220;when positioned on an element with a next sibling, MoveToNext() should succeed and point to the specific node&#8221;.</p>
<p>Each test case is defined by specifying values for the fields of class CanMoveArgs.</p><pre class="crayon-plain-tag">public class MoveTestArgs {
    // Xml document
    public string Xml;
    // XPath to select starting first position
    public string InitialPosition;

    // value to test against - no assertion for a given property when not set
    public string BaseURI;
    public bool? IsEmptyElement;
    public string LocalName;
    public string Name;
    public string NamespaceURI;
    public string NameTable;
    public XPathNodeType? NodeType;
    public string Prefix;
    public string Value;

    // Indicates whether the move should succeed or not
    public bool ShouldSucceed = true;

    // indicates whether the test is inconclusive
    public string Inconclusive;

    // TestCaseSource calls ToString() on each test case argument to create the test case name.
    public override string ToString() {
        if (ShouldSucceed)
            return string.Format("{0} -- {1} -- {2} -- {3}", Xml, InitialPosition, NodeType, LocalName);
        else
            return string.Format("{0} -- {1} -- fails", Xml, InitialPosition);
    }
}</pre><p>Method ExpectNodeProperties() implements the assertions depending on the configuration of its MoveTestArgs instance:</p><pre class="crayon-plain-tag">private void ExpectNodeProperties(XPathNavigator navigator, MoveTestArgs args) {
    if (args.LocalName != null) Expect(navigator.LocalName, EqualTo(args.LocalName), "bad localname");
    if (args.Name != null) Expect(navigator.Name, EqualTo(args.Name), "bad name");
    if (args.Prefix != null) Expect(navigator.Prefix, EqualTo(args.Prefix), "bad prefix");
    if (args.NamespaceURI != null) Expect(navigator.NamespaceURI, EqualTo(args.NamespaceURI), "bad namespace uri");
    if (args.NodeType != null) Expect(navigator.NodeType, EqualTo(args.NodeType), "bad node type");
    if (args.Value != null) Expect(navigator.Value, EqualTo(args.Value), "bad value");
}</pre><p></p>
<h3>Executing our tests</h3>
<p>We want our tests to be executed against the Microsoft implementation as well as our own implementation. The most straight-forward way of achieving this is to implement our tests in an abstract test fixture. The abstract fixture has an factory method to create an instance of XPathNavigator to test against. For each implementation, we create a subclass of our fixture and override the factory method.</p>
<p>CreateNavigable returns an IXPathNavigable. In turn IXpathNavigable lets us create a navigator positioned on the document root thanks to its CreateNavigator() method.</p><pre class="crayon-plain-tag">[TestFixture]
public abstract class XPathDocumentTests : AssertionHelper {
    protected abstract IXPathNavigable CreateNavigable(string xml);
    /* tests implementations */
}

public class MsXPathDocumentTests : XPathDocumentTests {
    protected override IXPathNavigable CreateNavigable(string xml) {
        TextReader textReader = new StringReader(xml);
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.IgnoreWhitespace = false;
        XmlReader reader = XmlReader.Create(textReader, settings);
        return new XPathDocument(reader, XmlSpace.Preserve);
    }
}</pre><p>We&#8217;ll add the test fixture for our own implementation when we have the skeleton available. In the mean time, this lets us verify our expectations against the actual implementation of XPathNavigator.</p>
<p>The next post on the topic will tackle the new implementation&#8217;s design. I&#8217;ll make the implementation and test available as a source code download at the end of this series of articles.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/06/testing-xpathnavigator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XPathDocument and whitespaces</title>
		<link>https://timoch.com/blog/2013/05/xpathdocument-and-whitespaces/</link>
		<comments>https://timoch.com/blog/2013/05/xpathdocument-and-whitespaces/#comments</comments>
		<pubDate>Fri, 24 May 2013 11:57:32 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xpath]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=287</guid>
		<description><![CDATA[Writing code is fun. At least it is for me. But sometimes it gets irritating. You know, you&#8217;re busy on something, you write the code, you know it&#8217;s right but it doesn&#8217;t work&#8230; You keep your focus on that one piece of code you just wrote and it keeps on not working. Sometimes, the reason [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Writing code is fun. At least it is for me. But sometimes it gets irritating. You know, you&#8217;re busy on something, you write the code, you know it&#8217;s right but it doesn&#8217;t work&#8230; You keep your focus on that one piece of code you just wrote and it keeps on not working. Sometimes, the reason it doesn&#8217;t work is obvious but sometimes, you keep reviewing your code, its surrounding, you debug away several variants of your solution and it keeps on not working &#8230;</p>
<p>I just had one of those moments&#8230;</p>
<p>And then, bang ! The solution jumps at me and it&#8217;s so obvious I almost felt shame <img src="https://timoch.com/blog/wp-includes/images/smilies/icon_neutral.gif" alt=":-|" class="wp-smiley" /> </p>
<p>I was writing the unit tests in preparation for my next article on creating a <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx">XPathNavigator</a> implementation. The code basically boils down to this:</p><pre class="crayon-plain-tag">TextReader textReader = new StringReader("&lt;root&gt;    &lt;/root&gt;");
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = false;
XmlReader reader = XmlReader.Create(textReader, settings);
XPathDocument doc = new XPathDocument(reader);
var nav = doc.CreateNavigator().SelectSingleNode("/root/text()");
var success = nav.MoveToParent();</pre><p>I am testing <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.movetoparent.aspx">MoveToParent()</a> from a whitespace node. <pre class="crayon-plain-tag">"/root/text()"</pre>  is expected to give me an <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx">XPathNavigator </a>located on the whitespace node inside the &lt;root&gt; element. And nav just keeps on being null. Since I had been busy writing pairs of xml samples and xpath queries to put my test in each situation I needed to test. I immediately assumed my xpath query was not correct. i just kept on tweaking here, there. nav is null still &#8230;</p>
<p>After some time, I decided to not put more effort into it and come back to it later, once I can take the necessary step back. I posted a question on <a href="http://stackoverflow.com/questions/16732622/select-whitespace-node-with-xpath-in-c-sharp">stackoverflow.com</a> and worked on something else.</p>
<p>I was busy on something completely different when it struck me. One of those &#8220;Haha&#8221; moments. <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument.aspx">XPathDocument</a> has a constructor that takes a <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlspace.aspx">XmlSpace</a> enum value. By default, if you don&#8217;t specify it, XPathDocument will simply skip all non-significant whitespace node.</p><pre class="crayon-plain-tag">// skips ignorable whitespaces
XPathDocument doc = new XPathDocument(reader);
// skips also
XPathDocument doc = new XPathDocument(reader, XmlSpace.Default);
// keeps non-significant whitespaces
XPathDocument doc = new XPathDocument(reader, XmlSpace.Preserve);</pre><p>That&#8217;s it &#8230; annoying.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/05/xpathdocument-and-whitespaces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>So what’s wrong with XPathDocument ?</title>
		<link>https://timoch.com/blog/2013/05/so-whats-wrong-with-xpathdocument/</link>
		<comments>https://timoch.com/blog/2013/05/so-whats-wrong-with-xpathdocument/#comments</comments>
		<pubDate>Fri, 24 May 2013 07:20:40 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xpath]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=224</guid>
		<description><![CDATA[This post is the first in a series of posts related to [crayon-69d57b89643ff910227283-i/] and [crayon-69d57b8964405969023929-i/]. I will highlight the qualities and drawbacks of the standard .Net implementations and go through the design and development of a new implementation that fits better to my needs. First, what is an XPathDocument ? An [crayon-69d57b8964407434557360-i/] is used when you [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>This post is the first in a series of posts related to <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument.aspx"><pre class="crayon-plain-tag">XPathDocument</pre></a> and <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a>. I will highlight the qualities and drawbacks of the standard .Net implementations and go through the design and development of a new implementation that fits better to my needs.</p>
<h3><span style="font-size: 1.17em;">First, what is an XPathDocument ?</span></h3>
<p>An <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument.aspx"><pre class="crayon-plain-tag">XPathDocument</pre></a> is used when you need to query xml data using XPath. For example, you can get a list of article id and ordered quantity from the following xml file:</p><pre class="crayon-plain-tag">&lt;order&gt;
  &lt;article id="1"&gt;
    &lt;quantity&gt;12&lt;/quantity&gt;
  &lt;/article&gt;
  &lt;article id="5"&gt;
    &lt;quantity&gt;8&lt;/quantity&gt;
  &lt;/article&gt;
  &lt;article id="6"&gt;
    &lt;quantity&gt;1&lt;/quantity&gt;
  &lt;/article&gt;
&lt;/order&gt;</pre><p>using the following code:</p><pre class="crayon-plain-tag">class Program {
    static void Main(string[] args) {
        XPathDocument doc = new XPathDocument(@"order.xml");

        XPathNavigator nav = doc.CreateNavigator();
        var articles = nav.Select("//article");
        foreach (XPathNavigator article in articles) {
            Console.WriteLine("{0}:{1}", 
                article.SelectSingleNode("@id").Value, 
                article.SelectSingleNode("quantity").Value);
        }
    }
}</pre><p>XPath, once you get a hang of it, is very powerful and flexible for accessing Xml data. It allows for complex queries and computation.</p>
<h3>Where&#8217;s the catch?</h3>
<p>This is great but there is a drawback. As per the documentation, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument.aspx"><pre class="crayon-plain-tag">XPathDocument</pre></a> <em>provides a fast, read-only, in-memory representation of an XML document by using the XPath data model. </em>This does not scale well with file sizes. If your files grow to tens of MB or larger, it will be as much data that will be loaded in memory. I recently built a mapping utility based on XPath. The starting requirements were to handle lots of small files. It turned out that once in the field, clients were using feeding it a small number of large files instead. Loading these large files in memory caused a lot of issues from bad responsiveness due to excessive swapping to plain <a href="http://msdn.microsoft.com/en-us/library/system.outofmemoryexception.aspx"><pre class="crayon-plain-tag">OutOfMemoryException</pre></a>.</p>
<p>The good news is that we can do something about it.</p>
<h2>How does XPath work in .Net?</h2>
<p>In the above code snippet, you can see that the only reference to <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument.aspx"><pre class="crayon-plain-tag">XPathDocument</pre></a> is to create it. We then use it only once to create an <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a>. The rest of the XPath querying involves only XPathNavigators.</p>
<h4>XPathNavigator class</h4>
<p>An <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a> is a cursor on an xml data structure. As a cursor, it provides basic operations to move the cursor, to query information about the data it points to and also to clone itself. <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a> can also be used to update the underlying data if the implementation supports it.</p>
<p>The data of the node pointed to by a navigator can be accessed using a set of properties. The most commonly used would be LocalName, NamespaceURI, Prefix but most importantly Value and its variants. NodeType is also important. The type of a node determines the allowed move operations supported.</p><pre class="crayon-plain-tag">public abstract string BaseURI { get; }
    public virtual bool HasAttributes { get; }
    public virtual bool HasChildren { get; }
    public virtual string InnerXml { get; set; }
    public abstract bool IsEmptyElement { get; }
    public abstract string LocalName { get; }
    public abstract string Name { get; }
    public abstract string NamespaceURI { get; }
    public abstract XmlNameTable NameTable { get; }
    public abstract XPathNodeType NodeType { get; }
    public virtual string OuterXml { get; set; }
    public abstract string Prefix { get; }
    public virtual IXmlSchemaInfo SchemaInfo { get; }
    public override object TypedValue { get; }
    public virtual object UnderlyingObject { get; }
    public override bool ValueAsBoolean { get; }
    public override DateTime ValueAsDateTime { get; }
    public override double ValueAsDouble { get; }
    public override int ValueAsInt { get; }
    public override long ValueAsLong { get; }
    public override Type ValueType { get; }
    public virtual string XmlLang { get; }
    public override XmlSchemaType XmlType { get; }</pre><p>To move a validator around, the following methods can be used. Notice that all but one of them return a boolean. It indicates whether the move operation succeeded. True means the navigator now points to the new node, false, means it has not moved and still point to the original node. The only method that does not return a boolean is MoveToRoot() because it always succeeds.</p>
<p>An operation may fail for various reasons. For example, MoveToNext() will fail if the current node has no next sibling (eg. the last element of a sequence) or if the current node is an attribute. MoveToChild() will fail if there is no child of the current node that satisfies the conditions.</p><pre class="crayon-plain-tag">public abstract bool MoveTo(XPathNavigator other);
    public virtual bool MoveToAttribute(string localName, string namespaceURI);
    public virtual bool MoveToChild(XPathNodeType type);
    public virtual bool MoveToChild(string localName, string namespaceURI);
    public virtual bool MoveToFirst();
    public abstract bool MoveToFirstAttribute();
    public abstract bool MoveToFirstChild();
    public bool MoveToFirstNamespace();
    public abstract bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope);
    public virtual bool MoveToFollowing(XPathNodeType type);
    public virtual bool MoveToFollowing(string localName, string namespaceURI);
    public virtual bool MoveToFollowing(XPathNodeType type, XPathNavigator end);
    public virtual bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end);
    public abstract bool MoveToId(string id);
    public virtual bool MoveToNamespace(string name);
    public abstract bool MoveToNext();
    public virtual bool MoveToNext(XPathNodeType type);
    public virtual bool MoveToNext(string localName, string namespaceURI);
    public abstract bool MoveToNextAttribute();
    public bool MoveToNextNamespace();
    public abstract bool MoveToNextNamespace(XPathNamespaceScope namespaceScope);
    internal bool MoveToNonDescendant();
    public abstract bool MoveToParent();
    public abstract bool MoveToPrevious();
    public virtual void MoveToRoot();</pre><p></p>
<h4>XPath queries?</h4>
<p>That&#8217;s all very good but you might ask &#8216;what about XPath queries?&#8217;. XPath queries can be executed using the following functions:</p><pre class="crayon-plain-tag">public virtual object Evaluate(string xpath);
    public virtual object Evaluate(XPathExpression expr);
    public virtual object Evaluate(string xpath, IXmlNamespaceResolver resolver);
    public virtual object Evaluate(XPathExpression expr, XPathNodeIterator context);
    public virtual bool Matches(string xpath);
    public virtual bool Matches(XPathExpression expr);
    public virtual XPathNodeIterator Select(string xpath);
    public virtual XPathNodeIterator Select(XPathExpression expr);
    public virtual XPathNodeIterator Select(string xpath, IXmlNamespaceResolver resolver);
    public virtual XPathNodeIterator SelectAncestors(XPathNodeType type, bool matchSelf);
    public virtual XPathNodeIterator SelectAncestors(string name, string namespaceURI, bool matchSelf);
    public virtual XPathNodeIterator SelectChildren(XPathNodeType type);
    public virtual XPathNodeIterator SelectChildren(string name, string namespaceURI);
    public virtual XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf);
    public virtual XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf);
    public virtual XPathNavigator SelectSingleNode(string xpath);
    public virtual XPathNavigator SelectSingleNode(XPathExpression expression);
    public virtual XPathNavigator SelectSingleNode(string xpath, IXmlNamespaceResolver resolver);</pre><p>Evaluate() returns a value dependent on the XPath query. The result can be an integer, a string or a node set etc. Matches() tells you whether the current satisfies conditions expressed as an XPath expression. The Select() functions return a node iterator over their result. That is a set of XPathNavigators each pointing to a node in the XPath expression result set.</p>
<h2>So how do we solve our problem?</h2>
<p>The key element that will help us solve our scaling issue lies in the implementation of the XPath querying methods (Evaluate, Match and Select). Their implementation is actually expressed in terms of Move() operations and property checks on XPathNavigators.</p>
<p>The following example uses on one hand Select() to find the &lt;article&gt; nodes of root element &lt;order&gt;, on the other hand, it uses a series of Move() operations to do the same.</p><pre class="crayon-plain-tag">private static void Example2Select() {
            XPathDocument doc = new XPathDocument(@"order.xml");

            XPathNavigator nav = doc.CreateNavigator();
            var articles = nav.Select("/order/article");
            foreach (XPathNavigator article in articles) {
                Console.WriteLine("node inner xml : {0}", article.OuterXml);
            }
        }

        private static void Example2Move() {
            XPathDocument doc = new XPathDocument(@"order.xml");

            XPathNavigator nav = doc.CreateNavigator();
            nav.MoveToChild("order", ""); // move to element order
            nav.MoveToChild("article", ""); // move to first element article

            do {
                Console.WriteLine("node inner xml : {0}", nav.OuterXml);
            } while (nav.MoveToNext("article", ""));

        }</pre><p>All XPath queries can be expressed as a series of Move() and Clone() operations. This is exactly what Select() does behind the scene. This is where the design of the <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a> class shines. Select() is implemented exclusively in terms of Move() and Clone() operations. This means that any implementation of <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a> that supports these operations can benefit from the XPath query language.</p>
<p>Did you notice earlier that some of the Move() operations are virtual, others abstract ? In the same manner that XPath queries can be expressed as a series of Move() operations, most Move() operations can be expressed as a series of some of the most basic move operations. For example, the default implementation of MoveToRoot() is simply <pre class="crayon-plain-tag">while (this.MoveToParent()) {}</pre> Properties of <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a> also follow the same pattern. Virtual properties have a default implementation that relies on the abstract properties.</p>
<p>This design hepls a lot in our case. We can get rid of the default .Net-provided <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a> implementation without changing our usage. We will create a new implementation that will not load all the xml data in memory ; instead, it will cache this information to disk. Of course, since disk IO will occur, our implementation will probably be slower. We will see what we can do about it in a later post.</p>
<p>Below are the limited list of methods and properties that must be implemented in order to support XPath querying.</p><pre class="crayon-plain-tag">public abstract string BaseURI { get; }
    public abstract bool IsEmptyElement { get; }
    public abstract string LocalName { get; }
    public abstract string Name { get; }
    public abstract string NamespaceURI { get; }
    public abstract XmlNameTable NameTable { get; }
    public abstract XPathNodeType NodeType { get; }
    public abstract string Prefix { get; }

    public abstract bool MoveTo(XPathNavigator other);
    public abstract bool MoveToFirstAttribute();
    public abstract bool MoveToFirstChild();
    public abstract bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope);
    public abstract bool MoveToId(string id);
    public abstract bool MoveToNext();
    public abstract bool MoveToNextAttribute();
    public abstract bool MoveToNextNamespace(XPathNamespaceScope namespaceScope);
    public abstract bool MoveToParent();
    public abstract bool MoveToPrevious();</pre><p>As you can see, the minimum interface we need to support is not as big as we could have thought. We still have a lot to do though. We have to design our solution and implement it but more importantly, we need to write tests for it.</p>
<h2>Conclusion</h2>
<p>In a next post, we will setup a series of unit tests. These tests will be run against both the standard implementation (to ensure we understand the requirements correctly) and our new implementation (to make sure we stick to the requirements).</p>
<p>The design of <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx"><pre class="crayon-plain-tag">XPathNavigator</pre></a> is quite clever. Basing the implementation of XPath queries on the abstract implementation of primitive Move() and Clone() operations enables implementors to keep their internal representation of the data completely decoupled. An implementation could very well provide an Xml-compatible view on a data structure completely unrelated to Xml. For instance, it is quite simple to expose the information of a tree of POCOs using Reflection. Another example would be to expose other data formats such as JSON to XPath-only consumers.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/05/so-whats-wrong-with-xpathdocument/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Game development irony</title>
		<link>https://timoch.com/blog/2013/04/game-development-irony/</link>
		<comments>https://timoch.com/blog/2013/04/game-development-irony/#comments</comments>
		<pubDate>Tue, 30 Apr 2013 14:54:21 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[game]]></category>

		<guid isPermaLink="false">http://timoch.com/blog/?p=214</guid>
		<description><![CDATA[The guys at http://www.greenheartgames.com/ pulled a nice trick yesterday. Just the day after they released their game development simulation game Game Dev Tycoon, they also uploaded a cracked version of the game for the pirates. What the heck ! What for ? Well, this cracked version is the same as the original game except the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>The guys at <a href="http://www.greenheartgames.com/">http://www.greenheartgames.com/</a> pulled a nice <a href="http://www.greenheartgames.com/2013/04/29/what-happens-when-pirates-play-a-game-development-simulator-and-then-go-bankrupt-because-of-piracy/">trick</a> yesterday. Just the day after they released their game development simulation game <a href="http://www.greenheartgames.com/app/game-dev-tycoon/">Game Dev Tycoon</a>, they also uploaded a cracked version of the game for the pirates.</p>
<p><strong>What the heck ! What for ?</strong><br />
Well, this cracked version is the same as the original game except the players are screwed, they cannot expand their in-game company above some limit due to &#8230;</p>
<p>Hum, well &#8230; Yes, <strong>piracy</strong> &#8230; Ironic, isn&#8217;t it ?</p>
<p>This really made my day <img src="https://timoch.com/blog/wp-includes/images/smilies/icon_smile.gif" alt=":-)" class="wp-smiley" />  I haven&#8217;t tested the game itself yet but it sure looks like fun.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/04/game-development-irony/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>std::unique_ptr semantics</title>
		<link>https://timoch.com/blog/2013/04/std-unique_ptr-semantic/</link>
		<comments>https://timoch.com/blog/2013/04/std-unique_ptr-semantic/#comments</comments>
		<pubDate>Sat, 13 Apr 2013 17:33:22 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[unique_ptr]]></category>

		<guid isPermaLink="false">http://www.timoch.com/blog/?p=180</guid>
		<description><![CDATA[Probably the best feature introduced by C++11 is std::unique_ptr. It will automagically make sure your dynamically allocated objects are deleted when you don&#8217;t use them anymore. In previous versions of C++, you needed to rely exclusively on documentation and conventions to ensure dynamically allocated memory was handled properly. With C++11, you can ask the compiler [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Probably the best feature introduced by C++11 is std::unique_ptr. It will automagically make sure your dynamically allocated objects are deleted when you don&#8217;t use them anymore.</p>
<p>In previous versions of C++, you needed to rely exclusively on documentation and conventions to ensure dynamically allocated memory was handled properly. With C++11, you can ask the compiler to help you out and enforce ownership semantics. Take the following code for example, you need to ensure you call delete when you are done with the object created by function factory(). The compiler will not complain if you forget and you end up with a memory leak.</p><pre class="crayon-plain-tag">struct A { int field; };
A* factory() { return new A(); }
void useFactory() {
    A* ptr = factory();
    std::cout &lt;&lt; ptr-&gt;field &lt;&lt; std::endl;
    // you must remember to call delete
    delete ptr;
}</pre><p></p>
<h3>What can std::unique_ptr do for you ?</h3>
<p>With std::unique_ptr, you cannot casually forget to delete the pointer. std::unique_ptr owns the allocated object unless this ownership is explicitly transferred to another entity (eg. another unique_ptr, a std::shared_ptr). When a std::unique_ptr goes out of scope, it will delete any object it owns.</p><pre class="crayon-plain-tag">struct A { int field; };
std::unique_ptr&lt;A&gt; factory() { return std::unique_ptr&lt;A&gt;(new A()); }
void useFactory() {
    std::unique_ptr&lt;A&gt; ptr = factory();
    std::cout &lt;&lt; ptr-&gt;field &lt;&lt; std::endl;
    // ptr will delete allocated A automatically 
}</pre><p>The most explicit way of transferring ownership is via function std::move(). Using the same above example, we can see how it works.</p><pre class="crayon-plain-tag">struct A { int field; };
std::unique_ptr&lt;A&gt; factory() { return std::unique_ptr&lt;A&gt;(new A()); }
void useFactory() {
    std::unique_ptr&lt;A&gt; ptr1 = factory(); 
    std::unique_ptr&lt;A&gt; ptr2 = std::move(ptr1);
    // now ptr2 owns the instance of A 
    // and ptr1 is holding a null pointer
}</pre><p>You cannot directly assign an instance of std::unique_ptr to another. This rule ensures that no two unique_ptr can claim ownership of the same dynamically allocated object. It prevents deleting an object multiple times.<br />
This is the magic of std::unique_ptr, you always know who owns the pointed value. By consistently using unique_ptr, you know at a glance when you own a heap object and when you yield ownership to another. Moreover, this rule is enforced by the compiler &#8212; the less you need to worry about, the better.</p>
<h3>How do you use std::unique_ptr ?</h3>
<p>std::unique_ptr helps you express your intent with regards to ownership transfer. Transfer of ownership occurs in the following general cases :</p>
<ul>
<li>Returning a dynamically allocated object from a function</li>
<li>Passing a such an object to a function</li>
</ul>
<h4>Returning a std::unique_ptr</h4>
<p>Returning a heap-allocated object from a function requires that the caller delete it when it is done with.</p>
<p>By returning a unique_ptr, you ensure the caller takes ownership of the pointed object. In the example below, the signature of createVector() ensures the caller takes the responsibility for releasing the created vector. Normal flow of execution guarantees memory will be released whenever the returned unique_ptr is destroyed.</p><pre class="crayon-plain-tag">typedef std::vector&lt;int&gt; Vector;
std::unique_ptr&lt;Vector&gt; createVector() { 
    return std::unique_ptr&lt;Vector&gt;(new Vector()); 
}

void caller() {
    std::unique_ptr&lt;Vector&gt; ptr = factory();
    // use the returned vector

    // nothing needs to be done here
    // the Vector will be deleted
}</pre><p></p>
<h4>Passing a std::unique_ptr to a function</h4>
<p>A function taking a unique_ptr takes definitive ownership of the pointed object. The caller will not even have the ability to access the pointed object after the function call.<br />
Notice the call to function std::move(), it is required and helps you actually see that ownership is transferred to the function.</p><pre class="crayon-plain-tag">void takePtr(std::unique_ptr&lt;int&gt; ptr) { /* ... */ }

void caller() {
    std::unique_ptr&lt;int&gt; ptr = new int(5);
    // explicitly transfer ownership with std::move
    takePtr(std::move(ptr));
    // now ptr holds a null pointer. takePtr() has effectively taken ownership.

    // a temporary (rvalue reference) is implicitly moved 
    takePtr(std::unique_ptr&lt;int&gt;(new int(6)));
}</pre><p></p>
<h4>Passing a const reference to a unique_ptr</h4>
<p>The called function can use the pointed object but may not interfere with its lifetime. The caller function keeps ownership of the pointed object.</p>
<p>In my opinion, there is no real benefit to using a const reference to a unique_ptr from simply using a raw pointer to the object. On the contrary, it introduces a constraint on the caller that it must manage the pointed object through a unique_ptr. But what if your caller context requires you have shared ownership (std::shared_ptr)? Since we mostly care about whether ownership is transfered (not how ownership is cared for), a raw pointer is perfect.</p><pre class="crayon-plain-tag">void useUniquePtr(const std::unique_ptr&lt;int&gt; &amp; ptr) { /* ... */ }
void useRawPtr(int * ptr) { /* ... */ }

void caller() {
    std::unique_ptr&lt;int&gt; ptr = new int(5);
    // useUniquePtr() can use but does not own the pointed object
    useUniquePtr(ptr);
    // same semantics
    useRawPtr(ptr.get());
}</pre><p></p>
<h4>Passing a non-const reference to a unique_ptr</h4>
<p>This is, in my opinion, the most complex situation. The called function may or may not take ownership of the passed pointer. &#8220;may or may not&#8221; is really part of the functions contract. If the called function uses std::move() on the passed unique_ptr, it effectively takes onwnership and once it gives control back to the caller, the caller does not own the pointer anymore, it doesn&#8217;t even know the value of the pointer anymore. On the other hand, if the callee merely uses the provided pointer without moving it, the caller still owns the pointed object.</p><pre class="crayon-plain-tag">void useUniquePtr(std::unique_ptr&lt;int&gt; &amp; ptr) { /* ... */ }

void caller() {
    std::unique_ptr&lt;int&gt; ptr = new int(5);
    useUniquePtr(ptr);
    // if useUniquePtr() used std::move() on ptr, it took ownership 
    // of the pointed int, so ptr is now holding a nullptr
    // otherwise it still owns the int and will delete it when the 
    // current scope ends
    if (ptr.get() == nullptr)
        std::cout &lt;&lt; "ptr has been moved away" &lt;&lt; std::endl;
    else
        std::cout &lt;&lt; "ptr is still ours" &lt;&lt; std::endl;
}</pre><p></p>
<h3>Conclusion</h3>
<p>C++11 provides us with a great tool for managing the lifetime of dynamically allocated object. When used consistently, std::unique_ptr lets your code really express when ownership of a dynamic object is transferred and in which direction directly. The compiler will even see that the semantics are respected <strong>at compile-time</strong>.</p>
<p>However, they are of no use when you don&#8217;t intend to express ownership semantics. Pass raw pointers whenever you can but make sure that you use std::unique_ptr or another similar smart pointer when you mean to transfer ownership.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/04/std-unique_ptr-semantic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>boost::serialization coupling issue</title>
		<link>https://timoch.com/blog/2013/04/boost-serialization-coupling-issue/</link>
		<comments>https://timoch.com/blog/2013/04/boost-serialization-coupling-issue/#comments</comments>
		<pubDate>Fri, 12 Apr 2013 15:00:45 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://www.timoch.com/blog/?p=159</guid>
		<description><![CDATA[I was evaluating boost::serialization today. Based on the design goals mentioned in the library&#8217;s introduction, I felt like boost::serialization would suit my needs. An interesting point is this : 8. Orthogonal specification of class serialization and archive format. That is, any file format should be able to store serialization of any arbitrary set of C++ [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I was evaluating boost::serialization today. Based on the design goals mentioned in the library&#8217;s <a href="http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html" target="_blank">introduction</a>, I felt like <span class="codecolorer me1">boost::serialization</span> would suit my needs.</p>
<p>An interesting point is this :</p>
<p><em>8. Orthogonal specification of class serialization and archive format. That is, any file format should be able to store serialization of any arbitrary set of C++ data structures without having to alter the serialization of any class.</em></p>
<p>At first, I interpreted it as an intent to decouple the serialization code (that knows about the object&#8217;s internals) and the archive format.<br />
Consider this:</p><pre class="crayon-plain-tag">struct ClassA {
    ...
    template &lt;typename Archive&gt;
    void serialize(Archive ar, unsigned int version) {
        ar &amp; member1_;
        ar &amp; member2_;
        ...
        ar &amp; membern_;
    }
    ...
}</pre><p>All is fine, ClassA does not know the specifics of type Archive. Any object implementing the Archive concept will do just fine.</p>
<p>Yet, I have a problem with this. Inline code in headers has a tendency to irritate me. It hides the structure of the classes you implement so I often use the PImpl idiom.<br />
I want to (or must in the case of PImpl) move the implementation to ClassA.cpp.<br />
But &#8230; can I ?</p>
<p>serialize() is a template method. Can I forward declare a template method ? Well, yes.</p>
<p>In ClassA.hpp :</p><pre class="crayon-plain-tag">struct ClassA {
    ...
    template &lt;typename Archive&gt;
    void serialize(Archive &amp; ar, unsigned int version);
    ...
}</pre><p>In ClassA.cpp:</p><pre class="crayon-plain-tag">template &lt;typename Archive&gt;
void serialize(Archive &amp; ar, unsigned int version) {
    ar &amp; member1_;
    ar &amp; member2_;
    ...
    ar &amp; membern_;
}</pre><p>In main.cpp, try to serialize an instance of ClassA :</p><pre class="crayon-plain-tag">#include "ClassA.hpp"
#include &lt;boost/archive/text_oarchive.hpp&gt;
#include &lt;boost/archive/text_iarchive.hpp&gt;
#include &lt;fstream&gt;

int main(int argc, char ** argv) {
  ClassA a;

  std::ofstream ofs("output.txt");
  boost::archive::text_oarchive oa(ofs);
  oa &lt;&lt; a;

  return 0;
}</pre><p>Compile and link :</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">g++ -c main.cpp -o main.o<br />
g++ -c ClassA.cpp -o ClassA.o<br />
g++ main.o -lboost_serialization -o program<br />
main.o: In function &lt;code&gt;void boost::serialization::access::serialize&amp;lt;boost::archive::text_oarchive, classa=&quot;&quot;&amp;gt;(boost::archive::text_oarchive&amp;amp;, ClassA&amp;amp;, unsigned int)':<br />
main.cpp:(.text._ZN5boost13serialization6access9serializeINS_7archive13text_oarchiveE6ClassAEEvRT_RT0_j[_ZN5boost13serialization6access9serializeINS_7archive13text_oarchiveE6ClassAEEvRT_RT0_j]+0x25): undefined reference to</div></td></tr></tbody></table></div>
<p>void ClassA::serialize&lt;boost::archive::text_oarchive&gt;(boost::archive::text_oarchive&amp;, unsigned int)&#8217;<br />
collect2: error: ld returned 1 exit status<br />
make: *** [program] Error 1</code><br />
Does this compile ? Yes. Does this link ? &#8230; No!</p>
<p>What&#8217;s the compiler trying to tell me ? Undefined reference to ClassA::serialize(&#8230;). But I defined it, no ?<br />
Well, yes and no. You wrote the code but it is a template function. So it needs to be instantiated at compile-time. When main.cpp is compiled, it sees the forward-declaration of ClassA::serialize() and assumes that the linker will find the implementation of void ClassA::serialize&lt;boost::archive::text_oarchive&gt;(boost::archive::text_oarchive&amp;, unsigned int) somewhere.<br />
But it does not because, ClassA.cpp while implementing the template function does not instantiate it. ClassA::serialize() is parsed but never compiled into actual machine code.</p>
<p>You can check for yourself. Look at the file size :</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">-rw-rw-r-- 1 timoch timoch 940 Apr 12 12:59 ClassA.o<br />
-rw-rw-r-- 1 timoch timoch 143088 Apr 12 12:59 main.o</div></td></tr></tbody></table></div>
<p>940 bytes ? That&#8217;s not a lot.</p>
<p>You can force the instantiation of ClassA::serialize() in ClassA.cpp. Add the following at the end:</p><pre class="crayon-plain-tag">#include
template void ClassA::serialize(boost::archive::text_oarchive &amp;, unsigned int);</pre><p>It works, but is it good ? Not to me.</p>
<p>I need to include a header defining the implementation of the specific format I serialize to. I also need to include text_iarchive.hpp for the loading process to work. Tomorrow, when my object needs to be serialized to another format as part as another use case, I will need to modify its implementation file to include the specifics of that other format. I will need to do this for each and every class to be serialized &#8230; not something I would enjoy.</p>
<p>&nbsp;</p>
<h4>Conclusion</h4>
<p>&nbsp;</p>
<p>Templates provide a huge flexibility. Here it is used to enable the &amp; operator to serve as both an extract and inject operator. However, it is at the expense of forcing the client application to put the saving/loading implementation in the same compile unit as the definitions of your target format. It completely voids the efforts put toward decoupling the serialized objects and the format they serialize to.</p>
<p>There are ways to achieve the same flexibility of &#8216;same operator&#8217; saving and loading while preserving decoupling with the serialization format. I will come back to that in a later post.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/04/boost-serialization-coupling-issue/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
