What needs to be done to make DynamicProxy work in Silverlight?

.NET CLR to Silverlight CLRSome time ago I sort of complained there's no Mocking Framework available for Silverlight. This has a lot to do with the not being available Castle's DynamicProxy for Silverlight. So I did some analyzing on DynamicProxy if it's possible to make it work under Silverlight.

The Castle.Core project

I did some analyzing by just counting the error's. It's about 130 errors that needs to be solved. Most of those errors are the usage of:

  • Serializable
  • MarshalByRefObject
  • ArrayList
  • Hashtable
  • ReadOnlyCollectionBase

I think that some of those error's that have to do with the collections can be solved like the missing classes: ArrayList, Hashtable and ReadOnlyCollectionBase.

I'm not sure about things like Serializable and MarshalRefByObject. I don't think we can solve them, they probably need to be omitted, but will this break basic features of the Castle Core?

The Castle.DynamicProxy project

The Castle.DynamicProxy project has a lot more errors that occur, around 210. Although while navigating through the source code I found out that nothing in the namespace Castle.DynamicProxy.Generators.Emitters needs to be changed. So does this say that Reflection.Emit has enough to do everything needed for the Mocking frameworks? Most of the errors are in the usage of:

  • Serializable
  • ISerializable
  • SerializationInfo
  • StreamingContext
  • MashalByRefObject
  • Hashtable
  • ArrayList
  • CollectionBase
  • ReaderWriterLock
  • FormatterService

Again some of those usages can be rewritten, but the things about serialization probably won't and what about the ReaderWriterLock and the FormatterService? Those are very internally implemented classes. Maybe it's possible to recode things to work without ReaderWriterLock and the FormatterService.

Conclusion

So there needs to be changed a lot in each of the DynamicProxy libraries about 340 lines. That's a lot I would guess. But what if we would solve all these incompatible lines by removing them sort of? I'm afraid this would leave DynamicProxy sort of handicapped. Maybe it's too much so there won't be any mocking frameworks that can make use of the handicapped DynamicProxy. Maybe it's because I've got too little knowledge on the inner workings of DynamicProxy and mocking frameworks like Moq and Rhino Mocks.

I hope somebody with a lot of knowledge can tell if things like Serializable, MarshalByRefObject and... are really necessary. Maybe the founder of the Castle Project, Hamilton Verissimo can help out.

Using Function Pointers a la EventHandler instead of return types

I did show it in my fourth article about Silverlight Networking, using a functionpointer in a call instead of a return type. This was to get the JavascriptWebResponse back asynchronous.

Working with the Silverlight Networking stack is only possible asynchronously. So we need to provide a callback function that get's called after execution. All the Silverlight examples I've seen have this callback function in the User Interface. But what about all the classes that have their own responsibility that normally live in between the User Interface and the actual call to the Networking stack? I'm sure I don't want to call the Networking stack right from the UI. I normally have at least one class between the UI and the Network call that does some transformation, preparation and other things. Let's have a solution that I designed for Silverlight but also works within the full CLR.

The Example Situation

For this example I was working on a simple Delicious application that only shows the Tags that are within your Delicious account. I do have two responsibilities that are covered inside the Delicious application, namely the compilation of the JavascriptWebRequest (IDeliciousConnector) and the transformation of a xml-based string to real Tag objects (IDeliciousService). I won't cover the the IWebRequestExecutor

The situation with return types

When we convert the example situation to a UML Sequence Diagram we get something like the following diagram.

Sequence Diagram with Return Types

 

The implementation with end-of-call function pointers

First of all I created the generic AsyncEventArgs class. It's very easy and only has one property called Result that you can be typed exactly the same as you would normally type the return type. The looks of AsyncEventArgs is as follows.

1 public class AsyncEventArgs<T> : EventArgs 2 { 3 public T Result { get; set; } 4 }

Easy isn't it? So instead of specifying a return type we now make every method of type void. And we add a callBack parameter to the method that's an AsyncEventArgs EventHandler of the return type. At the end of the execution we call the callBack function with the typed AsyncEventArgs parameter.  This results in the following Sequence Diagram, no return messages but just only message calls. In effect the callBack is a function pointer parameter so the IDeliciousConnector doesn't really know about the IDeliciousService, but it sort of looks like the diagram.

Sequence Diagram with end-of-call function pointers

The implementation of the interface is not that different, no voids anymore as you can see and a lot of callBack function pointers.

1 public interface IDeliciousService 2 { 3 void GetTags(EventHandler<AsyncEventArgs<IList<Tag>>> callBack); 4 } 5 6 public interface IDeliciousConnector 7 { 8 void GetTags(EventHandler<AsyncEventArgs<string>> callBack); 9 } 10 11 public interface IWebRequestExecutor 12 { 13 void Execute(JavascriptWebRequest request, 14 EventHandler<JavascriptResponseEventArgs> functionToCallOnResponse); 15 } 16

Let's do some implementation.

Time for the method implementation

For the implementation I make much use of anonymous methods. As a start the implementation of IDeliciousConnector.GetTags. I started with a call to the webRequestExecutor which also expects a function parameter. I expect the WebResponse to be part of the eventArgs so if everything goes well I will be calling my callBack with only the WebResponse.Body as string in lines 16-18.

