<?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>Arrange Act Assert &#187; MVVM</title> <atom:link href="http://www.arrangeactassert.com/category/mvvm/feed/" rel="self" type="application/rss+xml" /><link>http://www.arrangeactassert.com</link> <description>Jag Reehal on Agile Development, ASP.NET MVC and all manner of good stuff</description> <lastBuildDate>Thu, 24 Nov 2011 00:01:20 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /> <item><title>Using IDataErrorInfo for validation in MVVM with Silverlight and WPF</title><link>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/#comments</comments> <pubDate>Tue, 06 Jul 2010 23:01:57 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=968</guid> <description><![CDATA[In this post we will be looking at how validation can be done by implementing the IDataErrorInfo interface for a calculator we have been building as part of the Silverlight refactoring series. The IDataErrorInfo interface gives you the ability to do validation without throwing exceptions. The full solution for this post can be downloaded here. [...]]]></description> <content:encoded><![CDATA[<p>In this post we will be looking at how validation can be done by implementing the <a
href="http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx">IDataErrorInfo</a> interface for a calculator we have been building as part of the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a>.</p><p>The IDataErrorInfo interface gives you the ability to do validation without throwing exceptions.</p><p>The full solution for this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorValidationIDataErrorInfo.zip">here</a>.</p><h3 class="subheading">Pre IDataErrorInfo</h3><p>As you can see in the code below we are throwing exceptions in the setters for the two values we want to add together.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string  FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}
public string  SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        try
        {
            int.Parse(_secondValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre><h3 class="subheading">Implementing the IDataErrorInfo interface</h3><p>The IDataErrorInfo interface consists of two properties.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
string this[string columnName] {get;}
string Error {get;}
</pre><p>For the Error property we can just return null because we don’t want to return a single error message for the entire object.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string Error
{
    get { return null; }
}
</pre><p>For the property which returns an error for a text box we <strong>could</strong> do the validation like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string this[string columnName]
{
    get
    {
        string error = null;
        switch (columnName)
        {
            case &quot;FirstValue&quot;:
                try
                {
                    int.Parse(_firstValue);
                }
                catch (Exception)
                {
                    error = &quot;That is not a number&quot;;
                }
                break;
            case &quot;SecondValue&quot;:
                try
                {
                    int.Parse(_firstValue);
                }
                catch (Exception)
                {
                    error = &quot;That is not a number&quot;;
                }
                break;
        }
        return error;
    }
}
</pre><p>But as we saw in a previous post <a
href="http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/">about using ValidatesOnExceptions to do validation</a> it’s much easier to write unit tests when there are separation of concerns and the ViewModel is not responsible for validation.</p><p>So this means we need to create a class for storing the validation error for each textbox</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ValidationBase
{
    public readonly Dictionary&lt;string, string&gt; Errors;

    public ValidationBase()
    {
        Errors = new Dictionary&lt;string, string&gt;();
    }

    public void AddError(string propertyName, string message)
    {
        if (!Errors.ContainsKey(propertyName))
        {
            Errors[propertyName] = message;
        }
    }

    public void RemoveErrors(string propertyName)
    {
        Errors.Remove(propertyName);
    }

    public string GetErrorMessageForProperty(string propertyName)
    {
        string message;
        Errors.TryGetValue(propertyName, out message);
        return message;
    }

    public bool HasErrors()
    {
        return Errors.Count != 0;
    }
}
</pre><p>which is inherited by a CalculatorValidator class that returns a boolean value if the property value is not valid</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ValidationBase, ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public bool IsPropertyValid(string propertyName, string value)
    {
        RemoveErrors(propertyName);
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                AddError(propertyName, calculatorValidationRule.ErrorMessage);
                return false;
            }
        }
        return true;
    }
}
</pre><p>If you’re new to the series the validation rules for calculator are being imported by MEF.  Read how and why we are doing this in the &#8216;<a
href="http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/">Applying the Open Closed Principle in Silverlight and WPF using MEF</a>&#8216; post.</p><p>Now we can inject/import the CalculatorValidator into the ViewModel and use it to validate the users input.</p><p>As we only want the user to be able to click the calculate button when the form is valid we call we the CheckIfCalculteButtonShouldBeEnabled method when a text box value has changed.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export]
public class CalculatorViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private string _firstValue;
    private string _secondValue;
    private string _result;

    private readonly ICalculator _calculator;
    private readonly RelayCommand _calculateCommand;

    public event PropertyChangedEventHandler PropertyChanged;
    private readonly ICalculatorValidator _calculatorValidator;

    [ImportingConstructor]
    public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
    {
        _calculator = calculator;
        _calculatorValidator = calculatorValidator;
        _calculateCommand = new RelayCommand(Calculate) { IsEnabled = true };

        _firstValue = &quot;0&quot;;
        _secondValue = &quot;0&quot;;
    }
    public void Calculate()
    {
        Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
    }

    public string FirstValue
    {
        get { return _firstValue; }
        set
        {
            _firstValue = value;
            OnPropertyChanged(&quot;FirstValue&quot;);
        }
    }

    public string SecondValue
    {
        get { return _secondValue; }
        set
        {
            _secondValue = value;
            OnPropertyChanged(&quot;SecondValue&quot;);
        }
    }

    public void CheckIfCalculteButtonShouldBeEnabled()
    {
        _calculateCommand.IsEnabled = _calculatorValidator.HasErrors() == false;
    }

    public string Result
    {
        get { return _result; }
        private set
        {
            _result = value;
            OnPropertyChanged(&quot;Result&quot;);
        }
    }

    public RelayCommand CalculateCommand
    {
        get { return _calculateCommand; }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }

    public string this[string columnName]
    {
        get
        {
            string error = null;
            switch (columnName)
            {
                case &quot;FirstValue&quot;:
                    error = ValidateNumber(&quot;FirstValue&quot;, _firstValue);
                    break;
                case &quot;SecondValue&quot;:
                    error = ValidateNumber(&quot;SecondValue&quot;, _secondValue);
                    break;
            }

            CheckIfCalculteButtonShouldBeEnabled();
            return error;
        }
    }

    public string ValidateNumber(string propertyName, string value)
    {
        if (!_calculatorValidator.IsPropertyValid(propertyName, value))
        {
            return _calculatorValidator.GetErrorMessageForProperty(propertyName);
        }
        return null;
    }

    public string Error
    {
        get { return null; }
    }
}
</pre><p>The code below shows how we can unit test the ViewModel which implements the IDataErrorInfo interface.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_CalculatorViewModel
{
    private Mock&lt;ICalculator&gt; _calculator;
    private Mock&lt;ICalculatorValidator&gt; _calculatorValidator;
    private CalculatorViewModel _calculatorViewModel;

    [SetUp]
    public void SetUp()
    {
        _calculator = new Mock&lt;ICalculator&gt;();
        _calculatorValidator = new Mock&lt;ICalculatorValidator&gt;();
        _calculatorViewModel = new CalculatorViewModel(_calculator.Object, _calculatorValidator.Object);
    }

    [Test]
    public void Initial_value_of_first_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.FirstValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_second_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.SecondValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_calculate_button_is_enabled()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.CalculateCommand.IsEnabled;

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void ValidateNumber_returns_null_if_value_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;,&quot;X&quot;)).Returns(true);

        // Act
        var result = _calculatorViewModel.ValidateNumber(&quot;X&quot;,&quot;X&quot;);

        // Assert
        result.ShouldBeNull();
    }

    [Test]
    public void ValidateNumber_returns_error_message_if_value_is_not_valid()
    {
        // Arrange
        const string errorMessage = &quot;ErrorMessageText&quot;;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;, &quot;X&quot;)).Returns(false);
        _calculatorValidator.Setup(c =&gt; c.GetErrorMessageForProperty(&quot;X&quot;)).Returns(errorMessage);

        // Act
        var result = _calculatorViewModel.ValidateNumber(&quot;X&quot;, &quot;X&quot;);

        // Assert
        result.ShouldEqual(errorMessage);
    }

    [Test]
    public void Calculate_command_should_not_be_enabled_if_ViewModel_is_not_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.HasErrors()).Returns(true);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeFalse();
    }

    [Test]
    public void Calculate_command_should_be_enabled_if_ViewModel_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.HasErrors()).Returns(false);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeTrue();
    }
}
</pre><p>The final change we need to make is to change the text box binding to ValidatesOnDataErrors=True in the XAML file.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;TextBox Text=&quot;{Binding FirstValue, Mode=TwoWay, ValidatesOnDataErrors=True}&quot;/&gt;
&lt;TextBox Text=&quot;{Binding SecondValue, Mode=TwoWay, ValidatesOnDataErrors=True}&quot;/&gt;
</pre><h3 class="subheading">So what have we achieved?</h3><p>In this post we have refactored the code to use the IDataErrorInfo interface and are no longer throwing exceptions to do validation.</p><p>Whether you choose to use it or not depends if you want multiple errors for a single property to be combined into a single error message.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Enabling buttons in Silverlight and WPF using MVVM and ValidatesOnExceptions</title><link>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/</link> <comments>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/#comments</comments> <pubDate>Mon, 05 Jul 2010 23:10:40 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[Moq]]></category> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=957</guid> <description><![CDATA[In a previous post we saw how exceptions could be used for Silverlight validation. While could validate the users input using exceptions, it wasn’t possible to disable the calculate button if the input values were invalid (because they were either blank or non-numeric). The code used in this post can be downloaded here. So how [...]]]></description> <content:encoded><![CDATA[<p>In a <a
href=" Validation in Silverlight and WPF using ValidatesOnExceptions">previous post we saw how exceptions</a> could be used for Silverlight validation.</p><p>While could validate the users input using exceptions, it wasn’t possible to disable the calculate button if the input values were invalid (because they were either blank or non-numeric).</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorValidationUsingExceptions.zip">here</a>.</p><h3 class="subheading">So how are we going to solve the problem?</h3><p>Throughout the Silverlight refactoring series I’ve tried to illustrate how important <a
href="http://en.wikipedia.org/wiki/Solid_(object-oriented_design)">SOLID design principles</a> are for having testable applications.</p><p>So if we think about the ViewModel, we need to ask ourselves if it’s the right place or should be responsible for validation?</p><p>In this case I would say no.</p><h3 class="subheading">When should the button be enabled?</h3><blockquote><p>For a calculate button to be enabled, both text boxes must contain numeric values</p></blockquote><p>This means we have to know if both text boxes are valid <strong>at the same time</strong>.  Taking a step back here, let&#8217;s think about the bigger picture.</p><p>What if there are three or four text boxes?</p><p>What we really after is a class that will be responsible for knowing if any text boxes are invalid.</p><p>This can be done by using a validation base class.</p><p>In the code below notice how the ValidationBase class <strong>doesn&#8217;t</strong> know anything about enabling or disabling the calculate button.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class ValidationBase
{
    public readonly Dictionary&lt;string, string&gt; Errors;

    public ValidationBase()
    {
        Errors = new Dictionary&lt;string, string&gt;();
    }

    public void AddError(string propertyName, string message)
    {
        if (!Errors.ContainsKey(propertyName))
        {
            Errors[propertyName] = message;
        }
    }

    public void RemoveErrors(string propertyName)
    {
        Errors.Remove(propertyName);
    }

    public bool IsPropertyValid(string propertyName)
    {
        return !Errors.ContainsKey(propertyName);
    }

    public string GetErrorMessageForProperty(string propertyName)
    {
        string message;
        Errors.TryGetValue(propertyName, out message);
        return message;
    }

    public bool IsValid()
    {
        return Errors.Count == 0;
    }
}
</pre><p>The code below shows the unit tests for the ValidationBase class.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_ValidatiorBase
{
    private ValidationBase _validationBase;

    [SetUp]
    public void SetUp()
    {
        _validationBase = new ValidationBase();
    }

    [Test]
    public void IsValid_should_return_false_when_errors_exist()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.IsValid();

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void IsValid_should_return_true_when_no_errors_exist()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.IsValid();

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void IsPropertyValid_should_return_false_if_error_exists()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.IsPropertyValid(&quot;propertyName&quot;);

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void IsPropertyValid_should_return_true_if_error_does_not_exist()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.IsPropertyValid(&quot;X&quot;);

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    public void Should_be_able_to_return_message_for_error()
    {
        // Arrange
        _validationBase.AddError(&quot;propertyName&quot;, &quot;message&quot;);

        // Act
        var result = _validationBase.GetErrorMessageForProperty(&quot;propertyName&quot;);

        // Assert
        result.ShouldEqual(&quot;message&quot;);
    }

    [Test]
    public void Should_return_null_if_message_does_not_exist_for_error()
    {
        // Arrange
        // collection will be empty at this point

        // Act
        var result = _validationBase.GetErrorMessageForProperty(&quot;propertyName&quot;);

        // Assert
        result.ShouldBeNull();
    }
}
</pre><h3 class="subheading">Validating the users input</h3><p>There are three outcomes when validating what the user has entered:</p><ul><li>The value is blank</li><li>The value is not a number</li><li>The value is a number</li></ul><p>All the ViewModel wants to know is if the users input is valid, choosing the appropriate error message isn&#8217;t its concern.  This means we need a class that will be responsible for validation and returning the relevant message.</p><p>For this we will use the CalculatorValidator class we created in the &#8216;<a
href="http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/">Applying the Open Closed Principle in Silverlight and WPF using MEF</a>&#8216; post.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ValidationBase, ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public void ValidateNumber(string propertyName, string value)
    {
        RemoveErrors(propertyName);

        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                AddError(propertyName, calculatorValidationRule.ErrorMessage);
                return;
            }
        }
    }
}
</pre><p>This is useful because if we decide to change how to validate the user&#8217;s input neither the CalculatorValidator or the ViewModel classes need to be modified.</p><h3 class="subheading">Hooking it all up</h3><p>To use the CalculatorValidator in the ViewModel it has to be injected/imported.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[ImportingConstructor]
public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
{
    _calculator = calculator;
    _calculatorValidator = calculatorValidator;
    ...
}
</pre><p>Each time a user enters a value in the text boxes the CheckIfNumberIsValid method checks if the calculate button should be enabled and throws an exception if the users value is not valid.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        CheckIfNumberIsValid(&quot;FirstValue&quot;, out _firstValue, value);
    }
}

public string SecondValue
{
    get { return _secondValue; }
    set
    {
        CheckIfNumberIsValid(&quot;SecondValue&quot;, out _secondValue, value);
    }
}

public void CheckIfNumberIsValid(string propertyName, out string propertyValue, string value)
{
    _calculatorValidator.ValidateNumber(propertyName, value);

    CheckIfCalculteButtonShouldBeEnabled();

    if (_calculatorValidator.IsPropertyValid(propertyName))
    {
        propertyValue = value;
        OnPropertyChanged(propertyName);
    }
    else
    {
        throw new Exception(_calculatorValidator.GetErrorMessageForProperty(propertyName));
    }
}

public void CheckIfCalculteButtonShouldBeEnabled()
{
    _calculateCommand.IsEnabled = _calculatorValidator.IsValid();
}
</pre><h3 class="subheading">Unit testing the ViewModel in MVVM</h3><p>By using <a
href="http://code.google.com/p/moq/">Moq</a> we can unit test the ViewModel to ensure the button is enabled when there are no validation errors and not enabled when there are validation errors.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_using_the_CalculatorViewModel
{
    private Mock&lt;ICalculator&gt; _calculator;
    private Mock&lt;ICalculatorValidator&gt; _calculatorValidator;
    private CalculatorViewModel _calculatorViewModel;

    [SetUp]
    public void SetUp()
    {
        _calculator = new Mock&lt;ICalculator&gt;();
        _calculatorValidator = new Mock&lt;ICalculatorValidator&gt;();
        _calculatorViewModel = new CalculatorViewModel(_calculator.Object, _calculatorValidator.Object);
    }

    [Test]
    public void Initial_value_of_first_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.FirstValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_second_number_is_0()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.SecondValue;

        // Assert
        result.ShouldEqual(&quot;0&quot;);
    }

    [Test]
    public void Initial_value_of_calculate_button_is_enabled()
    {
        // Arrange
        // checking initial value

        // Act
        var result = _calculatorViewModel.CalculateCommand.IsEnabled;

        // Assert
        result.ShouldBeTrue();
    }

    [Test]
    [ExpectedException(typeof(Exception))]
    public void Will_throw_exception_if_input_is_invalid()
    {
        // Arrange
        string propertyValue;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;)).Throws(new Exception());

        // Act
        _calculatorViewModel.CheckIfNumberIsValid(&quot;X&quot;, out propertyValue, &quot;X&quot;);

        // Assert
        // should throw exception
    }

    [Test]
    public void Will_set_property_value_if_input_is_valid()
    {
        // Arrange
        string propertyValue;
        _calculatorValidator.Setup(c =&gt; c.IsPropertyValid(&quot;X&quot;)).Returns(true);

        // Act
        _calculatorViewModel.CheckIfNumberIsValid(&quot;X&quot;, out propertyValue, &quot;11&quot;);

        // Assert
        propertyValue.ShouldEqual(&quot;11&quot;);

    }

    [Test]
    public void Calculate_command_should_not_be_enabled_if_ViewModel_is_not_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsValid()).Returns(false);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeFalse();
    }

    [Test]
    public void Calculate_command_should_be_enabled_if_ViewModel_is_valid()
    {
        // Arrange
        _calculatorValidator.Setup(c =&gt; c.IsValid()).Returns(true);

        // Act
        _calculatorViewModel.CheckIfCalculteButtonShouldBeEnabled();

        // Assert
        _calculatorViewModel.CalculateCommand.IsEnabled.ShouldBeTrue();
    }
}
</pre><h3 class="subheading">So what have we achieved?</h3><p>By using a validation base class we are able to store validation errors and can determine if the controls on the page are all valid.</p><p>The ViewModel can take advantage of this functionality and use it to enable and disable the calculate button.</p><p>Using exceptions for validation isn&#8217;t every developers cup of tea, so be sure to keep an eye on the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a> to see other approaches we can take to do validation in Silverlight 4.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How to Apply the Single Responsibility Principle to View Models in Silverlight and WPF</title><link>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/</link> <comments>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/#comments</comments> <pubDate>Mon, 14 Jun 2010 21:46:41 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[Unit tests]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=828</guid> <description><![CDATA[When you&#8217;re using the MVVM pattern with WPF or Silverlight it&#8217;s very easy to a have ViewModels that do too much. In this part of the Silverlight Refactoring series we will convert a ViewModel with multiple responsibilities so that it adheres to the Single Responsibility Principle (SRP). The code used in this post can be [...]]]></description> <content:encoded><![CDATA[<p>When you&#8217;re using the MVVM pattern with WPF or Silverlight it&#8217;s very easy to a have ViewModels that do too much.</p><p>In this part of the Silverlight Refactoring series we will convert a ViewModel with multiple responsibilities so that it adheres to the <a
href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle (SRP)</a>.</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorSingleResponsibilityPrinciple.zip">here</a>.</p><h3 class="subheading">Why should you care?</h3><p>Currently the ViewModel looks like this</p><pre class="brush: csharp; gutter: false; highlight: [22,23,24,25]; title: ; toolbar: true; notranslate">
using System;
using System.ComponentModel;
using System.Windows.Input;

