Web service versioning for dummies – level 200

This post is aimed at providing a good way to version web services.  Note that there are many ways to do this, and this is just one way.

When versioning a service, it’s important to be able to run multiple versions side by side.  When you upgrade the web service for one client, you can’t immediately take away the current version from existing clients.  Existing clients will move to the new version if/when they can/want to.

The identifier for the web service is the Url, so the version number must be embedded in the url.

Here is one way to do it:
https://theServer/v1_0/theService.asmx
When you want to modify the web service, do so, but deploy it side-by-side with the current version:
https://theServer/v1_5/theService.asmx

With this versioning strategy, you will be able to publish upgraded web services while maintaining service to existing customers.  Down the road, when you have confirmed that all customers of the v1.0 service have moved to the v1.5 service, you can discontinue the v1.0 version.

I’ve learned that if there are urls with dots (.) in the path, then the IIS lockdown tool won’t work with them.  For that reason, it’s probably good to use (_) instead of (.) for the version delimiter.  I also agree with the first commenter that major and minor versions are enough.

There are plenty of folks talking about web service versioning:
http://www-128.ibm.com/developerworks/webservices/library/ws-version/
http://www.webservicesarchitect.com/content/articles/irani04.asp

Using enum strings with NHibernate persistence – level 400

One of the things that is not very obvious when using NHibernate is how to using Enumerations.  If you merely map an enum with the hbm.xml, NHibernate will persist that class member as an int, which is the underlying type of an Enum value type.  Even if you have your database table configured with a string field, you’ll get an integer in your string field.

To have NHibernate use the string representation of the enum for storing in the database, you need to use a special type class.  Below is a simple example of using the EnumStringType that NHibernate provides.  Consider the following enum that I want to use in my class (this is a very simplified example):

    public enum DeliveryStatus
    {
        Pending,
        Ready,
        Sent
    }

When mapping this in my class, NHibernate would persist 0, 1, and 2 in my database.  What I actually want are the strings to be stored in my table (no comments about normalization, please).  Here is a wierd thing you have to do to achieve this goal.  Here is my mapping:
<?xml version=”1.0″ encoding=”utf-8″ ?>
<hibernate-mapping xmlns=”urn:nhibernate-mapping-2.0″>
    <class name=”Palermo.Shipping.Shipment, Palermo.Shipping” table=”Shipment”>
        <id name=”TrackingId” column=”TrackingId” type=”String” length=”30″ >
            <generator class=”assigned”/>
        </id>
       
        <property name=”DeliveryState” column=”DeliveryState”
            type=”Palermo.Shipping.DeliveryStatusType, Palermo.Shipping”/>
       
    </class>

</hibernate-mapping>

Notice that I have a new type referenced for DeliveryState:  DeliveryStatusType.  This is what’s new.  This type helps NHibernate map an enum string instead of the int.  For this, I must define this type in my code:

    public class DeliveryStatusType : EnumStringType
    {
        public DeliveryStatusType() : base(typeof (DeliveryStatus), 30)
        {
        }
    }

Note that this is very simple, and the 30 specifies the max length of the enum string.  I’d recommend setting this number the same as the length of your string field in your database.

With these small steps, NHibernate will now map Pending, Ready, and Sent to the database field.  Normal programmatic interaction is the same.  NHibernate will take care of all the data access.  Without the above solution, one might be tempted to use string constants, but I’d highly recommend using enums when the possible values are known. 

EVERY application has a natural domain model – level 200

I’m in the camp that loves OO.  I want smart objects for
everything.  I don’t like data-centric programming.  I don’t
like thowing raw data around in DataSets.  I create custom objects
for everything in my applications.  I was reflecting on a very
simple application, and I realized that every application has a natural
domain model.  I’ve had conversations where a developer has said,
“Our application is different.  It’s not an enterprise
application.  Domain-driven design doesn’t apply.”  I’ve come
up with a really simple example to illustrate my point.

Suppose you have an application that only maintains social security
numbers.  That’s it. It doesn’t store person information, just
social security numbers.  In fact, your entire database is one
table with one char(9) field.  One might just go ahead and
keep the social security numbers in a string.  Would that
work?  Yes, but consider the natural domain object for this:

    public class SocialSecurityNumber
    {
        private string _rawNumber;

        public SocialSecurityNumber(string number)
        {
            _rawNumber = number;
        }

        public string GetWithoutDashes()
        {
            return; //the ssn without dashes.
        }

        public override string ToString()
        {
            //format ssn nicely and output.
            return; //the nice output.
        }

        public override bool Equals(object obj)
        {
            return true; //or false if they don’t match.
            //Use some intelligence to compare for sameness.
        }
    }

You could store the information in a string, but then that is a magic
string floating around your application, and every class _just_ has to
know that it must be a social security number.  There is no strong
typing to enforce that there are exactly 9 numerals in the
string.  What about dashes?  with this SocialSecurityNumber
class, you have your domain model, and now you can enforce all the
rules about the number easily.  Maybe you want to always store it
in the database without dashes but want to display it on the UI with
dashes.  Instead of string manipulation elsewhere, encapsulate
that logic directly inside the domain object.  If you use this
object throughout your system, it’s clear that constraints will always
be enforced, and you never have double check that a social security
number is really there – the compiler picks up that burden for you as
well as runtime strong type checking.

Consider your current applications.  Do you have a prominent
string, bool, or int?  Would it be helpful if that piece of
information could carry around describing and validating
information?  Consider creating a domain object to house that
single piece of information and enforce rules about it.  I think
it’ll make the application a lot simpler.

How VirtualPathUtility combines paths in .Net 2.0 – level 100

This is a warning that the VirtualPathUtility class in .Net 2.0 takes
some time to understand the rules under which it operates.  It
wasn’t obvious to me, and I had to do some investigation to learn it’s
behavior.  I expected the following test to pass.  It didn’t.

        [Test]
        public void ShouldCombineTwoWebsitePaths()
        {
            string parentPath = “/websiteRoot”;
            string subDirectory = “newPage”;
            string expected = “/websiteRoot/newPage”;

           
string actual = VirtualPathUtility.Combine(parentPath, subDirectory);
            Assert.AreEqual(expected, actual);
        }

I expected it to actually “Combine” the base path and the path that was
relative to the base path.  After all, if these combine, the
product will be the sum of both, right?  Not really.  Here’s
my test output:

    String lengths differ.  Expected length=20, but was length=8.
    Strings differ at index 1.
   
    expected:<“/websiteRoot/newPage”>
     but was:<“/newPage”>
    ————^

Thanks to the first comment below, I realized that this method
tries to act like a web browser in resolving relative paths.  If I
add a “/” to the end of “/websiteRoot”, the test would have
passed.  As it stands, it assumes that “websiteRoot” is a page and not
a directory.

Hiding errors is evil – level 200

Hiding errors:

  • Swallowing informative excpetions
  • Returning a magic value instead of the error
  • Ignoring errors

I’m sure many can relate this this experience:  I’m using an application or a programming API.  The code runs and returns.  I move on.  I find out later that the code failed, and the work was never done.

This scenario can kill an application’s reliability and reputation.  When this happens, you don’t find out about errors until some time later.  Because of this, you really can’t say that the application is working correctly at any point in time unless you explicitly investigate a log somewhere where errors are stored.

Hiding errors makes life harder.  Finding out about errors when they happen makes for more reliable systems.  I’ll give one quick example from the .Net Framework v2.0.  This example uses C#.
            

string loweredUrl “/mypage.aspx”;

string loweredApplicationPath = “/myApplication”;

 

string appRelativeUrl = VirtualPathUtility.ToAppRelative(loweredUrl, loweredApplicationPath);

Console.WriteLine(appRelativeUrl.Length);

This seems simple enough.  We’re using the VirtualPathUtility class to convert a url to it’s application-relative form.  In this case, I’m passing an invalid argument in.  The rule this method uses is that if the url is not a part of the given application path, it’s invalid.  What does VirtualPathUtility do in this case?  It returns NULL!  I passed in an invalid argument, and it returns null.  The more appropriate response would be throwing an ArgumentException.  Because of this error hiding, I have to know the internal rules of this method and code around them.  I can’t afford for this code to continue while appRelativeUrl is null.  The next line would throw a NullReferenceException.

Because of the error hiding, my code ends up like this:

string loweredUrl “/mypage.aspx”;

string loweredApplicationPath = “/myApplication”;

 

if (!loweredUrl.Contains(loweredApplicationPath))

{

    throw new ApplicationException(string.Format(“url {0} is not in application path {1}”, loweredUrl, loweredApplicationPath));

}

 

string appRelativeUrl = VirtualPathUtility.ToAppRelative(loweredUrl, loweredApplicationPath);

Console.WriteLine(appRelativeUrl.Length);

I have to do an explicit check and compensate for the undesirable behavior of the API.

If an error condition happens, I want to know about it.  The term “fail fast” is very popular.  It means that if the application encounters a condition where it can’t continue, stop now and output the exception information.  Don’t have the application limp along until it crashes in flames.  If you break your arm, you stop what you are doing and get a cast put on.  Yes, you _could_ go to work if it’s not your mousing arm, but you cause less damage if you stop right away and address the problem.