Drinking the F# Kool-Aid

Friend Colin Whitlatch just sent me the following C# code snippet to mess with my Saturday morning.  Note the underscore:

 

Action<object> strangeLambda = _ => 
    Console.WriteLine("F# Rules");
strangeLambda(null);
Console.ReadLine();

DevLink Dynamic Object Code Sample

Several people asked about the Dynamic code I used for making Restful calls at the end of the Dynamic Types and Dynamic Objects talk at DevLink.

I have uploaded the sample to my skydrive.  Please use this code in any way you like.  Just keep in mind that most of the magic going with JSON and XML parsing was written by Nikhil Kothari.

Addendum to Dynamic Method Bags

Bill Wagner has an interesting article on MSDN about implementing Dynamic Objects in C# 4: http://msdn.microsoft.com/en-us/library/ee658247.aspx.  He leaves it up to the reader to figure out the right way to implement the class he describes and provides suggestions.  This is a great way to structure a propaedeutic of this sort, as it affords the clever reader an opportunity to dig into the material on her own.

At the same time, it is often helpful to have a key against which to compare one’s own work.  To that end, the full code required to run the sample application described in the article follows.

Here is the code that serves as our test.  Bill Wagner describes an object that inherits from DynamicObject that will run the following code:

    var newType = new MethodBag();
    newType.SetMethod("Write", () => Console.WriteLine("Hello World"));
    newType.SetMethod("Display", (string parm) => Console.WriteLine(parm));
    newType.SetMethod("IsValid", () => true);
    newType.SetMethod("Square", (int num) => num * num);
    newType.SetMethod("Sequence", () => from n in Enumerable.Range(1, 100)
                                        where n % 5 == 2
                                        select n * n);
    dynamic dispatcher = newType;
    dispatcher.Write();
    var result = dispatcher.IsValid();
    Console.WriteLine(result);
    dispatcher.Display("This is a message");
    var result2 = dispatcher.Square(5);
    Console.WriteLine(result2);
    var sequence = dispatcher.Sequence();
    foreach (var num in sequence)
        Console.WriteLine(num);

    Console.ReadLine();

 

Here is an implementation of MethodBag that will fulfill the expectations established above:

internal class MethodBag: DynamicObject
{
    private Dictionary<string, MethodDescription> methods = 
        new Dictionary<string, MethodDescription>();

    #region Method Descriptions

    private abstract class MethodDescription
    {
        internal abstract int NumberOfParameters
        {
            get;
        }
        internal Expression target
        {
            get;
            set;
        }
        internal abstract object Invoke(object[] parms);
    }

    private class ActionDescription: MethodDescription
    {
        internal override int NumberOfParameters
        {
            get { return 0; }
        }
        internal override object Invoke(object[] parms)
        {
            var target2 = target as Expression<Action>;
            target2.Compile().Invoke();
            return null;
        }
    }

    private class ActionDescription<T> : MethodDescription
    {
        internal override int NumberOfParameters
        {
            get { return 1; }
        }
        internal override object Invoke(object[] parms)
        {
            dynamic target2 = target;
            target2.Compile().Invoke(parms[0]);
            return null;
        }
    }

    private class FuncDescription<T> : MethodDescription
    {
        internal override int NumberOfParameters
        {
            get { return 0; }
        }
        internal override object Invoke(object[] parms)
        {
            dynamic target2 = target;
            return target2.Compile().Invoke();
        }
    }

    private class FuncDescription<T,S> : MethodDescription
    {
        internal override int NumberOfParameters
        {
            get { return 1; }
        }
        internal override object Invoke(object[] parms)
        {
            dynamic target2 = target;
            return target2.Compile().Invoke(parms[0]);

        }
    }

