Crimes against internationalization

What’s wrong with this snippet from Authorize.net’s .NET SDK?

public CardPresentPriorAuthCapture(string transactionID, Decimal amount)
    {
      this.SetApiAction(RequestAction.PriorAuthCapture);
      this.Queue("x_ref_trans_id", transactionID);
      this.Queue("x_amount", amount.ToString());
      ...

Did you get it yet? Think about that last line, amount.ToString() — what’s that going to do?

Let’s see — what’s the meaning of $25.99? Well that’s twenty-five dollars and ninety-nine cents. What’s the meaning of €25.99? That’s not as clear – Europeans use “.” where Americans use “,” to denote thousands. Maybe it should be read €25.990; almost twenty six thousand Euros! Or perhaps it’s a typo and that decimal point shouldn’t be there at all, it’s meaningless in the position it’s in anyway, so perhaps the meaning is twenty-five-hundred and ninety-nine Euros.

Well sure enough, Authorize.net’s API assumes that “.” denotes decimals and “,” denotes thousands. If the thread that calls into their SDK is in a European culture that .ToString() call will output 25,99. But when Authorize.net’s API sees that request they parse it as twenty-five-hundred and ninety-nine dollars.

And that is a crime against internationalization. If you’re writing an SDK please do not use .ToString() without a format provided. In this case, if Authorize.net has just added a couple more characters – .ToString(“0.0″) –  the format would stay constant across cultures.

GOTO Not Always Considered Harmful

Many if not most developers have a certain ingrained contempt for the goto statement available in many languages. I’ll contend though that there are times it can aid readability and its existence in modern programming languages is useful.

Take the following code snippet:

function gc_auth_login_validate($form, &$form_state) {
  if ($account) {
    // drupal user exists
    $roles = array_values($account->roles);
    if (in_array(GC_AUTH_ROLE_NAME, $roles)){
      // this is a gc user, authenticate against gc
      $max_login_attempts = $account->data[GC_AUTH_MAX_LOGIN_ATTEMPTS_VARIABLE_NAME] ?: variable_get(GC_AUTH_MAX_LOGIN_ATTEMPTS_VARIABLE_NAME);
      if (gc_auth_check_user($account->mail, $password, $max_login_attempts)->success) {
        goto VALID_GC_CREDENTIALS;
      } else {
        gc_auth_increment_user_login_attempts($account);
      }
    }
  } else {
    // no drupal user exists
    // check for a Group Commerce API user
    // ['values']['name'] contains a username-ified version of the email address
    // ['input']['name'] contains the actual email address inputted
    $email = $form_state['input']['name'];

    $response = gc_auth_check_user($email, $password);
    if ($response->success) {
      $account = gc_auth_create_corresponding_drupal_user($email, $response->userKey);
      if (!$account) {
        // something went wrong creating the corresponding account
        form_set_error(NULL, t('An error occurred.  Please try again or contact support.'));
        return;
      }
      goto VALID_GC_CREDENTIALS;
    }
  }
  VALID_GC_CREDENTIALS:
  // reset max login attempts on user
  user_save($account, array(
    'data' => array(
      GC_AUTH_MAX_LOGIN_ATTEMPTS_VARIABLE_NAME    => variable_get(GC_AUTH_MAX_LOGIN_ATTEMPTS_VARIABLE_NAME),
      GC_AUTH_LOGINS_ATTEMPTED_KEY                => 0,
      )
    )
  );
  $form_state['uid'] = $account->uid;
  user_login_submit(array(), $form_state);
  return;

  NOT_A_GC_USER:
  // form is empty or this is not a gc user, authenticate using the default validators
  foreach($form_state['values']['validators'] as $validator) {
    $validator($form, $form_state);
  }
  return;
}

In this case, the goto statement prevents having to refactor into its own method and enables me to easily code multiple branches that end up performing the same functionality. The alternative would have been to refactor into its own method which is unwanted in this case since the functionality belongs with the login functionality.

snaplet-environment always returning fallback

posted this SO question a while back: http://stackoverflow.com/questions/9879543/snaplet-environment-always-returning-fallback

i was having an issue with the haskell package snaplet-environment – the lookupEnvDefault function wasn’t picking up the correct environment, always returning the fallback value.

my snaplet.cfg looked like:

app
{
  environments
  {
    production
    {
      config-url = "http://www.google.com"
    }
  }
}

well, after a lot of trial and error i found that i had to modify the config to look like this:

app
{
  environments
  {
    production
    {
      config-url = ""
    }
  }
}
environments
{
  production
  {
    config-url = "http://www.google.com"
  }
}

this has got to be a bug, right?  i guess i’ll have to look at the snaplet-environment code sometime… geez!

UPDATE: well thanks to @antipax i’ve submitted a pull request

Social engineering in the wild

My friend just called me to tell me something that happened to him.  He received a phone call from an unknown number.  There was a man on the other line who claimed to be from the internet provider or something of the sort and told my friend that he noticed that my friend’s router and therefore computers had been infected with a virus.  My friend was told to go to one of his internet-connected computers and the caller would step him through the necessary process to rid himself of this virus.  Luckily my friend realized this seemed fishy (or phishy I suppose) and started asking the caller some questions, received no good answers, and decided to hang up.

Beware!

Dynamic configuration settings in .NET 4

We have a default implementation over our API that we can customize for clients.  In order to support different feature-sets we have a custom configuration section inside our web.config that looks similar to this:

<sites>
    <add name="statichippo">
        <hosts>
            <add name="blog.statichippo.com" />
        </hosts>
        <profile enabled="true" />
    </add>
...
</sites>

and this works well for the most part.  But we have some clients that have certain one-off features and settings that aren’t part of our main offering and don’t make sense to be added to our custom ConfigurationSection class.  But it is still important to me to be able to store the associated settings in the same place and I still wanted the settings to be accessible from the same class.

<sites>
    <add name="statichippo">...
        <custom myspaceUrl="whostillusesmyspace?" />
    </add>
</sites>

I ended up adding a CustomSettings property to the SiteElement that the <sites> elements map to.  It’s type?  dynamic.  The API is real simple, you just use the same attribute/element name specified in the web.config to access the value, e.g. CustomSettings.myspaceUrl.  In our case we use AutoMapper to map to a poco class which is useful to prevent runtime issues due to fat fingers on the dynamic type (plus AutoMapper provides a test to ensure you mapped all your properties).  I overrode the OnDeserializeUnrecognizedElement hook inherited from the parent ConfigurationElement class to set it.  Here’s the code:

/// <summary>
/// Custom settings, set via OnDeserializeUnrecognizedElement
/// </summary>
private dynamic CustomSettings { get; set; }

protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader)
{
    if (elementName == "custom")
    {
        // create dyamic element to house the settings
        CustomSettings = new DynamicElement(elementName);
        // deserialize settings into dynamic element
        CustomSettings.Deserialize(reader);
        // yes, we've handled the unrecognized element
        return true;
    }
    return base.OnDeserializeUnrecognizedElement(elementName, reader);
}  

This basically just alters the hander to deal with a <custom> element by using the DynamicElement.’s Deserialize method to read the section.  Here’s the code for DynamicElement:

/// <summary>
/// Used to interpret custom settings
/// </summary>
public class DynamicElement : System.Dynamic.DynamicObject
{
    #region ConfigElement class
    /// <summary>
    /// Used to plug into protected ConfigurationElement methods that need overriding
    /// </summary>
    private class InnerConfigurationElement : ConfigurationElement
    {
        private DynamicElement _parent;
        internal InnerConfigurationElement(DynamicElement parent)
        {
            _parent = parent;
        }

        protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
        {
            if (_parent.Attributes.ContainsKey(name))
                return false;

            _parent.Attributes.Add(name, value);
            return true;
        }

        protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader)
        {
            var element = new DynamicElement(elementName);
            element.Deserialize(reader);
            _parent.ChildElements.Add(element);
            return true;
        }

        internal void Deserialize(System.Xml.XmlReader reader)
        {
            DeserializeElement(reader, serializeCollectionKey: false);
        }
    }
    #endregion

    public string Name { get; private set; }
    internal readonly Dictionary<string, string> Attributes = new Dictionary<string, string>();
    internal readonly List<DynamicElement> ChildElements = new List<DynamicElement>();
    private InnerConfigurationElement _configElement { get; set; }
    internal DynamicElement(string name)
    {
        Name = name;
        _configElement = new InnerConfigurationElement(this);
    }

    public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
    {
        // search attributes first
        if (Attributes.ContainsKey(binder.Name))
        {
            result = Attributes[binder.Name];
            return true;
        }

        // then search child elements
        var childElement = ChildElements.FirstOrDefault(x => x.Name == binder.Name);
        if (childElement != null)
        {
            result = childElement;
            return true;
        }

        result = null;
        return false;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return base.GetDynamicMemberNames();
    }

    public override bool TryConvert(System.Dynamic.ConvertBinder binder, out object result)
    {
        return base.TryConvert(binder, out result);
    }

    public void Deserialize(System.Xml.XmlReader reader)
    {
        _configElement.Deserialize(reader);
    }
}

it’s a bit longwinded but it’s actually pretty simple.  The ConfigElement class region just contains the definition for an InnerConfigurationElement class.  I didn’t want to have to write any xml parsing code since Microsoft provides that out of the box via the ConfigurationElement class.  However, since that class’s entry hook, DeserializeElement, is protected I inherited from it and declared an internal Deserialize method that just calls into this one.  I also overrode the OnDeserializeUnrecognizedAttribute and OnDeserializeUnrecognizedElement methods the latter of which just creates a new DynamicElement and recursively calls the Deserialize method on it.

The rest of the code outside the region is pretty straight forward.  There’s a Dictionary containing attribute name/values and a List<DynamicElement> containing child elements.  Now that I’m writing this it strikes me perhaps this should be a Dictionary itself to reduce lookup times but I leave that as an exercise to the reader (or maybe I’ll update this post at some point… maybe).  When someone attempts to get the value of a property like CustomSettings.SomeValue I first look in the attributes and then if it doesn’t exist there I look in the child elements.

And there you have it – dynamic configuration settings in .NET 4!

Do not take Windows Updates lightly

Recently we experienced an odd issue; on an intermittent basis authenticated users would see a non-authenticated view of the page they were on.  A little debugging revealed that each server behaved well in isolation but when the load balancer was in the mix moving requests between servers things got wonky.  Using his mad curl skillz, @andrewmglenn determined that the authentication cookie set from one of our servers was not playing nicely with the others.  This turned out to be a two way street – one server didn’t like the cookies set from the other servers and the others didn’t like the cookie set from this one.

It turned out this one server had a security update installed not long before we experienced the issue.  The link in Windows Update points to http://support.microsoft.com/kb/2656351 and mentions something about a “vulnerability that would allow an unauthenticated remote attacker to compromise your system”.  The update included updated versions of numerous important files including System.Web.dll and aspnet_wp.exe.  But it takes 2 clicks from the support url to actually get to a page with real information on the exploit and the solution taken in the security update.  Over at http://technet.microsoft.com/en-us/security/bulletin/ms11-100 towards the bottom of the page in the FAQ section there’s a mention of the workaround taken by the update: “The update addresses this vulnerability by correcting how the ASP.NET Framework authenticates users.”

So it seems that this server is generating and verifying authentication cookie values using a new algorithm!

The moral of the story is clear and is an important lesson for small shops: do not take Windows Updates lightly.

C9 Lectures: Dr. Erik Meijer–Functional Programming Fundamentals Playlist

BillRob turned me on to these Channel9 Function Programming lectures by Dr. Erik Meijer.  Unfortunately the episodes are really hard to find – I didn’t see a single playlist or search query that returned all 13 episodes.  And reverse engineering their URLs didn’t work either!  So after performing 13 different searches to find every episode I figured I’d post the links here.  Hopefully MSDN will introduce a Course or Playlist feature that gives quick access to multipart series!

Chapter 1 of 13

Chapter 2 of 13

Chapter 3 of 13

Chapter 4 of 13

Chapter 5 of 13

Chapter 6 of 13

Chapter 7 of 13

Chapter 8 of 13

Chapter 9 of 13

Chapter 10 of 13

Chapter 11 of 13

Chapter 12 of 13

Chapter 13 of 13

Graceful degradation via ASP.NET OutputCacheProvider

Like everyone, we never want our site to go down.  Some pages display data and if something happens to the database we’d like at the very least to display old data instead of an error.  In that vain I wrote a proof of concept that might help.  This is not live and may never go live but it tests well and I thought it was interesting enough to post.

The implementation is based on two interconnected pieces – an OutputCacheProvider and an HttpModule.  The OutputCacheProvider, like the built in output cache provider, is responsible for storing and retrieving cached pages.  In addition, however, it keeps cached pages around past their expiration in case the need arises to render them.  The HttpModule’s responsibility is to handle exceptions and by writing out cached versions of the page regardless of their age.

The sourcecode is available at on github but I’ll step through the initial check version of the code here to better explain what’s going on.

GracefulDegradationOutputCacheProvider

This is just a standard OutputCacheProvider (OutputCacheProviders were introduced with ASP.NET 4.0.  Check out http://weblogs.asp.net/gunnarpeipman/archive/2009/11/19/asp-net-4-0-writing-custom-output-cache-providers.aspx for more info).  The interesting piece to note though is that the standard Get method implemented for OutputCacheProvider just calls another Get method that takes a boolean parameter called respectExpiration.  The “standard” Get method just passes in true for this.  Here’s the code:

 

/// <summary>
/// Gets an item from the cache by key
/// </summary>
/// <param name="key">Key to fine</param>
/// <param name="respectExpiration">If true, don't return stale results.  This parameter should be true
/// in regular caching cases and false if we're retrieving from cache when an exception occurred</param>
/// <returns></returns>
internal object Get(string key, bool respectExpiration)
{
    Debug.WriteLine("Cache.Get(" + key + ")");

    CacheItem existing;
    if (!_items.TryGetValue(key, out existing))
        return null;

    if (!respectExpiration)
        return existing.Item;

    if (existing.Expires > DateTime.UtcNow)
        return existing.Item;

    return null;
}

as you can see, the respectExpiration flag is used to override the cache expiration and return the value anyway.  This is used by the:

GracefulDegradationCacheModule

this just catches the HttpApplications’s Error event and attempts to write the cached output out to the response stream.  There are a couple pieces of interest inside the handler:

Finding the provider

The handler starts off by finding the GracefulDegradationOutputCacheProvider among the available CacheProviders for the application:

// Find the GracefulDegredationOutputCacheProvider
foreach (var provider in OutputCache.Providers)
{
    var inMemoryProvider = provider as GracefulDegradationOutputCacheProvider;
    if (inMemoryProvider == null)
        continue;

the reason this provider isn’t cached in some field is because this can be modified programmatically and so I just loop every time and attempt to find the provider.

Writing the cache out to the response

At first I was using a roundabout method to determine an error threshold with a timer firing and clearing error counts – it was pretty awkward.  When I mentioned it to my peers, Joe (http://twitter.com/#!/joecianflone) really felt the pain and BillRob came up with the much simpler approach of just writing the response out from the cache on error.  Duh!  With a few helpful hints from Bill, here’s what I came up with:

var context = HttpContext.Current;
var response = context.Response;
// clear response
response.Clear();

// we don't want anyone caching this old response, right?
response.CacheControl = "no-cache";

var responseBytes = GetResponseBytes(cacheItem, context);
// write out response body
// you can also append some content if you wish,
// perhaps a floating div that tells the user
// the page they're seeing is old
responseBytes.ForEach(x =>
{
    response.OutputStream.Write(x, 0, x.Length);
});

// Don't want to show the error page (though you
// probably want to alert someone!)
context.ClearError();

notice that we explicitly tell clients not to cache this!  Also, as mentioned in the comments, I could see adding some hook here to place some floating div somewhere to let people know what they’re seeing may be stale.  Also, the error is cleared so you probably want to log it somewhere – just because your end user doesn’t see an error doesn’t mean you don’t want to know it happened!

Testing SyntaxHighlighter

So I found what looks like it might be a good solution to some issues I’m having with syntax highlighting on my blog.  It’s a combination of a script called SyntaxHighlighter (http://alexgorbatchev.com/SyntaxHighlighter/) and a Windows LiveWriter plugin called PreCode Snippet (http://precode.codeplex.com/).  So here’s a little test to make sure it works well with both C# and F# (I found the F# brush for SyntaxHighligher over at Steve Gilham’s blog - http://stevegilham.blogspot.com/2009/10/syntaxhighlighter-20-brushes-for-f-and.html)

public class Foo
{
    public object Bar { get; set; }
    private object _baz;
    public void SetBaz(object o)
    {
        if (o == null)
            throw new ArgumentNullException();
        _baz = o;
    }
}
let rec fib x =
    if x = 0 then
        0
    elif x = 1 then
        1
    else
        fib (x-1) + fib (x-1)

So it seems that when I press Enter to exit the PreCode Snippet that it just creates a new snippet and I have to go into the Source and type something outside of the <pre> tag so that I can go back to Edit mode and start typing some regular text.

Now to publish and see how it looks online. Took a couple tweaks but it looks pretty good!

F# and Entity Framework, not there yet

Based on this article on MSDN I decided to code the data layer for an app in F#.  After a few weeks of hobby time coding, I don’t believe that EF via F# is a viable solution yet.  Here’s why:

NOTE: Windows Live Writer is crashing constantly on me.  I’ve got 2 reasons so far and may update this post with more when Live Writer starts behaving (going to restart at some point this week I suppose) or I find a more stable editor.

1. No protected keyword

Because the Entity Framework’s proxy classes inherit from their base classes (and because they do not support setting private properties of their ancestors), the protected keyword becomes especially important.  Protected becomes a way of creating properties that can be set only by the class itself and by Entity Framework’s proxy classes.  I’m especially fond of this in constructors.  Take the following code snippet:

   1: public class Person

   2: {

   3:     public string FirstName { get; set; }

   4:     public string LastName { get; set; }

   5:     public void Person(string firstName, string lastName)

   6:     {

   7:         FirstName = firstName;

   8:         LastName = lastName;

   9:     }

  10:     protected void Person() {}

  11: }

This requires client code to specify a first and last name for a Person while still allowing Entity Framework to construct a new Person object via its default constructor (a requirement) before setting the properties.  This is also really useful for lists and such – by making them protected you can ensure that they are never null and wrap list inserts inside a method like so:

   1: ...

   2: protected List<string> people { get; set; }

   3: public void AddPerson(string name)

   4: {

   5:     // business logic around the name

   6:     people.Add(name);

   7: }

   8: ...

Since F# doesn’t support the protected keyword, there’s no alternative to generating a public default constructor and exposing your lists getter and setter for all.

2. Awkward null support

When writing functional code, the lack of implicit support for null values is very useful.  However, Entity Framework is used to interact with a database – somewhere where nulls are commonplace and very useful.  I wrote a blog post about one issue with this (F#, System.Linq extensions and the case of the missing null) but there are others including lack of support for Nullable<T> (in case you think you’re unfamiliar with Nullable<T>, you’re probably not.  You may never have written Nullable in your code — the ? in C# is syntactic sugar around it.  So if you’ve ever written int? in C#, you’ve used Nullable<int>).  F# has it’s own way of achieving something similar to Nullable<T> called Option<T> but it’s based on F# Discriminated Unions and is not supported by Entity Framework. 

The biggest use case for Nullable<T> in Entity Framework in my opinion is with DateTime.  DateTime is a value type and cannot be null.  But null datetime values in the database are a frequent occurrence usually meant to signify that something has never taken place.  Take the following code:

   1: public class Email

   2: {

   3: ...

   4:     public DateTime? DateSent { get; set; }

   5: ...

   6: }

In this case, the Email class defines a DateSent property that presumably will be null until the email is actually sent.  This makes a lot of sense in the database and even in C# but doesn’t work out so well in F#.  First of all there’s the syntactic sugar in C#.  Consider the same code written in F#:

   1: open System

   2: type Email =

   3: ...

   4:     let mutable m_dateSent = new Nullable<DateTime>()

   5:     member this.DateSent with get () = m_dateSent 

   6:                                 and set v = m_dateSent <- v

   7: ...

Aside from the verbosity, check out this snippet that doesn’t compile (if you’re not familiar with the syntax, I’m using the F# PowerPack Linq extensions):

   1: let unsentEmails = query <@ seq { for e in context.Emails do

   2:                                     if e.EmailSent = null then

   3:                                         yield e

   4:                                  } @> 

 

Can you guess why that won’t compile?  Line 2 checks EmailSent, which is a Nullable<DateTime> against null which is not permitted a null value.  You can get around this by changing that line to

   1: if e.EmailSent.HasValue = false then

However, the outputted SQL (using the default, MSSQL connector) from this line is far worse than the equivalent in C# (using the “= null”).  In C#, the expected SQL is outputted – including a where clause that checks for the column against null which allows the use of an index in MSSQL (although not for mySQL which is another conversation altogether!).  The F# code, checking the HasValue property of the Nullable<DateTime>,  generates some awful SQL in the where clause using CASE and CAST seemingly just to annoy by preventing the use of indexes:

   1: WHERE 0 = 

   2: (CASE 

   3:     WHEN ([Extent1].[EmailSent] IS NOT NULL) THEN cast(1 as bit)

   4:     WHEN ([Extent1].[EmailSent] IS NULL) THEN cast(0 as bit)

   5:  END)