namespace SilverlightCalculator
{
    public class CalculatorViewModel : INotifyPropertyChanged
    {
        private string _firstValue;
        private string _secondValue;
        private string _result;

        private readonly ICommand _calculateCommand;       

        public event PropertyChangedEventHandler PropertyChanged;

        public CalculatorViewModel()
        {
            _calculateCommand = new RelayCommand(Calculate){IsEnabled = true};
        }

        public void Calculate()
        {
            Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();
        }

        public string FirstValue
        {
            get { return _firstValue; }
            set
            {
                _firstValue = value;
                OnPropertyChanged(&quot;FirstValue&quot;);
            }
        }

        public string SecondValue
        {
            get { return _secondValue; }
            set
            {
                _secondValue = value;
                OnPropertyChanged(&quot;SecondValue&quot;);
            }
        }

        public string Result
        {
            get { return _result; }
            private set
            {
                _result = value;
                OnPropertyChanged(&quot;Result&quot;);
            }
        }

        public ICommand CalculateCommand
        {
            get { return _calculateCommand; }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
</pre><p>As you can see the logic to add two numbers is in the Calculate method of the ViewModel.</p><p>Therefore <strong>the ViewModel is responsible for calculating two numbers</strong>.</p><p>A ViewModel without separation of concerns is difficult to test, maintain and contains code you can&#8217;t reuse.</p><p>Although we&#8217;re only adding two numbers here, brushing the issue under the carpet will have consequences later down the line.</p><p>For example in addition to adding numbers what if another developer was given the task of storing the result in a database.</p><p>If the ViewModel was as it is now, with no <a
href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>, there is a chance they would put the code to store the value in the calculate method like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    // Calculate result
    Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();

    // Store value in database
    DatabaseConnection connection = new DatabaseConnection();
    DatabaseCommand command = new DatabaseCommand(&quot;TSQL TO STORE RESULT&quot;, connection);
    command.ExecuteNonQuery();
}
</pre><p>Now the ViewModel would be responsible for two things.  Next it would be three and this would continue until someone decides to separate the concerns or it gets to a stage where it&#8217;s impossible to work with let alone read.</p><h3 class="subheading">Refactoring the ViewModel to follow the single responsibility principle</h3><p>Let’s start by creating a class for calculating numbers.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class Calculator
{
    public int Add(int firstValue, int secondValue)
    {
        return firstValue + secondValue;
    }
}
</pre><p>Notice how the parameters passed to the method are integers, the calculator doesn&#8217;t accept string values.</p><p>What we are saying here is while it&#8217;s acceptable for the ViewModel to use strings for storing numbers the domain layer (or business logic if you prefer) does not.</p><p>In other words the add method does nothing more than add two numbers together.  Validation should be handled elsewhere.</p><p>This makes the unit tests for the calculator very easy to write</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
[TestFixture]
public class When_calculating_numbers
{
    [Test]
    public void Should_be_able_to_add_two_numbers_together()
    {
        // Arrange
        Calculator calculator = new Calculator(); 

        // Act
        var result = calculator.Add(5, 5);

        //Assert
        Assert.That(result, Is.EqualTo(10));
    }
}
</pre><p>The code below shows how the ViewModel <strong>could</strong> create an instance of the Calculator class and call the Add Method.  Notice how I say could and not should.  We&#8217;ll see why later in the series.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public void Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre><h3 class="subheading">So what have we achieved?</h3><p>As <a
href="http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule">good boy scouts</a> we have ‘left the ViewModel cleaner than we found it’.</p><p>By following the single responsibility principle we have created a ViewModel which is a better canvas for other developers to work with.</p><p>If you have arrived here from a search engine, this post is part of series about refactoring Silverlight applications.  So if you’re thinking why is the calculator class tightly coupled to the ViewModel?  Find out how this can be resolved by <a
href="http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/"> applying SOLID design principles using MEF in Silverlight and WPF</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>How to Implement MVVM, INotifyChanged and ICommand in a Silverlight Application</title><link>http://www.arrangeactassert.com/how-to-implement-mvvm-inotifychanged-and-icommand-in-a-silverlight-application/</link> <comments>http://www.arrangeactassert.com/how-to-implement-mvvm-inotifychanged-and-icommand-in-a-silverlight-application/#comments</comments> <pubDate>Wed, 09 Jun 2010 23:36:59 +0000</pubDate> <dc:creator>Jag Reehal</dc:creator> <category><![CDATA[MVVM]]></category> <category><![CDATA[Silverlight]]></category> <category><![CDATA[WPF]]></category><guid
isPermaLink="false">http://www.arrangeactassert.com/?p=765</guid> <description><![CDATA[In this post we will be converting an application that adds two numbers together to use the MVVM (Model-View-ViewModel) pattern as part of the How To Refactor And Build Better Microsoft Silverlight Applications series. The code used in this post can be downloaded here. Why MVVM? While I could write about what MVVM is, I [...]]]></description> <content:encoded><![CDATA[<p>In this post we will be converting an application that adds two numbers together to use the MVVM (Model-View-ViewModel) pattern as part of the <a
href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">How To Refactor And Build Better Microsoft Silverlight Applications</a> series.</p><p>The code used in this post can be downloaded <a
href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorUsingMVVM.zip">here</a>.</p><h3 class="subheading">Why MVVM?</h3><p>While I could write about what MVVM is, I would just be repeating what Josh Smith and Jesse Liberty have already covered in the <a
href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"> ‘WPF Apps With The Model-View-ViewModel Design Pattern’</a> MSDN article and the ‘<a
href="http://jesseliberty.com/2010/05/08/mvvm-its-not-kool-aid-3/">MVVM – It’s Not Kool-Aid*</a>’ blog post.</p><p>I like the MVVM pattern because it helps me to write code and develop solutions that:</p><ul><li>keeps my code behind files as code free as possible</li><li>can be unit tested</li><li>are simpler to read and understand</li><li>are less headache to maintain</li><li>adhere to good programming principles</li><li>make validation easier to implement</li></ul><p>It’s important to remember MVVM isn’t the solution to every problem.  If you don’t need to use it, don’t, <strong>do whatever is right for your application</strong>.</p><h3 class="subheading">The application pre MVVM</h3><p>In the current application the XAML looks like this</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot; Height=&quot;100&quot; Width=&quot;350&quot;&gt;
        &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition/&gt;
            &lt;ColumnDefinition/&gt;
            &lt;ColumnDefinition/&gt;
            &lt;ColumnDefinition/&gt;
            &lt;ColumnDefinition/&gt;
        &lt;/Grid.ColumnDefinitions&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition/&gt;
            &lt;RowDefinition/&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;TextBox Grid.Column=&quot;0&quot; Text=&quot;0&quot; Height=&quot;25&quot; TextAlignment=&quot;Right&quot; x:Name=&quot;tbFirstValue&quot;/&gt;
        &lt;TextBlock Grid.Column=&quot;1&quot; Text=&quot;+&quot; Height=&quot;25&quot; TextAlignment=&quot;Center&quot;/&gt;
        &lt;TextBox Grid.Column=&quot;2&quot; Text=&quot;0&quot; Height=&quot;25&quot; TextAlignment=&quot;Right&quot; x:Name=&quot;tbSecondValue&quot;/&gt;
        &lt;TextBlock Grid.Column=&quot;3&quot; Text=&quot;=&quot; Height=&quot;25&quot; TextAlignment=&quot;Center&quot;/&gt;
        &lt;TextBlock Grid.Column=&quot;4&quot; Text=&quot;0&quot; Height=&quot;25&quot; TextAlignment=&quot;Left&quot; x:Name=&quot;tbResult&quot;/&gt;
        &lt;Button Grid.Row=&quot;1&quot; Grid.ColumnSpan=&quot;5&quot; Margin=&quot;0,5,0,0&quot; Content=&quot;Calculate&quot; x:Name=&quot;btnCalculate&quot; Click=&quot;btnCalculate_Click&quot; /&gt;
    &lt;/Grid&gt;
</pre><p>and the code behind looks like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void btnCalculate_Click(object sender, RoutedEventArgs e)
    {
        tbResult.Text = (Convert.ToInt32(tbFirstValue.Text)  + Convert.ToInt32(tbSecondValue.Text)).ToString();
    }
}
</pre><h3 class="subheading">It’s all about the ViewModel</h3><p>The name of the ViewModel for this application will be CalculatorViewModel.</p><p>If you follow the convention of naming the ViewModel using the name of the consumer who will be using it, knowing what the ViewModel is used for is easier as the application grows.</p><p>This will also help to ensure you do not use the same ViewModel for multiple controls, something which is considered to be a best practice.</p><p>Setting the CalculatorViewModel as the data context of the Silverlight user control is usually done in one of two ways (some people implement service locators or use a provider).</p><p>setting the ViewModel as the DataContext in the code behind</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public CalculatorPage()
{
    InitializeComponent();
    DataContext = new CalculatorViewModel();
}
</pre><p>or setting the ViewModel as the DataContext in XAML</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;UserControl.DataContext&gt;
    &lt;local:CalculatorViewModel/&gt;
&lt;/UserControl.DataContext&gt;
</pre><h3 class="subheading">INotifyChanged</h3><p>By implementing the INotifyChanged interface (or inheriting from a base class which implements it), events can be raised when a property value changes.</p><p>For the calculator example events will be used to update the user interface when the values for the two input numbers or the calculated result change.</p><p>The code below shows how the OnPropertyChanged method is called in the property setters to raise the PropertyChangedEventHandler.</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
private string _firstValue;
private string _secondValue;
private string _result;

public event PropertyChangedEventHandler PropertyChanged;

public string FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}

