<?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</title>
	<atom:link href="http://www.arrangeactassert.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.arrangeactassert.com</link>
	<description>Jag Reehal on Agile Development, ASP.NET MVC, Silverlight and all manner of good stuff</description>
	<lastBuildDate>Wed, 28 Jul 2010 06:22:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Code First Entity Framework Unit Test Examples</title>
		<link>http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/</link>
		<comments>http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 00:47:07 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=1072</guid>
		<description><![CDATA[Following the release of the Entity Framework 4 CTP 4 and Scott Gu’s excellent blog post about Code-First Development with Entity Framework 4, we&#8217;ll be having a look at what your Code-First Entity Framework unit tests might look like. The code used in this post is available here. Remember in order to run the code [...]]]></description>
			<content:encoded><![CDATA[<p>Following the release of the <a href="http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4announcement.aspx">Entity Framework 4 CTP 4</a> and <a href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx">Scott Gu’s excellent blog post about Code-First Development with Entity Framework 4</a>, we&#8217;ll be having a look at what your Code-First Entity Framework unit tests might look like.  </p>
<p>The code used in this post is available <a href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/UnitTestingCodeFirstDevelopmentWithEF4.zip">here</a>.</p>
<p>Remember in order to run the code or to create unit tests shown in this post you need to download and install:</p>
<ul>
<li><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4e094902-aeff-4ee2-a12d-5881d4b0dd3e&#038;displaylang=en">Microsoft ADO.NET Entity Framework Feature Community Technology Preview 4</a></li>
<li>
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=0d2357ea-324f-46fd-88fc-7364c80e4fdb&#038;displaylang=en">Microsoft SQL Server Compact 4.0 Community Technology Preview for Windows Desktop</a></li>
</ul>
<h3 class="subheading">Getting started</h3>
<p>The entities we will be using are the same Dinner and RSVP entities Scott used in his post</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class Dinner
{
    public int DinnerID { get; set; }
    public string Title { get; set; }
    public DateTime EventDate { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }
    public string HostedBy { get; set; }

    public virtual ICollection&lt;RSVP&gt; RSVPs { get; set; }
}

public class RSVP
{
    public int RsvpID { get; set; }
    public int DinnerID { get; set; }
    public string AtendeeEmail { get; set; }

    public virtual Dinner Dinner { get; set; }
}
</pre>
<p>as well as the NerdDinners class which inherits from DbContext</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class NerdDinners : DbContext
{
    public DbSet&lt;Dinner&gt; Dinners { get; set; }
    public DbSet&lt;RSVP&gt; RSVP { get; set; }
}
</pre>
<h3 class="subheading">Creating Entity Framework Code-First Unit Tests</h3>
<p>So let’s start off by writing a test to check a Dinner can be saved in the database.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Should_be_able_to_save_new_dinner()
{
    // Arrange
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory(&quot;System.Data.SqlServerCe.4.0&quot;);
    NerdDinners nerdDinners = new NerdDinners();

    Dinner dinner = new Dinner
                        {
                            Title = &quot;Dinner with the Queen&quot;,
                            Address = &quot;Buckingham Palace&quot;,
                            EventDate = DateTime.Now,
                            HostedBy = &quot;Liz and Phil&quot;,
                            Country = &quot;England&quot;
                        };

    nerdDinners.Dinners.Add(dinner);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    Dinner savedDinner = (from d in nerdDinners.Dinners
                            where d.DinnerID == dinner.DinnerID
                            select d).Single();

    savedDinner.Title.ShouldEqual(dinner.Title);
    savedDinner.Address.ShouldEqual(dinner.Address);
    savedDinner.EventDate.ShouldEqual(dinner.EventDate);
    savedDinner.HostedBy.ShouldEqual(dinner.HostedBy);
    savedDinner.Country.ShouldEqual(dinner.Country);
}
</pre>
<p>There are a couple of things to note here.  </p>
<p>In the LINQ query to get the saved Dinner from the database we can use the ID of the Dinner we created because when you call the SaveChanges() method the Entity Framework will set the identity value of the object(s) being persisted. </p>
<p>The other thing we could have done is use a &#8216;domain signature&#8217; to check for equality, but that’s for a future blog post.</p>
<h3 class="subheading">Testing entities with foreign keys</h3>
<p>The code below shows a test for saving an RSVP.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Should_be_able_to_save_new_rsvp()
{
    // Arrange
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory(&quot;System.Data.SqlServerCe.4.0&quot;);
    NerdDinners nerdDinners = new NerdDinners();

    RSVP rsvp = new RSVP();
    rsvp.AtendeeEmail = &quot;someone@somedomain.com&quot;;
    Dinner dinner = new Dinner
                        {
                            Title = &quot;Dinner with the Queen&quot;,
                            Address = &quot;Buckingham Palace&quot;,
                            EventDate = DateTime.Now,
                            HostedBy = &quot;Liz and Phil&quot;,
                            Country = &quot;England&quot;
                        };
    rsvp.Dinner = dinner;

    nerdDinners.RSVP.Add(rsvp);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    RSVP savedRSVP = (from s in nerdDinners.RSVP
                        where s.RsvpID == rsvp.RsvpID
                        select s).Single();

    savedRSVP.AtendeeEmail.ShouldEqual(rsvp.AtendeeEmail);
}
</pre>
<p>One thing you might have noticed here is that we had to create a Dinner as well as an RSVP.  This is because of the foreign key constraint for the DinnerID.</p>
<p>So at this point you could be asking why we can&#8217;t use the Dinner we created in the first test?  The trouble, danger and bad practice of doing that is falling into the trap of creating a dependency of your tests running in some sort of order or sequence.    </p>
<h3 class="subheading">AlwaysRecreateDatabase</h3>
<p>In his post Scott created a NerdDinnersInitializer class which inherited from RecreateDatabaseIfModelChanges.  But this is not good enough for a unit test because we need to ensure each test starts off in a known state.</p>
<p>This doesn’t mean we have to create a Dinner each time we want to save an RSVP because we can create an NerdDinnersInitializer which is already populated with a dinner by overriding the Seed method.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class NerdDinnersInitializer : AlwaysRecreateDatabase&lt;NerdDinners&gt;
{
    protected override void Seed(NerdDinners context)
    {
        var dinners = new List&lt;Dinner&gt; { new Dinner()
                                                {
                                                    Title = &quot;Dinner with the Queen&quot;,
                                                    Address = &quot;Buckingham Palace&quot;,
                                                    EventDate = DateTime.Now,
                                                    HostedBy = &quot;Liz and Phil&quot;,
                                                    Country = &quot;England&quot;
                                                }
        };
        dinners.ForEach(d =&gt; context.Dinners.Add(d));
    }
}
</pre>
<p>And use it in a test to check we can create an RSVP</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Should_be_able_to_save_new_rsvp_using_existing_dinner()
{
    // Arrange
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory(&quot;System.Data.SqlServerCe.4.0&quot;);
    Database.SetInitializer&lt;NerdDinners&gt;(new NerdDinnersInitializer());
    NerdDinners nerdDinners = new NerdDinners();

    RSVP rsvp = new RSVP();
    rsvp.AtendeeEmail = &quot;someone@somedomain.com&quot;;
    rsvp.DinnerID = nerdDinners.Dinners.First().DinnerID;

    nerdDinners.RSVP.Add(rsvp);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    RSVP savedRSVP = (from s in nerdDinners.RSVP
                        where s.RsvpID == rsvp.RsvpID
                        select s).Single();

    savedRSVP.AtendeeEmail.ShouldEqual(rsvp.AtendeeEmail);
}
</pre>
<h3 class="subheading">The disadvantage of always creating a database is the amount of time it takes to actually create the database</h3>
<p>So the more times you call SetInitializer in which you&#8217;re always recreating a database, the longer it will take for your tests to run.  </p>
<p>My recommendation is to create dummy/stub dinners upfront and call SetInitializer before you run the tests.  In NUnit this is done in the TestFixtureSetUp as shown below. </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[TestFixtureSetUp]
public void TestFixtureSetup()
{
    Database.SetInitializer&lt;NerdDinners&gt;(new NerdDinnersInitializer());
}
</pre>
<h3 class="subheading">Tests to check updates</h3>
<p>So now you can save a Dinner, the next test you might write is to check you can update it. </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Should_be_able_to_update_existing_dinner()
{
    // Arrange
    NerdDinners nerdDinners = new NerdDinners();

    Dinner dinner = nerdDinners.Dinners.First();
    dinner.HostedBy = &quot;Charlie and Camilla&quot;;

    // Act
    nerdDinners.SaveChanges();

    // Assert
    Dinner savedDinner = (from d in nerdDinners.Dinners
                            where d.DinnerID == dinner.DinnerID
                            select d).Single();

    savedDinner.HostedBy.ShouldEqual(dinner.HostedBy);
}
</pre>
<h3 class="subheading">Testing your models</h3>
<p>The examples in this post follow the Entity Framework convention you get out of the box. </p>
<p>As we have already established the property DinnerID is a foreign key in the RSVP entity.  </p>
<p>But if you forgot to add it, the Dinner property would always be null.  </p>
<p>The test below verifies we are able to view information about a dinner when we retrieve an RSVP from the database. </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Should_be_able_to_view_dinner_details()
{
    // Arrange
    NerdDinners nerdDinners = new NerdDinners();
    var dinner = nerdDinners.Dinners.First();

    RSVP rsvp = new RSVP();
    rsvp.AtendeeEmail = &quot;someone@somedomain.com&quot;;
    rsvp.DinnerID = dinner.DinnerID;

    nerdDinners.RSVP.Add(rsvp);

    // Act
    nerdDinners.SaveChanges();

    // Assert
    RSVP savedRSVP = (from s in nerdDinners.RSVP
                        where s.RsvpID == rsvp.RsvpID
                        select s).Single();

    savedRSVP.Dinner.Title.ShouldEqual(dinner.Title);
}
</pre>
<h3 class="subheading">Jag Reehal’s Final Thought on ‘Examples of Code First Entity Framework Unit Tests’</h3>
<p>In this post I wanted to show a few examples of how you might create unit tests for your Entity Framework projects.  </p>
<p>The ADO.NET team have really done a great job enabling developers to be able to do code-first development and allow them to move a step closer to doing test driven development using the Entity Framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using INotifyDataErrorInfo for validation in MVVM with Silverlight</title>
		<link>http://www.arrangeactassert.com/using-inotifydataerrorinfo-for-validation-in-mvvm-with-silverlight/</link>
		<comments>http://www.arrangeactassert.com/using-inotifydataerrorinfo-for-validation-in-mvvm-with-silverlight/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 23:13:15 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=1038</guid>
		<description><![CDATA[In this post we will be looking at how validation can be done by implementing the INotifyDataErrorInfo interface for a calculator we have been building as part of the Silverlight refactoring series. Like the IDataErrorInfo interface, the INotifyDataErrorInfo interface gives you the ability to do validation without throwing exceptions. The full solution for this post [...]]]></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.inotifydataerrorinfo%28VS.95%29.aspx">INotifyDataErrorInfo </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>Like the <a href="http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/">IDataErrorInfo interface</a>, the INotifyDataErrorInfo 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/SilverlightCalculatorValidationINotifyDataErrorInfo.zip">here</a>.</p>
<h3 class="subheading">Note to WPF developers &#8211; INotifyDataErrorInfo isn&#8217;t available in WPF (yet)</h3>
<p>But you can vote for <a href="https://connect.microsoft.com/VisualStudio/feedback/details/568212/inotifydataerrorinfo-for-wpf">INotifyDataErrorInfo to be in a future release of WPF</a>.</p>
<h3 class="subheading">Pre INotifyDataErrorInfo</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; toolbar: true;">
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 INotifyDataErrorInfo interface</h3>
<p>As we only want the calculate button to be enabled when the user has entered valid numbers to add together, we need to keep track of any validation errors.  </p>
<p>Similar to how we have done in other posts, we will use a class for storing validation errors instead of making it the responsibility of the ViewModel.</p>
<p>And that class is the EntityBase class, which I borrowed from <a href="http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/11/18/silverlight-4-rough-notes-binding-with-inotifydataerrorinfo.aspx">Mike Taulty</a>.  Cheers Mike! </p>
<p>The code below shows how the EntityBase class implements the ErrorsChanged event, GetErrors method and the HasErrors property defined in the INotifyDataErrorInfo interface.  </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class EntityBase : INotifyDataErrorInfo
{
    public event EventHandler&lt;DataErrorsChangedEventArgs&gt; ErrorsChanged;
    readonly Dictionary&lt;string, List&lt;string&gt;&gt; _currentErrors;

    public EntityBase()
    {
        _currentErrors = new Dictionary&lt;string, List&lt;string&gt;&gt;();
    }

    public IEnumerable GetErrors(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
        {
            return (_currentErrors.Values);
        }

        MakeOrCreatePropertyErrorList(propertyName);
        return _currentErrors[propertyName];
    }

    public bool HasErrors
    {
        get
        {
            return (_currentErrors.Where(c =&gt; c.Value.Count &gt; 0).Count() &gt; 0);
        }
    }

    void FireErrorsChanged(string property)
    {
        if (ErrorsChanged != null)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(property));
        }
    }
    public void ClearErrorFromProperty(string property)
    {
        MakeOrCreatePropertyErrorList(property);
        _currentErrors[property].Clear();
        FireErrorsChanged(property);
    }
    public void AddErrorForProperty(string property, string error)
    {
        MakeOrCreatePropertyErrorList(property);
        _currentErrors[property].Add(error);
        FireErrorsChanged(property);
    }

    void MakeOrCreatePropertyErrorList(string propertyName)
    {
        if (!_currentErrors.ContainsKey(propertyName))
        {
            _currentErrors[propertyName] = new List&lt;string&gt;();
        }
    }
}
</pre>
<p>The EnitityBase class can be unit tested like this</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[TestFixture]
public class When_using_the_EntityBase
{
    private EntityBase _entityBase;

    [SetUp]
    public void SetUp()
    {
        _entityBase = new EntityBase();
    }

    [Test]
    public void HasErrors_should_return_true_when_errors_exist()
    {
        // Arrange
        _entityBase.AddErrorForProperty(&quot;X&quot;, &quot;X&quot;);

        // Act
        var result = _entityBase.HasErrors;

        // Assert
        result.ShouldBeTrue();
    }

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

        // Act
        var result = _entityBase.HasErrors;

        // Assert
        result.ShouldBeFalse();
    }

    [Test]
    public void Should_be_able_to_clear_error_from_property()
    {
        // Arrange
        _entityBase.AddErrorForProperty(&quot;X&quot;, &quot;X&quot;);

        // Act
        _entityBase.ClearErrorFromProperty(&quot;X&quot;);
        var result = _entityBase.GetErrors(&quot;X&quot;) as List&lt;string&gt;; 

        // Assert
        result.Count().ShouldEqual(0);

    }

    [Test]
    public void Should_be_able_to_get_error_for_property()
    {
        // Arrange
        const string errorMessage = &quot;ErrorMessage&quot;;
        _entityBase.AddErrorForProperty(&quot;X&quot;, &quot;ErrorMessage&quot;);

        // Act
        var result =  _entityBase.GetErrors(&quot;X&quot;) as List&lt;string&gt;;

        // Assert
        result[0].ShouldEqual(errorMessage);

    }
}
</pre>
<h3 class="subheading">How the ViewModel validates user input</h3>
<p>We need to validate the users input each time the value of a property changes. </p>
<p>If you have been following the series you’ll know <a href="http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/">the benefits of injecting/importing a class responsible for validation</a>, the CalculatorValidator, into the ViewModel and to validate the users input.</p>
<p>In the code for the CalculatorValidator class, the Validate method could have returned a collection of error messages, but to keep this example simple we&#8217;ll just return the first validation error we encounter.      </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Export(typeof(ICalculatorValidator))]
public class CalculatorValidator : ICalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public ValidationResult Validate(string value)
    {
        List&lt;ValidationResult&gt; validationResults = new List&lt;ValidationResult&gt;();
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                return new ValidationResult()
                            {
                                IsValid = false,
                                ErrorMessage = calculatorValidationRule.ErrorMessage

                            };
            }
        }
        return new ValidationResult() { IsValid = true };
    }
}

public class ValidationResult
{
    public bool IsValid { get; set; }
    public string ErrorMessage { get; set; }
}
</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 ‘<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>‘ post.</p>
<h3 class="subheading">Using the INotifyDataErrorInfo interface in the ViewModel</h3>
<p>In the code for the ViewModel shown below take note of how:   </p>
<ul>
<li>the ViewModel inherits from the EntityBase class</li>
<li>the CheckIfNumberIsValid method is called whenever a property value changes  </li>
<li>the INotifyDataErrorInfo HasErrors property is used to determine if the button should be enabled in the CalculatorViewModel_ErrorsChanged handler for the ErrorsChanged event.  <strong>This is one of the advantages INotifyDataErrorInfo  has over IDataErrorInfo.</strong> </li>
</ul>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Export]
public class CalculatorViewModel : EntityBase, INotifyPropertyChanged
{
    private string _firstValue;
    private string _secondValue;
    private string _result;       

    private readonly ICalculator _calculator;
    private readonly RelayCommand _calculateCommand;

    public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection&lt;string&gt; FirstValueErrors { get; set; }
    private readonly ICalculatorValidator _calculatorValidator;

    [ImportingConstructor]
    public CalculatorViewModel(ICalculator calculator, ICalculatorValidator calculatorValidator)
    {
        _calculator = calculator;
        _calculatorValidator = calculatorValidator;
        _calculateCommand = new RelayCommand(Calculate) { IsEnabled = true };
        ErrorsChanged += new EventHandler&lt;DataErrorsChangedEventArgs&gt;(CalculatorViewModel_ErrorsChanged);

        _firstValue = &quot;0&quot;;
        _secondValue = &quot;0&quot;;
    }