    #endregion

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args
        , out object result)
    {
        result = null;
        if (!methods.ContainsKey(binder.Name))
            return false;
        // Described later
        MethodDescription method = methods[binder.Name];
        if (method.NumberOfParameters != args.Length)
            return false;
        result = method.Invoke(args);
        return true;

    }

    #region Set Methods

    public void SetMethod(string name, Expression<Action> lambda)
    {
        var desc = new ActionDescription { target = lambda };
        methods.Add(name, desc);
    }

    public void SetMethod<T>(string name, Expression<Action<T>> lambda)
    {
        var desc = new ActionDescription<T> { target = lambda };
        methods.Add(name, desc);
    }

    public void SetMethod<T>(string name, Expression<Func<T>> lambda)
    {
        var desc = new FuncDescription<T> { target = lambda };
        methods.Add(name, desc);
    }
    
    public void SetMethod<T,S>(string name, Expression<Func<T,S>> lambda)
    {
        var desc = new FuncDescription<T,S> { target = lambda };
        methods.Add(name, desc);
    }

    #endregion
}

 

Your output should look like this:

Hello World

True

This is a message

25

4

49

144

289

484

729

1024

1369

1764

2209

2704

3249

3844

4489

5184

5929

6724

7569

8464

9409

New Edition of Effective C# in Progress

effective_csharp

I just noticed that Safari Books has put up a rough cut of the 2nd Edition of Bill Wagner’s Effective C#.  My Safari license only allows me to preview but I can already see from the table of contents that he is including new chapters on working with C# 4.  This is pretty exciting.  If you recall, the 1st Edition only covered C# 1 and after a largish gap Bill Wagner published a completely different book, More Effective C#, to cover the C# 2 and C# 3 features.

I have long recommended both of Bill’s books to anyone who wants to get a deeper understanding of the C# language.  I’ve only recently started seriously reading through John Skeet’s C# In Depth, however.  I was originally put off with how much time he puts into explaining C# 1 and C# 2.  Now that I am into the second half of the book, I am very excited about his coverage of lambdas in C# 3.  His passion about this interesting language feature is both palpable and infectious.  He also does a good job of clearing up the fud around the stack and the heap.

Having these three books on the bookshelf will make anyone a more effective C# developer – well, that’s an idiom of course.  To be clear, having these three books and also reading them will in fact make anyone a more effective C# developer.  Well – just to be extremely clear – I should have said “reading and re-reading them”.  I’ve read through both of Bill Wagner’s books twice and actually had to read his introduction to generics about 6 times before I finally understood most of what he is saying.  The fault however is due not with the exposition and only partly due to the limited faculties of this non-ideal reader – C# programming can be extremely complicated stuff and we are all fortunate to have both Bill Wagner and John Skeet doing the heavy lifting involved in explaining it to the rest of us.

That Wild and Crazy Dynamic Type

I had a mind-blowing weekend playing with the ExpandoObject in C# 4.0.  When an article appeared on MSDN about it prior to the release of Visual Studio 2010 Beta 2, it looked interesting but not particularly useful.  The ExpandoObject appeared to be merely a property bag that was useful in limited circumstances in which the program flow is aware of the properties being added.  The ExpandoObject is, in essence, a property bag (and also a method bag?) that pretends to be a real type.  With the Beta 1, I tried to bind a WPF Window to it and was quickly disappointed to find that WPF just treated it as a dictionary (which is what it really is) rather than as the typed class it is pretending to be.

With the Beta 2, however, this changed.  The WPF binding stack had apparently been modified to recognize the ExpandoObject and to treat it on its own terms.  If I have a binding on a TextBox in WPF to an arbitrary property called, for instance, “Name”, all I have to do is add that string to the ExpandoObject’s internal dictionary and the value I added will show up in my TextBox.  Even better, the ExpandoObject automatically supports INotifyPropertyChanged on that new pseudo-property.

           dynamic Employee = new ExpandoObject();
           Employee.Name = "Jim Henson";

This small change makes the ExpandoObject suddenly very useful, especially in situations where we need a glue layer between servers and clients that are indifferent to static typing such as an object layer between a REST service and WPF.

Phil Haack has a playful post about this aspect of programming with the dynamic type on his blog: http://haacked.com/archive/2009/08/26/method-missing-csharp-4.aspx .  He prefaces it with this:

Warning: What I’m about to show you is quite possibly an abuse of the C# language. Then again, maybe it’s not. 😉 You’ve been warned.

There’s a lot of truth in this.  On the one hand, dynamic types goes deeply against the grain of anyone who has programmed in C# for the past several years.  I’m not sure how this feels to VB developers who always have had the option to turn Option Strict off in their code.  It gives me the heebie-jeebies, though.

At the same time, it looks extremely fun.  Maybe even a little subversive. I want to start finding applications for this new code feature for working within C# rather than simply using it for interop with supported dynamic languages.

The ExpandoObject does some rather cool things not initially obvious.  For one thing, I can add methods to it as well as properties.  This can be done by passing a delegate to it that references a lambda statement, for instance:

        dynamic obj = new ExpandoObject();

        obj.DoSomething = new Func<string>(() => 
            { Console.WriteLine(DateTime.Now.ToLongTimeString()); return "Hello"; });

        obj.DoSomethingWithParams = new Func<string, bool>((x) => 
            { Console.WriteLine(DateTime.Now.ToLongTimeString());  
                Console.WriteLine(x); 
                return true; 
            });
        Console.WriteLine(obj.DoSomething());
        Console.WriteLine(obj.DoSomethingWithParams("something different"));

Another thing it can do is load properties dynamically (loading a dynamic type dynamically, yeah!) by simply casting it back to the dictionary it really is internally.  Here’s a sample of dynamically loading up an ExpandoObject based on an XML Document:

           XDocument root = XDocument.Load("Employee.xml");
            //convert xml document into an ExpandoObject
           dynamic Employee = new ExpandoObject();

           var EmployeeDictionary = Employee as IDictionary<string, object>;
           foreach (XElement el in root.Elements())
            {
                    EmployeeDictionary.Add(el.Name.LocalName, el.Value);
            }

I now have an object that I can bind to the DataContext of a WPF Window.  I could, of course, have just bound the original XMLDocument to my WPF, but then I wouldn’t have nice extras like INotifyPropertyChanged that I normally expect to have at my disposal in WPF development.

The Dynamic Type is a complicated beast however.  Just reading over Bill Wagner’s post on implementing a Method Bag fills me with anxiety: http://msdn.microsoft.com/en-us/library/ee658247.aspx

That post was nothing, however, compared to this gem I found on Nikhil Kothari’s blog from over a year ago!  http://www.nikhilk.net/CSharp-Dynamic-Programming-REST-Services.aspx

Mr. Kothari builds a class that can point to multiple (and, thanks to the Dynamic Type, interchangeable) REST services and generates properties based on the XML or JSON that comes back.  It does much more than this, also, I think, but Nikhil Kothari is so far beyond me that I have trouble understanding everything that is happening in his code.

The source code, by the way, doesn’t actually compile as it is currently written – but then he did this over a year ago, so…

In any case, walking through and coming to terms with what he has created is certainly one of my goals for November.  It is an implementation that is a game-changer for C# development, and raises Dynamic Types from an oddity to something that will actually solve architectural bottlenecks … at least, I think it does.  As I said, I don’t actually understand it, yet.

Covariance and Contravariance In 5 Minutes

C# 4.0 will introduce new language features to help manage covariance and contravariance.  While this is a a wonderful capability, it forces us to come to terms with these (to me) somewhat unfamiliar terms.

As I have been working through Eric Lippert’s excellent series of posts on this topic as well as the wikipedia entry, it has occurred to me that the best way to come to grips with these concepts is to examine gradually more complex examples of covariance and contravariance as it currently exists in C# 3.  If this appears to be a rehash of Eric Lippert’s work, this is probably because it is.  Consequently, any mistakes are purely mine, while any virtues in this explanation are clearly his.

First, however, it is necessary to learn some vocabulary.

Take the following class hierarchy:

        public class Animal{}
        public class Mammal : Animal { }
        public class Tiger : Mammal { }

We would typically say that Mammal is more derived than Animal.  Mammal, conversely, is less derived than Tiger in this inheritance chain.

To understand covariance and contravariance, we need to replace more derived and less derived with the metaphorical terms smaller and bigger.

We do this because more derived and less derived are not adequate to describe the relation between objects such as arrays of types.

        Animal[] A;
        Mammal[] M;
        Tiger[] T;

An array of Mammal does not derive from an array of Animal.  Both Mammal[] and Animal[] are derived from System.Array. There is no inheritance relation, however, between Mammal[] and Animal[] themselves.  Nevertheless there is obviously some sort of relation present.  By convention, we call this relation a smaller than \ greater than relation.  Mammal[] is smaller than Animal[] because Mammal is more derived than Animal.  It is bigger than Tiger[] because Mammal is less derived than the type Tiger.

It is worth repeating that smaller and bigger are not the same thing as the relation between classes in an inheritance hierarchy.  They also do not have anything directly to do with memory management.  They are pure metaphors.

The C# classes above model concepts.  When we talk about concepts such as animal, mammal and tiger, we talk about these concepts falling under each other.  Socrates falls under the concept of man.  Man falls under the concept of an animal (traditionally, man is defined as a bipedal, hairless animal that laughs; see Haecceity).

Metaphorically, we can think of animal as a bigger concept than mammal because many more things fall under animal than under mammal.  Tiger, in turn, is a smaller concept than mammal because so few things fall under it.

Once we have smaller than and bigger than under our belts, we can start talking about covariance and contravariance.  Covariance and contravariance, at the most basic level, concerns the assignment of types to variables.

An assignment is covariant if we can assign a smaller type to a bigger type:

covariance

If we can assign a bigger type to a smaller type, the assignment is said to be contravariant:

contravariance

1. Covariance with simple reference types

An example will help to illustrate this. 

    Mammal m = new Tiger();
    Animal a = m;
    //Tiger t = a;  -- will not compile

We can assign a smaller type, Tiger to a variable allocated as a Mammal.  Similarly we can assign our Mammal instance to a variable allocated as an Animal.  In other words, in the assignment of simple reference types, we can assign smaller things to bigger things.  This is a covariant relation.

We cannot, however, assign an Animal instance to a Tiger.  The C# compiler just won’t let us do it, because it will not let us assign something bigger to something smaller in this case.  The assignment of simple reference types is therefore not covariant.

2. Covariance with arrays

The C# compiler also happens to allow covariant array assignments.  For instance:

    Mammal[] M = new Tiger[0];
    Animal[] A = M;
    //Tiger[] t = A;  -- will not compile

The compiler doesn’t need to allow this.  It just happens to.  What’s interesting is that the compiler will not allow us to do the same thing with generic collections. 

3. Invariance with generics

Assignment of generics is invariant in C# 3.

    // List<Mammal> mammals = new List<Tiger>(); -- will not compile
    // List<Animal> animals = mammals; -- will not compile
    // List<Tiger> tigers = animals;  -- will not compile
    //

4. Covariance with method parameters

Parameter assignment also happens to be covariant in C#.  To prove it to yourself, take the following static method:

     public static void TakeMammal(Mammal m){}

Which of the following operations is permissible in C# and which is not?

    TakeMammal(new Tiger());

    TakeMammal(new Animal());

    TakeMammal(new Mammal());

