My name is Juri Strumpflohner and this is my technical blog. I'm a software architect, .Net, Android, Web and Java dev, TDD and best practices promoter and martial arts practitioner.

Recent Posts Subscribe

Dear reader of Juri's TechBlog,
I moved my blog to a new domain and a new hosting solution as well. I'm now blogging on juristr.com.

Juri Goes GIT - First Steps

Yes, I'm going "git" ;). An inherent part of structured, well organized working is to have your stuff under version control (1st point on the Joel Test). I remember when I first got in touch with version control, the first year at the university and I was impressed. Cool I thought, a central repo, easy collaboration, change history etc. And still, I saw many students continuing to send code files over mail... Since that, a lot changed and version control became self-evident in software development.

Don't Let Your Test Doubles Fool You

During unit testing it is common to substitute dependencies with a test double (see Martin Fowler's disambiguation). This is necessary for isolating the tested environment and consequently also the potential source of error in case of a test failure. Thus also the name unit testing.

Let's assume the very simple example of an AnimalFactory which, given the name of an animal and some type, creates an according object representation. When coding a unit test for some object which is dependent on the AnimalFactory, you'd most probably exchange that factory with a stub which returns exactly the object you need in your test case. A possible setup of Moq could look as follows.

Testing Your SUT Against Exceptions

When you test your method for exceptions (which is good practice) the usually naive approach - which btw I was following myself till today - is to wrap your method under test with an appropriate try-catch and set a boolean.

[TestMethod]
public void TestMapPositionUpdate_NullPosition_ShouldFireArgumentException()
{
    //Setup
    Position nullPosition = null;

    //Exercise
    bool exceptionCaught = false;
    try
    {
        ObjectMapper.MapPositionUpdate(nullPosition, "", "", false, "someValue");
    }
    catch (ArgumentException)
    {
        exceptionCaught = true;
    }

    //Verify
    Assert.IsTrue(exceptionCaught, "The exception should have happened");
}
I really don't like this approach because it involves writing a lot of code just to verify an exception has been raised and consequently it clutters up the test code and impacts on the readability.
Today I found that MS unit tests provides a nice attribute to overcome this problem, namely ExpectedException. This allows to nicely refactor the previous test method as follows:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestMapPositionUpdate_NullPosition_ShouldFireArgumentException()
{
    //Setup
    Position nullPosition = null;

    //Exercise
    ObjectMapper.MapPositionUpdate(nullPosition, "", "", false, "someValue");
}
Clean, isn't it. Already by looking at this test code, you immediately understand what it is about. If you happen to know other such interesting attributes, feel free to leave a comment ;)

Android: Attaching ClickListeners Declaratively

If you define a click listener for - say - a button in an android Activity, then you basically have three different possibilities.

The "old" Java like Way
This is the normal programmatic approach; you retrieve the button object and attach the click listener by implementing the according interface.

Button myButton = (Button)findViewByid(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      //TODO your logic
   }
});
Nothing special, right? However this will lead to quite messy code if you have multiple buttons. The main point though is that we're on a mobile. Although the devices get more and more powerful, CPU and memory are still an issue. What this code does is basically to create an anonymous object implementing the View.OnClickListener interface and directly passing it to the myButton object. This has the disadvantage that we're having one listener object per button which is not very memory efficient.
The next solution provides a more optimized way.

More Than Just Synching - Dropbox

You know Dropbox, right (if not, head on to get it here)? I totally love that tool. I mean, you nearly don't notice its presence and actually that's what I love so much. It is totally intuitive, you don't have to know anything, just run that daemon in the back and you can be sure you have your files synched and backed up.

But beside "just" synching between OSs and any kind of devices you could imagine there are much more interesting use cases about how people use Dropbox. Here are some of them (I'll update this post to add more as I find them).

HowTo: Install your Android app OTA on your device for testing
This is a post mostly for Android developers where I describe how you can make use of Dropbox for deploying your application over-the-air onto your Android device for testing. Really great if you don't want to send emails around or connect your USB cable.

HowTo: MySQL Workbench to Remote Ubuntu Production Server Using SSH Port Forwarding

Before starting, I'm totally not the Linux command line guru, unfortunately. It feels like years of just using Windows base OS makes you a wizard-click-through guy ;). My recent (well, a year ago) acquisition of a MacBook Pro made this a little better, but still I feel quite naked when it comes to good old command line knowledge.

Yesterday I was about setting up my Linux Ubuntu based production server which was kindly provided to me by the university to deploy my MSc thesis project. Actually theres not much to set up, a Tomcat webserver and an according MySQL database server. The university admin gave me a VPN client and credentials to get access over SSH. After installing Tomcat and MySQL I tried to get access from the MySQL workbench installed on my local OSX machine to the remote Ubuntu MySQL server. I mean, this is not strictly necessary, but nevertheless very comfortable for synchronizing your database model based on your ER schema design.

After hours of reading me through tutorials and serverfault posts I got it to work, and actually it turned out to be pretty simple - after you understood the mechanics behind.

Reinvention Summit: World’s First Virtual Summit on the Future of Storytelling

I recently got an invitation to attend the world's first virtual summit on the future of storytelling. Unfortunately I'm quite busy these weeks and therefore I'll not be able to attend. Nevertheless I'd like to share the event with some of you out there which may be interested to participate.
My current time constraint is also why I'll not going to write a lot now, and it's also the reason why my new post frequency is quite low at the moment. But hey, lots of unfinished, interesting stuff is in the drafts folder waiting to be published :)

So here are the details about the event (taken from reinventionsummit.com):

WHAT: This two-week virtual conference will focus on the power of the narrative to challenge assumptions and identify ways to change the world. Via webinar and online voice and video calls, business leaders and social change-makers will share best practices for creating and delivering stories that can help us to reinvent – as organizations and individuals.

WHO: Michael Margolis, president of Get Storied, has organized a list of speakers to present summit content and engage people across disciplines. Speakers include:

  • John Gerzema, President BrandAsset Consulting, Young & Rubicam
  • Tiffany Shlain, founder, Webby Awards, and doc/cultural filmmaker
  • John Elkington, pioneer of corporate social responsibility/sustainability
  • Nancy Duarte, author, Slideology and Resonate: Present Visual Stories
  • Julien Smith, co-author, Trust Agents, pioneering podcaster
A full list of speakers is available at www.reinventionsummit.com/speakers.

WHEN: Nov. 11 through 22, 2010 (with sessions recorded for playback)

WHERE: Online at www.reinventionsummit.com with costs starting at $11.11 and offering 30+ hours of content, online collaboration, and bonus downloadable materials.

WHY: Against the backdrop of the nation’s recession and quickly changing communications, many organizations and individuals experience the need to reinvent themselves, their campaigns, and their engagement strategies. A longtime storytelling consultant, Margolis focuses on the power of narrative — the most basic and emotionally resonant form of human communication.

Have fun and stay tuned for new interesting posts ;)

Intercepting WCF Operation Calls with Impersonated Identity

Take the following scenario. You have a WCF webservice with several operations. The communication runs within a secure SSL channel and uses Kerberos authentication. The webservice application runs with an assigned application pool user, in your .Net code represented by the WindowsIdentity.

The requirement is to make a call to another webservice - let's call it the authorization service - which takes the currently authenticated Identity and performs some further business logic in order to determine whether the user has the right to access given resources.
What comes immediately to mind is that we need to impersonate the caller in order to have the right identity sent to the authorization service. Otherwise we'd get the application pool user identity transferred which would be nonsense. Impersonation on WCF operations turns out to be quite straightforward. All you need is to annotate your operation with the right attribute

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string Hello(string message)
{
   //execute the call to the authorization service

   //if the current identity is authorized execute the custom
   //business logic

   return "hello";
}
This would work. I don't like this approach however. The problem is that most of the webservices would need to first check the user authorization by calling the authorization service. So every single programmer would need to implement the call which is not an acceptable, clean solution and way too much error prone.

Solution approach 1: Implement a custom WCF authorization policy
WCF allows you to specify so-called authorization policies. All you need to do is to implement the IAuthorization interface appropriately.
public class MyCustomAuthorizationPolicy : IAuthorizationPolicy
{

   public boolean Evaluate(EvaluationContext context)
   {
      evaluationContext.Properties["Principal"] = //call the authorization service to retrieve an appropriate principal
      ...
   }
}
In the service's configuration you need to register your policy

This is a nice mechanism because it allows you to decouple the authorization logic (i.e. the call to the authorization service) from the real business logic. Your webservice operation doesn't even get called.
The problem with this approach however is that I was not able to impersonate the caller at this level.

Solution approach 2: Parameter Inspectors
Not succeeding with custom authorization policies I tried to find an alternative to intercept the WS call in order to to my authorization logic. Parameter inspectors seemed to be suitable at first glance. Their main purpose is to do parameter validation.
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{ }

public object BeforeCall(string operationName, object[] inputs)
{ }
The method names are quite self-explanatory. However, you already guessed it, impersonation didn't work at this level neither.

Final approach and solution
My last hope was to rely on OperatonInvokers. They are the last one to be called in the chain of calls (see below) that are executed when a webservice operaton gets invoked.
  1. Message Inspection
  2. Operation Selector
  3. Message Formatting
  4. Parameter Inspection
  5. Operation Invoker
The main methods of interest in the IOperationInvoker interface are the Invoke(...), BeginInvoke(...) and EndInvoke(...)

Invoke - Returns an object and a set of output objects from an instance and set of input objects.
BeginInvoke - An asynchronous implementation of the Invoke method.
EndInvoke - The asynchronous end method.

So, my custom operation invoker implementation turned out to be as follows
class AuthenticationOperationInvoker : IOperationInvoker
{
    private IOperationInvoker defaultInvoker;

    public AuthenticationOperationInvoker(IOperationInvoker defaultInvoker)
    {
        this.defaultInvoker = defaultInvoker;
    }

    public object[] AllocateInputs()
    {
        return defaultInvoker.AllocateInputs();
    }

    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        //execute the custom authorization logic and set the thread principal accordingly

        return defaultInvoker.Invoke(instance, inputs, out outputs);
    }

    public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
    {
        return defaultInvoker.InvokeBegin(instance, inputs, callback, state);
    }

    public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
    {
        return defaultInvoker.InvokeEnd(instance, out outputs, result);
    }

    public bool IsSynchronous
    {
        get { return defaultInvoker.IsSynchronous; }
    }
}
Note, my custom OperationInvoker is mainly a wrapper, taking the default operation invoker in the constructor and delegating all operations to it in order to not break anything existing. In line 17, within the Invoke method I do inject my custom authorization logic and yes, here impersonation works.

To make this whole thing usable I wrap everything in a custom "authorization attribute" which implements the IOperationBehavior interface.
public class AuthorizedMethodAttribute : Attribute, IOperationBehavior
{
    public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    { }

    public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)
    { }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
    {
        IOperationInvoker defaultInvoker = dispatchOperation.Invoker;
        dispatchOperation.Invoker = new AuthenticationOperationInvoker(defaultInvoker);
    }

    public void Validate(OperationDescription operationDescription)
    {}
}
In line 11 and 12 I fetch the default operation invoker and inject it into my custom which then replaces the operation invoker used by my webservice.

That's it, now developers can just implement their webservices just as normal and add my custom attribute in order to augment the authorization process by calling the authorization service.
[AuthorizedMethod]
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string Hello(string message)
{
   //execute the custom webservice's business logic

   return "hello";
}