Cod Chowder

moby-dick

Early in Melville’s Moby Dick, Peter Coffin, proprietor of the Spouter Inn, recommends the Try Pots, an inn known for its chowders and run by Peter Coffin’s cousin Hosea Hussey, as a good place for a meal.

Fishiest of all fishy places was the Try Pots, which well deserved its name; for the pots there were always boiling chowders. Chowder for breakfast, and chowder for dinner, and chowder for supper, till you began to look for fish-bones coming through your clothes. The area before the house was paved with clam-shells. Mrs. Hussey wore a polished necklace of codfish vertebra; and Hosea Hussey had his account books bound in superior old shark-skin. There was a fishy flavor to the milk, too, which I could not at all account for, till one morning happening to take a stroll along the beach among some fishermen’s boats, I saw Hosea’s brindled cow feeding on fish remnants, and marching along the sand with each foot in a cod’s decapitated head, looking very slip-shod, I assure ye.

The description of the cod chowder at the Try Pots has always captivated me.  I’m a fan of canned clam chowder and have occasionally had the pleasure of a bowl of clam chowder at Legal Sea Foods next to the Georgia Aquarium – but cod chowder has never made its way to my table.

"Come on, Queequeg," said I, "all right. There’s Mrs. Hussey."

And so it turned out; Mr. Hosea Hussey being from home, but leaving Mrs. Hussey entirely competent to attend to all his affairs. Upon making known our desires for a supper and a bed, Mrs. Hussey, postponing further scolding for the present, ushered us into a little room, and seating us at a table spread with the relics of a recently concluded repast, turned round to us and said—"Clam or Cod?"

"What’s that about Cods, ma’am?" said I, with much politeness.

"Clam or Cod?" she repeated.

"A clam for supper? a cold clam; is THAT what you mean, Mrs. Hussey?" says I, "but that’s a rather cold and clammy reception in the winter time, ain’t it, Mrs. Hussey?"

But being in a great hurry to resume scolding the man in the purple Shirt, who was waiting for it in the entry, and seeming to hear nothing but the word "clam," Mrs. Hussey hurried towards an open door leading to the kitchen, and bawling out "clam for two," disappeared.

"Queequeg," said I, "do you think that we can make out a supper for us both on one clam?"

However, a warm savory steam from the kitchen served to belie the apparently cheerless prospect before us. But when that smoking chowder came in, the mystery was delightfully explained. Oh, sweet friends! hearken to me. It was made of small juicy clams, scarcely bigger than hazel nuts, mixed with pounded ship biscuit, and salted pork cut up into little flakes; the whole enriched with butter, and plentifully seasoned with pepper and salt. Our appetites being sharpened by the frosty voyage, and in particular, Queequeg seeing his favourite fishing food before him, and the chowder being surpassingly excellent, we despatched it with great expedition: when leaning back a moment and bethinking me of Mrs. Hussey’s clam and cod announcement, I thought I would try a little experiment. Stepping to the kitchen door, I uttered the word "cod" with great emphasis, and resumed my seat. In a few moments the savoury steam came forth again, but with a different flavor, and in good time a fine cod-chowder was placed before us.

We resumed business; and while plying our spoons in the bowl, thinks I to myself, I wonder now if this here has any effect on the head? What’s that stultifying saying about chowder-headed people? "But look, Queequeg, ain’t that a live eel in your bowl? Where’s your harpoon?"

We have a crock pot in our kitchen – a repackaged gift from Christmases past – and I decided to put it to good use this past weekend.  The recipe itself was quite simple:

    • 1 cup finely chopped onion
    • 1 stick butter
    • 4 cups diced potato
    • 1 can creamed corn
    • 1 1/2 lb Cod
    • 1 1/2 cup water
    • 1 pint half-and-half
    • salt, pepper and thyme to taste
    • 1 bay leaf

Cook the onion in the butter until it is transparent.  Throw chopped onion and liquid butter in the crock-pot along with potatoes, creamed corn, water, cod and spices.  Cook on low for 4 1/2 to 5 hours and then add the half-and-half.  Cook for another hour.

I served it with some hushpuppies and an upside-down cake for dessert.  I have heard that crumbled bacon on top is also tasty.  The cod was a bit pricey at around $9 a pound at Kroger, and I imagine that tilapia would make a good replacement – though it wouldn’t fill my literary hunger quite so well.

 

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.

A Lazier Singleton with .NET 4.0

This post examines how the new Lazy<T> type can improve standard implementations of the Singleton pattern in C#.

I will ignore for the moment the common jeremiads against the Singleton pattern and the reports made by some latter-day design pattern nihilists that the Singleton is dead.   I do not mean to imply that they are wrong – it’s just that it galls me that the Singleton pattern should be the object of such scorn and ridicule when the Flyweight is allowed to go along its merry way.

Besides which, the Singleton and the Facade are the only patterns I can write from memory and without a lot of research, so I love ‘em.

The best source for design patterns in C# is probably Judith Bishop’s C# 3.0 Design Patterns published by O’Reilly Press, which provides C# versions of all 23 patterns from the Gang of Four’s Elements of Reusable Object-Oriented Software.  The elegant implementation of the Singleton pattern she recommends looks like this:

 

public sealed class Singleton {
   // Private Constructor
   Singleton( ) { }

   // Private object instantiated with private constructor
   static readonly Singleton instance = new Singleton( );

   // Public static property to get the object
   public static Singleton Instance {
          get { return instance;}
       }
}

There is a problem with this, however.  Because of the way classes with static methods work in C# (or in this case, a static property), type instantiation of the private Singleton field instance happens at an unexpected point.  For an interesting if somewhat dense read on the effect of the beforeFieldInit flag, go here.

I will simply demonstrate the problem by adding some tracking code to Judith Bishop’s recommended implementation:

    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();
        private Singleton()
        {
            // no default constructor
            Console.WriteLine(" >> singleton initialized");
        }

        public static Singleton Instance
        {
            get
            {
                Console.WriteLine("before singleton retrieval");
                return instance;

            }
        }
    }

I will retrieve an instance of this Singleton class from a console application like so:

    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Calling Singleton instance");
            var s = Singleton.Instance;
            Console.WriteLine("Finished calling Singleton instance");
            Console.ReadLine();
        }
    }

When will the private type be initialized? When will the private constructor be called?  In w

hat order do you think the Console.WriteLines will be invoked?

Ideally the static members of this class would be initialized only when we needed them, and the output would be:

  1. Calling Singleton instance
  2. before singleton retrieval
  3. >> singleton initialized
  4. Finished calling Singleton instance

In actuality, however, this is the result:

singlton_results_1

This is not so bad, you may be thinking.  If our singleton is a large object this creates some additional strain to the system – but as long as the Singleton instance gets used fairly soon after it is instantiated it’s no big deal.

However, what if I come in after you have coded the singleton and decide to add another static method to your class — not understanding the intricate details of beforeFieldInit – like this:

        public static void Test()
        {
            Console.WriteLine("testing singleton");
        }

 

and rewrote the calling code like this:

            Console.WriteLine("Calling Singleton test method");
            Singleton.Test();
            Console.WriteLine("Calling Singleton instance");
            var s = Singleton.Instance;
            Console.WriteLine("Finished calling Singleton instance");
            Console.ReadLine();

 

It may not be immediately obvious but I have seriously messed up your code.  Here is the output:

singlton_results_2

Even if we never retrieve the Singleton instance, it will still be initialized when any other static method on our type is called – this is commonly known as a language runtime bummer.

.NET 4.0 introduces a new generic type called Lazy<T> which helps us out of this dilemma.  Lazy<T> is a wrapper class that facilitates thread safe, lazy instantiation of objects.  We can use it to create a new Singleton implementation that replaces the private static Singleton instance with a private static Lazy<Singleton>  instance.  The Instance property will also require a small rewrite to pull our Singleton out of the Lazy wrapper.

The full implementation of the lazy version of the singleton looks like this:

    public sealed class LazySingleton
    {
        // Private object with lazy instantiation
        private static readonly Lazy<LazySingleton> instance = 
            new Lazy<LazySingleton>(
                delegate { 
                    return new LazySingleton(); 
                }
                //thread safety first
                ,LazyExecutionMode.EnsureSingleThreadSafeExecution);

        private LazySingleton()
        {
           // no public default constructor
        }

        // static instance property
        public static LazySingleton Instance
        {
            get{ return instance.Value; }
        }
    }

Some things of note:

1. I pass a delegate as the first parameter to the Lazy constructor. There is a no parameter constructor for the generic Lazy<T> class, but it requires that type T have a public default constructor – which I obviously do not want to provide.  The delegate parameter allows me to indicate that I want to use a different constructor – in order to pass a constructor parameter to Type T, for instance, or to invoke a private constructor, in this case – than the default. 

2. The second parameter, also optional, tells the Lazy instance that I want the lazy instantiation of type T to be thread safe.

3. I retrieve the wrapped type T by asking for the Lazy type’s Value property.

Now it’s time for a contest. I add some Console.WriteLine statements as in the original and I append the malicious static Test() method as in the original.  I rewrite my Console app code to call my original Singleton code and then the new and improved — .NET 4.0 enhanced — Lazy Singleton code:

    Console.WriteLine("Calling Singleton test method");
    Singleton.Test();
    Console.WriteLine("Calling Singleton instance");
    var s = Singleton.Instance;
    Console.WriteLine("Finished calling Singleton instance");
    Console.WriteLine();

    Console.WriteLine("Calling Lazy Singleton test method");
    LazySingleton.Test();
    Console.WriteLine("Calling Lazy Singleton instance");
    var lazyS = LazySingleton.Instance;
    Console.WriteLine("Finished calling Lazy Singleton instance");
    Console.ReadLine();

and get the following, very pleasing, results:

singlton_results_3

Now that’s lazy!

What can one do with Silverlight: Part deux

Corey Schuman, Roger Peters and Mason Brown – whom many of you met at the Atlanta Silverlight Firestarter – have been under wraps for several months working on a project for IQ Interactive they repeatedly insisted they couldn’t tell me about.

Now that the beta of My Health Info on MSN has been published, not only do I finally get to see what they have been working on but I also get to share it with you.

My Health Info is an aggregator of sorts for personal medical information – a tool to help the user keep track of her personal medical history.  Unlike other portals that support widgets, however, this one is built using Silverlight.

My Health Info is an interesting alternative to the Ajax-based web portal solutions we typically see and serves as a good starting point for anyone looking to combine the “portal” concept with Silverlight technology.  The Silverlight animations as one navigates through the application are especially nice; they strike the appropriate balance between the attractive and the distracting – between cool and cloying.

Do computers think?

sheep

The online Stanford Encyclopedia of Philosophy has just published David Cole’s update to the entry on The Chinese Room Argument.

The thought problem was posed by John Searle almost 30 years ago and has been a lightening rod for discussions about theories of consciousness and AI ever since.

For those unfamiliar with it, the argument is not against the notion that machines in general can think – Searle believes that minds are built on biological machines, after all – but rather against certain projects in AI that attempt to use computational theories to try to explain consciousness.  Searle’s argument is that computational models are a dead end and that thinking machines must be investigated in a different (apparently “biological”) way.

Of course, if biology can be reduced to the computational model (for instance) then Searle’s argument may be applicable to all machines and we will have to search for consciousness elsewhere.

Here’s the crux of the argument, from the SEP entry:

“The heart of the argument is an imagined human simulation of a computer, similar to Turing’s Paper Machine. The human in the Chinese Room follows English instructions for manipulating Chinese symbols, where a computer “follows” a program written in a computing language. The human produces the appearance of understanding Chinese by following the symbol manipulating instructions, but does not thereby come to understand Chinese. Since a computer just does what the human does—manipulate symbols on the basis of their syntax alone—no computer, merely by following a program, comes to genuinely understand Chinese.”

If this sort of problem excites you, as it does me, then you may want to examine some of the articles about and around consciousness collected on David Chalmers’ website: http://consc.net/online .

What can one do with Silverlight?

rubens

The ComponentArt Summer Silverlight Coding competition is about to wrap up in a few hours.  It has managed to garner approximately 80 entries – all with publicly accessible Silverlight sites.

In the process of hosting this contest, Miljan Braticevic has achieved a wonderful thing – almost as a side-effect.  He has gathered a fantastic gallery of Silverlight applications which answer the often unvoiced question: What can one actually do with Silverlight?

If you are simply looking for ideas or, more to the point, trying to find a way to explain to your boss what Silverlight is, go here: http://www.componentart.com/community/competition2009/contestants.aspx .

The contest entries run the full gamut of mapping tools, social networking, dashboards, standard web site alternatives and games.

I do not envy the judges the task of bequeathing their golden apples.

Craft and Exposure

derek_jacobi

With Silverlight 3, Silverlight seems to have reached a critical stage – that is, people are starting to criticize it.  This is a good thing since it means we can now talk about the reality of Silverlight rather than the promise of Silverlight as a technology.

Some recent comparisons have been made between Silverlight and Flash by Michael Lankton as well as Silverlight and HTML + JQuery by Dave Ward, a truly great developer.

One topic that hasn’t been broached, I believe, is the comparison of Silverlight and WPF.  For some die-hard WPF developers I know, Silverlight just seems like a crippled version of the technology they love.  This is somewhat unfair.  Silverlight has definite limitations when compared to WPF; it also, however, is able to reach a much broader audience because it is browser-based and platform neutral.  Until a mono version of WPF is implemented, Silverlight is going to be the main way for .NET developers to get their state-of-the-art applications onto their Mac using friends’ computers.

This reminds me of a comment I heard Derek Jacobi, the great Shakespearean actor, once make to the effect of:

“I do movies for the money.  I do television for the exposure.  But I do theater for love of the craft.”

As much as I have always enjoyed windows development and have cursed the many tricks and hacks one must know to do web development, web development was still always fun because people had a greater appreciation for what one did.  In part this is because web applications simply reach a wider audience.  It is also due, I think, to the fact that users are much more savvy about the web and the way they feel it should look than consumers of desktop applications.

And so those lessons might be applied to how we look at the relationship between Silverlight and WPF.  WPF allows one to practice one’s craft – which is an enjoyable but mostly solitary affair.  Silverlight, on the other hand, provides the developer with exposure for his work – and this is no bad thing. 

The Beatles Rock Band

beatles-yellow-submarine

Scott Hanselman, perhaps the current reigning rock star in the Microsoft development world with an incredibly popular blog, Computer Zen, has approximately 17.5 thousand followers on Twitter.  William Shatner, a television actor currently up for an Emmy, has 114 thousand followers.  Colin Meloy, lead singer of a band I like, The Decemberists, has 910 thousand Twitter minions.

As involved as I tend to be in the life-world of software development – and despite its significance in the technological transformation of business and society –  I sometimes have to admit that it is a bit marginal.  Not only are my rock stars different from other people’s.  They are also less significant in the grand scheme of things.  By contrast, the biggest rock stars in society are, in fact, rock stars.

While it would be nice if we treated our teachers, our doctors, our nurses like rock stars, I am actually missing President Obama’s speech on healthcare tonight in order to play the just released Beatles Rock Band with my family.  According to this glowing review in The New York Times, it is not only the greatest thing since sliced bread – it is possibly better.  [Warning: the phrases cultural watershed and transformative entertainment experience appear in the linked article.]

The game is indeed fun and traces out The Beatles’ careers if one plays in story mode.  We had in fact gotten to 1965 before my 12 year old noticed the chronology and exclaimed, “Oh my Gawd.  They are so old.  I thought they were from the 80’s or something.”

This got me thinking incoherently about the fickle nature of fame which quickly segued into a daydream about sitting in the green room after a concert while my roadies picked out groupies at the door to come in and engage me in stimulating conversation.

Sometime in the 1990’s my philosophy department was trying to lure Hubert Dreyfus, then the leading interpreter of poststructuralists like Derrida and Foucault in America, into our university.  Apparently everything was going swimmingly until the haggling started and we discovered that not only did he want the chairmanship of the department but he also wanted a 300K salary and merchandizing rights to any action figures based on his work.   300K is a lot of money in any profession, but it is an uber-rock star salary when you consider that most American academics supplement their meager incomes by selling real estate and Amway.  Negotiations quickly deteriorated after that.

I’m not saying, of course, that Hubert Dreyfus doesn’t deserve that kind of scratch.  He had his own groupies and everything.  The problem is simply that our society doesn’t value the kind of contributions to the common weal provided by Professor Dreyfus.

Perhaps a video game could change all that.  I could potentially see myself playing an XBOX game in which I kiss-butt as a graduate student (as I recall, I in fact did do that) in a foreign country, write a marginal dissertation, get a teaching position somewhere and then write a counter-intuitive thesis in a major philosophy journal (the kind with at least a thousand subscribers, maybe more) such as “Why Descartes was not a Cartesian”, “Why Spinoza was not a Spinozist”, “Why Plato was not a Platonist” (true, actually) or “Why Nietzsche was not a Nihilist” (at the beginner level).  With the success of that article, the player would then ditch his teaching position at a state college for a big-name university and gather graduate students around himself.  He would then promote his favorite graduate students to tenure track positions and they would in turn write glowing reviews of all the player’s books as well as teach them in all their classes.  It’s called giveback, and the game would be called Academic Rock Star.  I really could potentially see myself playing that game, possibly.

There are rock stars in every field, and one might offer suggestions for other titles such as Financial Rock Star, Accounting Rock Star, Presidential Candidate Rock StarMicrosoft Excel Rock Star, Blogging Rock Star.

Perhaps the reason Microsoft has not picked up on any of these ideas is because – just as we all secretly believe that we will one day be rich – we all secretly believe that becoming a rock star in our own industry or sub-culture is attainable.

No one really believes, however, that he can ever become like The Beatles.  Consequently we settle for the next best thing: pretending to be The Beatles in a video game.

Three Silverlight Contests Hath September

There are three Silverlight contests in the month of September.  Each is, interestingly, sponsored by a different set of control vendors.

Due September 14th (link): Telerik Silverlight Contest – Telerik is offering a $500 Amazon gift card for a two page written case study of an application that uses their RadControl suite.  According to the contest announcement, you must:

    1. Build an application with the RadControls for Silverlight (you can even use the trials)
    2. Create a 1 – 2 page case study describing your project
    3. Submit the case study by September 14th, 2009

Due September 19th (link): DevExpress, Infragistics and Telerik are putting up prizes for a contest hosted at www.gosilverlight.org. You must write a Silverlight control to enter the contest. First prize has a combined award of $700 in gift cards as well as licenses for the control suites of each of the sponsors.  The Silverlight Show is also a sponsor.  According to the contest announcement, you must:

1. Controls must be designed to work with Silverlight 2 or later. Silverlight 1 Entries will not be accepted or evaluated.

2. All entries must be received between now and 12:00 AM ET, 9/19/2009 12:00:00 AM. Entries received after this date will not be accepted or evaluated. The deadline may change at any time for any reason.

3. Contestants must provide the control source code as part of the submission. The source code should be provided as a ZIP archive and should include the following items:

  • A single Visual Studio 2008 Solution containing each of the solution projects.
  • A Silverlight Application project that contains the custom control.
  • A Test Silverlight Web Project that will host the Silverlight control. The host web project must demonstrate the control in use.
  • The code must compile. If the code does not compile, the entry will not be evaluated.

See the contest rules page for a complete list of instructions.

Due September 22nd (link): ComponentArt is also hosting a Silverlight contest in September for Silverlight applications.  The Grand Prize in this contest is $10,000. 

  • The use of ComponentArt products is not required to participate in the Summer Silverlight Coding Competition. The contest is open to the entire Silverlight developer community.

  • Each Entry must be a Silverlight 1.0, Silverlight 2.0 or Silverlight 3.0 application. Each Entry must be accessible through a public URL. If authentication is required, a demo username and password must be provided.

  • The Entry must not contain any content or material that is obscene, sexually explicit, defamatory, or otherwise inappropriate as determined by ComponentArt at its absolute discretion.

  • Each Entrant will be required to provide their full name, email address, physical address, and country of residency.

  • ComponentArt employees are not eligible to participate in the Competition.

  • Each Entry must be of the Entrant’s original creation, created solely by the Entrant(s), must not infringe the copyright, trademark, privacy, publicity, or other intellectual rights of any person or entity.

  • Participants using third party libraries, controls and/or code in their application, are required to identify the applicable third party components.

See the contest page for a full list of rules.

I certainly wouldn’t feel comfortable suggesting that anyone slack off from their day jobs for this.  At the same time, however, the incentive has never been better to take a week off and hone your Silverlight skills.

I don’t see any rules that disallow submitting the same basic project for all three contests — hence tripling your chances of winning something — so here’s a sample strategy for doing that:

1. Start working on a cool Silverlight app for the ComponentArt contest.

2. Along the way, you will need to build some cool controls.  Take the coolest one and submit it for the gosilverlight.org contest.

3. Rewrite your application using some Telerik controls and submit a write-up for the Telerik Silverlight contest.

If by some chance you manage to win all three September contests, you will have made $11,200 as well as control suites worth an additional $3000 or so.  Really not so bad for a couple of weeks worth of work.

WCF, Arrays and the ExecutionEngineException

This is an anti-recipe for the ExecutionEngineException.  By an anti-recipe, I mean I will demonstrate how to get a certain result that you never want to get, with the expectation that it will help you steer clear of it.

ExecutionEngineException messages are a bit scary. They happen at a pretty low level, first of all, and aren’t easy to debug.  Second, the exception remarks provided on MSDN are:

“Execution engine errors are fatal errors that should never occur. Such errors occur mainly when the execution engine has been corrupted or data is missing.”

I want to point out one scenario which might provoke your code to throw this exception on the principle that forewarned is forearmed.  More importantly, don’t freak out if you run into this – there are some easy workarounds.

When writing a service contract for a WCF web service, you may want to use a IEnumerable<T> as the return type.  Generally this is fine.  If you try to return an array as the underlying type, however, you will get the ExecutionEngineException in .NET 3.5.

This is simply a bug, so you will need to work around it.  You have two choices: either change the signature of your service method or change the underlying type.

If you use the extension method ToList() on your array, everything will work fine.

Alternatively, if you are able to rewrite your service contract, just return the array type rather than trying to use IEnumerable<T>, ICollection<T>, or IList<T>, all of which will cause the same scary exception to be thrown if the underlying type is an array of custom objects (e.g. CustomType[]).

Arrays of simple types (e.g. string[]) do not seem to be a problem.

Arrays of custom objects will generate the exception whether they are the return type on art of the signature of the service method or if they are members of an object returned by the service method. 

I said there are two workarounds, but there are actually three.  This exception seems to only be thrown when you host your service in IIS or Cassini.  If you self-host your service, even using the BasicHttpBinding type, the problem doesn’t show up. 

To reiterate, the problem occurs when a web service contract specifies an IEnumerable<T>, ICollection<T> or IList<T> as the return type and the underlying type returned is actually an array of custom objects.

This has been noted as a bug by Microsoft (https://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=433569).  It also appears to be fixed in .NET 4.0.  I have ported my troubled code to VS 2010 Beta 1, and the code works fine.

I don’t think this problem is actually encountered that often for two reasons.  First, we typically don’t use raw arrays that often.  Instead we use generic Lists or even ArrayLists which, even if they are a bit fatter than simple arrays, are awfully convenient.  Second, while it is considered to be a best practice to always return least derived types in methods and properties – in practice this seems to be the exception rather than the rule.

Finally, it doesn’t appear to be a problem with the DataContractSerializer as some have suggested elsewhere.  I can serialize my data contracts just fine when I use the DataContractSerializer on its own.  The problem only seems to happen for me when I try to expose these contracts through a WCF service.  Also, if it were a DataContractSerializer problem, changing to self-hosting shouldn’t help.