(Note, however, that ref and out parameters are invariant: http://blogs.msdn.com/ericlippert/archive/2009/09/21/why-do-ref-and-out-parameters-not-allow-type-variation.aspx .)

5. Delegate contravariance with respect to inputs

Understanding this characteristic of parameter assignments is important in order to demonstrate how contravariance occurs in C#.  In C#, delegate assignments are contravariant with respect to inputs.  Consider this code:

 public static void TakeAnimal(Animal a) {}
 public static void TakeMammal(Mammal m){}
 public static void TakeTiger(Tiger t) {}

public delegate void MammalHandler(Mammal m);

MammalHandler funcA = TakeAnimal; //OK
MammalHandler funcM = TakeMammal; //OK
MammalHandler funcT = TakeTiger;  //No!

            funcA(new Mammal()); //OK
            funcM(new Mammal()); //OK
            funcT(new Mammal()); //No!

The delegate method MammalHandler is designed to only take the Mammal type as input.  Any delegate instance – funcA, funcM, funcT – in turn may be passed Mammal objects.  If we pass a Mammal to delegate instance funcA, it ultimately gets passed to our TakeAnimal method.  Since parameter assignments – as we showed above – are covariant, passing a Mammal to TakeAnimal is permissible.  Obviously passing a Mammal to TakeMammal is also permissible.

We cannot, however, pass a Mammal to TakeTiger.  The C# compiler does not allow this.

Consequently, we also cannot assign TakeTiger to our MammalHandler delegate.  Assigning TakeTiger to funcT is illegal.

But in this impermissible delegate assignment, which thing is bigger: MammalHandler or TakeTiger?  MammalHandler, right?  With regard to delegate assignments, then, we are saying that assigning something smaller to something bigger is not allowed.  Assigning something bigger to something smaller, however, is permissible.

Delegate assignments like those above are therefore contravariant.

6. Delegate covariance with respect to return types

I say “like those above” because this is actually true only with respect to delegate inputs.  Delegates can also, of course, return objects – and when they do, this is a covariant relation.  Delegate assignments are said to be contravariant with respect to inputs, but covariant with respect to return types.  You can prove this to yourself by looking through the following code in which the delegate signature has a return value but no parameters.

 

public static Animal GetAnimal() {} public static Mammal GetMammal(){} public static Tiger GetTiger() {} public delegate Mammal GetMammalDelegate(); GetMammalDelegate funcA = GetAnimal; // No! GetMammalDelegate funcM = GetMammal; // OK GetMammalDelegate funcT = GetTiger; // OK

 

 

 

So why is this important for understanding C# 4.0?  As we briefly covered above, C# 3 has this peculiar characteristic in that the compiler treats array assignments as covariant operations, but treats the generic assignment of List<T> as an invariant operation. This is obviously a little weird.  In C# 4.0, there will be support for covariance and contravariance in generic interfaces which will allow us to specify how we want our generics to behave – for instance, a special kind of covariant IEnumerable<out T> could be implemented that would provide the sort of covariance now supported for arrays.

Alternatives to returning Void: Continued

“If you look long enough into the void the void begins to look back through you." – Nietzsche

Returning types rather than void on methods that do not necessarily require a return value, as occurs in the implementation of the Append methods on the StringBuilder, allows us to do some interesting method chaining in our code.

Bill Wagner suggests doing something similar with collections in More Effective C# .  My examples are a bit more contrived, however.

Suppose – for the sake of the premise if for nothing else – that we have a business requirement to take a decimal collection of prices and then add 6 percent to each collection member.  We could write the following custom collection to do this:

    public class Prices: IEnumerable<decimal>
    {
        private List<decimal> _mySequence;
        public Prices()
        {
            _mySequence = new List<decimal>();
        }
        public Prices Add(decimal d)
        {
            _mySequence.Add(d);
            return this;
        }
        public IEnumerator<decimal> GetEnumerator()
        {
            foreach (decimal d in _mySequence)
                yield return d;
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            foreach (decimal d in _mySequence)
                yield return d;
        }
        public Prices AddSixPercentAndWrite()
        {
            foreach(decimal d in _mySequence)
                Console.WriteLine(string.Format("{0:C}",d * 1.06m));
            return this;
        }
    }

Which we would then call thus:

        var prices = new Prices();
        for(decimal d = 0; d< 20m;d++)
        {
            prices.Add(d);
        }
        prices.AddSixPercentAndWrite();
 

The business is initially happy with this, but then comes back a week later to say that the six percent tax is nine percent in a different store. Additionally, while sometimes the business wants to see the final price, they also sometimes want to see the original price alongside of it. 

Besides our original output, we now also need to be able to push a list that looks something like this:

$0.00 $0.00

$1.00 $1.06

$2.00 $2.12

$3.00 $3.18

$4.00 $4.24

$5.00 $5.30

$6.00 $6.36

$7.00 $7.42

$8.00 $8.48

$9.00 $9.54

$10.00 $10.60

$11.00 $11.66

$12.00 $12.72

. . .

Seeing where this is headed, we realize that to handle all foreseen and unforeseen scenarios, we should come up with a way to chain up our methods in order to make the code more flexible.

We could restructure the AddSixPercent method to take a parameter; we could then break out the Write method so we can call it multiple times if needed.  We could also change the signatures on our methods to return our Prices collection instead of void, allowing us to chain the methods together.

There’s a hitch, however.  While returning Prices would allow us to do some chaining, we still wouldn’t get the right results since each method would iterate through the whole collection before returning.  Consequently we would end up printing out all the items in the first column before getting around to printing the items in the second column (the calculated cost with tax), which isn’t what we want at all.

. . .

$12.00

$13.00

$14.00

$15.00

$16.00

$17.00

$18.00

$19.00

$0.00

$1.06

$2.12

$3.18

$4.24

$5.30

$6.36

$7.42

$8.48

$9.54

$10.60

$11.66

$12.72

. . .

By using iterators, on the other hand, every method in our chain would act on a particular iteration rather than on the whole sequence.  Besides getting the output that we want, this would also happily give us much more efficient code since we only have to iterate through our collection once rather than once per chained method call.

If we are to use iterators, however, we can’t return the Prices type.  Instead we have to return an IEnumerable type.  Leaving the rest of our Prices custom collection class alone, here’s what that new code would look like:

public static IEnumerable<decimal> AddXPercent(IEnumerable<decimal> sequence
    , short percent)
{
    foreach (decimal d in sequence)
        yield return d + (d * percent * .01m);
}
 
public static IEnumerable<decimal> WriteToConsole(IEnumerable<decimal> sequence)
{
    foreach (decimal d in sequence)
    {
        Console.Write(string.Format("{0:C} ", d));
        yield return d;
    }
}

Our calling code, in turn, would look like this:

    foreach (decimal d in Prices.WriteToConsole(
        Prices.AddXPercent(
        Prices.WriteToConsole(
        prices), 6)
            )
        )
        Console.WriteLine();
 

We’ve managed to achieve chaining, but not so elegantly, all things considered.  First, we have to include the name of our Type in order to chain our methods together.  Second, the chaining is done with nested methods instead of the clean With-like syntax I was extolling in the previous post.  Finally, the sequence of activity isn’t particularly clear.  Because we are chaining our methods by using nesting, the innermost nested method occurs first, while the first shall be processed last.

Fortunately extension methods allow us to alter the way our methods are called.  In order to get the sort of syntax we want, we just need to pull our iterator methods into an extension methods class like so:

    public static class PricesExtension
   {
        public static IEnumerable<decimal> AddXPercent(
            this IEnumerable<decimal> sequence
            , short percent
            ) 
        {
            foreach (decimal d in sequence)
                yield return d + (d * percent * .01m);
        }
 
        public static IEnumerable<decimal> WriteToConsole(
            this IEnumerable<decimal> sequence
            )
        {
            foreach (decimal d in sequence)
            {
                Console.Write(string.Format("{0:C} ", d));
                yield return d;
            }
        }
    }

Giving us the results we were looking for:

$0.00 $0.00

$1.00 $1.06

$2.00 $2.12

$3.00 $3.18

$4.00 $4.24

$5.00 $5.30

$6.00 $6.36

$7.00 $7.42

$8.00 $8.48

$9.00 $9.54

$10.00 $10.60

$11.00 $11.66

$12.00 $12.72

. . .

 

We can now call our code like this:

    foreach(var d in prices
            .WriteToConsole()
            .AddXPercent(6)
            .WriteToConsole()
            )
            Console.WriteLine();

This alternative to returning void involves three tricks:

1) Returning an IEnumerable type instead of void.