    void CalculatorViewModel_ErrorsChanged(object sender, DataErrorsChangedEventArgs e)
    {
        _calculateCommand.IsEnabled = HasErrors == false;
    }

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

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

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

    public void CheckIfNumberIsValid(string propertyName, string value)
    {
        ClearErrorFromProperty(propertyName);

        var validationResult = _calculatorValidator.Validate(value);
        if (validationResult.IsValid  == false)
        {
            AddErrorForProperty(propertyName, validationResult.ErrorMessage);
        }
        OnPropertyChanged(propertyName);
    }

    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));
        }
    }
}
</pre>
<h3 class="subheading">XAML changes for INotifyDataErrorInfo</h3>
<p>The final change required to implement INotifyDataErrorInfo interface is to change the text box bindings and set ValidatesOnNotifyDataErrors=True</p>
<pre class="brush: xml; gutter: false; toolbar: true;">
&lt;TextBox Text=&quot;{Binding FirstValue, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}&quot;/&gt;
&lt;TextBox Text=&quot;{Binding SecondValue, Mode=TwoWay, ValidatesOnNotifyDataErrors=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  INotifyDataErrorInfo interface and are no longer throwing exceptions to do validation.</p>
<p>As well as allowing you return multiple validation errors for a property, the <a href="https://www.silverlight.net/learn/videos/all/asynchronous-data-validation/">INotifyDataErrorInfo interface can be used for asynchronous data validation as demonstrated by Jesse Liberty in this video</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/using-inotifydataerrorinfo-for-validation-in-mvvm-with-silverlight/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
[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; toolbar: true;">
[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; toolbar: true;">
[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; toolbar: true;">
&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>1</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[MVVM]]></category>
		<category><![CDATA[Moq]]></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; toolbar: true;">
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; toolbar: true;">
[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; toolbar: true;">
[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; toolbar: true;">
[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; toolbar: true;">
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; toolbar: true;">
[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>Validation in Silverlight and WPF using ValidatesOnExceptions</title>
		<link>http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/</link>
		<comments>http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 23:43:06 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=941</guid>
		<description><![CDATA[With the application as it is the user is able to enter non-numeric values and add them together. Clicking the calculate button to add two non-numeric values together will cause the application to do nothing and the user will have no idea why. Try it for yourself here. It would be common sense to validate [...]]]></description>
			<content:encoded><![CDATA[<p>With the application as it is the user is able to enter non-numeric values and add them together.</p>
<p>Clicking the calculate button to add two non-numeric values together will cause the application to do nothing and the user will have no idea why.</p>
<p>Try it for yourself <a href="http://www.arrangeactassert.com/wp-content/themes/resources/SilverlightDemos/CalculatorDemo/CalculatorDemo.html">here</a>.</p>
<p>It would be common sense to validate what the user has entered and let them know if and what the problem is.  </p>
<h3 class="subheading">What I&#8217;ve seen most beginners do for validation in Silverlight and WPF</h3>
<p>One of easiest way (in terms of the amount of code you have to write) to do validation in Silverlight and WPF is to use exceptions.</p>
<p>To do this we need to make changes in the ViewModel and the Calculator XAML file.</p>
<p>In the ViewModel an exception needs to be thrown when the input value cannot be converted to a number.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        try
        {
            int.Parse(_firstValue);
        }
        catch (Exception)
        {
            throw;
        }
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}
</pre>
<p>In the XAML file we set ValidatesOnExceptions equal to true for the text box binding.</p>
<pre class="brush: xml; gutter: false; toolbar: true;">
&lt;TextBox Grid.Column=&quot;0&quot; Text=&quot;{Binding FirstValue, Mode=TwoWay, ValidatesOnExceptions=True}&quot; Height=&quot;25&quot; TextAlignment=&quot;Right&quot;/&gt;
</pre>
<p>The screenshot below shows what happens if the user does not enter a number into the text box.</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/blog/DefaultSilverlightException.png" alt="Default Silverlight Exception" /></p>
<p>As you can see error message isn&#8217;t very user friendly.  </p>
<p>To resolve this issue we could set the message of the exception thrown when parsing a number but we would be repeating/duplicating code when validating the SecondValue.  </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
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(_firstValue);
        }
        catch (Exception)
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre>
<h3 class="subheading">Silverlight validations the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don&#8217;t Repeat Yourself</a> Way</h3>
<p>A better way would to do this is by creating a reusable method for validating the users input.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
void ValidateNumber(string value)
{
    try
    {
        int.Parse(value);
    }
    catch (Exception)
    {
        throw new Exception(&quot;That's not a number&quot;);
    }
}
</pre>
<p>which could be used like this</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public string FirstValue
{
    get { return _firstValue; }
    set
    {
        _firstValue = value;
        ValidateNumber(value);
        OnPropertyChanged(&quot;FirstValue&quot;);
    }
}

public string SecondValue
{
    get { return _secondValue; }
    set
    {
        _secondValue = value;
        ValidateNumber(value);
        OnPropertyChanged(&quot;SecondValue&quot;);
    }
}
</pre>
<p>Now when a user enters an invalid number the they would see an error that looks like this</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/blog/CustomSilverlightException.png" alt="Custom Silverlight Exception" /></p>
<h3 class="subheading">So what have we achieved?</h3>
<p>With a few lines of code we are able to validate the users input and let them know what the problem is if it&#8217;s not valid.</p>
<p>If you have arrived here from a search engine, this post is part of series about <a href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">refactoring Silverlight applications</a>. </p>
<p>So if you’re thinking, this is all very well but the user is still able to click the calculate button even if they have entered invalid values to add together, see how this can prevented in the next part of the series.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Applying the Open Closed Principle in Silverlight and WPF using MEF</title>
		<link>http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/</link>
		<comments>http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 23:27:39 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[MEF]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=900</guid>
		<description><![CDATA[In this post I want to show how MEF can be used to apply the Open Closed Principle where a class is open for extension but closed for modification. In the Calculator application we have been building as part of the Silverlight refactoring series we could have used the code below to validate a users [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I want to show how <a href="http://mef.codeplex.com/">MEF</a> can be used to apply the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open Closed Principle</a> where a class is open for extension but closed for modification.</p>
<p>In the Calculator application 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> we could have used the code below to validate a users input. </p>
<p>By the way we are throwing exceptions because the application is using ValidatesOnExceptions.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class CalculatorValidator
{
    public void ValidateNumber(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            throw new Exception(&quot;Please enter a number&quot;);
        }

        int number;
        if (!int.TryParse(value, out number))
        {
            throw new Exception(&quot;That's not a number&quot;);
        }
    }
}
</pre>
<p>If we wanted to add more validation rules to check the value cannot be negative or greater than a hundred we have to modify the CalculatorValidator class with two additional if statements.  </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class CalculatorValidator
{
    public void ValidateNumber(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            throw new Exception(&quot;Please enter a number&quot;);
        }

        int number;
        if (!int.TryParse(value, out number))
        {
            throw new Exception(&quot;That's not a number&quot;);
        }

        if (number &lt; 0)
        {
            throw new Exception(&quot;Number cannot be negative&quot;);
        }

        if (number &gt; 100)
        {
            throw new Exception(&quot;That number is too big!&quot;);
        }
    }
}
</pre>
<p>and this pattern would continue every time you added a new rule, leaving the code as maintainable and stable as a wobbly tower!</p>
<h3 class="subheading">Implementing the Open Closed Principle</h3>
<p>Lets start by creating an interface for a validation rule</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public interface ICalculatorValidationRule
{
    bool IsValid(string number);
    string ErrorMessage { get; }
}
</pre>
<p>Next we create a class for each validation rule by implementing the ICalculatorValidationRule interface</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsNotNullOrEmpty : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        return !String.IsNullOrEmpty(value);
    }

    public string ErrorMessage
    {
        get
        {
            return &quot;Please enter a number&quot;;
        }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsANumber : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        if (!String.IsNullOrEmpty(value))
        {
            int number;
            return int.TryParse(value, out number);
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return &quot;That's not a number&quot;; }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsNotNegative : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        int number;
        if (int.TryParse(value, out number) &amp;&amp; number  &lt; 0)
        {
            return false;
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return &quot;Number cannot be negative&quot;; }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsLessThanHundred : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        int number;
        if (int.TryParse(value, out number) &amp;&amp; number &gt; 100)
        {
            return false;
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return &quot;That number is too big!&quot;; }
    }
}
</pre>
<p>An alternative to parsing the value to an integer in the validation rules to check the range would be to order how MEF composes the validation rules and ensure rule to validate the value is an integer is done earlier.</p>
<p>More information about this can be found in answer to this question on Stack Overflow &#8211; <a href="http://stackoverflow.com/questions/1770297/how-does-mef-determine-the-order-of-its-imports/1772554">How does MEF determine the order of its imports?</a> </p>
<h3 class="subheading">ImportMany example in MEF</h3>
<p>By using the ImportMany attribute on a collection in MEF we can iterate over all of the parts which export the ICalculatorValidatorInterface and check the value passes the validation rule by calling the IsValid method.</p>
<p>If the value is not valid a exception is thrown with the relevant error message.</p>
<p>The code below shows how the CalculatorValidator class would look</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class CalculatorValidator
{
    [ImportMany]
    public IEnumerable&lt;ICalculatorValidationRule&gt; CalculatorValidationRules { get; set; }

    public void ValidateNumber(string value)
    {
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                throw new Exception(calculatorValidationRule.ErrorMessage);

            }
        }
    }
}
</pre>
<h3 class="subheading">Couldn&#8217;t have done it without the extensibility of MEF</h3>
<p>If we wanted to add a new validation rule, all we have to do is create another class which implements the ICalculatorValidationRule interface, add an export attribute and MEF will do the rest.</p>
<blockquote><p>The CalculatorValidator class is now open to extension but closed for modification</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/applying-the-open-closed-principle-in-silverlight-and-wpf-using-mef/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SOLID design principles using MEF in Silverlight and WPF</title>
		<link>http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/</link>
		<comments>http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 21:14:01 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[MEF]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=851</guid>
		<description><![CDATA[In this part of the Silverlight refactoring series we will be looking at two ways the Managed Extensibility Framework (MEF) can help you refactor Silverlight or WPF applications to follow SOLID design principles. The code used in this post can be downloaded here. Apart from saying through discovery and composition MEF gives you the ability [...]]]></description>
			<content:encoded><![CDATA[<p>In this part of the <a href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">Silverlight refactoring series</a> we will be looking at two ways the <a href="http://mef.codeplex.com/">Managed Extensibility Framework (MEF)</a> can help you refactor Silverlight or WPF applications to follow <a href="http://en.wikipedia.org/wiki/Solid_(object-oriented_design)">SOLID design principles</a>.</p>
<p>The code used in this post can be downloaded <a ref="nofollow" href="http://cid-8a29bf85dc9538dc.office.live.com/self.aspx/.Public/Silverlight%20Demos/SilverlightCalculator/SilverlightCalculatorMEF.zip">here</a>.</p>
<p>Apart from saying </p>
<blockquote><p>through discovery and composition MEF gives you the ability to build applications which will be flexible enough for your every need</p></blockquote>
<p>I won’t be covering what MEF is or how it works in depth in this post.  Instead I recommend checking out the following blogs as well as the <a href="http://mef.codeplex.com/">MEF site on Codeplex</a> for some great tutorials.  </p>
<ul>
<li><a href="http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/default.aspx">Mike Taulty&#8217;s Blog</a></li>
<li><a href="http://blogs.msdn.com/b/gblock/">Glenn Block&#8217;s Blog</a></li>
</ul>
<h3 class="subheading">What problem does MEF solve in this application?</h3>
<p>The code below shows the Calculate method in the ViewModel.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public void  Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre>
<p>Notice how Calculator class is created and used within the method.  This means there&#8217;s no way of changing what class is used for calculations without modifying the code in the ViewModel.  </p>
<p>In other words <strong>the calculator is tightly coupled to the ViewModel</strong>.</p>
<h3 class="subheading">Composing, Initializing, Setting up, Bootstrapping, Configuring or whatever you want to call it in MEF</h3>
<p>MEF works by using a catalog to discover extensions within assemblies.  As the assemblies used in this application are in same XAP we can call the CompositionInitializer SatisfyImports method to automatically configure a container and compose the parts within it.</p>
<p>Looking at the class diagram for the application</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/SilverlightMVVMViewModelSRP.png" alt="Silverlight Class Diagram" /></p>
<p>we could decide</p>
<ul>
<li>only the Calculator class will be an composable part</li>
<li>the ViewModel and the Calculator will be composable parts</li>
<li>the CalculatorPage, ViewModel and the class should all be composable parts</li>
</ul>
<p>As this application only contains a single page we will go with the second option.  This means we will be calling the CompositionInitializer SatisfyImport method in the CalculatorPage constructor as shown below</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public CalculatorPage()
{
    InitializeComponent();
    CompositionInitializer.SatisfyImports(this);
}
</pre>
<h3 class="subheading">Adding MEF Export Attributes</h3>
<p>An export attribute is used to make classes and properties discoverable to the catalog and composable by the container.</p>
<p>As the Calculator class is used by the ViewModel we need to add an Export attribute to it. Because the Calculator implements the ICalculator interface we can use this as the <a href="http://mef.codeplex.com/wikipage?title=Parts&#038;ANCHOR">contract type</a>.   </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Export(typeof(ICalculator))]
public class Calculator : ICalculator
{
public int Add(int firstValue, int secondValue)
{
    return firstValue + secondValue;
}
}
</pre>
<p>Similarly as the ViewModel is used by the CalculatorPage it also needs to be decorated with an Export attribute.  As no contract is specified, MEF will use the fully qualified name of the type as the contract.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Export]
public class CalculatorViewModel : INotifyPropertyChanged
{
    .....
}
</pre>
<p>An important thing to remember is that the export attribute is not allowed on the instance passed to SatisfyImports otherwise you will see the error below</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/MEFExportError.png" alt="MEF Export Error" /></p>
<h3 class="subheading">Using MEF Property Imports</h3>
<p>To use property imports in MEF we need to add a Calculator property to the ViewModel add decorate it with an Import attribute.  In Silverlight MEF requires the property to be public.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Import]
public ICalculator Calculator { get; set; }
</pre>
<p>The Calculate method in the ViewModel uses the property like this</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public void Calculate()
{
    Result = Calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre>
<p>In the code behind of the CalculatorPage we need to add a CalculatorViewModel property, decorate it with an Import attribute and set it as the data context.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public partial class CalculatorPage : UserControl
{
    [Import]
    public CalculatorViewModel CalculatorViewModel { get; set; }

    public CalculatorPage()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(this);
        DataContext = CalculatorViewModel;
    }
}
</pre>
<p>If we run the application as it is MEF composes all the parts of the application and we are able to add numbers together&#8230; which is good but not great because I don’t recommend you should build applications only using property imports.</p>
<h3 class="subheading">Using MEF Constructor Imports</h3>
<p>I always try to follow the SOLID design principles whenever I’m developing applications. </p>
<p>The D in SOLID design principles stands for <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion Principle</a>. </p>
<p>One of the first things you should be taught when learning test driven development or even good coding practices is how SOLID design principles will help you create applications that are easier to develop, configure, maintain and unit test.  </p>
<p>See my blog post &#8216;<a href="http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-stubs/">How to write better unit tests using RhinoMocks and stubs</a>&#8216; for an example.</p>
<p>The good news is MEF supports constructor imports.</p>
<p>Using the ImportingConstructor attribute the CalculatorViewModel now takes in a Calculator in its constructor as shown below</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[ImportingConstructor]
public CalculatorViewModel(ICalculator calculator)
{
    _calculator = calculator;
    ...
}
</pre>
<p>and the calculate method uses the calculator like this</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public void Calculate()
{
    Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}
</pre>
<h3 class="subheading">Take care not to over engineer</h3>
<p>So what about the importing the ViewModel in the CalculatorPage?  We could stick to using a property for the ViewModel or pass it in the ViewModel constructor (in which case the call to CompositionInitializer SatisfyImports method will have to done in the App.xaml code behind).</p>
<p>I would be inclined to leave it as it is.  Because we want to be able to unit test the ViewModel it makes sense to use importing constructors so we stub out the calculator.</p>
<p>Are we ever going to unit test the CalculatorPage?  Probably not, and if we do need to, it’s not a major refactoring task.</p>
<p>In any case thanks to MEF the ViewModel can be changed without modifying the code behind for the CalculatorPage.</p>
<h3 class="subheading">So what have we achieved?</h3>
<p>By using SOLID design principles and MEF we have managed to remove the tight coupling between the ViewModel and the Calculator.  </p>
<p>There is a lot of discussion about what MEF is in the development community.  Despite numerous claims and comments that it&#8217;s not a dependency injection framework, I can&#8217;t help thinking it takes a step closer to being one with each release. </p>
<p>The last thing I&#8217;ll say about MEF is that </p>
<blockquote><p>the number of options you have of using MEF is either impressive or confusing depending on what side of the fence you sit on</p></blockquote>
<p>If you have arrived here from a search engine, this post is part of series about <a href="http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/">refactoring Silverlight applications</a>.  </p>
<p>So if you’re thinking, what if there&#8217;s an exception converting a string into an integer, check out the post &#8216;<a href="http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/">Validation in Silverlight and WPF using ValidatesOnExceptions</a>&#8216; which shows one approach in solving this problem using exceptions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/feed/</wfw:commentRss>
		<slash:comments>1</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]; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
[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; toolbar: true;">
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>0</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; toolbar: true;">
    &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; toolbar: true;">
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; toolbar: true;">
public CalculatorPage()
{
    InitializeComponent();
    DataContext = new CalculatorViewModel();
}
</pre>
<p>or setting the ViewModel as the DataContext in XAML</p>
<pre class="brush: xml; gutter: false; toolbar: true;">
&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; toolbar: true;">
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; toolbar: true;">
        &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; toolbar: true;">
&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; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
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; toolbar: true;">
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>6</slash:comments>
		</item>
		<item>
		<title>How To Refactor And Build Better Microsoft Silverlight Applications</title>
		<link>http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/</link>
		<comments>http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 23:24:44 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=729</guid>
		<description><![CDATA[As with all development technologies if you asked two developers how to solve a problem it’s unlikely both would come up with the same solution. It’s no surprise then the same solution to a problem using Silverlight and WPF applications can be implemented in a number of ways. In a series of posts I want [...]]]></description>
			<content:encoded><![CDATA[<p>As with all development technologies if you asked two developers how to solve a problem it’s unlikely both would come up with the same solution. </p>
<p>It’s no surprise then the same solution to a problem using Silverlight and WPF applications can be implemented in a number of ways.  </p>
<p>In a series of posts I want to show how we can refactor a Silverlight application which “works” to be a lot cleaner, easier to maintain and adheres to good development practices.  </p>
<p>Although I’m using Silverlight many of the changes and suggestions would also apply to a WPF application.</p>
<h3 class="subheading">So what’s the application?</h3>
<p>The application adds two numbers together.  </p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/SilverlightCalculator.png" alt="Silverlight Calculator" /></p>
<p>Yes that’s it. <a href="http://www.arrangeactassert.com/wp-content/themes/resources/SilverlightDemos/CalculatorDemo/CalculatorDemo.html">Click here to see a live demo of the calclator</a>.</p>
<p>Using a simple example (as opposed to a huge complex monster) allows us to focus on refactoring and making improvements rather than trying to understand what the application is doing and wading through hundreds of lines of code.</p>
<h3 class="subheading">So what’s wrong with it?</h3>
<p>The XAML is shown below</p>
<pre class="brush: xml; gutter: false; toolbar: true;">
    &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 this is what the code behind looks like</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
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>
<p>As it stands the application:</p>
<ul>
<li>Contains code in the code behind file.  OK it&#8217;s not so much of an issue for this example and is down to individual preference, but this can quickly become a nightmare to maintain during the life of an application</li>
<li>Isn’t unit testable – we can’t test two values can be added together</li>
<li>Has no separation of concerns – the code behind shouldn’t be responsible for adding the numbers together</li>
<li>A lot of repetition for the styling of the input boxes – if we wanted to make the input boxes bigger we would have to make multiple changes, ideally changes should only need to be made in one place.</li>
<li>No validation – if the user enters alphabetical characters into application and hits the calculate button the application crashes</li>
</ul>
<h3 class="subheading">So how are we going to improve it?</h3>
<p>By taking an agile approach the aim at the end of each refactoring is to have a releasable application i.e. be able to add two numbers together.  Therefore each refactoring will involve small incremental changes.  </p>
<p>After each refactoring exercise we will review the application to see what improvements have been made and if any new problems have been introduced&#8230;</p>
<ul>
<li>
<strong>Step 1:</strong> <a href="http://www.arrangeactassert.com/how-to-implement-mvvm-inotifychanged-and-icommand-in-a-silverlight-application">Implement the MVVM (Model-View-ViewModel) pattern to reduce the amount of code in the Silverlight code behind file and follow some best practices for Silverlight development</a><br />
<br/><br />
<strong>Review:</strong> The code behind file looks much cleaner now, thanks to the use of commands and the INotifyChanged interface, but should the ViewModel be responsible for calculating the two numbers together?
</li>
<p><br/></p>
<li>
<strong>Step 2:</strong> <a href="http://www.arrangeactassert.com/how-to-apply-the-single-responsibility-principle-to-view-models-in-silverlight-and-wpf">Remove the responsibility and concerns for calculating numbers in the ViewModel</a><br />
<br/><br />
<strong>Review:</strong> This refactoring has allowed us to reduce the responsibility of the ViewModel and unit test we can add two numbers together, but we are tightly coupled to the calculator class.
</li>
<p><br/></p>
<li>
<strong>Step 3:</strong> <a href="http://www.arrangeactassert.com/solid-design-principles-using-mef-in-silverlight-and-wpf/">Using SOLID design principles and MEF to remove tight coupling</a><br />
<br/><br />
<strong>Review:</strong> The application is now made up of loosely coupled components which give us a good platform to build upon.  But without any validation of what a user enters for a number the application isn’t very stable.
</li>
<p><br/></p>
<li>
<strong>Step 4:</strong> <a href="http://www.arrangeactassert.com/validation-in-silverlight-and-wpf-using-validatesonexceptions/">Validating what the user has entered using exceptions</a><br />
<br/><br />
<strong>Review:</strong> If the users input is not valid they are now are shown an error message.  This is all very well but the user is still able to click the calculate button even if they have entered invalid values to add together.
</li>
<p><br/></p>
<li>
<strong>Step 5:</strong> <a href="http://www.arrangeactassert.com/enabling-buttons-in-silverlight-and-wpf-using-mvvm-and-validatesonexceptions/">Validating what the user has entered using exceptions and disabling the calculate button if there are any validation errors</a><br />
<br/><br />
<strong>Review:</strong> The user is only able to click the calculate button when there are no validation errors.  Even though throwing exceptions for validation works, some developers aren&#8217;t so keen on doing this so what are the alternatives?
</li>
<p><br/></p>
<li>
<strong>Step 6a:</strong> <a href="http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/">Validating what the user has entered using IDataErrorInfo</a><br />
<br/><br />
<strong>Review:</strong> By implementing the IDataErrorInfo  interface we are able to do validation without throwing exceptions.
</li>
<p><br/></p>
<li>
<strong>Step 6b:</strong> <a href="http://www.arrangeactassert.com/using-inotifydataerrorinfo-for-validation-in-mvvm-with-silverlight/">Validating what the user has entered using INotifyDataErrorInfo<br />
</a><br />
<strong>Review:</strong> By implementing the INotifyDataErrorInfo interface we are able to do validation without throwing exceptions.
</li>
</ul>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/how-to-refactor-and-build-better-microsoft-silverlight-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