1 public void GetTags(EventHandler<AsyncEventArgs<string>> callBack) 2 { 3 var webRequest = new JavascriptWebRequest(); 4 //Some construction of the webRequest 5 webRequestExecutor.Execute( 6 webRequest, 7 (sender, eventArgs) => 8 { 9 if (eventArgs.WebResponse == null) 10 throw new Exception("Something went wrong. No WebResponse was available."); 11 if (eventArgs.WebResponse.StatusCode != "200") 12 throw new Exception( 13 string.Format("Expected statuscode 200 but was actually {0}", 14 eventArgs.WebResponse.StatusCode)); 15 if (callBack != null) 16 callBack(this, 17 new AsyncEventArgs<string> 18 {Result = eventArgs.WebResponse.Body}); 19 }); 20 }

Time for the implementation of the IDeliciousService.GetTags which will "return" a list of Tags. I used Linq2Xml for translating the Xml inside the string to a list of objects, see lines 7-16. And at the end I call the callBack function with the list of tags as result property in line 18.

1 public void GetTags(EventHandler<AsyncEventArgs<IList<Tag>>> callBack) 2 { 3 deliciousConnector.GetTags( 4 (sender, eventargs) => 5 { 6 string tagsXml = eventargs.Result; 7 XElement tagsElement = XElement.Load(new StringReader(tagsXml)); 8 IEnumerable<Tag> tags = 9 from tagElement in tagsElement.Descendants() 10 select new Tag 11 { 12 Count = 13 Convert.ToInt32( 14 tagElement.Attribute("count").Value), 15 Name = tagElement.Attribute("tag").Value 16 }; 17 if(callBack!=null) 18 callBack(this, new AsyncEventArgs<IList<Tag>> {Result = tags.ToList()}); 19 }); 20 }

I think this implementation is pretty clean, because almost everything happens inside of the anonymous method. There isn't very much of magic glue, only an anonymous method with a generic AsyncEventArgs object. But it's also important to test these kind of code. Let's go over to the testing.

How to test this kind of code?

In the situation when we have just a return type we can easily assert if it's the way we like it. But in the situation of async the Test method must be instructed to wait for the result to be available before testing the result. So the following code won't work most of the time.

1 [Test] 2 public void ExpectReturnOf8TagsWrong() 3 { 4 IDeliciousService sut = SUT(); 5 IList<Tag> tags = null; 6 sut.GetTags((sender, eventargs) => 7 { 8 tags = eventargs.Result; 9 }); 10 Assert.AreEqual(8, tags.Count); 11 }

A better implementation will be by using a waitHandle, which will work.

1 [Test] 2 public void ExpectReturnOf8TagsGood() 3 { 4 IDeliciousService sut = SUT(); 5 IList<Tag> tags = null; 6 var waitHandle = new ManualResetEvent(false); 7 sut.GetTags((sender, eventargs) => 8 { 9 tags = eventargs.Result; 10 waitHandle.Set(); 11 }); 12 waitHandle.WaitOne(); 13 Assert.AreEqual(8, tags.Count); 14 }

I hope everyone thinks this article to be interesting. If anyone does have something to add I'd like to know. And don't have any license for a real UML tool so I can't help there are watermarks all over the images.

Thinking about Silverlight and Mocking

There are quite some Mocking frameworks available. But sadly no one is ported to Silverlight, yet. I know about the porting of NUnit to Silverlight, but while working on Unit tests for the "Silverlight Networking through Javascript" library I found out there's no Mocking framework yet to support the Silverlight runtime.

I would like to see some support for Silverlight from either Moq or Rhino Mocks. That's because I like the way those Mocking frameworks work. I think they both make use of Castle's DynamicProxy, so that's another thing that first needs to become Silverlight enabled.

I'm sure more people thought about Mocking in a Silverlight runtime but didn't find a solution too. I'm interested if anyone started to port one of the above Mocking frameworks to Silverlight. I'm not even totally sure if it's possible but at least a part of Reflection.Emit exists.

What are anyone's thoughts about Mocking in Silverlight?

Book review: Test Driven by Lasse Koskela

Some time ago I did the technical review of the Manning Book Test Driven by Lasse Koskela. The book is available since October 10th.

The book is devided in three rough parts: Part 1, A TDD primer; Part 2,  Applying TDD to specific technologies; Part 3, Building products with acceptance TDD.

Part 1, A TDD primer: This part is about Testing in general and covers refactoring and patterns as well. Everything is written with Test Driven Development in mind. So don't expect all possible refactorings and patterns covered here.

Part 2, Applying TDD to specific technologies: This part covers testing on specific technologies. Where the first part can help people start testing, the second part will help people continue testing even if the more complicated tests need to be written. Specially complex testing on Web components, data access, etc.

Part 3, Building products with acceptance TDD: The last part covers more on acceptance testing. I haven't got any experience with automated acceptance testing but this part covers it quite well.

Although this book has some influence from the Java world almost everything can be applied within other technology worlds as well, like .NET, Ruby and PHP. I like this book and will use it every once in a while to keep myself focused.

Very good book about PHP: PHP in Action by Dagfinn Reiersol ea

Some time ago I did the technical proofreading of the Manning book PHP in Action by Dagfinn Reiersol. The book is available since the end of June. During the technical proofreading and even before this during the normal review, I began to really like this book. It's about building PHP applications, but doesn't stop after "Hello, world!". Not it doesn't stop there at all, PHP in Action covers a lot of practices for building more enterprise like PHP applications and also covers design patterns. Although I'm not longer a active PHP developer I really thing that every self-respecting php-developer should have this book on his bookshelf.