2) Taking an IEnumerable type as a parameter.

3) Using these signatures in extension methods rather than the custom collection class itself.

If the syntax looks familiar, this is because this is also how LINQ to Objects is implemented.  For that very reason, we could have accomplished similar results by using LINQ:

    foreach(var d in prices
        .Select(d => { Console.Write(string.Format("{0:C} ", d)); return d; })
        .Select(d => d + (d * 6 * .01m))
        .Select(d => { Console.Write(string.Format("{0:C} ", d)); return d; })
        )
    {
        Console.WriteLine();
    }

It’s funky code, no doubt, but I also find it highly compelling.  I know that as I loop through my prices, I am writing out the original price, I add 6 percent to it in the following line, then I write out that result in the final line.  Inside the foreach block, I then perform any follow-up operations: in this case, writing a new line.

Alternatives to returning Void

I was playing with the Unity Framework recently when I came across the following C# code sample on msdn:

    IUnityContainer uContainer = new UnityContainer()
        .RegisterType<IMyInterface, FirstObject>()
        .RegisterType<MyBaseClass, SecondObject>();
    MyObject myInstance = uContainer.Resolve<MyObject>();

This looked so much like the VB With syntax that I uncharitably assumed that the authors at MSDN had somehow confused C# and VB.  After all, they had written this the standard C# syntax elsewhere:

    // Create container and register types
    IUnityContainer myContainer = new UnityContainer();
    myContainer.RegisterType<IMyService, DataService>("Data");
    myContainer.RegisterType<IMyService, LoggingService>("Logging");
 
    // Retrieve an instance of each type
    IMyService myDataService = myContainer.Resolve<IMyService>("Data");
    IMyService myLoggingService = myContainer.Resolve<IMyService>("Logging");

C# developers with more than 8 or so years of experience can generally be broken down into two types who are mutually suspicious of one another: those who came up through the VB6 programming ranks and those who came up through C++ or Java.  I did the former, and for the most part have never looked back.  I don’t even get involved in disputes between C# lovers and VB lovers.  They’re both nice language.  I just happen to use the former for most things.

The one thing I do miss from VB, however, is the With command.  It always seemed an elegant piece of syntactic sugar and easier to read when you find code that manipulates the same object repeatedly.  My “you can’t do that on television” moment over the msdn sample code came out of that longing for something I thought I’d simply had to leave behind.

It took me a while to realize that the sample code was taking advantage of a trick that has always been available to C# developers but just not extensively used. (I even had to show it to several colleagues just to make sure I wasn’t just being slow – everyone’s first thought, blessedly, was that it was somehow a VB-to-C# translation mistake.) The trick is that the RegisterType method is returning an IUnityContainer object.  Because a C# statement, unlike a VB statement, can be spread out over multiple lines in the editor until a semicolon delimiter is encountered, the code can be made to take on this VB-ish cast.  In fact, the Append method of the StringBuilder type similarly returns its own container type, making the following code blocks equivalent:

    StringBuilder sb = new StringBuilder();
 
    // this code ...
    sb.AppendLine("one");
    sb.AppendLine("two");
    sb.AppendLine("three");
 
    // is equivalent to this ...
    sb.AppendLine("one").AppendLine("two").AppendLine("three");
 
    // is equivalent to this ...
    sb.AppendLine("one")
      .AppendLine("two")
      .AppendLine("three");

This trick won’t work for properties, of course, but it is still pretty fun, and I’m kicking myself for never having come across it earlier.

ASP.NET AJAX: Script Globalization without the ScriptManager

bigfoot

I just spent about four hours trying to solve a problem I’ll probably never actually encounter in the wild.  Someone posted on the asp.net forums about script globalization using ASP.NET AJAX.  This can be set up pretty easily by simply using the ScriptManager control and setting its EnableScriptGlobalization property to true.  ScriptManager takes care of importing the necessary scripts and handling all the underlying code required to make things work.

What the seeker on the forums wanted to know, however, was whether this could be accomplished without the ScriptManager.  In theory, all the ASP.NET AJAX framework scripts can be downloaded and used in a non-platform dependent manner.

Certain software problems are ubiquitous, and people tend to fall over themselves blogging and posting about them until Microsoft or some other vendor eventually either fixes the problem and it goes away.  On the other hand, there are problems in the software bestiary that are so rare that working on them is the programming equivalent of doing cryptozoology.

This was a juicy problem of that sort.  And I believe I have a solution. It basically involves redoing some of what the ScriptManager does automatically, but what the hey.

To support globalization in ecmascript, the ScriptManager basically sets a variable called __cultureInfo behind the scenes.  This is then used by various ASP.NET AJAX script methods to provide formatting information.  This is actually explained in the Microsoft documentation for the feature.

Behind the scenes, it seems clear, the ScriptManager is querying the CurrentUICulture of the current thread in order to determine the browser’s preferred language, and passing this to the __cultureInfo variable.  The trick, then, is to determine the format of the culture data passed to __cultureInfo.

Here I had to use reflection to discover that there is an internal ClientCultureInfo type in the Sys.Web.Extensions assembly.  It made sense that this was being serialized and passed to the __cultureInfo variable.  With some trial and error, I finally got the serialization correct.

To make this work, you will need to download the Ajax Framework Library, which is a collection of javascript files.  You will need to import the MicrosoftAjax.js file into your web project, and then reference it in your page, like this:

<script src=”MicrosoftAjax.js” type=”text/javascript”></script>

You will also need to create the ClientCultureInfo class for your project, and make sure that it is serializable.  I tried DataContractJsonSerializer class to do my serializing,  but had problem getting the DateTimeFormatInfo type to serialize correctly, so I finally opted to use the now obsolete JavaScriptSerializer.  Here’s what the class looks like:

    public class ClientCultureInfo

    {

 

        public string name;

        public DateTimeFormatInfo dateTimeFormat;

        public NumberFormatInfo numberFormat;

 

        public ClientCultureInfo(CultureInfo cultureInfo)

        {

            this.name = cultureInfo.Name;

            this.numberFormat = cultureInfo.NumberFormat;

            this.dateTimeFormat = cultureInfo.DateTimeFormat;

        }

 

        public static string SerializedCulture(ClientCultureInfo info)

        {

            JavaScriptSerializer js = new JavaScriptSerializer();

            return js.Serialize(info);

 

        }

 

    }

Now that we have the culture info formatted correctly, we need to be able to pass it to the client variable.  We’ll create a public property in the code-behind that is accessible from the client, and set its value in the Page.Load event handler:

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!Page.IsPostBack)

            {

                CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentUICulture;

                ClientCultureInfo o = new ClientCultureInfo(cultureInfo);

                SerializedCulture = ClientCultureInfo.SerializedCulture(o);

            }

 

        }

 

        public string SerializedCulture

        {

            set

            {

                ViewState[“kultur”] = value;

            }

            get

            {

                if (ViewState[“kultur”] == null)

                    return string.Empty;

                else

                    return ViewState[“kultur”].ToString();

            }

        }

Finally, we  need to use this code-behind property to set __cultureInfo.  Just add the following script block to your markup in order to set the current culture:

 

<script type="text/javascript">
    // Get the name field of the CurrentCulture object   
    var __cultureInfo = '<%= this.SerializedCulture %>';
    Sys.CultureInfo.CurrentCulture = Sys.CultureInfo._parse(__cultureInfo);
</script>

 

I added this to the bottom of the page.  To test whether this works, you will need to set the language property of your browser (if you are using IE, like I am).  I set mine to French for testing.  Then append the following script block below the one setting the culture above:

<script type="text/javascript">
    var currentCultureInfoObj = Sys.CultureInfo.CurrentCulture;
    var d = new Date();
    alert("Current culture is " + currentCultureInfoObj.name 
    + " and today is " 
    + d.localeFormat('dddd, dd MMMM yyyy HH:mm:ss'));  
</script> 

 

If you encounter any problems, it is possible that the web.config file is overriding the culture information from the browser.  In that case, make sure the culture is set to “auto” in the config file, like this:

 

    <system.web>

        <globalization uiCulture=auto culture=auto />

    </system.web>