public string SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}

public string Result
{
    get { return _result; }
    private set
    {
        _result = value;
        OnPropertyChanged(&quot;Result&quot;);
    }
}

protected void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this,
            new PropertyChangedEventArgs(propertyName));
    }
}
</pre><p>The next step is to change the text controls in the XAML file to bind to the properties in the ViewModel</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
        &lt;TextBox Grid.Column=&quot;0&quot; Text=&quot;{Binding FirstValue, Mode=TwoWay}&quot; Height=&quot;25&quot; TextAlignment=&quot;Right&quot;/&gt;
        &lt;TextBlock Grid.Column=&quot;1&quot; Text=&quot;+&quot; Height=&quot;25&quot; TextAlignment=&quot;Center&quot;/&gt;
        &lt;TextBox Grid.Column=&quot;2&quot; Text=&quot;{Binding SecondValue, Mode=TwoWay}&quot; Height=&quot;25&quot; TextAlignment=&quot;Right&quot;/&gt;
        &lt;TextBlock Grid.Column=&quot;3&quot; Text=&quot;=&quot; Height=&quot;25&quot; TextAlignment=&quot;Center&quot;/&gt;
        &lt;TextBlock Grid.Column=&quot;4&quot; Text=&quot;{Binding Result, Mode=OneWay}&quot; Height=&quot;25&quot; TextAlignment=&quot;Left&quot;/&gt;
</pre><p>Notice how the binding mode on the text boxes are two way but the result text block is only one way.</p><p>We need to use a two way binding to be able to update the ViewModel with the values the user enters.</p><p>As the user cannot enter a value in the result text block the binding only needs to be one way.</p><p>If you want more information about data binding check out the <a
href="http://msdn.microsoft.com/en-us/library/ms752347.aspx">Data Binding Overview</a> article on MSDN.</p><h3 class="subheading">Commands in Silverlight 4</h3><p>New in Silverlight 4 are commands (WPF already had them).  Commands enable us to replace the click event for the calculate button in the XAML file with a command as shown below.</p><pre class="brush: xml; gutter: false; title: ; toolbar: true; notranslate">
&lt;Button Grid.Row=&quot;1&quot; Grid.ColumnSpan=&quot;5&quot; Margin=&quot;0,5,0,0&quot; Content=&quot;Calculate&quot; Command=&quot;{Binding CalculateCommand}&quot;  /&gt;
</pre><p>The command binds to a CalculateCommand property in the ViewModel which looks like this</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
private readonly ICommand _calculateCommand;
public ICommand CalculateCommand
{
    get { return _calculateCommand; }
}
</pre><h3 class="subheading">So how does the command know what to do?</h3><p>The answer is by using a RelayCommand (which implements the ICommand interface) and passing a method (which adds two values together) in its constructor.  A relay command allows for cleaner command implementation in ViewModel classes.</p><p>The code for the RelayCommand is shown below (I can’t take any credit for this as I’ve taken it from Josh Smiths MSDN article).</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public class RelayCommand : ICommand
{
    private Action _handler;
    public RelayCommand(Action handler)
    {
        _handler = handler;
    }

    private bool _isEnabled;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value != _isEnabled)
            {
                _isEnabled = value;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }
    }

    public bool CanExecute(object parameter)
    {
        return IsEnabled;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _handler();
    }
}
</pre><p>The code below shows the calculate method and how the relay command is set up in the ViewModels&#8217; constructor</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
public CalculatorViewModel()
{
    _calculateCommand = new RelayCommand(Calculate){IsEnabled = true};
}

private void Calculate()
{
    Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();
}
</pre><h3 class="subheading">So what have we achieved?</h3><p>Given that all we are doing here is adding two numbers together the effort of implementing the MVVM pattern looks to be a lot of work.</p><p>The important thing to take away is what an MVVM ViewModel looks like without the use of any third party frameworks such the <a
href="http://www.galasoft.ch/mvvm/getstarted/">MVVM Light Toolkit</a>. <strong>The code in this post only uses the libraries that ship with Microsoft Silverlight 4</strong>.</p><p>The class diagram for the ViewModel looks like this</p><p><img
src="http://www.arrangeactassert.com/wp-content/themes/resources/images/SilverlightMVVMViewModel.png" alt="Silverlight MVVM ViewModel"></img></p><p>and the complete code listing for the ViewModel is shown below</p><pre class="brush: csharp; gutter: false; title: ; toolbar: true; notranslate">
using System;
using System.ComponentModel;
using System.Windows.Input;

namespace SilverlightCalculator
{
    public class CalculatorViewModel : INotifyPropertyChanged
    {
        private string _firstValue;
        private string _secondValue;
        private string _result;

        private readonly ICommand _calculateCommand;       

        public event PropertyChangedEventHandler PropertyChanged;

        public CalculatorViewModel()
        {
            _calculateCommand = new RelayCommand(Calculate){IsEnabled = true};
        }

