DeveExpress CodeRush and Refactor! Pro

Just a quick post today, since I’m on holiday.  :)

Yesterday I attended a couple of product-related events in Bradford.  The first was an MSDN event around the changes in Visual Studio 2008 SP1 (Including the Entity Framework, Data Services and a host of other good stuff).  I’ll post more on that once I get my head around what to write.

The second part of the day was a presentation by Oliver Sturm of DevExpress on the CodeRush and Refactor! Pro products.  I had not previously been aware of these products, but the presentation won me over.  There’s a lot of power and cusomisability in these products, and they should really help cut down on developer effort required to create and maintain applications in Visual Studio.  Luckily for me, I managed to win a licence for the products (thanks Oliver!) , and I’m really looking forward to installing and playing with the technologies.  I seriously recommend you look up the tools, and strongly consider getting a licence for you and your team.

TC Electronics – Who writes your manuals?

Yesterday I succumbed to temptation and upgraded my guitar rig with a TC Electronics Nova System.  I’m extremely impressed with pretty much everything about the unit itself, but I have a problem.

As with most electronic deices these days, you really do need to be able to refer to the manual to make the most of it.  Unfortunately, the manual for this device (you can find a download on the link above if you want to take a look) is pretty near incomprehensible.  It was obviously adapted from the G Major manual by someone who knew the system inside-out.  As a result there are lots of assumptions made about the depth of the users’ knowledge.  That’s where it falls down.  I just don’t have that knowledge and so I can’t make much sense of what’s written there.

Come on, TC – you’ve made an excellent product but it is sadly let down by the manual.  Please re-write it so the average user can understand how to make the most of the device.

HTTP Error 407 – Proxy authentication required

Recently I deployed an application into the live environment at work and all was running smoothly until a proxy setting change suddenly stopped the app being able to talk to the outside world. I didn’t much fancy having to rework the code to allow proxy authentication, so I did a bit of searching on Google, and came up with the following block to go into the app.config file.

<system.net>
  <defaultProxy enabled="true" useDefaultCredentials="true">
    <proxy bypassonlocal="True" proxyaddress="http://proxy"/>
  </defaultProxy>
</system.net>

Adding the section to the config file instructs the assembly to provide the default credentials to the proxy when requested, and saved me having to recompile and go through the system test phase or of product lifecycle. Hopefully it might save someone else the pain, too.

Programming Quotes

I like these…

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” (Damian Conway from the book Perl Best Practices). 

and

“Before software can be reusable it first has to be usable.” (unknown)

Fault handling in WCF services

It is oprobably very well known to most WCF developers, but there is a methodology previously unknown to me for handling exceptions in a WCF service, and handling them gracefully.  Hopefully this post will give enough of an overview to the required steps to communicate fault conditions to the client to allow you to handle them in your code.

There are a few steps required in order to create the fault data, but they are all quite simple.

First, you need to create a DataContract object to hold the fault details.  Mine looks like this.

using System;
using System.Runtime.Serialization;
 
namespace MyOrganisation.MyService
{
    [DataContract(Namespace = "http://schemas.MyOrganisation.com/CentreService/2008/08")]
    public class UnexpectedServiceFault
    {
        private int errorCode = -1;
        private string errorMessage = "UNDEFINED";
        private string additionalData = String.Empty;
 
        [DataMember]
        public int ErrorCode
        {
            get { return errorCode; }
            set { errorCode = value; }
        }
 
        [DataMember]
        public string ErrorMessage
        {
            get { return errorMessage; }
            set { errorMessage = value; }
        }
 
        [DataMember]
        public string AdditionalData
        {
            get { return additionalData; }
            set { additionalData = value; }
        }
    }
}

That’s the object that will hold the data for presentation to the client. Now we’ll examine how to use it.

In the interface for your service class, you’ll need to decorate the methods for which you wish to provide fault handling. This is a simple case of adding the following line to the code.

[FaultContract(typeof(UnexpectedServiceFault))]

so, and example method signature would look like this.

/// <summary>
/// A dummy method to demonstrate fault handling
/// </summary>
/// <param name="aParam">A parameter to the method</param>
[FaultContract(typeof(UnexpectedServiceFault))]
[OperationContract]
void MyMethod(string aParam);

This tells the compiler to generate the WSDDL required to support fault handling for this method. Now, we need to implement this in the actual service code.

/// <summary>
/// A dummy method to demonstrate fault handling
/// </summary>
/// <param name="aParam">A parameter to the method</param>
[FaultContract(typeof(UnexpectedServiceFault))]
[OperationContract]
void MyMethod(string aParam);

This tells the compiler to generate the WSDDL required to support fault handling for this method. Now, we need to implement this in the actual service code.

/// <summary>
/// A dummy method to demonstrate fault handling
/// </summary>
/// <param name="aParam">A parameter to the method</param>
[FaultContract(typeof(UnexpectedServiceFault))]
[OperationContract]
public void MyMethod(string aParam)
{
  try
  {
    
  }
  catch(Exception ex)
  {
    UnexpectedServiceFault fault = new UnexpectedServiceFault();
    fault.ErrorMessage = ex.Message;
    fault.ErrorCode = 101;  // an error code to identify the fault location
    fault.AdditionalData = ex.StackTrace;
    FaultException<UnexpectedServiceFault> faultException = new FaultException<UnexpectedServiceFault>(fault);
    throw faultException;
  }
}

So, in the catch block, we created a new object of type UnexpectedServiceFault (as we defined in the first step), populated it’s data, and then wrapped it in the FaultException type provided by System.ServiceModel. It is this FaultException that we throw to the client.

In order to enable passing the fault data back to the client, we need to configure the host (in my case IIS) to pass exception details back to the caller. In my web config, I created a new ServiceBehaviour element containing a serviceDebug element. I then set the value of IncludeExceptionDetailsInFaults to true, and associated the behaviour with the service.

<?xml version="1.0"?>

<configuration>
  <system.serviceModel>
    <services>
      <service name="MyOrganisation.MyService" 
           behaviorConfiguration="MyServiceBehaviour">
        <endpoint contract="MyOrganisation.MyService" binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceBehaviour" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Now all that remains is to implement the handling at the client. Once you’ve updated the service reference information, you can catch excpetions of type System.ServiceModel.FaultException and handle them as required. In a simple case like so :

catch(FaultException<UnexpectedServiceFault> ex)
{
  Console.WriteLine("An error occurred :: " + ex.Detail.ErrorMessage);
}

Quite a simple process, but it can be a bit fiddly. If you have problems, I’d suggest going back and re-checking each step of this guide. I’m going to do the same in the next day or two, just to make sure I haven’t missed anything. :)

FIA strikes again

Once again, the FIA (Ferarri International Assistance) have shown the world where there true allegience lies.

At yesterday’s Belgian Grand Prix, the stewards decided to impose a 25 second penalty on Lewis Hamilton after ruling that he “gained an advantage by short-cutting the circuit.”

I was watching the race live, and saw the incident in question, and one thing I can tell you for certain is that Hamilton did indeed gain an advantage, but that he immediately backed off and returned the lead of the race to Raikkonen.  In fact, in order to pass him at the next corner, Hamilton went around the back of the Finn’s car in a perfectly legal manouvre.  I’m sure you can find the footage on YouTube by now to see for yourself.

What really get’s me wound up is the fact that Raikkonen managed to get in front of Hamilton again just a few laps later, and the win for Hamilton only came as a result of Raikkonen losibng control of his car on the wet track and spinning into the wall.  Hamilton can’t have gained that big an advantage then, can he?

So my message to the FIA is this.  This kind of activity is what we call “racing”.  This is different from the official view of motor racing, which in recent years seems to have been defined as ’20 cars driving in procession around a track for 90 minutes’.  Restricting the cars for the sake of it is not in the spirit of the sport.  Penalising drivers because they happen to not drive for Ferrari is not in the spirit of the sport.  Failing to apply rules on safety (Massa’s unsafe release from the pits in Spain) is not in the spirit of the sport.

It’s no wonder that so many people are giving up on the sport.  I am not going to continue to watch a corrupt sham, and I am not alone in that opinion.

note : all views expressed in this post are my personal opinion, and should not be miscontrued as fact.

WCF Services – a compatibility hack

I’ve recently had to start developing a set of WCF services for my company to use.  All good stuff, you might say – and tyou’d be right.  For the most part.

The area in which things get “interesting” is around the requirement for backwards-compatibility with some existing .Net 1.1 applications that consume traditional web services.  These applications are horrendously complex, and the fewer changes to the code base we have to make, the better.  With this in mind, we created the WCF services to mirror the old web services as closely as possible and that’s where the fun began.

The issue that set me on a journey of discovery and hackery was around a method that returned a simple boolean type.

public bool NameIsInList(string name)

{

// implementation

return true;

}

Nothing fancy there.  However, exposing the service using basicHttpBinding had an unfortunate side effect.  The method signature was refactored to :

public void NameIsInList(string name, out bool NameIsInListResult, out bool NameIsInListResultSpecified);

Less than ideal.

No matter what I tried (including contacting Amit) I couldn’t make the down-level compatible web service return a simple boolean result.  Given how much effort we would have to go to to update the calling methods in the legacy systems, I had to find another way forward.

In the end, the solution was extremely simple, if a little hacky.  Create an ASMX web service that handled the calls to the WCF service, and presents the legacy apps with the data they expect.

[WebMethod]
public bool NameIsInList(string name)
{
using (MyWcfService.ServiceClient WcfClient = new MyWcfService.ServiceClient(“WSHttpBinding_MyService”))
{
return WcfClient.NameIsInList(name);
}
}

Not the prettiest solution, but it works.

There are a few extra benefits that I wasn’t expecting from this approach, too.  I’ll post about those tomorrow.

Stack Overflow – pretty darned cool

Over the course of the last week, I have been participating in the private beta of a new website, Stack Overflow.

The site is for programmers, by programmers and focussed on – you guessed it – programming.  So far it all looks pretty sweet.  Users aren’t required to register, and more importantly they aren’t required to pay to use the service (I’m looking at you, Experts Exchange!).  The overall quality of questions and answers seems pretty high, although I understand that the site is still in beta.  The quality may change once the site goes live, but the system of self management by the community should keep standard fairly high overall.

If you want to keep up to date with the project, and hopefully learn when the public launch is going to happen check out the blog.

The little things in life

More often than not, it’s the little things in life that make a difference.  for example, I arrived at the office this morning to discover that our new chairs had been delivered.  Not a major thing by any means, but given that my old chair had virtually no back support I was long overdue for a new one.

And what did the company provide for us?  To my surprise, Herman Miller Mirras – from the same people who took an unfair amount of flack during the dotcom bubble.

I am impressed.

Hint text in ASP.NET TextBox controls

More and more often these days, you see hint text in a textbox control on a web form.  You know the kind of thing – “user name” or “password” appearing in silver text within an input control.  Well, I had to implement that functionality today and it is surprisingly easy to achieve.

The first thing you need to do is create your TextBox control on the page.  Once you’ve done that, add the following method to your codebehind file.

private void SetTextBoxHints(TextBox textBox, string defaultText)
{
textBox.Attributes.Add(“onfocus”, “clearText(this,'” + defaultText + “‘)”);
textBox.Attributes.Add(“onblur”, “resetText(this,'” + defaultText + “‘)”);
if (textBox.Text == “”)
{
textBox.Text = defaultText;
textBox.ForeColor = System.Drawing.Color.Silver;
}
else if (textBox.Text == defaultText)
{
textBox.ForeColor = System.Drawing.Color.Silver;
}
else
{
textBox.ForeColor = System.Drawing.Color.Black;

}

 Next, you’ll need to add the javascript to the page/user control to look after the dynamic changes in content/colour. 

<script type="text/javascript" language="javascript">
<!--
function clearText(ctrl,defaultText) {
if(ctrl.value == defaultText)
ctrl.value = ""
ctrl.style.color = "#000000";
}
function resetText(ctrl,defaultText) {
if(ctrl.value == "")
{
 ctrl.value = defaultText
 ctrl.style.color = "#C0C0C0";
}
}
// -->
</script>

Then, you need to call the setup method for each Textbox you want to control.

SetTextBoxHints(myControl, "the text you want to show as default...");

And that, as they say, is that. Enjoy.