Tuesday, 30 September 2008

Rhinos Stampeding Bristol User Group

People in the community are generally quite a friendly bunch but now and again the green eyed monster can creep up on you when you find that a fellow user group has managed to get an absolutely great speaker and this one is no exception.

Our good friend Guy Smith-Ferrier has managed to secure a session with Oren Eini (aka Ayende Rahien), the founder of Rhino Mocks and major contributor to Castle and NHibernate, over at the .NET Developer Network in Bristol. This has come at relatively short notice as Oren is only around for the next couple of weeks. The event takes place on Monday 13th October, more details can be found here.

The session details are as follows:

"Producing Production Quality Software" Abstract:

Working software is no longer the only thing that we need to produce. We need to create a software system that has a chance of surviving in the cruel world of production system, outside the clean room and sterile environment of development and QA. Understanding bottlenecks in the system, preventing cascading failures and recovery strategies have ceased being the problems of the very high end players. With the cost of system downtime being measures in $$$/second, this is an area we have to consider all the way. In this talk we will cover how we can map common weaknesses in the system design, preemptively protect ourselves from them, and produce software systems that can withstand the real world hostile environment.

"Interaction based testing with Rhino Mocks" Abstract:

Beyond the simplest scenarios, all objects had collaborators that they work with. This flies in the face of testing objects in isolation. This is the problem that mock objects were created to solve. In this talk you will learn what mock objects are, how to utilize them and best practices on when / how to utilize them. Rhino Mocks is a mock objects framework for .Net whose core goals are to let the developer rely on the compiler work well with refactoring tools.

Seriously, if you want to hear from a person whom many consider a legend in our industry and you can make it to Bristol on that day, this would be one not to miss!

Sunday, 21 September 2008

Remix '08 and Ready, Steady, Speak Success

I've spent Thursday and Friday at Remix '08 and I must say I had a great time, from the key note by Bill Buxton and Scott Guthrie to the excellent Swag Phrase events at the community stage during the intervals it was a excellent couple of days that were well worth attending.

Admittedly I had already learned a lot about some of the developer talks that were taking place by attending other community events I had attended over the year so I took the opportunity to go to a couple of the design flavoured talks by Bill Buxton and I must say it was well worth it, design certainly is not my strong point and anything I can do to try and improve my understanding of how it should be applied cannot be a bad thing, I managed to pick up of few key points about not trying to design the perfect product in one go and some cheeky little prototyping tricks such as using magnets to mimic working screen shots.

Certainly my highlight of the event was the Ready, Steady, Speak competition. It was my first opportunity to talk to about my chosen subject to a large number of people at a major UK event, I've done a couple of nuggets at NxtGenUG - Southampton from time to time but nothing on this kind of scale. My chosen topic was WatiN and arriving at Remix I was happy with the presentation I had put together. There were six competitors in total taking part in two heats on the Thursday with the top two going through to a final session on the Friday, topics from other competitors included ASP .NET MVC, OAuth, HSL (Hue/Saturation/Luminance), Rasta and using Silverlight to perform cross browser window communication.

In the first heats I was last on which gave me an opportunity to see all of the competition but also for the nerves to build up, and up and up :-). There were four panel judges who passed judgement on each of the presentations and gave some useful comments on how the presentations could be improved, after my first attempt I had a couple of comments about the colour of my hyperlinks and also the fact that I seemed to keep pacing forwards and then backwards which gave away how nervous I was. Thankfully I was voted through to the final and had an opportunity to improve the presentation over night.

The following day the final was at lunch time and I had to perform the same presentation again, I had changed the colour of my hyperlinks and was determined to make use of the entire stage as had been suggested by the judges from the previous heat, this surprisingly had the effect of taking my mind off of how nervous I was and I had a couple of comments from people who had said that my nerves didn't show through so that was could.

So all the presentations were over and it was up to the judges final decision, and they chose me...woo hoo cool! For all of my efforts I won an XBox 360 Elite with three games, nice!

John Mcloughlin and I did plenty of networking and made sure that we gave out as many NxtGen business cards as we could and also drummed up as much swag as possible, we also managed to secure a few sessions for the new year including the potential of a Microsoft Surface demo and talk after we had our own hands on experience of it.

All in all, I thought the Remix event was excellent and well worth attending (possibly slightly influenced by by winning a competition), special thanks goes out to Dave McMahon, Richard Costall and John Price (the NxtGenUG founders) for organising the Ready, Steady, Speak competition and allowing me to have this opportunity.

Wednesday, 10 September 2008

CSLA .NET at NxtGenUG Southampton

Tomorrow night, Thursday 11th September, we've got a great session lined up at NxtGenUG, Andrew Hallmark, Technical Architect from Maritz, is coming over to talk to us about the CSLA .NET framework and code generation tools.

If anyone managed to make to our session on Object Thinking by Alan Dean be sure not to miss this session, essentially Alan spoke about the theory behind Object Thinking and how we should be changing our approaches to developing object oriented. Well Rockford Lhotka, author of the CSLA, has based his "Expert Business Objects" framework upon some of those theories and in my opinion this is the closest you will get to an implementation of true Object Thinking. Even if you think you know CSLA already there may be a few tips and tricks and implementation ideas that you may find useful.

As usual there will be pizza and swag, so what are you waiting for sign up now and come along, see you there.

Monday, 8 September 2008

Ready, Steady, Speak at Remix 08

Next week, 18th and 19th September, sees the arrival of Remix 08 in Brighton and as seems to be the general trend at these big events of late, NxtGenUG are getting really involved and this time they'll be running another Ready, Steady, Speak competition similar to those seen at Tech Ed and the Microsoft 2008 UK Launch.

The general format is as follows:

Contestants will present a 5 min session on a subject of their choice relating to Web Development or Web Design.  They will present in front of the REMIX audience and in front of a panel of judges.  If there are more than a  certain number of contestants (TBD), there will be ‘heats’ earlier in the day with the winners of the heats in a ‘speak-off’ in the evening session.  The ‘speak-off’ will take place as stated in the evening of the first day of MIX and the first prize is an XBox 360 + Goodies!

Prerequisites:

Mandatory

· Speakers must NOT have previously presented ‘full sessions’ at DDD, TechEd, DevWeek, SDN, SQLBITS, VBUG Conference, NxtGenUG FEST or any similar such conferences.

· Speakers must create a new session of their own with new material which can be based on existing material but cannot be a simple copy of it.

· Speakers must limit their session to as close to 5 mins as possible( overrunning time will cause the speaker to be marked down.)

· Speakers must not have previously won Speaker Idol or “Ready Steady Speak” UK Launch – Sorry to James Coulter J!

· Speakers must state their desire to enter the competition by no later than COP Monday 15th September 2008.

Desirable

· Speakers should provide if at all possible their own laptop, but one can be provided if necessary.  The speaker should notify the organisers of any software prerequisites.

· Speakers should have spoken previously at a User Group meeting even if only for a 10 min mini-session or ‘nugget’.  This is NOT mandatory

To show my support and get a bit of exposure to a larger audience for speaking, I have offered to join in the fun and take part in the competition with a slightly re-worked version of my WatiN nugget that I performed in Southampton last month. So I'll be spending the next couple of weeks getting really nervous and trying to figure out the best presentation I can muster.

Remix 08 looks set to be a great event including at least one session from Scott Guthrie, I'll be there and it would be good to see some of you there too (if not only for the moral support!).

Friday, 22 August 2008

WatiN, Ajax and some Extension Methods

Whilst I've been working with WatiN over the past couple of months I have encountered a few issues especially that unfortunately WatiN was unable to solve straight out of the box, so I thought I would knock a post together that contains the extension methods I have managed to cobble together from various sources on the Internet and a little bit from my own head.

WaitUntilEnabled

I encountered this issue whilst working with the CascadingDropDown provided by the Ajax Control Toolkit, now WatiN does provide a function called WaitUntil which allows you to pass in the name of the attribute you want to examine and the value that you expect the attribute to become, unfortunately however, it seems the CascadingDropDown adds a "disabled" attribute with a value of "true" to the html page. The drop down list then becomes enabled when the disabled attribute no longer exists or is set to false. Therefore it was necessary to write an extension method that waited until the control no longer had a "disabled" property with a value of "true. The method is as follows:

        /// <summary>
