Edmonton IT Blogger Roll
RSS
 
Creating A Global Error Handler In WCF

One of the key things in any application is to have an exception handler that logs any unhandled exception so that the application can be debugged in the future.

In many applications I see this done by wrapping every external method in a try / catch block. While this works it has several drawbacks. First of all it is a pain to type the same code over and over again. It is easy to forget to add the try / catch / log block one one method. The biggest pain is if you need to change the way you log you have to change every single instance of that code.

In WCF there is an easy way to intercept all exceptions and log them via adding in by implementing a few simple interfaces that extend WCF.

The first one is the IErrorHandler interface:

 public class ErrorHandler : IErrorHandler
    {
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
          
        }

        public bool HandleError(Exception error)
        {
            if (!EventLog.SourceExists("Operations")) EventLog.CreateEventSource("Operations", "Application");
            EventLog.WriteEntry("Operations", error.ToString());
            return false;
        }
    }

The HandleError() method will be called whenever an exception occurs. Here we log to the event log and then return false so the error can continue to propagate up the chain. The ProvideFault() method can be used to transform exceptions into faults but for this example we are not going to do any rewriting of the fault message that is to be returned and will leave the method blank.

Next we have to write a service behaviour that will allow us to add our custom error handler for each channel we have a service running on. This is done by implementing the IServiceBehavior interface.

public class ErrorServiceBehavior : IServiceBehavior 
    {
        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
           
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
            
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            ErrorHandler handler = new ErrorHandler();
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                dispatcher.ErrorHandlers.Add(handler);
            }
        }
    }

Here we are enumerating all channels and adding the error handler to the collection. We do not need to change anything in the other methods of the interface.

Now we need to do is create a simple behaviour extension element so that we can use the error service behaviour in our config.

 public class ErrorHandlerBehavior : BehaviorExtensionElement
    {
        protected override object CreateBehavior()
        {
            return new ErrorServiceBehavior();
        }

        public override Type BehaviorType
        {
            get { return typeof(ErrorServiceBehavior); }
        }
    }

Lastly we can put the behaviour in the config file for our service.

 <system.serviceModel>
    <extensions>
      <behaviorExtensions>
<!—Add in our custom error handler -->
<add name="ErrorLogging" type="Dispatch.Service.ErrorHandlerBehavior, Dispatch.Service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c62bf877ee633f38" /> </behaviorExtensions> </extensions> <services> <service name="Dispatch.Service.DispatchService" behaviorConfiguration="Dispatch.Service.Service1Behavior"> <endpoint address="" binding="wsHttpBinding" contract="Dispatch.Service.IDispatchService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Dispatch.Service.Service1Behavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> <ErrorLogging /> <!—Name from behaviorExtensions Element --> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

As you can see I added the extension to the Extensions element and then placed the name in the behaviour. My assembly is strong named but it should not be required to implement this behaviour (you should just be able to use PublicKeyToken=null if it is not strong named).

Posted on 6/24/2009 9:23:57 AM by Dave Woods
Using IntelliJ for Android Development

So I have this semi-fancy Google Android Dev Phone 1.  Lately I've been devoting part of my spare time to learning about programming for Android (the OS of the phone).  Google (probably because they didn't ask for my opinion and/or input) decided to use Java as the lingua franca for Android programming.  If you ask me - and I know you will - they should have used C# and Mono (I might be a bit biased here).  Luckily, years ago I had done Java programming, so I wasn't that intimidated by the use of Java on Android.

The first big question that every developer faces is which IDE?  There are a few Java IDE's out there, but if you ask me the only ones worth considering are Eclipse and IntelliJ.  The documentation for Android points you to using Eclipse.  Eclipse is a good IDE.  However, back in the day when I was getting paid for Java development, my employer got us all copies of IntelliJ, from JetBrains.  I liked it.  I like it enough that if I landed a contract tomorrow that involved Java, I'd buy me a copy of IntelliJ. 

So, all that being said, I figured I'd give IntelliJ a spin as I travelled down the stack-trace of Android programming.  Here are my observations, in general:

  1. There is an Android plug-in for IntelliJ.  Now, you might believe that development on the Android plug is dead.  Not true.  The plug-in is undergoing active development - it just seems to be kind of slow
  2. I found the installation of the Android plug-in for IntelliJ far easier than for Eclipse.  Just download the most current release, and then unzip to your plugins folder in your IntelliJ installation.  With Eclipse, it is simple, but not when the documentation is wrong.
  3. The IntelliJ plug-in is simple, and seems to get the job done.  It's a bit to simple at this time, if you ask me.  The ADT for Eclipse provides a far richer dev-centric experience for Android coding.  For example there are designers to help you with laying out your form, a lot more control over starting up the Android emulator, and better tooling for hooking up the debugger to either the emulator or an app running on the physical phone.
  4. Being a Resharper junkie, I found that IntelliJ was more natural for me to use.
  5. I didn't run into to many problems when I was trying to use/convert Eclipse project with IntelliJ. This is good, because the vast majority (all?) projects I've seen are all Eclipse based.

So, my conclusion at the end of the day, is that I'm going to stick with Eclipse for my Android development.  There just seems to be less friction at the moment if you're using Eclipse.  In a couple of months maybe I revisit IntelliJ and see what's new with it and Android development.  However, at this time, I'd like to really concentrate on learning the Android SDK, and it seems simplest to me right now with Eclipse.



Tom Opgenorth  ...
Posted on 6/17/2009 8:58:18 PM by
Apply SRP to your emails….please

I recently got an email that had no fewer than eight significant topics in it. Yes, it was a long email. As a result of this email I was unable to remember and act on all the different topics.  Sound like a big messy class/method to you?  Sure it does. 

I propose that people now send emails as they would write code: singly responsible. I don’t care if I get eight emails instead of one, it didn’t cost me anything. I can, however flag for follow up, organize or delete each as I see fit.  Like a good method name the subject line should reveal the entire intent of the email.  Like a method name, the urge to put “and”, “or”, and “plus” in the subject line should be a smell indicating that you have too many topics.

If your emails come in with more than one topic in them I’m likely to miss one item. Heck, I’m likely to delete the email when I’ve acted only on part of what you need me to. In that case, it’s tough shit on you I’m afraid. While it’s convenient for you to type it all up in one window, it’s easier for me to do the job you require of me if I have the separate.

With that, I’m going to start working on an intelligent Outlook filter for this problem.

Posted on 6/16/2009 8:11:13 PM by The Igloo Coder
Plain text passwords are bad. Period. Don't do it.
In conversation with a support representative for my domain registrar regarding me locking out my account I was able to discern they store at least some part of my password in plain text. For you're viewing pleasure, here's the conversation and how it played out. You'll easily be able to find the spot where the representative gives the clue that they have access to at least some portion of my password in plain text. Please, please, please, don't ever store passwords in your applications in plain text. Think about this whenever you decide you need security in your system. Just read what happened to PHPBB (one of the largest PHP-based forum software deployed worldwide).

Again.. Don't ever think it's alright to store passwords in plain text. Anywhere.

Catherine P.: Hello, you've contacted **** Live Support! How can I help you today?
Jason Hunt: Hello.... I can't log into my account... I have reset my password and then tried logging in with the changed credentials and it says I am now not able to log in due to failed attempts.
Jason Hunt: username: ****
Catherine P.: Wait a minute please
Jason Hunt: waiting
Catherine P.: I'll check
Jason Hunt: thank you
Catherine P.: Could you please provide me with 2 first and 2 last symbols of your new password
Jason Hunt: ** **
Catherine P.: You account was locked due to 6 failed attempts to login
Jason Hunt: seems an odd request... unless my password is stored in PLAIN TEXT *grrr*
Catherine P.: I'll unlock it in a moment
Jason Hunt: