Brendan Enrick

Daily Software Development

Making Text Clickable in Silverlight for Windows Phone 7

I’ve seen a lot of snippets of code online where people are trying to make text clickable in Windows Phone 7, and plenty of them are using the OnMouseLeftButtonDown event to do it. Well to put this lightly, this is not the best way of handling a click in the Windows Phone 7 environment. The reason is that we have to put the “left button” down in order to scroll. The “left button” is our finger, so if we try to scroll down and press our finger on the text we will be activating the event by mistake.

In order to resolve this we need to have the click event. Well, the click event is on the Button not on the TextBlock. In this example I will be using the MVVM Light toolkit and showing how I can wire up a Click event to a command on my ViewModel.

This example is a DataTemplate being used to display a list of colors each one as a bound item in a ListBox. I will be setting the text of each item to be the name of the color and I will be handling the click event by binding it to a command on my ViewModel the command will take in the color’s ID as a parameter. Notice that since I am in a DataTemplate I have to access the ViewModel for this view by accessing my view. While in the DataTemplate my current DataContext is the Color item I am binding in the list. Read more about accessing the ViewModel from a DataTemplate.

<DataTemplate x:Key="colorListTemplate">
<Grid>
<Button>
<Button.Template>
<ControlTemplate>
<TextBlock Text="{Binding Name}" FontSize="64" />
</ControlTemplate>
</Button.Template>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand
Command="{Binding DataContext.PickColor, ElementName=TheView}"
CommandParameter="{Binding Path=ID}"/>
</i:EventTrigger>
<i:Interaction.Triggers>
</Button>
</Grid>
</DataTemplate>

Notice that I set the ContentTemplate of the Button. This means that I am telling the control to not display how it would normally display and instead to display how I want it to. I do this so that I can display text as normal so that it looks like a have a regular list of items, and I am able to make this text handle the event when someone clicks on it. Keep in mind that a click and a scroll are two different operations in the Windows Phone, so non one is going to accidentally click on my item when they are trying to scroll. If I had done this with a MouseLeftButtonDown event as I’ve seen shown in the past it will cause the command to happen when someone is trying to scroll the list on the phone.
 
Remember that a button can look like anything in Silverlight. You have a ContentTemplate you can define for the button, so you have the power to always have a Click event. So if you need to make something clickable, make a button and put your control as the template for the button.

Unit Testing With a Base Test Class

Writing good code that can be trusted to work means unit testing your code. In order to effectively maintain these tests you will need to follow the same principles you would with any other code. This of course means that you extract logic to achieve code reuse, name methods and objects clearly, use composition, and use inheritance.

In this post I am going to show how you can get some code reuse when you’re following another good testing practice. You should keep things well abstracted. I like to keep my tests in folders and I keep test classes in those folders. I do this so that I can have each test class be small and only be testing one things. By doing this I make my test classes a lot cleaner and easier to work with. This means, however, that if I do not extract some of the duplication I could be creating more maintenance work later.

On way that I keep my tests more maintainable is to keep duplicated logic for initialization in base classes. When I am testing methods of a certain class, I will keep a folder of those tests and have a class for each area of the code I want to test. This lets me keep some of the initialization logic in a base class. Many of the test classes will need an instance of the object being tested, so I can put logic in the base class to initialize my mock objects pass them to the constructor of the class I will be testing.

Setting up a base class is easy. The following examples show how to set up a base test class in MSTest and NUnit.

Setting Up a Base Test Class with MSTest

[TestClass]
public class BaseTestClass
{
public BaseTestClass()
{
Console.WriteLine("BaseTestClass.Ctor()");
}

[TestInitialize]
public void BaseTestInitialize()
{
Console.WriteLine("BaseTestClass.BaseTestInitialize()");
}

[TestCleanup]
public void BaseTestCleanup()
{
Console.WriteLine("BaseTestClass.BaseTestCleanup()");
}
}

[TestClass]
public class ConcreteTestClass :BaseTestClass
{
public ConcreteTestClass()
{
Console.WriteLine("ConcreteTestClass.Ctor()");
}

[TestInitialize]
public void MyTestInitialize()
{
Console.WriteLine("ConcreteTestClass.MyTestInitialize()");
}

[TestCleanup]
public void MyTestCleanup()
{
Console.WriteLine("ConcreteTestClass.MyTestCleanup()");
}


[TestMethod]
public void TestMethod1()
{
Console.WriteLine("ConcreteTestClass.TestMethod1()");
}

[TestMethod]
public void TestMethod2()
{
Console.WriteLine("ConcreteTestClass.TestMethod2()");
}
}

MSTestBaseClassTestOutput

BaseTestSessionOutput

Setting Up a Base Test Class using NUnit

[TestFixture]
public class BaseTestClass
{
public BaseTestClass()
{
Console.WriteLine("BaseTestClass.Ctor()");
}

[SetUp]
public void BaseSetUp()
{
Console.WriteLine("BaseTestClass.SetUp()");
}

[TearDown]
public void BaseTearDown()
{
Console.WriteLine("BaseTestClass.TearDown()");
}
}

[TestFixture]
public class ConcreteTestClass : BaseTestClass
{
public ConcreteTestClass()
{
Console.WriteLine("ConcreteTestClass.Ctor()");
}

[SetUp]
public void SetUp()
{
Console.WriteLine("ConcreteTestClass.SetUp()");
}

[TearDown]
public void TearDown()
{
Console.WriteLine("ConcreteTestClass.TearDown()");
}


[Test]
public void TestMethod1()
{
Console.WriteLine("ConcreteTestClass.TestMethod1()");
}

[Test]
public void TestMethod2()
{
Console.WriteLine("ConcreteTestClass.TestMethod2()");
}
}

NUnitBaseClassTestOutput

BaseTestSessionOutput

Notice in these examples how the Base method setups happen first and then the local class ones. This allows you to depend on the code happening on the base class first. Then when you tear everything down you will first clear up things in the local method and then the base class will run.

Make sure you follow this example by having different names for the base methods so they don’t collide with the local names. This lets you have them both run without one having to call the other. If the names match you will either be overriding the base or hiding it, but they will not both run.

Accessing the ViewModel Inside a DataTemplate in Silverlight

I’ve been doing a lot of Windows Phone 7 Development, which means that I have also been doing a lot of Silveright development, so here is a tip for accessing your ViewModel when you’re in a DataTemplate.

In Silveright, DataTemplates are used when binding data to a control. For example if I want to list users I will define the DataTemplate, which will define the XAML that will be bound to for each of the users in the list. When I do this, the data context for the DataTemplate is my user and no longer the VM. I have a few options here, I can modify the user to have what I need, I can access some global class which has what I need or can access my ViewModel, or I could do what I prefer doing, which is just to name my View.

I give my name a view, and I can then create a binding which accesses an element by name instead of by using its current data context. To do this I can just name my View like this.

<Views:ViewBase
...
x:Name="TheView"
DataContext="{Binding BarViewModel, Source={StaticResource SL}}">

 

Then in my binding I can access it using the ElementName property like this. This example is wiring up a Click event using MVVM Light Toolkit’s EventToCommand.

<Custom:Interaction.Triggers>
<Custom:EventTrigger EventName="Click">
<Command:EventToCommand
Command="{Binding DataContext.DoSomething, ElementName=TheView}"
CommandParameter="{Binding}" />
</Custom:EventTrigger>
</Custom:Interaction.Triggers>

 
This allows me to access the commands on my ViewModel while I am using a DataTemplate. Without doing the “ElementName=TheView”, I would not easily be able to access the command from my ViewModel. I would only be able to access the commands from the User object.

Commenting Methods Using Liskov Substitution Principle

After reading the title of this post, some people might be wondering why I am advocating commenting at all, because I’ve spoken out against commenting code before. My team and I were recently reading through some code that was littered with comments, and I do mean littered. There were tons, they were mostly useless statements like “//run”, and I swear there were more of them than actual code. This of course sparked some preaching to our choir about how comments in code are often less-than-useful. We of course settled on the time when they are useful being the XML comments on methods, but those should also only be used when writing public libraries where others will not have access to the source code or unit tests.