        private void Calculate()
        {
            Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();
        }

        public string FirstValue
        {
            get { return _firstValue; }
            set
            {
                _firstValue = value;
                OnPropertyChanged(&quot;FirstValue&quot;);
            }
        }

        public string SecondValue
        {
            get { return _secondValue; }
            set
            {
                _secondValue = value;
                OnPropertyChanged(&quot;SecondValue&quot;);
            }
        }

        public string Result
        {
            get { return _result; }
            private set
            {
                _result = value;
                OnPropertyChanged(&quot;Result&quot;);
            }
        }

        public ICommand CalculateCommand
        {
            get { return _calculateCommand; }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
</pre><p>With the foundation code in place adding additional properties or commands is easy.</p><p>While MVVM can be used and implemented in the wrong way (as with every pattern), by applying good software craftsmanship skills a Silverlight or WPF application using the MVVM pattern will encourage you to adopt best practices (as we will see later in the series).</p><p>If you have arrived here from a search engine, this post is part of series about refactoring Silverlight applications.  So if you’re thinking calculating numbers this way is a &#8216;code smell&#8217;, see how this can be resolved by <a
href="http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf/">applying the Single Responsibility Principle to View Models in Silverlight and WPF</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.arrangeactassert.com/how-to-implement-mvvm-inotifychanged-and-icommand-in-a-silverlight-application/feed/</wfw:commentRss> <slash:comments>22</slash:comments> </item> </channel> </rss>
<!-- Served from: www.arrangeactassert.com @ 2012-02-06 00:12:22 by W3 Total Cache -->
