Wednesday, May 27, 2009 #

MVC Rocks

I’ve not blogged much recently, for the simple reason that I’m not doing much development in my new job.  I’ve done a couple of weeks of new development using C'# 3.0 in the last six months, but mostly I seem to be supporting legacy apps, planning and carrying out deployments and analysing data.

I don’t mind this at the moment, but I have to say I was very pleased when Amazon finally sent me a copy of Steve Sanderson’s “Pro ASP.NET MVC Framework”.  I needed a developer fix, and I’m getting it here.

I’ve always found ASP.NET very heavyweight as a web framework and completely removed from what’s actually going on with HTTP and HTML.  I suppose it’s OK if you want your web development to seem like WinForms, but the fact is that it’s NOT WinForms, and never will be.

I’m 200 pages into the book now and it’s come as a breath of fresh air.  Apps built with ASP.NET MVC are testable, (relatively) easy to understand, use clean HTML and better reflect the stateless nature of HTTP.

The model binding is clean and reminds me of the M-V-VM pattern in WPF, of which I’m a big fan.

I hope to use MVC for some private projects in the near future, so I’ll be blogging about how I get along.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Wednesday, May 27, 2009 9:10 AM | Feedback (0)

DDD South West

Last Saturday (the 23rd of May), I had the privilege of attending DDD South West at Queen’s College in lovely Taunton.

The venue was beautiful, the presentations educational and fun, the company convivial and the food plentiful and delicious.  I only wish I’d had more sleep and less beer the night before.

I had wondered if the presentations would contain a lot of material from DDD7, but as far as I could tell there was no overlap.  I attended sessions on the DLR and dynamic languages, jQuery, refactoring, WCF and C# 4.0 and learned new stuff from all of them.

All in all it was a cracking day and a real credit to the organisers.  I’m sure the event will be back next year, and you’ll need to get in quick to get a place!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Wednesday, May 27, 2009 9:09 AM | Feedback (0)

Thursday, March 19, 2009 #

Method signature in IOperationInvoker?

As I said in my previous post, I’m currently implementing a web service in WCF.  It has to be consumable by code that’s been written for a .NET 2.0 style web service (in Perl, as it happens), and so I’m using the BasicHttpBinding and Xml serialisation.

One of the reasons I’m using WCF is to be able to wrap all operations (in the WCF sense) in the same error handling code.  The requirements of the client are always to have the following class returned:

public class Result<T> {

public T Data { get; set; }

public int ErrorNumber { get; set; }

public string ErrorDescription { get; set; }

public bool Success { get { return ErrorNumber > 0; } }

}

If everything goes swingingly, Data is non-null, ErrorNumber is 0 and ErrorDescription is empty.

Should the method on the service class throw an unhandled exception however, Data is null, ErrorNumber is non-zero and ErrorDescription describes what went wrong.

Since this has to happen for every method in the service contract, I wrote an attribute deriving from IServiceBehavior whose ApplyDispatchBehavior method adds an instance of a class implementing IOperationBehavior to every operation on every end point exposed by the service:

public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
                foreach (OperationDescription operation in endpoint.Contract.Operations)
                    operation.Behaviors.Add(new ErrorWrappingOperationBehavior());
        }

ErrorWrappingOperationBehavior, in turn, inserts an instance of a class implementing IOperationInvoker into the invocation pipeline for each method.  The following code represents the bits of this class that don’t just pass straight through to the default invoker:

public class ErrorWrappingOperationInvoker : IOperationInvoker
    {
        private IOperationInvoker invoker;

        public ErrorWrappingOperationInvoker(IOperationInvoker invoker)
        {
            if (invoker.GetType().GetProperty("Method") == null)
            {
                throw new InvalidOperationException("The invoker supplied must have a Method property");
            }
            this.invoker = invoker;
        }

        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            object result;
            try
            {
                result = invoker.Invoke(instance, inputs, out outputs);
            }
            catch (Exception ex)
            {
                // TODO: Is there a nicer way of getting at the method being invoked? Seems like quite a
                // common requirement when we're hooking the pipeline?
                MethodInfo webMethod = (MethodInfo)invoker.GetType().GetProperty("Method").GetValue(invoker, null);
                // All web methods should return a Result<T>, which implements IResultDescription
                IResultDescription resultDescription = (IResultDescription)Activator.CreateInstance(webMethod.ReturnType);
                resultDescription.ErrorNumber = (int)EnvironmentError.CouldNotConnectToDatabase;
                resultDescription.Description = ex.Message + Environment.NewLine + ex.StackTrace;
                result = resultDescription;

                // Must assign "out" parameter
                outputs = new object[0];
            }
            return result;           
        }