Comments on those methods are useful since tons of people will use the method and will not be able to see the guts of the method or examples of how to use it. This makes the comments useful. However, they need to be kept up-to-date (difficult task).

So what does all of this have to do with Listkov Substitution? Well, the principle basically says that all of the classes which implement an interface (or inherit) need to work the same way. There should be no difference between implementations as far as the calling code is concerned. In fact it is really about making sure that we maintain a consistent abstraction. If we say something about the interface it must hold true for the implementation. This means that any comments about the interface must hold true for every implementation.

We were wondering if the comments needed to be on each of the concrete classes or if we could just put it on the interface, and this was confirmed for me by Ben Heimann who quickly made an interface and a concrete class. Then he commented just the interface method and not the concrete one. We of course knew we would see the comment when using the interface, but we also saw it when we were dealing with the concrete class. Great work Visual Studio 2010! This means we don’t have to duplicate and also signals that we should follow LSP.

The concern is that if you have the comment in both places you would have to update them both. This also means that they could differ, and if they ever needed to intentionally differ then it means that we are violating LSP. Having the comment in the one place should at least point to the fact that we should maintain the same behavior for the calling code in all implementations of our interfaces.

One Year of Hudson Software Craftsmanship

HudsonSC Over a year ago, Steve Smith, Rich Henning, and I met to plan our first meeting of the Hudson Software Craftsmanship group. We decided on a format for the group, planned how we were going to organize the events, and came up with some topics to discuss for our first meeting since we didn’t expect people to arrive for the first meeting with lightning talks and discussion topics prepared. We also came up with the time for the meeting which would be the third Wednesday of each month, and we set up the first meeting of the group.

Since that point we have been very impressed with the core group of members who have stepped up to take part in the group and really help improve their own and others’ craft. We put on a local Software Engineering 101 event in Cleveland where four HudsonSC members, @ardalis, @brendoneus, @kevinkuebler, and @ropog, took the time to discuss some topics and run the group in exercising their skills. The class was a great success and I, as a member of HudsonSC was proud to be a part of it.

The group is always looking for new members, so if you’re in the Northeast Ohio area, please drive to Hudson, Ohio once a month on the third Wednesday of the month. We prefer if you sign up, but you can just show up and we will not turn you away. Everyone is welcome.

Sign up for the August 2010 event now!

Look for more information on the group on the Hudson Software Craftsmanship site.

Fresh opinions, ideas, and technology are always welcome.

Thank you for a great year, HudsonSC!

Using Dynamic Typing When an Interface was Needed

Interfaces and base classes allow us a great deal of power in object oriented programming. We are able to accept a base type or interface and be given an implementation or an inheritor and continue working correctly. What if, however, we need to be able to accept more than one type, which have the same methods or properties, but to not share an interface or base class? Often the best answer is to add a common interface to these, so that the shared behavior is defined. In most of my cases when I need to do something like this, it is because I don’t have the source code for one or more of the classes.

Our answer in this case is the dynamic types which we added in to C# 4.0. In this new revision of the language, we are able to declare an object deferring its type until runtime. We will define how we will use the object now, and at runtime our code will attempt to use that object.

The following is some example code showing how to use the dynamic keyword to use two classes interchangeably:

class Program
{
public static List<DateTime>
Dates = new List<DateTime>();

static void Main(string[] args)
{
var someClass = new SomeClass(DateTime.Now);
GetEventDate(someClass);
var otherClass = new OtherClass(DateTime.Now);
GetEventDate(otherClass);

var values = Dates.Select(d => d.ToShortDateString());
Console.WriteLine(string.Join("---", values));
}

private static void GetEventDate(dynamic objectWithDate)
{
Dates.Add(objectWithDate.Date);
}
}

public class SomeClass
{
public DateTime Date { get; set; }

public SomeClass(DateTime date)
{
Date = date;
}
}

public class OtherClass
{
public DateTime Date { get; set; }

public OtherClass(DateTime date)
{
Date = date;
}
}

So in this example, if we say that I didn’t have access to OtherClass in order to give it some interface, using the dynamic would allow me to get around this and use a convention-based approach to development. When the alternative is some cluttered approach, I am always in favor of simplifying the readability and usability of my source code. Now there is less of a reason to complain that a certain class from a library or generated code doesn’t implement an interface. (There is still reason, but at least we can avoid some of the issues at play.)

Combining Object Oriented Principles, Practices, and Patterns

Now that the dust has settled from the recent Software Engineering 101 event we put on in Cleveland, I figured I would repost some of the material I talked about. This means some of connections that I vocalized and supplement the material from the slides I used for Software Engineering 101.

Object Oriented Principles, Practices, and Patterns

My first talk of the day was on Object Oriented Principles, Practices, and Patterns in which I start by discussing some common principles of object oriented programming: abstraction, encapsulation, inheritance, polymorphism, and I added composition in for good measure, which of course isn’t on its own a principle, but I feel deserves to be mentioned as its own entity at that point.

I covered an assortment of good practices for software developers to follow. Since Steve Smith was following my talk with one on SOLID, so I didn’t take the opportunity to discuss the Open/Closed Principle, which states that your code should be open to extension and closed to modification. This means that you can add to the behavior of your code by adding new code and not modifying what you already have.

In my patterns section I covered two of my favorite design patterns: the Strategy Pattern and the Template Method Pattern. These two are great for discussing with people. They’re very similar yet very different; one encapsulates the structure of an algorithm and allows for modification of the details of the steps while the other focuses on allowing for different algorithms to be used interchangeably. Each uses polymorphism, abstraction, encapsulation, and inheritance. They’re simple to explain and demonstrate, and they’re also very powerful. This makes them great examples.

 

Combining Everything

When we combine these principles and some design patterns we can achieve some great things. The strategy pattern is one of my favorite patterns, because it is very useful and improves maintainability greatly. I use it often. It uses, abstraction, encapsulation, composition, polymorphism, and either inheritance or interface implementation. On top of that it also helps follow the Open/Closed Principle, increasing the ease for changing the behavior of an application when the requirements change.

In my talk I was asked a great question, “if I don’t know design patterns, how will I know what I don’t know.” In other words, how can you possibly select the correct design problem to solve a problem. I recommended reading learning plenty just so you’ll be more prepared. There are plenty of books, and you don’t always need “the best” solution. Usually a good solution to the problem is enough. Steve Smith chimed in with a great answer though, he suggested practicing coding katas, which will often solve problems using design patterns or at least good, worthwhile practices.

Here be Books

Steve Smith tagged me with his books post last week, which was his response to Sadukie’s post on books. I will of course keep this modern chain letter going. Here be dragons books.

Currently and just finished reading:  I just visited my local library and picked up a copy of Planet of Twilight, which is the third book in a Star Wars trilogy. I’ve recently finished reading the second book of the same trilogy, Darksaber. Although I don’t like the name “Darksaber,” it is a well-written, entertaining book. My wife tells me, however, that I will not find the same to be true of Planet of Twilight.

On the technical side of things I’ve just started reading Agile Principles, Patterns, and Practices in C#, which lines up very well with a lot of the techniques I use in my day-to-day development, and I will be adding it to my required reading list shortly.

I plan to be reading a little bit less right now as I have been playing StarCraft 2. Let me know if you want to play a match.

From what medium I like my books: I haven’t ever gotten any of the digital readers, but I have read PDFs on my computer and on my phone. I’ve also used some of the book reader applications for my phone, and I tend to prefer reading books on pages printed on dead trees. Perhaps it’s just that I’ve not yet tried a good enough interface for digital reading. I intend to try one eventually.

Some book recommendations: If you’re interested in reading any Star Wars novels I would recommend that you begin with either the Thrawn trilogy by Timothy Zhan: Heir to the Empire, Dark Force Rising, and The Last Command or with the Michael Stackpole’s X-wing series: Rogue Squadron, Wedge's Gamble, The Krytos Trap, and The Bacta War.

If you’re interested in reading some fantasy stories I would recommend starting the Drizzt books starting with the first trilogy written about him, The Icewind Dale trilogy: The Crystal Shard, Streams of Silver, and The Halfling's Gem.

For technical books, please check my not-so-up-to-date list of recommended software development books.

Tag, You're Up Next...

What are you reading?

Scott Forsyth

Ben Heimann

Andy Vanek

Jeffrey Palermo

Chris Wagner

The Art of Agile Development

A while back I started reading a copy of the Art of Agile Development, which is a great book. I was reading the book for more than one reason. I obviously wanted to learn more about how others approach agile development, but I was also looking for a book to recommend to other developers as well as to businesses.

One of the biggest troubles with agile development is the initial resistance to agile development shown by both developers as well as businesses. I am even talking about the developers and businesses who have already bought in to the idea that agile can be a good thing. People agree with the overall idea of agile, when it forces them to change their existing practices many will put up at least passive resistance.

This book is my new answer to some of that. The book is written with a good amount of details and examples that will backup the information it provides about agile development, and it does so in such a way that both development teams and those working with the teams can have a better understanding of how agile development can work.

The Art of Agile Development is loaded with information about real-world problems faced by software development teams, and how agile development worked in these situations. The book covers these examples while describing the specific steps the author recommends for performing agile software development.

I don’t follow the same practices in all cases as what the book describes. I don’t manage stories in the same way, and I don’t estimate and track the time on that work the same way. This doesn’t matter, because the book is really providing information on how agile can work and how it has worked in the past. Each team needs to find how best they can apply agile and work with them. I use a mix of Agile, Scrum, XP, and anything else that the team thinks will make us work better. As long as the process helps us deliver better software we’re all about it.

If you’re considering agile or trying to convince other people to consider agile, I would recommend reading this book and passing it along to others when you’re done reading it.

Full disclosure: I did not pay for this book. The copy of the book that I read was sent to me by the publisher.

Making Web Requests in Medium Trust

Trust levels in web development can be a pain in the rear. As a developer, I tend to not like them, because when they’re important it means that my options are being restricted. I am often required to perform extra work to complete the same tasks I would be performing elsewhere.

Medium trust is the trust level commonly used by web hosting companies, because it gives them a good balance of security and options. Ideally, as a programmer I can work in full trust, which allows me to do pretty much anything I want. That is, however, not at all what shared hosting requires. They need some extra added security.

Generally we develop for medium trust when we are either on a medium trust hoster or are working on a program which could be hosted in many places (including shared hosting).

For a project on which I am currently working, we needed to bypass some restrictions of medium trust to allow us to make an external request to a web service on another domain. Doing this will cause a security exception at run time. Keep in mind that the trust level can be violated when the site compiles, because certain things cannot be used at all in medium trust. In this case, it is our external service which caused the issue. I believe you could also have an issue if you’re running a web farm.

So how do we get around it?

We need to set up our trust element in the web.config file and hope that the hosting company is not overriding the use of this work-around. If the hoster is blocking this trick then you will want to see if you can resolve the issue using proxies. Some hosting companies will work with you to get your application running as long as it is not a security risk for them.

The key is the “originUrl” property of the trust element. We need to set that using a regular expression to define which URL we want to use. You should try to be more specific with the regular expression, but “.*” is still OK. That one will basically say any combination of any characters is OK. If we want to be more specific we might say that since our web service calls are all on the same domain we could use something like this “http://www.mywebservicedomain.com/.*”, and this would allow anything on that site.

<trust level="Medium" originUrl=".*" />
<!-- or this -->
<trust level="Medium" originUrl="http://mywebservicedomain.com/.*" />

If you need it, you can use this Regular Expression Cheat Sheet and this Regular Expression Tester.