///
Waits until the specified element is enabled within the web page.
/// </summary>
/// <param name="element">
The element.</param>
public static T WaitUntilEnabled<T>(this IElement element) where T : class
{
var timer = new SimpleTimer(IE.Settings.WaitForCompleteTimeOut);

do
{
var value = element.GetAttributeValue("disabled");

if (value != "True" &&
value != "true")
{
return element as T;
}
Thread.Sleep(200);
}
while (!timer.Elapsed);

throw new TimeoutException("Waited too long for " + element.Id + " to become enabled");
}



UPDATED 15/09/08: Whilst preparing for my Ready, Steady, Speak session at Remix I came across a small bug where the value retrieved for the disabled attribute was "True" instead of "true" as initially thought, I don't know what caused the difference to occur but I have added the additional check anyway.



The usage of this method is as follows:



        ie.SelectList(Find.ById("MyCascadingDropDown")).WaitUntilEnabled().Select("AValue");



IfExists



This is just an extension method I wrote to make it a little easier to work with elements that don't exist:



        /// <summary>
///
Checks whether the element exists, if so performs the specified action,
/// otherwise just returns the current element object.
/// </summary>
/// <typeparam name="T">
The type of element to check for existence.</typeparam>
/// <param name="element">
The element.</param>
/// <param name="action">
The action.</param>
/// <returns></returns>
public static T IfExists<T>(this Element element, Action<T> action) where T : class
{
if (element.Exists)
{
action(element as T);
}

return element as T;
}


This method can be used as follows:



        ie.TextField(Find.ById("MyTextField")).IfExists<TextField>(e => e.TypeText("AValue"));


 


WaitForAsyncPostBackToComplete



If you are working with controls within an update panel you will inevitably come across a situation where a value is changed via an async postback and whilst that postback is taking place WatiN will try and perform another action which results in an error.The solution to this problem was found after searching the Internet for a little while and I came across this post which explains the problem in a little more detail.



I have modified the original method slightly to make it an extension for the IE browser object, it is used to determine whether the current page is within an asynchronous postback, unfortunately in order to use this method the page you are testing needs to have a JavaScript method defined so if you don't have control over the website you could be a little stuck, here is the Javascript:




<script type="text/javascript">      
var
prm = Sys.WebForms.PageRequestManager.getInstance();
function IsPageInAsyncPostback()
{
return prm.get_isInAsyncPostBack();
}
</script>




The C# method implementation is as follows:



        /// <summary>
///
Waits for async post back to complete.
/// </summary>
/// <param name="ie">
The ie instance to use.
</param>
public static void WaitForAsyncPostBackToComplete(this IE ie)
{
bool isInPostback = true;
while (isInPostback)
{
isInPostback = Convert.ToBoolean(ie.Eval("IsPageInAsyncPostback();"));
if (isInPostback)
{
Thread.Sleep(200);
//sleep for 200ms and query again
}
}
}


After a kind comment from Jo (see below), I have modified this as there is no need to place the IsPageInAsyncPostback method inside of the page, I just needed to modify the Eval method to make the entire call, as follows:



        /// <summary>
///
Waits for async post back to complete.
/// </summary>
/// <param name="ie">
The ie instance to use.</param>
public static void WaitForAsyncPostBackToComplete(this IBrowser ie)
{
switch (ie.BrowserType)
{
case BrowserType.InternetExplorer:
{
bool isInPostback = true;
while (isInPostback)
{
isInPostback = Convert.ToBoolean(ie.Eval("Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack();"));
if (isInPostback)
{
Thread.Sleep(200); //sleep for 200ms and query again
}
}
break;
}
}
}



And can be used like this:



            SelectList list = ie.SelectList(Find.ById("MySelectList"));
list.Option("TestOption").Select();

ie.WaitForAsyncPostBackToComplete();

SelectList childList = ie.SelectList(Find.ById("MyChildSelectList"));
list.Option("TestChildOption").Select();



ByPartialId



The final useful method is ByPartialId, this is merely a wrapper around a regular expression but it does save quite a bit of typing and needing to remember the regular expression syntax. I found this on Ayende Rahien's blog:



        /// <summary>
///
Gets an attribute constraint using a partial id.
/// </summary>
/// <param name="partialElementId">
The partial element id.</param>
/// <returns></returns>
public static AttributeConstraint ByPartialId(string partialElementId)
{
return Find.ById(new Regex(".*" + partialElementId + "$"));
}


 

Foundations Of Programming - eBook Review

I was recently catching up on some articles from the Code Better RSS feed and came across this Foundations of Programming eBook, which is essentially a composition of a number of Karl Seguin's posts on the code better site all neatly presented in an eBook, best of all it's free. I had missed many of Karl's original posts so I decided to download it, take a look and give it a quick review if anyone is interested.

Chapter 1: ALT .NET - this chapter gives quite a nice overview of what ALT .NET is all about, why it exists and where it fits within the community. It also contains some explanations for all of those little acronyms and terms that you hear bouncing around all over place, items such as YAGNI (You Aren't Going to Need It!) and DRY (Don't Repeat Yourself), Coupling, Last Responsible Moment.

Chapter 2: Domain Driven Design - a brief introduction into what DDD is and how it differs from Data-Centric design. Karl uses very simple code samples to get his point across but these do the job well and the tips and tricks section is well worth a read to refresh your knowledge on typical patterns and practices you should be following when developing software applications.

Chapter 3 - Persistence - it seems that the concept of persistence and persistence ignorance is a bit of a buzz word at the moment, what with various discussions about Entity Framework vs NHibernate etc (just Google these terms and you'll come up with some discussion or another). In this chapter Karl neatly summarises the main issue in-hand i.e. the Object-Relational Impedance Mismatch and continues to discuss the use of Data Mappers and, with the use of some example code, highlights the drawbacks of using manual mapping (hand writing the code to perform the mapping of relational to object data), which had I not been convinced of already, this chapter would have pushed me to look for alternatives. I think the title of this chapter is a little misleading as it does mainly focus on manual data mapping and I was expecting the chapter to go into more details about other persistence mechanisms available, I'll keep reading and see where it takes me.

Chapter 4 - Dependency Injection - this section discusses the balance between decoupling and coupling of items within an application, introduces the concept of unit testing which requires at least some form of decoupling and details how the Dependency Injection pattern can be used. The chapter  also focuses on the StructureMap dependency injection tool written by fellow CodeBetter blogger Jeremy Miller, there are plenty of other DI frameworks out there such as Castle Windsor, Unity, ObjectBuilder each has their own pro's and con's so I leave it to you to make a decision on which might be the most preferable for your situation.

Chapter 5 - Unit Testing - the previous chapter briefly introduced unit testing as a way of introducing the need for decoupling within a system, this section delves a little more into unit testing and why should we use it, I especially liked the section on "Why Wasn't I Unit Testing 3 Years Ago?" which rang very true to me. Karl then goes on to discuss unit testing and the tools you need to do it, these include NUnit, TestDriven .NET and RhinoMocks and he details simple some code examples to give the reader and idea of the kind of things you can do with them.

One point worthy of note is that Karl mentions that UI testing "is complicated and suffers from very tight coupling" which is true, but I would definitely recommend looking into integrating WatiN into your continuous integration build process, the tests are not be as fast as unit tests so you may want to use them in a separate build process but I believe that can be equally invaluable to ensure the UI meets the needs of the user.

Also, when it comes to testing of the database, I have recently found some success in using a LINQ to SQL data context which exposes the stored procedures within the database can be extremely useful for testing individual stored procedures and ensuring they perform as expected (may be I'll do a blog about that some day).

Chapter 6 - Object Relational Mappers - starting head on with details about the Stored Procedures vs Inline SQL debate, Karl explains some of the key points involved in this discussion and argues the reasons for inline SQL over stored procs which leads on to the use of an object relational mapping tool. I for one agree with Karl's arguments and believe that the use of an O/R Mapper should be a developers first port of call and then stream line to use stored procs when bottle necks appear. The chapter then moves on and describes how to configure and use NHibernate for your O/R Mappings, recently I have had a lot of experience of LINQ to SQL and I find this to be pretty useful even though it probably lacks a level of abstraction that tools such as NHibernate would provide, it certainly does the job if your just focusing of SQL Server databases in a smallish application.

Chapter 7 - Back to Basics: Memory - I personally believe every developer should read this section even if its just to recap your knowledge on these items, it's always good to keep an idea of what the memory usage of your application in your mind even when in a managed environment. Karl covers all of the areas you would expect to see such as Boxing, ByRef, Managed Memory Leaks, Fragmentation and Pinning and the use of IDisposable. The chapter is relatively brief considering the subject matter but it is easy to read and digest, compared to CLR via C# (I book I would thoroughly recommend you get if you haven't got it already) Karl's is a lot more lightweight but serves the purpose of getting developers thinking about the things that matter.

Chapter 8 - Back to Basics: Exceptions - the suggested exception handling is simply two rules 1) Only handle exceptions that you can actually do something about, and 2) You can't do anything about the vast majority of exceptions and Karl goes on to state that "Most new developers do the exact opposite of the first rule, and fight hopelessly against the second. I believe he is right, exception handling can actually be quite an overwhelming concept and developers can easily be too defensive when dealing with them. Karl continues to highlight what to do when handling exceptions that you can do something with also asserts that exception swallowing is bad. The chapter continues to detail how to throw exceptions and the subtle differences this can have on the stack trace, when to throw exceptions i.e. in exceptional circumstances or when expected behaviour cannot be executed. Finally, the chapter rounds up with a section on custom exceptions.

Chapter 9 - Back to Basics: Proxy This and Proxy That - the chapter looks inheritance and polymorphism in terms of the Proxy Domain Pattern and how this is used within NHibernate to handle lazy loading of objects. There is an interesting side note about NHibernate which is that it is considered to be a frictionless or transparent O/R Mapper because it doesn't require modification of any of your domain classes, although if you require lazy loading then you must mark all of your methods as virtual but you still don't have to add NHibernate specific constructs to your classes. The chapter then turns into a discussion about the lazy loading capabilities of NHibernate and how the proxy pattern is used to achieve this. The intention of the chapter was to make the reader think about what methods should and shouldn't be virtual, I am not sure whether this was achieved but it certainly got me thinking a little bit more about looking into NHibernate.

Chapter 10 - Wrapping It Up - this final chapter simply summarises the contents of the eBook and Karl gives what I consider to be a good list of core principles to good software engineering, I have summarised these as follows (see the eBook for more detail):

  • The most flexible solution is the simplest (YAGNI, DRY, KISS and explicitness)
  • Coupling is unavoidable, but must be minimised
  • You are responsible for the code you write, test your code because this helps you identify bad coupling, find awkwardness in your API, document behaviour and expectations, and lets you make small and radical changes with far greater confidence and far less risk
  • It's more fun developing projects using agile and iterative development
  • Always look for alternatives and learn all of the time

I must say I really enjoyed reading this eBook, so much so that it inspired me to write this review of it. At only 79 pages it is manageable and IMO makes some absolutely valid points about how to "Code Better", reading this eBook will be a great learning aid for those wanting to progress their programming knowledge and a stark reminder for those with a greater knowledge that it is always worth reminding yourself of your coding principles, practices and understanding of the underlying framework that you work with everyday.

The eBook has opened my eyes to the way of the ALT .NETer and I am now far more interested in learning about NHibernate and how it could make my life as a programmer a better place to be. Some might say that the focus on NHibernate should not be considered as a "Foundation of Programming" but the principles that lie behind the development of NHibernate certainly should be. All in all I would definitely recommend reading this eBook when you have a spare  5 minutes.

WatiN Nugget at NxtGen Southampton

So last night I managed to get through my nugget on WatiN relatively unscathed, the demo overran which I was a little disappointed about but I hope everybody took something from it.

I was in a small dilemma prior to performing the nugget as I wanted to talk about how great WatiN is and demonstrate what you can do with it but in the back of my mind I knew that it is very easy for you WatiN tests to become large in number and unmaintainable, so I wanted to talk about the controller framework I have been developing to give people an idea of the kind of things you can do to make sure your tests do not get out of hand.

I shall be performing this nugget again at the Cambridge NxtGenUG, its titled Not Wifeswap, Coordinator Swap, the title doesn't really tell you what its about but basically John and I are going to perform the session we did last night up at the Microsoft Research Centre where the Cambridge boys are based.

So the main lessons learned from last nights session were I think that 15 minutes isn't long enough (by a long way) to talk about best practices of writing WatiN tests, so I shall just focus on what WatiN can do, may be show a few more of the functions for working Ajax based web sites and then just point people to my blog for more information about the framework etc. If anyone reading my blog attended the event last night, I'd be really interested in your feedback.