Appalled?  The problem is that I have to new up an instance of the return type for the method being invoked.  The method being invoked, however, isn’t a member of the IOperationInvoker interface.  Rather it is a property on the default invoker, whose type is internal to its assembly.  So I had to resort to some dodgy reflection to get what I want.

This all works, but leaves me feeling slightly uneasy.  Does anyone have any insight into why the method being invoked isn’t exposed?  This may of course be a case of doing something not recommended.  I imagine I should be returning SOAP faults to adhere to SOA principles, but the consumer (which is internal to our company) is not even reading the WSDL for the service, so this level of adherence isn’t necessary.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Thursday, March 19, 2009 5:32 PM | Feedback (3)

Wednesday, March 18, 2009 #

WCF Process Identity

I have to say that I’m a big fan of WCF’s modularity and power.  At the moment though, I’m struggling with impersonation issues and feeling overwhelmed by the sheer size of the thing.  “With great power comes great responsibility”, I suppose.

We have a legacy policy in our company whereby web services impersonate a particular user account that can write to certain file shares and access databases.  This has served us well for intranet web apps, but I’ve run into difficulties because I’m forging ahead and writing our first WCF based web service.

I’ve put the service into “ASP.NET compatibility” and dutifully added the right attribute to the service class, but the <identity impersonation=”true”…> tag in the web.config stubbornly refuses to come into play.  I’ll dig more tomorrow, but all this hassle has prompted me to wonder how it really should be done.

There are lots of articles out there about impersonating the caller of the WCF service.  We could do that, but then we’d have to add A LOT of users to a group with privileges to access the database we’re using.  Far better, at my current stage of thinking, to have a single user (without interactive logon privileges) that only the service knows about.  But there’s the catch – I can’t find anything on the internet about this particular scenario.  How do I get the WCF service to run under a particular identity?  I’m hosting it in IIS, but it seems that if I specify anonymous access in IIS and supply a username and password, that doesn’t get transferred to WCF.  It seems hell bent on running as the NETWORK SERVICE account, or else the caller if I explicitly tell it to.

There are two possibilities to explain my current predicament:

  • I have not found the technical solution
  • The technical solution either doesn’t exist or is obscure (PInvoke anyone?) and this is so for a reason, i.e. what I’m trying to do is not best practice and I need to do it differently.

All comments gratefully received!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Wednesday, March 18, 2009 9:17 PM | Feedback (2)

Monday, February 16, 2009 #

Temporary Leave of Absence

Those of you who subscribed to my blog after the initial flurry of posts may be wondering where I’ve been for the last few months.

I’ve had some major events in my family life which I won’t go into, and I’ve also changed jobs, so I’ve been preoccupied with other stuff.

In my last job I was doing WPF / WCF development in .NET 3.5.  In my new role, I’m doing some of that, but also supporting apps in VB6, ASP, ASP.NET and .NET 1.1 and 2.0.  It’s quite an eye-opener and I’ll have a lot more to say in future blog posts about how far we’ve come in terms of tooling and programming paradigms!

It’s good to be back in the blogosphere.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Monday, February 16, 2009 3:02 PM | Feedback (2)

Tuesday, September 30, 2008 #

Firefox / IE blogging woes

I have discovered after a few blog posts on this excellent site that writing a post in Word and pasting it into Subtext in Firefox is not a good recipe.  I noticed today that my lists and images have somehow been mangled.

Also, I was wondering why I could navigate away from my work without being warned.  I got burned by that one on my first post, which is why I started using Word in the first place.  I accidentally left the editor and when I got back my lovingly crafted prose had done a runner.

I composed a blog post in IE today using Word and got lots of helpful messages that simply don't appear in Firefox (actually Gran Paradiso).  Has anyone had similar experiences I wonder?

I'll fix up the lists and images in my previous posts some time soon.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Tuesday, September 30, 2008 9:48 PM | Feedback (0)

Oren Eini is coming to Bristol

If you're in the Bristol area and want to hear a real software development pro speak about writing software fit to publish, then get along to the DotNetDevNet .NET user group on Monday the 13th of October.

Oren Eini (a.k.a. Ayende Rahien) is coming to town!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Tuesday, September 30, 2008 9:42 PM | Feedback (0)

So much to learn...

I’ve been doing development professionally now for maybe 18 months and my experiences over the last 8 months in an agile shop have made me realise just how much there is to know in the development arena and, more importantly, how much I would like to know in order to be really creative in my job and produce truly excellent software.
In my previous job, I used a text editor to write Perl. There was no such thing as unit testing and copying and pasting was viewed as an aid to productivity rather than a horrific sin.
In my current job, I write C# and a lot of XAML. We use MbUnit for our unit testing and TeamCity for continuous integration. I work with guys who know a lot more than me both at the technical level (custom IL generation anyone?) and the architectural level (a la “I think we’ve reached the point where we need an IoC now”). I’ve produced some code that I’m proud of, and I’ve also spent some time wondering which way was up. Happily, we pair program most of the time, and for this I am eternally grateful.
I’ve become a regular attendee at the Bristol DotNetDevNet group, an avid consumer of RSS feeds from topical blogs and a blogger myself. Exposure to this whirl of information has given me a broad view of things I aim to get to grips with over the coming years, and so I thought I’d compile a shopping list to refer back to.
Also, my current company is very Alt.Net-ish, and there has been a lot of discussion on the UK mailing list for Alt.Net about barriers to entry to doing software development the Alt.Net way. I think this shopping list proves them right.
Nuts and bolts
I use C# on a daily basis and it seems to me that being intimately acquainted with the language(s) you’re using is common sense. I’ve read a book or two and at some point I intend to (skim) read ECMA 334 and ECMA 335.
I’d also like to become very familiar with the .Net framework. The C# 3.0 Cookbook is on my list and maybe I’ll take a Microsoft exam or three?
As well as knowing the language and the BCL, I’d like to be conversant with WPF, WCF, WF and Linq. I have books on all of them sitting on my bookshelf and I’m about half way through the gargantuan Apress tome on WPF.
So that will give me technical knowledge that will be very useful for my current job, but there is oh so much more after which I hanker.
Architecture
How does one go about writing good software? I’ve read a couple of design patterns books, but they were at an introductory level and so I have these in my sights:
-          Head First Design Patterns
-          The Gang of Four book
And with those firmly tucked under my belt, I’d like to explore DDD (Domain Driven Development). Evans’ book is good, apparently.  I’ve heard about n-tier architecture too, but don’t have much idea what that entails. And I’d like to explore ORMs a bit more, especially NHibernate.
Other things that spring to mind here are refactoring, Patterns of Enterprise Architecture and Working with Legacy Code. I hope I get through all the reading before my eyes wear out. One day, I might even dream in code, write beautiful code or become a pragmatic programmer.
The Development Process
And then there’s TDD. This has a famous toolkit, and the things that spring to mind that I’d like to spend more time with are:
-          MbUnit
-          Mocking (e.g. Rhino Mocks)
-          IoC (e.g. Windsor from the Monorail project)
-          Msbuild
-          TeamCity
I can hear terms like “programming to interfaces” and “loose coupling” here.
I’ve heard the term Git bandied about a bit too, and not just when I break the build. How is that different from more traditional source control systems like SVN?
Is it all about objects though?
C# blurs the boundaries slightly between OO and functional programming with lambda syntax and Action<T> and Func<T,...> and I’ve found this to be very powerful in my limited use of it so far. So I’d like to explore functional programming. F# anyone? ML? Haskell?
And what about concurrency?
Also, I’ve tussled with multi-threading over the last few months and I’ve wondered why it seems so fraught with danger. How do languages like Erlang get round this problem and produce high availability, massively parallel systems?
This is going to become more and more topical as multi-core processors become ubiquitous.
Can I lose the chaperone (and possibly get into trouble)?
And then there’s unmanaged code. C# and .NET are amazing, but at some point I’d like to get down and dirty with the guts of the machine just for the experience. I wrote a simple pixel shader for use with WPF recently and that was great fun.
Back to Uni?
And finally, I am aware that my colleagues have a Computer Science degree and I don’t (I’m a mathematician and an actuary). I have heard it said that these CS degree thingies are a bit overrated, but I’m not so sure that’s true. I don’t know about different sorting algorithms and I don’t understand O() notation. I sense that my colleagues have a familiarity with certain key concepts in computing (e.g. networking) that I don’t share, and I’d like to get there. Reading may do it (there’s a networking book on my pile) or maybe at some point I’ll get the opportunity to go back to school.
Every journey of a thousand miles starts with the first step
It’s a daunting list. I have the joy of learning though and I expect to have it indefinitely.  Clearly it’s going to take me years to get to grips with the main stuff. And all the while Microsoft (and maybe even other organisations and individuals) will be bringing out new stuff to stimulate my grey matter.
I like the article “Learning Programming in 10 years”. It seems to me that it’s spot on.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Tuesday, September 30, 2008 9:33 PM | Feedback (4)

Sunday, September 28, 2008 #

UserControl in WPF considered harmful?

I am currently working on a large app that is using WPF as its UI technology.  I’m on a small team of talented developers (i.e. I think my colleagues are talented!) and we came at WPF six months ago from scratch, although everyone apart from me had WinForms experience.

As we built our app, we made frequent use of the WPF UserControl.  I think the main reasons for this were:

  • Visual Studio lists UserControl as an item and this encourages its use.
  • It’s a convenient container for XAML that can be reused anywhere.
  • It feels WinForms-ish and allows you to do whatever you like in the code behind

As we got further into the project, however, it soon became apparent that UserControl allows you to do things that don’t fit very well with “the way of WPF” and we have pretty much refactored out every UserControl in the app, in favour of DataTemplate, ContentPresenter and custom controls, e.g. sub-classes of ContentControl.

This is very much inspired by the Prism project and the use of Model – View – ViewModel (see Dan Crevier’s blog for a good description of this), which we have found a very natural way of structuring the app.

From my experience so far, I’d observe the following:

  • DataTemplate rocks as a way of representing data in the UI
  • If you need to wire things up, bindings and triggers are the first things to think about
  • Code behind comes relatively low down on the list.  Certainly, if a lot of behaviour is going in the code behind I would think quite hard about why.

I’m still in the early days of my journey with WPF, but I’m very impressed with DataTemplate and the use of M-V-VM.  I wanted to get my experiences with UserControl out there and see if anyone else has had similar experiences.  What are the legitimate uses of UserControl?  Any comments?

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Sunday, September 28, 2008 3:14 PM | Feedback (2)

Saturday, September 27, 2008 #

Aligning text baseline in WPF

I had a very frustrating experience last week trying to align the baselines of adjacent pieces of text in a WPF app.  The problem seems to be that this is supported behaviour in a flow document, but not in general UI (e.g. the visual tree of a Window).

After a lot of fiddling, head scratching and googling we discovered that the easiest way to do this is to have two TextBlock elements inside an outer TextBlock.  The following markup:

produces this end result:


 

The TextBlock has magically communicated with its TextBlock children and pulled them into line.

However, we are using a Label next to a ContentPresenter to present arbitrary data with a DataTemplate and we couldn’t find a way to automatically line up the baseline of text in each control.

This isn’t really surprising, since the ContentPresenter could present just about anything.  It just so happens in our app that this is a line of text (with a different font size to the label next to it).

In the end, we had to resort to top aligning the Label (small font size) and the ContentPresenter (larger font size) and binding the Margin property on the Label to its FontSize property via a converter.  This did the trick, but involved a hack because we couldn’t understand the Baseline property on the FontFamily class.

It seems from the MSDN docs that the Baseline property on this class should be the proportion of a font’s height represented by the distance from the very top to the baseline of the text, i.e. it should be less than 1.  However, for Verdana it is 1.005!

The code in our converter ended up looking like this and I’m a bit shamefaced to be publishing it!  I know that we will have to revisit this in the future and I’m frustrated that we couldn’t find an elegant solution to the problem.


The 0.75 bit is particularly gratuitous.  Can anyone shed any light on this?

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Saturday, September 27, 2008 12:19 PM | Feedback (1)

Copyright © CodeCurve

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski