Posted on 3/31/2009 10:06:17 PM by Justin Etheredge
Other parts in this series
In this fourth part of this series (which is a bit delayed due to my travels to MIX 09) I am going to discuss mocking multiple interfaces and doing callbacks in Moq 3. While these are not features that you are going to use very often, they are features that when you need them, it is often in situations where you have no other option.
Before we get to these two features, I want to really quickly touch on a previous feature that we have already looked at. On Twitter a little bit ago, there was a question about confirming that a method was not called on the mock. To check the number of calls:
mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Exactly(1));
We can use the same construct to make sure that the method was never called:
mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Never());
It is essentially the equivalent of saying “Times.Exactly(0)”, but it just looks much nicer, and provides a better error message. I just wanted to clear this up in case anyone else was wondering.
Mocking Multiple Interfaces
So now let’s look at mocking multiple interfaces. As we have already seen, if we want to create a mock of an interface then we can do it like this:
var mockFileWriter = new Mock<IFileWriter>();
But a situation that you can often get in is where a method requires a particular method, but then also expects the class to implement IDisposable. With some mocking frameworks this can be problematic. Thankfully Moq 3 provides us with an easy way to implement this by use of the “As” method on the mock itself. Some frameworks refer to this as a multi-mock:
var mockFileWriter = new Mock<IFileWriter>();
mockFileWriter.As<IDisposable>();
Now that our mock supports two interfaces, how do we create expectations and verifications on this mock? Well, in the call above, the “As” method returns a Mock<IDisposable"> which allows us to do setup and perform verification on it. We could either hold onto this mock, or if we wanted to later perform verification we could just call “As” again, since we can’t add an interface twice:
mockFileWriter.As<IDisposable>().Verify(d => d.Dispose());
Extremely powerful and very easy to work with!
Callbacks
Next we are going to look at callbacks, which are a feature in Moq that it is entirely possible that you’ll never use. They allow you to specify a chunk of code to be executed when a method is called. So, looking again at the “WriteLine” method above, we could record every invocation into a list:
var values = new List<string>();
mockFileWriter.Setup(fw => fw.WriteLine("1001,10.53")).Callback((string value) => values.Add(value));
Or we could ignore the parameter and just increment a count or something:
int count = 0;
mockFileWriter.Setup(fw => fw.WriteLine("1001,10.53")).Callback(() => count++);
But since Moq provides functionality in both of these areas for most of what you would want to do, there isn’t really too many different points at which you would need these tools. In fact, if you think you need to use “Callback” you should probably look a little harder to see if Moq can do what you want to do automatically.
Summary
We looked at how to guarantee that a method is never called on a mock. Then we saw how to implement multiple interfaces on a single mock and finally how to use callbacks in Moq. I hope that you found this information useful, and hopefully the next entry in this series will be up soon. In that entry we are going to discuss raising exceptions and events from Mocks.
Posted on 3/30/2009 11:01:48 PM by Justin Etheredge
Today on Twitter Pete Brown mentioned that he had put up a post about using lambdas to set events in Silverlight. It is a really clean pattern, and it is useful in most places that you need to set events (this is a stripped down version of the code that Pete posted on his blog):
public class Test
{
public void LoadPolicyDetail()
{
var client = new IvcDataServiceClient();
client.GetPolicyDetailCompleted += (s, e) =>
{
// Do something
};
client.GetPolicyDetailAsync();
}
}
In this code you can see that we are creating a client class and then assigning a statement lambda to the event. The code inside of the event isn’t really important, and so I just removed it. Then we call “GetPolicyDetailsAsync” which will make an asynchronous call which when it completes invokes the “GetPolicyDetailCompleted” event.
Will It Leak?
The question is, since the method leaves asynchronously whether or not there are any resources leaked or there is any chance of something being garbage collected too early since the client and lambda are both going out of scope as soon as the method exits.
In order to get an answer to this we are going to have to consider how the lambda in this method is going to be generated. Since this lambda isn’t leaving the scope of this method, the C# compiler is going to emit it as a private static method on the test class like this:
[CompilerGenerated]
private static void <LoadPolicyDetail>b__0(object s, EventArgsSpecial e)
{
}
So all we are really doing is assigning this static method to the event handler. Since we are assigning this static method to the event handler then it doesn’t really matter what happens to the current instance of this class…but hold that thought. Let’s look at the program which runs this code:
class Program
{
static void Main(string[] args)
{
var test = new Test();
test.LoadPolicyDetail();
Console.ReadLine();
}
}
So we create the Test object call the method on it, and then just wait until the user hits a button in order to exit the program. So as you can see the “test” class is going to be garbage collected right after the “LoadPolicyDetail” method is called, but since the event was on the static method it will still be called.
Now the client class is a bit different, it doesn’t get garbage collected. But how? Doesn’t it go out of scope when we leave the “LoadPolicyDetail” method? Let’s look at how we implemented that class:
public class IvcDataServiceClient
{
public event Action<Object, EventArgsSpecial> GetPolicyDetailCompleted;
public void GetPolicyDetailAsync()
{
ThreadPool.QueueUserWorkItem(_ =>
{
Thread.Sleep(5000);
GetPolicyDetailCompleted(this, new EventArgsSpecial());
Console.WriteLine("Event Finished");
});
}
}
So, yes, the variable goes out of scope, but a reference is still held to the class by the thread that was spun up in the thread pool. This is because if you notice this lambda is referencing the instance by using “this” and “GetPolicyDetailCompleted”, and so it is created as an instance method on the “IvcDataServiceClient” class. Aaaaaaaah. Are you lost yet?
In the end it kinda feels like you are trying to stitch together the compiler magic in your head just to see if something is going to be kept alive or not. But how can we tell if something has been garbage collected? If we have a reference to it, then we know it won’t be collected. I bet you were wondering where Heisenberg came into this!
WeakReference To The Rescue
Well, it is a good thing that the .NET Framework team saw fit to bless us with the WeakReference class. This wonderful little class allows us to get a reference to an object which is “weak”, meaning that you can hold a reference but it won’t be counted as a reference by the garbage collector. This class has a property on it called “IsAlive” which returns a boolean that says whether or not the instance had been garbage collected.
So how can we use this to our advantage? Well, we can get a weak reference to the class that we expect to be collected, and then force a garbage collection. If the class is collected, then we know that we don’t have a leak. So in this case we could do this:
public class Test
{
public WeakReference LoadPolicyDetail()
{
var client = new IvcDataServiceClient();
var weakReference = new WeakReference(client);
client.GetPolicyDetailCompleted += (s, e) =>
{
// Do something
};
client.GetPolicyDetailAsync();
return weakReference;
}
}
And so now we are going to return a weak reference to the client class, and in the calling program we can check this:
class Program
{
static void Main(string[] args)
{
var test = new Test();
WeakReference wr = test.LoadPolicyDetail();
GC.Collect();
Console.WriteLine(wr.IsAlive);
Console.ReadLine();
GC.Collect();
Console.WriteLine(wr.IsAlive);
Console.ReadLine();
}
}
We get the weak reference and then force a collection, then we check to see if the client is still alive. Which of course it is. Then we pause until the user hits enter. We can then wait for the event to finish and we will see the “Event Finished” message appear. If all went well then we can force another collection and then “IsAlive” should return false. In this case, it does, and we can now know that what we are doing will not leak memory. If we got a true back, then that would mean that even though the event finished and we have no more references to the objects, somehow the instance survived a garbage collection. Time to start looking into why that is happening. And when that happens, you might need the big guns like WinDbg and SOS.
Summary
WeakReference provides a fairly low level way of determining if something is leaking. It is also a way in which you can reference other classes without actually holding a strong references to them. This is actually quite useful in a number of different instances. I hope that you found this post interesting, and maybe even added another simple tool to your tool chest.
Posted on 3/29/2009 5:24:27 PM by Justin Etheredge
Stop the presses! Word just in is that I am speaking at DevLink this year. I am pretty excited about it. It’ll be my first time speaking at a conference this large (about 800 people) and so I am pretty pumped. I will be giving two sessions at DevLink (please excuse the rushed abstracts, I’m glad that they did):
Parallel Development in .NET 4.0
Parallel development is currently a major to pain to many developers. We have some tools currently which make threading a little less painful, but the parallel computing team at Microsoft is getting ready to give us quite a few more. From the Task Parallel Library, Parallel LINQ, parallel data structures, and parallel control structures, in the next version of Visual Studio we are going to inundated with new technologies to make parallel development more palatable. Come join us and learn about these libraries and how to leverage these libraries within your applications.
Digging Deep Into Expression Trees
If you are using C# 3.0 then you are probably using Linq. Linq is an amazing technology that has a lot going on under the covers. Linq expression trees are the key that has enabled Linq To Sql, Linq To Xml, and all of the other Linq To X tools. Come join us and learn what expression trees are, how they work, and how you can build/parse them. Then you will be able to better understand how you can leverage them within your application. We will also take a look at a few frameworks that use expression trees heavily and see how they are using them to make your life easier.
I think the two sessions are going to be awesome, and if you are interested in seeing the entire speaker list you can view them here. If you are interested in attending DevLink then registration opens on April 1st at DevLink.net. Hope to see you there!
Posted on 3/27/2009 12:01:44 AM by Justin Etheredge
If you are as much of a fan of the book “The Pragmatic Programmer” as I am, then you might remember the phase:
“Select” Isn’t Broken
You can find this nugget, along with others, on pragmatic press’ site. In the book though they go in further detail to lay out a story where a programmer was convinced that he had found a bug in the “select” Solaris API call. Obviously after wasted time, hilariousness, and much chicanery, the programmer was forced to analyze the problem and discovered that, alas, it was in his own code.
If this sounds familiar to you, then shame on you, but you may be sitting there saying “Pssssshhhhhaaaaaa, I always assume that my code is the problem. And then I fix that junk and release some killer builds.” And if you are saying that, then why are you speaking like that? But seriously, I applaud you for being so humble. It is good to look at your own work with a cautious eye, and sometimes it can keep you from getting seriously embarrassed.
As good as you may be about assuming that your code is always broken, are you just as good at assuming that it is your understanding that is broken? Are you just as good at looking at your own beliefs with a cautious eye? That may sound like a bizarre question, but think about it for a second. How many times have you come across a concept that looks extremely foreign to you and you say “Bah, there is no value in that. I don’t need it.” Then you find yourself 3 months down the road employing that same concept or tool and wondering how you ever lived without it. Sound familiar?
Let me just lay out a list of items, and you tell me how they are all related:
- Dependency Injection
- Immutability
- Closures
- Lambdas (and Anonymous Functions)
- GIT
- Continuous Integration
- ORMs
- Javascript
- Mocking
- Charlie The Unicorn (Shuuuuuuuuuuun)
Any ideas? Well, there are probably at least a few things in that list that you violently revolted against, or at least actively ignored, only to discover later on that they made your life better. So what was the problem? Well, we generally think we know better than everyone else… at least that is my theory.
So What Are You Trying To Get At?
Well, I am trying to say that there aren’t a billion developers out there singing the glories of GIT solely because it is the cool thing to do. Sure, about half of them probably are (or maybe three-quarters), but the rest really see value in the tool. In fact, I have seen two converts over to Git in just the past week or so, and one of them, Chris Allport, made me even more impressed with it. I thought I saw value, but I wasn’t even fully there yet!
So, next time you see a huge number of developers selecting a tool, technology, or concept; do some serious research into it. Go find someone who loves the tool and ask them to sell you on it. You might find that you’re just being a grumpy old geezer who doesn’t want to change his/her ways. Sure those crazy kids won’t get off your lawn, but maybe you could at least listen to their drunken hippy talk for a few minutes. They just might have something to tell you.
Now I know that I’m going to probably catch a lot of flack from people who will say that I am encouraging you to just go along with the crowd, and to a certain extent I am. Guilty. But it is survival of the fittest out there, and we need to at least ask the community why they find value in the tools that we just don’t get. You may be pleasantly surprised. (Or you may find a corporate backed tool with a great marketing campaign)
Posted on 3/23/2009 2:30:17 PM by Justin Etheredge
I'm sure that there are about a million MIX wrap-up articles out there, but this one is going to be filled with mystery and intrigue...
The first day keynote was actually quite interesting, with Bill Buxton leading up the group with a very interesting talk on interactive design. He gave a very cool presentation on why user experience matters and gave numbers from within Microsoft showing that they have been hiring user experience professionals at an even faster rate than developers. He even cracked a few jokes about the fact that, yes, Microsoft actually does employ some user experience people.
The Gu's Keynote
After Bill Buxton finished up Scott Guthrie did his usual MIX talk, chock full of announcements of new technologies. The focus was obviously very heavily weighted on Silverlight 3, being that this is the technology that Microsoft is mostly heavily focused on commercially right now. In this keynote there were a handful of big announcements that really caught my eye, some were surprising, others predictable:
Expression Web 3 is now available, and they did introduce some interesting features around css styling and validation.
SuperPreview is part of Expression Web and now provides an official way to test IE6, 7, and 8 all within the same tool. It will also pull in local copies of Opera, Firefox, Safari, Chrome, etc... and on top of that, Microsoft is setting up a cloud of servers that will feed down screenshots of browsers that you can't install locally. Even those that run on OS-X. You can then pull up images and web-pages of multiple browsers side by side, and then even overlay them in onion-skin mode. You can also click on elements in one browser and see where the element rendered in the other browser and where it was supposed to be. It'll even let you view the html and css for each preview so that you can see what is causing the rendering to be incorrect. It looks like a great tool for anyone who is going to be doing lots of html/css.
ASP.NET MVC 1.0 Shipped - They announced that ASP.NET MVC 1.0 started officially shipping, which is good news since it has been a long time in the making. Judging from the fact that it was second only to Silverlight in terms of the number of talks on it, I think it is safe to say that Microsoft is taking this technology very seriously.
Microsoft Web Platform Installer 2 Beta - Microsoft's Web Platform installer is a tool for getting up and running with many of Microsoft's tools as well as Third party tools on a web server. The big advancement in version 2 is the inclusion of third party applications which can be integrated into it. This means that you can go in and install Wordpress, BlogEngine.net, DotNetNuke, etc... all by clicking one button and it will even install dependencies. It looks like this is also going to be a very important tool going forward.
Windows Azure Enhancements - They announced that they are going to start supporting Fast-CGI and Full-Trust for apps running in the cloud. They also announced the Sql Data Services are going to be moving back to a more traditional relational database instead of the non-schematized direction that it was currently going. I will wait to see if this hinders them in their efforts to scale this new platform.
Silverlight 3 - This was the focus of much of Scott's keynote and they had a slew of announcements. First they are going to support cross platform hardware acceleration. Allowed for some interesting effects, it'll be neat to see how people use and abuse this. Silverlight 3 will support standard video codecs like H.264 and it will allow developers to write their own codecs in managed code which can be deployed with their own application. They are launching an IIS plug-in that will work with Silverlight called IIS media services. It is going to provide a huge number of features for video streaming, caching, etc.... They also announced that they are going to include a huge number of controls in Silverlight 3 in order to make the developer experience much nicer.
The biggest announcement on this front that I saw was that Silverlight 3 will be able to run out of the browser by default. This will allow what they called "data snacking applications" (man I love that phrase!). Essentially Silverlight will now be a real competitor to Adobe AIR. The applications will have program menu icons and will receive updates automatically when they are run. It looks like an even more simple way to distribute apps than ClickOnce.
Expression Blend is going to have a new tool in it called SketchFlow which looked like a neat tool for designing interfaces. It basically allows you to drag and drop controls onto a form and graphically design the flow of an application. You can then render hand-drawn looking controls which can respond to user input to allow page transitions, animations, etc... Then they are going to have a client application that will allow users to open and view these mocks. Overall it looks like a pretty neat tool for creating simple mock ups of Silverlight or Web Apps.
And finally, from the "not sure where that came from department" Microsoft announced that they are releasing plugins for Eclipse to allow you to do Silverlight development on both Windows and Mac OSX. Kinda interesting, but I'm not sure who is going to be using them. Only time will tell I guess.
Dean Hachamovich's Keynote
Okay, so Internet Explorer 8 shipped. Woohoo. Man I couldn't care less. That may sound harsh, but honestly until they force IE6 users to upgrade their browsers they could release a browser that printed free money whenever I browsed to a new page and I'm still not sure that it would faze me very much. It does look like they are doing a few neat things in IE8 with web slices and whatnot, but they totally dropped the ball by not developing a faster javascript engine. They keep saying IE8 is faster than the other browsers, but the only speed problems I generally run into are sites with tons of javascript. IE8 sadly won't change this experience very much. So, you can say that I'm not big on IE8, I hope that Microsoft can impress me with IE9.
Conference Sessions
There were quite a few interesting topics, but I'll just say that the events I attended were very much skewed toward ASP.NET MVC which is the Microsoft web technology that I am most excited about. Here are the talks that I attended:
Microsoft ASP.NET 4.0 : What's Next? - There are a few neat little things coming in ASP.NET 4.0, but it seems like a lot is around fixing tiny issues like fixing control IDs and making rendering on some controls more palatable. I think ASP.NET WebForms is now a mature baked platform with innovation mostly coming in the surrounding libraries such as Dynamic Data and the like.
Web Development Using Microsoft Visual Studio: Now and in the Future - Nice look at the enhancements in Visual Studio 2010 that are coming down the pipe for web development.
Windows Azure Storage - Neat look at the non-relational storage options coming for Windows Azure.
Choosing between ASP.NET Web Forms and MVC - Great talk focused on the fact that WebForms and MVC are going to both be around for a long time.
File|New -> Company: Creating NerdDinner.com with Microsoft ASP.NET Model View Controller - Real world look at building an ASP.NET MVC website.
Microsoft ASP.NET Model View Controller (MVC): Ninja on Fire Black Belt Tips - Awesome look at some advanced tips and techniques for building ASP.NET MVC websites.
There's a Little Scripter in All of Us: Building a Web App for the Masses - Cool talk on how over-architecting our applications can actually hurt their adoption. Simple applications (mainly PHP ones) have dominated the market for several reasons, the first of which is easy setup and config.
All of the talks that I attended I thought were excellent, but not really surprisingly the best content I got from the weekend was through my many random discussions with all of the wonderful people that I met (well, at least in person). The conversations with some insanely smart people are the entire reason I go to these events, and why I look forward to going back each and every year.
Well, I hope that this wrap-up didn't bore you too much, the conference was an all around excellent time!