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>

The Imp of the Perverse

nightmare

No college freshman in America is able to escape his courses without encountering Kant’s Categorical Imperative in some form or other.  Drawing on a Medieval moral tradition that held that God has placed in each man’s heart, whether Catholic, pagan, or apostate, the knowledge of right and wrong, Kant held that each person has an inherent rational knowledge of the Moral Law, or the pure form of moral action, which is commonly known as the Golden Rule.  Behind the Golden Rule is, furthermore, an impulse to act according to the Moral Law which Kant dubbed the Categorical Imperative — a concept which Freud later took up and reinterpreted as an irrational force: the Super Ego.

For Kant, however, the Categorical Imperative was always a rational impulse which revealed our transcendent selves.  How, then, to explain the not infrequent impulse to not fulfill one’s duty to the Moral law?  According to Kant:

"We are not, then, to call the depravity of human nature wickedness taking the word in its strict sense as a disposition (the subjective principle of the maxims) to adopt evil as evil into our maxim as our incentives (for that is diabolical); we should rather term it the perversity of the heart, which, then, because of what follows from it, is also called an evil heart. Such a heart may coexist with a will which in general is good: it arises from the frailty of human nature, the lack of sufficient strength to follow out the principles it has chosen for itself…" — Religion Within the Limits of Reason Alone

Edgar Allan Poe made a point of exploring that which Kant would rather leave aside as pointless and empty of content.  In an 1850 short story, he wrote:

"Induction, a posteriori, would have brought phrenology to admit, as an innate and primitive principle of human action, a paradoxical something, which we may call perverseness, for want of a more characteristic term. In the sense I intend, it is, in fact, a mobile without motive, a motive not motivirt. Through its promptings we act without comprehensible object; or, if this shall be understood as a contradiction in terms, we may so far modify the proposition as to say, that through its promptings we act, for the reason that we should not.

"There lives no man who at some period has not been tormented, for example, by an earnest desire to tantalize a listener by circumlocution. The speaker is aware that he displeases; he has every intention to please, he is usually curt, precise, and clear, the most laconic and luminous language is struggling for utterance upon his tongue, it is only with difficulty that he restrains himself from giving it flow; he dreads and deprecates the anger of him whom he addresses; yet, the thought strikes him, that by certain involutions and parentheses this anger may be engendered. That single thought is enough. The impulse increases to a wish, the wish to a desire, the desire to an uncontrollable longing, and the longing (to the deep regret and mortification of the speaker, and in defiance of all consequences) is indulged.

"We have a task before us which must be speedily performed. We know that it will be ruinous to make delay… We glow, we are consumed with eagerness to commence the work, with the anticipation of whose glorious result our whole souls are on fire. It must, it shall be undertaken to-day, and yet we put it off until to-morrow, and why? There is no answer, except that we feel perverse, using the word with no comprehension of the principle." — The Imp of the Perverse

The tendency which Poe calls perversity — the tendency to say the wrong thing, to zig when one should zag, to procrastinate merely to see what will happen next — seems to be more ubiquitous in software programming than in other occupations.  I’ve known programmers who not only say things they shouldn’t, but seem to take a particular joy in doing so.  They do not simply lack an internal censor that would keep them from saying certain things, but seem to actually be possessed by some sort of Socratic daimon who eggs them on.

Yet sometimes I think it is not the programmers who are especially possessed of this imp, but simply they who are not able to mask it behind other, more acceptable, modes of behavior.   We often hear of the disgruntled chef who spits in a difficult customer’s food, or the unhygienic bartender who slips unsanitary items in a customer’s drink.  The same impulse, I think, takes over middle-managers at times.  They, who are forced to do unpleasant tasks by their direct managers, and who in the end are blamed by both the people under them as well as those over them when things go wrong, are always suspected of taking a particular pleasure — dare I say a perverse pleasure — when unpleasant things, such as dressing down an employee or on occasion firing one, must be done.  What is more perverse, after all, than actually taking pleasure in performing unpleasant tasks, and who could blame them if they did?

Similar to Poe’s "mobile without motive," Robert Herrick captured the mood as one of Delight in Disorder (1648):

A SWEET disorder in the dress
Kindles in clothes a wantonness :
A lawn about the shoulders thrown
Into a fine distraction :
An erring lace which here and there
Enthrals the crimson stomacher :
A cuff neglectful, and thereby
Ribbons to flow confusedly :
A winning wave (deserving note)
In the tempestuous petticoat :
A careless shoe-string, in whose tie
I see a wild civility :
Do more bewitch me than when art
Is too precise in every part.

The sexual element that is implicit in Herrick’s understanding of the imp of perversity is remarkably absent from Poe’s, just as the element of danger, pervasive in Poe, is absent in Herrick.  Our contemporary notion of the perverse tends to span both elements, and is generally accessorized with leather where Herrick has petticoats, and piercings where Poe envisions only murder.  Yet even in our own times perversity has started to lose some of its perverse luster.  The Christian Coalition may decry the slipping of moral standards as a slow slouching towards the Rapture, but I see the problem, rather, as one in which we’ve denied ourselves the real pleasures of perversity.  When even leather and piercings have lost their power to outrage as well as titillate, where shall we turn?

I’ve recently been enjoying pulp novels from the 40’s with a certain amount of furtive excitement that those authors are writing things they would never get away with writing today.  For instance, from Mickey Spillane’s 1948 I, The Jury (for those unfamiliar with the series, Mike Hammer is a tough detective, while Velda is his faithful secretary):

"Here’s one you’ll like, chum," Velda grinned at me.  She pulled out a full-length photo of a gorgeous blonde.  My heart jumped when I saw it.  The picture was taken at a beach, and she stood there tall and languid-looking in a white bathing suit.  Long solid legs.  A little heavier than the movie experts consider good form, but the kind that make you drool to look at.  Under the suit I could see the muscles of her stomach.  Incredibly wide shoulders for a woman, framing breasts that jutted out, seeking freedom from the restraining fabric of the suit.  Her hair looked white in the picture, but I could tell that it was a natural blonde.  Lovely, lovely yellow hair.  But her face was what got me.  I thought Velda was a good looker, but this one was even lovelier.  I felt like whistling.

"Who is she?"

"Maybe I shouldn’t tell you.  That leer on your face could get you into trouble…"

And so on and so forth.  I, The Jury was a runaway bestseller and made Mickey Spillane’s career.  This was due in no small part to the racy writing and tight plot, but something should also be said for the cover art.  Here’s the cover of the original 1948 edition:

ITheJury

And here’s the cover redone for a later edition:

ithejury2

Finally, here’s the poster art for a film version:

IJuryMovie

Do you notice a common theme?  A man with a gun pointed at a woman undressing.  Is he holding the pistol in order to force her to undress?  Or is she undressing in order to compel him to drop the pistol?  Thousands of readers in the 40’s and 50’s felt compelled to read the book in order to find out what was behind this juxtaposition of sex and violence, drawn by the imp of the perverse. 

Last of the Great Whistleblowers

Solzhenitsyn

Anne Applebaum has written one of the better obituaries for Alexander Solzhenitsyn in her column for the Washington Post:

"Even Solzhenitsyn’s expulsion from Russia in 1974 only increased his notoriety, as well as the impact of "The Gulag Archipelago." Though it was based on "reports, memoirs and letters by 227 witnesses," the book was not quite a straight history — obviously, Solzhenitsyn did not have access to then-secret archives — but, rather, an interpretation of history. Partly polemical, partly autobiographical, both emotional and judgmental, it aimed to show that, contrary to what many believed, the mass arrests and concentration camps were not an incidental phenomenon but an essential part of the Soviet system — and had been from the very beginning.

"Not all of this was new: Credible witnesses had reported on the growth of the Gulag and the spread of terror since the Russian Revolution. But what Solzhenitsyn produced was simply more thorough, more monumental and more detailed than anything that had preceded it. His account could not be dismissed as a single man’s experience. No one who dealt with the Soviet Union, diplomatically or intellectually, could ignore it. So threatening was the book to certain branches of the European left that Jean-Paul Sartre himself described Solzhenitsyn as a "dangerous element." Its publication certainly contributed to the recognition of "human rights" as a legitimate element of international debate and foreign policy.

"His manuscripts were read and pondered in silence, and the thought he put into them provoked his readers to think, too. In the end, his books mattered not because he was famous or notorious but because millions of Soviet citizens recognized themselves in his work: They read his books because they already knew that they were true."

It is a peculiar meme in Western Culture that, at some level, the evil of Stalin’s Soviet regime cannot be viewed on the same level as, say, Hitler’s Third Reich.  It sometimes takes the form of faint attempts to explain it away, or to see it as an aberration of the Soviet state, and generally ends in a change of subject.  This aura of lingering romanticism about the Soviet State among Westerners is odd and, I think, rather inexplicable.  A meme is probably the best way to describe it.

In Russia itself, the attitude is perhaps easier to understand.  No one likes to be reminded of their own sins, and no one likes bad news that is unlikely to gain them anything.  In her book, Gulag: A History, Applebaum describes the typical reactions of people she encounters in Russia once they discover that she is doing a historical investigation of the Gulag system.

"At first, my presence only added to their general merriment.  It is not every day one meets a real American on a rickety ferry boat in the middle of the White Sea, and the oddity amused them.  They wanted to know why I spoke Russian, what I thought of Russia, how it differs from the United States.  When I told them what I was doing in Russia, however, they grew less cheerful.  An American on a pleausre cruise, visiting the Solovetsky Islands to see the scenery and the beautiful old monastery — that was one thing.  An American visiting the Solovetsky Islands to see the remains of the concentration camp — that was something else.

"One of the men turned hostile.  ‘Why do you foreigners only care about the ugly things in our history?’ he wanted to know. ‘Why write about the Gulag?  Why not write about our achievements?  We were the first country to put a man into space!’  By ‘we’ he meant ‘we Soviets.’

"His wife attacked me as well.  ‘The Gulag isn’t relevant anymore,’ she told me.  ‘We have other troubles here.  We have unemployment, we have crime.  Why don’t you write about our real problems, instead of things that happened a long time ago?’

"In my subsequent travels around Russia, I encountered these four attitudes to my project again and again.  ‘It’s none of your business,’ and ‘it’s irrelevant’ were both common reactions.  Silence — or an absence of opinion, as evinced by a shrug of the shoulders — was probably the most frequent reaction.  But there were also people who understood why it was important to know about the past…"

This is toward the end of the book.  Just as interesting is how the book begins, with an observation on a bridge.

"Yet although they lasted as long as the Soviet Union itself, and although many millions of people passed through them, the true history of the Soviet Union’s concentration camps was, until recently, not at all well known.  By some measures, it is still not known.  Even the bare facts recited above, although by now familiar to most Western scholars of Soviet history, have not filtered into Western popular consciousness.

"I first became aware of this problem several years ago, when walking across the Charles Bridge, a major tourist attraction in what was then newly democratic Prague.  There were buskers and hustlers along the bridge, and every fifteen feet or so someone was selling precisely what one would expect to find for sale in such a postcard-perfect spot.  Paintings of appropriately pretty streets were on display, along with bargain jewelry and ‘Prague’ key chains.  Among the bric-a-brac, one could buy Soviet military paraphernalia: caps, badges, belt buckles, and little pins, the tin Lenin and Brezhnev images that Soviet schoolchildren once pinned to their uniforms.

"The sight struck me as odd.  Most of the people buying the Soviet paraphernalia were Americans and West Europeans.  All would be sickened by the thought of wearing a swastika.  None objected, however, to wearing the hammer and sickle on a T-shirt or a hat.  It was a minor observation, but sometimes, it is through just such minor observations that a cultural mood is best observed.  For here, the lesson could not have been clearer: while the symbol of one mass murder fills us with horror, the symbol of another murder makes us laugh."

I do not play the game myself, but a friend tells me that there is a similar controversy in Civilization IV concerning the presence of Stalin as a player character in this PC game and the absence of Hitler.  Here is a small flame war over it, with links to more flame wars.  Another friend, who is ethnic Chinese, resents the presence of Mao in the game.

Perhaps the greatest trick the Devil ever played, to paraphrase Kaiser Sose, was to convince people that he was Adolf Hitler, while men like Alexander Solzhenitsyn worked to convince us that things were otherwise.  To quote the man himself:

"If only there were evil people somewhere insidiously committing evil deeds, and it were necessary only to separate them from the rest of us and destroy them. But the line dividing good and evil cuts through the heart of every human being. And who is willing to destroy a piece of his own heart?”  – The Gulag Archipelago

The Quiet Mind

IMG_1298

Like an Empiricist prescription or an occult warning, depending on how you take it, Wittgenstein wrote as a coda to the Tractatus Logico-Philosophicus,  Wovon man nicht sprechen kann, darüber muß man schweigen.  C. K. Ogden translates this as “Whereof one cannot speak, thereof one must be silent.”

I have spent the past week trying to learn how to be silent, again.  I unplugged myself from the Internet and went to the beach with my family where I spent several days trying to silence the various voices that constitute a perpetual background cacophony in my head.  The ocean swell helped me to accomplish this quiescence of the noetical Madding crowd, until finally there was nothing left but stillness in my brain and the inbreath and outbreath of the sea as it filled up the new tide pools of my mind, and a gasp escaped my lips and traveled over the waters as I realized that this really was a vacation, at last, and it wasn’t what I had expected.

This sense of quietude is what I have always taken Heidegger to be referring to when he discusses Lichtung — the clearing — in his writings, for instance in Being and Time where he writes:

“In our analysis of understanding and of the disclosedness of the “there” in general, we have alluded to the lumen naturale, and designated the disclosedness of Being-in as Dasein’s “clearing”, in which it first becomes possible to have something like sight.” — tr. Macquarrie & Robinson

Except that for me, sight is a place holder for my inner monologue, and the clearing is a place to rediscover my inner voice.  We are all social animals, after all, and when we are with other people our inner voices become drowned out by the various social pressures that sweep us along, whether this is in politics, or at work, or on the Internet, the biggest stream of voices available.  My general strategy in life is to fill my mind with so many voices that they eventually begin to cancel each other out so that my rather weak voice can have some influence within my own head.  But this doesn’t always work, and I eventually need to detox in a quiet place.

Heidegger uses a clearing in the woods as his metaphor for this place, but I think the ocean serves the purpose even better.  The ocean is a natural source of white noise, and the way white noise affects human beings is peculiar.  According to some studies, the appeal of white noise seems to be specific to primates, and to humans in particular.  According to the Aquatic Ape theory, human evolution is intimately tied to the coast, and this might explain, in a hand-waving sort of way, our affinity for the ocean and the sounds of the ocean.  It is the music that calms the inner beast.

The inner monologue is a peculiar, though pervasive, phenomenon.  An interesting observation concerning it occurs in Augustine’s Confessions.  Augustine expresses amazement at the fact that his mentor, Ambrose, is able to read without moving his lips.  This gives us a strange impression of the Roman world — apparently it has not always been the case that people read silently in an ALA approved manner.  This in turn has led various philosophers to wonder if the inner monologue existed for these Romans, or if they simply articulated everything they thought.

For Derrida, this became a motif for his philosophical studies.  In an early work, Speech and Phenomena, Derrida tries to find the source of Husserl’s phenomenological insight in The Logical Investigations, and concludes that it is due to a basic confusion between observation and speech.  Because in speech we are capable of this inner monologue, Husserl, according to Derrida, made the analogous assumption that we can exist, in some peculiar way, without the world.

“For it is not in the sonorous substance or in the physical voice, in the body of speech in the world, that he [Husserl] will recognize an original affinity with the logos in general, but in the voice phenomenologically taken, speech in its transcendental flesh, in the breath, the intentional animation that transforms the body of the word into flesh, makes of the Körper a Leib, a geistige Leiblichkeit.” — tr. David B. Allision

Just as Derrida saw in the Logical Investigations the germ of the entire Husserlian project, the Husserlian David Carr used to tell us that the germ of Derrida’s project could be found in this brief passage.  Taking the problem of authorial intent to a philosophical level, Derrida wants to cast doubt on the meaning of the inner voice, and it’s privileged status as the arbiter of the meaning of its utterances.  It is a sort of Neo-Empirical game that resembles the attacks often made by material-reductionists on the folk-psychology of consciousness, which has at its core the notion that for the most part we all know what we are talking about when we talk about something.  Instead, the inner voice is a sort of illusion to be dispelled, like witchcraft and theology.

And yet I can’t help but feel that there is something to the inner voice.  For instance what was George Bush thinking about when he was first notified about the 911 attacks?  What was Bill Clinton thinking and intending in that fateful pause between the phrases “woman” and “Monica Lewinsky” that changed the meaning of this statement (skip to end for the good bit)? 

Silence isn’t simply a turning off of the mind.  When the lights go out, we may stop seeing things, but when all noise is shut out, we continue to hear ourselves, and it is perhaps the best time to hear ourselves and in the act recollect ourselves.

I leave you with John Cage’s composition 3′ 44”, which is pregnant with the composer’s intent, as well as the performer’s in this unique rendition.

Mad Men

madmen

The second season of Mad Men begins tonight on AMC.  If you haven’t seen it, then I highly recommend that you do and that you also rent the first season on DVD or through your favorite peer-to-peer network and catch up on this beautiful piece of television.

Mad Men is about Madison Avenue advertising executives in the early 1960’s, when the 60’s looked like the 50’s in the same way that what we think of as the 60’s is really the 70’s.  It is a world in which men smoke and drink, swagger and get things done.  They were veterans of either Korea or WWII, and knew how to accomplish great things.  In the process they created a wonderland that was America at its height, which had within it the seeds of America’s decline.  In Mad Men, we are afforded the opportunity to see it all.

There is something peculiar about enjoying Mad Men.  The sleezy misogyny and petty racism of the period is laid out for us to see.  Yet despite this, there is a sense that men were really men back then — and certainly not Robert Bly-reading tree hugging faux-woodsmen trying to recapture something we didn’t realized we had lost.  They are the real deal — a generation that gave us James Bond as well as a militant communist-hating wing of the Democratic party.  Damn those were the days.

It is, in a sense, an antidote to The Office, the satirical show about office work that makes us feel like we all suck and it’s alright — a show about spin going out of control to the point that the criteria for success and failure are utterly open to interpretation.

In Mad Men, there is no ambiguity about what success and failure entail.  Success means a well-padded expense account, an attractive secretary and a corner office with a bar built into the wall.  Failure means being denied these things.

And yet the world of the mad men have led us to the place where we are now.  They may have been men of character in their own way, but they created a world in which spin matters more than character, and one manages not by example but by personality tests and manipulation.  Perhaps the world of the mad men was no less corrupt, but they attempted to hide it and build something more beautiful, while we tend to cover it up with self-effacing humor ala John Stewart, Stephen Colbert and Conan O’Brien, our contemporary zeitgeist-setters whose humor shares the common conceit that they know they are privileged and have no intention of giving it up, but they are more than willing to feel bad about it.

In Mad Men, no one seems to have regrets, and a bold face is the essence of a moral stance.  The warts are all there to see, and they are ugly indeed.  But at the same time there is a sense of style and elegance that we no longer find in the modern office, and it draws the viewer like a slow seduction into something we know is not good for us.

Geek Chic

huey

Tom Wolfe’s 1970 essay Radical Chic captured a peculiar phenomenon in American culture — the courting by wealthy New York socialites of political radicals and revolutionaries like the Black Panthers — people who, in turn, should have despised the socialites trying to cultivate them.  You can read an excerpt here.  Perhaps it was an example of opposites attracting, or perhaps it was merely an extreme exercise in mauvais fois.

I don’t mean to rain on anyone’s parade, however.  I mean only to point out that when socialite courtesans like Paris Hilton date the likes of Jimmy Wales, founder of Wikipedia, we know that the trend continues, but instead of the Huey Newtons of the world, it is nerds who are now being pursued.

It has been a long time since Robert Carradine and Anthony Edwards (Louis and Gilbert) showed the world back in 1984 that nerds could sleep with cheerleaders.  This was followed up by Val Kilmer’s more testosterone fueled portrayal of the nerd archetype in Real Genius.  All the while, Bill Gates and Steve Jobs were busy demonstrating to the world and Wall Street the power of Geek culture, and now we find ourselves where we are today, with nerds making inroads into every area of society, and kids wanting to grow up and be like them.  As Eryn Loeb wrote for Salon:

"The information age has been good to nerds. No longer are they relegated to getting sand kicked in their faces by that other familiar archetype, the jock. We’ve gotten used to watching Steve Jobs grin awkwardly as he announces the latest hot techie toy, and when it comes to pop culture, nerds like Superbad writer/star Seth Rogen are increasingly in control of their own image."

We’ve come a long way, baby.  But perhaps not as far as we think.

revenge

The only way to truly measure the influence of a sub-culture is to compare it with another one.  This month’s Ebony has a feature article on the 25 Coolest Brothers of All Time.  When one peruses the list, one realizes how much the accomplishments of nerds fall short, and how fragile their claim to  chic really is.  The mere fact that Ebony can talk about the brothers is insta-cool.  Many a nerd would give up his pocket protector to be called brother by an actual black man.

Billy Dee Williams is on the list.  Like Barack Obama, who is also on the list, he has cross-cultural appeal and stands out as an icon of both Geek culture and Black culture, though for vastly different reasons.  Ebony mentions Billy Dee’s swagger, his confidence and his effortless style.  On the other hand, Wikipedia (in case you ever doubted its firm position as a cornerstone of Geek culture) begins its entry on Billy Dee with this:

"Billy Dee Williams (born April 6, 1937) is an African American actor and writer, best known for his role as Lando Calrissian in the Star Wars film series."

The entry for Harrison Ford, interestingly, begins like this:

"Harrison Ford (born July 13, 1942) is an Academy Award- and BAFTA-nominated, as well as Golden Globe-winning, American actor." 

Ford’s association with the Star Wars franchise isn’t mentioned until the second sentence.

 

miles

The full list of 25 Coolest Brothers follows, in no particular order.  I find little to quibble about here except for the presence on the list of Obama, with whom I don’t naturally associate coolness — although, like many others, I admire his Dickensian life story.

Barack Obama
Don Cheadle
Billy Dee Williams
Sidney Poitier
Quincy Jones
Lenny Kravitz
Jimi Hendrix
Richard Roundtree
Denzel Washington
Sammy Davis, Jr.
Bob Marley
Ed Bradley
Tupac Shakur
Adam Clayton Powell, Jr.
Gordon Parks
Muhammad Ali
Miles Davis
Walt Frazier
Shawn ‘Jay-Z’ Carter
Samuel L. Jackson
Malcolm X
Snoop Dogg
Prince
Michael Jordan
Marvin Gaye

 

billy bill

Concerning Samovars

samovar

We have two in the house.  Passed down through the generations in my wife’s family, they currently sit in our living room as decorations, whispering to us of bygone times.

They once played a central role in the cultural life of the Russian emigre intelligentsia.  Alexandra Kropotkin evokes images of this bygone world in her wonderful book on Russian Cooking:

Among Russians who have gone away to dwell in other countries, it is easy enough to arouse mild attacks of homesick longing for Russian life and Russian flavors.  But to launch the expatriate Russian soul on a really unbridled jag of nostalgia, try mentioning our vechernyi t’chai, our evening tea.

There is the magic phrase that reawakens all out dearest memories of home!

When the samovar goes on the dining-room table, usually about 10 o’clock in the evening, the entire family gathers for the most intimate kind of get-together.  This is the hour of comfortable relaxation, with old and young meeting as equals in talk, drinking innumerable glasses and cups of tea while wandering conversationally into all fields of anecdote and gossip, of thought and speculation.

The babies and younger children are in bed.  The adolescents feel grown up.  The oldsters are sure of an audience.  And guests always drop in.  It is perfectly correct for friends to drop in, uninvited, for evening tea at any time between 10 P.M. and midnight.  The lady of the house is not expected to set out anything special for company.  There is no fuss or formality.  The scene is cozy and homelike.  When you come for evening tea, you take potluck with the family.

The dining-room table is covered with an embroidered tablecloth.  Beside the lady of the house, at her right hand, the steaming samovar stands on a little table of its own.  Or if there is no side table, the samovar will be standing directly on the dining-room table, with the hostess peeking around it to see and take part in whatever is going on.

A small china teapot fits into a metal fixture on top of the samovar.  The hostess herself has measured tea leaves into the china teapot, has brewed the tea with boiling water from the samovar, and has set the pot of tea on top of the samovar to keep on brewing.

The tea is made as strong as household supplies permit.  A few drops of this strong tea from the small china pot will be poured into each cup or glass, which will then be filled with hot water from the samovar.

Tea glasses in metal or silver holders that have handles, like American ice-cream-soda glasses, are set out for the men.  In Russia the men drink tea from glasses, adn the women drink tea from cups.

On our evening tea table are plates of cold cuts and plates of sliced cheese.  We don’t serve fish at evening tea unless the season is Lent, or when times are particularly hard.  The bread basket offers slices of black bread and slices of white.  Unsalted butter is on the table in a pretty dish … Plenty of sweet things will be arrayed in front of us in any case.  There will be homemade preserves, crystallized fruits, fruit confections known as pastilla, and the semi-jellied fruit candies that Russians call marmelade …

At vechernyi t’chai, it seemed that the tea was consumed endlessly, most Russians taking it with thin slices of lemon.  The hostess always sliced the lemon herself with a special silver knife.  After cutting the lemon she always held the knife for a moment in the steam from the samovar to prevent the knife from tarnishing.

Everyone at the tea table had a plate and a small saucer, usually of cut glass.  The saucer was for preserves, which you either ate with a spoon or put into your tea.  Many Russians like preserves better than sugar as a sweetening for their tea.  After years in America it still irks me not to be able to find saucers of the right size for preserves to go with Russian tea.  We call these saucers blewdichki dlia vareniya.  They are about 3 inches across.  Very few Russians take milk or cream in their evening tea.  They take it that way on for breakfast.

The best breakfast in the world, of course, is a hot bowl of pho, which is a part of my cultural heritage.  My mother makes it for us whenever she visits, and I generally have it for lunch at least two or three times a month.  Nevertheless, the best time of day for ph? is the morning.  It includes a strong beef broth for protein, noodles for carbs, and spices to help you wake up as well as a variety of herbs, bean sprouts and citrus. 

Andrea Nguyen has written an excellent series of articles about pho for the Mercury News which covers the history and the rituals surrounding the flavorful soup.  She even provides a recipe, though it is a bit of a lark since few people will have the patience to actually try it out.  It requires some unusual herbs as well as long hours of boiling bones and meat for the broth.  My mother typically boils two chickens (either Vietnamese or Thai chickens, since she says American chickens have no flavor) as well as a large beef bone for about 8 hours until the meat has practically disintegrated into the broth.

Garnishing pho is like putting together your own hamburger — you can have it your way. So, before putting any pho into your mouth, add your own finishing touches. Then dive in with a two-handed approach: chopsticks in one hand to pick up the noodles, the soup spoon in the other to scoop up broth and other goodies.

Your pho ritual may include:

Bean sprouts: Add them raw for crunch or blanch them first.

Chiles: Dip and wiggle thin slices of hot chile in the hot broth to release the oil. Leave them in if you dare. For best fragrance and taste, try Southeast Asian chiles such as Thai bird or dragon rather than jalapeños. Serranos are better than jalapeños.

Herbs: Strip fresh herb leaves from their stems, tear up the leaves and drop them into your bowl. Available at Viet markets, pricey ngo gai (culantro, thorny cilantro, saw-leaf herb) imparts heady cilantro notes. The ubiquitous purple-stemmed Asian/Thai basil (hung que) contributes sweet anise-like flavors. Spearmint (hung lui), popular in the north, adds zip. [For details, see Essential Viet herb page on this site.]

Lime: A squeeze of lime gives the broth a tart edge, especially nice if the broth is too sweet or bland.

Sauces: Many people squirt hoisin (tuong) or Sriracha hot sauce directly into the bowl. I don’t favor this practice because it obliterates a well-prepared, nuanced broth. But I do reach for the hoisin and Sriracha bottles to make a dipping sauce for the beef meatballs (bo vien).

I typically do put both hoisin and Sriracha in my soup because this is the way my mother has always made it for me.  Additionally, I squirt some of each into a dipping bowl, pick out thin slices of rare beef out of my soup bowl with chopsticks and alternate between dipping the slices in the chile sauce and the sweet hoisin.

Unlike the Russian tea ritual, the Vietnamese pho ritual is no time to talk about politics or religion.  Eating soup is a serious business, and involves the constant motion of chewing on noodles and preparing carefully for the moment when one swallows one’s noodles by synchronized hand motions, with the chopstick hand picking out pieces of meat from the bowl and dipping them in the sauce dish, while the soup spoon hand gathers more noodles to chase the slices of beef.

Talking generally resumes after the meal, as all participants look with satisfaction at the empty soup bowls and the pieces of discarded herbs and sprouts strewn across the table.

The Vietnamese are a coffee rather than a tea people, having been colonized by the French rather than the English.  For breakfast I like a strong cup of coffee with my pho, and I like to sweeten it with condensed milk.  A meal like this generally leaves me full well into the dinner hour.

Hellboy 2: When Elves Go Bad

hellboy

Hellboy is, at its heart, a conceit that allows Mike Mignola, the comic book author,  to riff on various horror and fantasy motifs by inserting a gun-toting, cigar-smoking modern action hero (albeit one with a tail) into genres where he does not belong.  The payoff in the comic books, sometimes successful and sometimes not, is simply in seeing how events unwrap.

There is a naturalness to adapting Hellboy for the big screen, since this is where this type of action hero was originally born.  In Guillermo del Toro’s hands, what occurs is a reversal of the transposition Mike Mignola accomplishes in his graphic novels.  We import into the action movie genre elements that do not natively belong to it and see what happens.  As with the comic books, this is sometimes successful and sometimes not.

The original movie played with themes from H.P. Lovecraft’s Cthulu stories.  The monsters were beautifully realized using CGI effects, but the incomprehensible horror that typically drove Lovecraft’s stories were displaced.  They simply cannot exist in a world that revolves around an indefatigable hero.

The Hellboy sequel in turn plays, more than anything else, with Tolkien’s elves.  The elves in The Golden Army are tall and filled with martial virtue.  They are also masters of magic, and preservers of nature.  Part of the high concept behind Peter Jackson’s production of Lord of the Rings was to bring out the nature loving motifs in every elven design, while highlight the industrial aspects of orc culture.  As National Geographic (among others) points out:

Tolkien’s concern for nature echoes throughout The Lord of the Rings. Evil beings of Middle-earth dominate nature and abuse it to bolster their own power. For example, Saruman, the corrupt wizard, devastates an ancient forest as he builds his army.

The Elves, in contrast, live in harmony with nature, appreciating its beauty and power, and reflecting a sense of enchantment and wonder in their artful songs.

Orcs, however, always exist in some sense as placeholders for modern men.  In The Golden Army, del Toro asks what would happen if Tolkien’s elves ever saw what we have now become.  Del Toro’s answer is that they would go to war with us in order to preserve what remained of their world.

Visually, we once again see the Hieronomous Bosch inspired monsters we first glimpsed in Pan’s Labyrinth.  They are beautiful and horrible at the same time — horrible enough to justify Hellboy as a hero as he battles them, but so beautiful at times that it seems a shame.  It is this second aspect of the film, and Del Toro’s constant affection for outsiders, that undercuts the film as a participant in the action genre.  Instead, the battles become exhausting over time, and we wish they would go away so we can enjoy the gentle details of Del Toro’s exotic world which have always been his specialty.

Hayao Miyazaki’s films can be identified as another influence on the visuals and mood of this film.  One of the monsters from Hellboy II seems to be pulled right out of Princess Mononoke.  The bestiary we encounter in the Goblin Market, likewise, recalls the parade of grotesques from Spirited Away.  More than anything else, however, what is borrowed from Miyazaki is the device of placing a child in the middle of the battle between good and evil.  We are forced to see the world through the eyes of a child who finds both good and evil to be ambiguous, which is the emotional location of all fairy tales.  In Del Toro’s film, Anna Walton performs this role as Princess Nuala, the sister to the elf protagonist of the story who, with her big yellow eyes and zombie-like complexion, is strangely affecting and sympathetic.

All in all, the film is not successful — not because it does not know what it wants to be, whether action movie or heroic fantasy, but because there is nothing for it to be.  These genres do not combine easily, and what we are left with instead is a plotline and a set of overlapping genres that provide Del Toro with a canvas upon which he paints detailed images that could not make an appearance in any other way.  Those details were, for me, well worth the price of admission.

The big question is what Del Toro will do when he gets his hands on a real fantasy property.  He is slated to direct the highly anticipated Hobbit movie, with Peter Jackson producing.  There is, of course, what the movie ought to be — a continuation of the epic fantasy genre, done with the same accomplishment that Jackson achieved with The Lord of the Rings.  If The Golden Army is any indication, however, this is unlikely to be what we will get.  Del Toro’s recent interviews point to the same conclusion:

I was never into heroic fantasy. At all. I don’t like little guys and dragons, hairy feet, hobbits — I’ve never been into that at all. I don’t like sword and sorcery, I hate all that stuff.

This is fine with me.  I’ve always been a fan of the Rankin/ Bass cartoon (with music by Glen Yarborough), and don’t see any reason to try to improve upon it.  Seeing Del Toro take another stab at twisting the genre to his own ends is well worth waiting for.

The Devil’s Triad

brokenkeys

According to tradition, the tritone was called the Devil’s Chord or the Diabolis in Musica, a sound so dissonant and so puissant it was believed to be capable of raising the Lord of Hell himself.  For this reason, in it’s irrationality, the Roman Catholic Church banned the Devil’s Triad, on pain of excommunication.  Today, of course, bands such as Metallica and Black Sabbath  use the tritone on a regular basis with no adverse effects.

The irrational is a powerful force that may be harnessed, dear reader, by those willing play on the fringes of reality.  Three magical phrases, irrational yet powerful and well known to the practitioners of the dark arts, can be invoked by anyone who desires to kill a technical project they dislike.  Today, dear reader, I will teach you these three phrases.

But first, a word about motivations.  According to Nietzsche, the driving force behind modern man’s desire for power is, tout court, resentment.  We all resent the guy who comes in the middle of a software project and starts making suggestions about how to improve it.  As the new guy, in turn, we resent the old and crusty way things are done, as if the way things are done is the only way.  Resentment, in other words, is the mother of invention when it comes to technology, and we each, in our own way, embrace it as we strive toward a new tomorrow.  In a perfect world, we may all act as the angels, but in the real world, we may occasionally be forced to make deals ex inferis.  Which is not to recommend what I am about to teach you.  I ask you, moreover, to use these techniques judiciously.  One should not call upon the powers of the underworld lightly.  But should you find yourself in a situation where rational discourse is no longer possible, and rhetorical brute force is required, then these phrases may be of use to you.

1. It’s too complex.  It’s not maintainable.

This is a wonderful phrase.  It is universally applicable since any useful piece of code will end up being complex, and one can never overemphasize the incompetence of one’s peers when discussing maintainability.  And with luminaries like Joel Spolsky and Jeff Atwood backing you, how can you go wrong?  If you want to kill any technology — WCF, WPF, .NET Remoting, 3-tier architecture — just invoke this magic phrase and it will wither away.

2. It’s not scalable.

Amazingly enough, this diabolical mantra can be called upon without any evidence.  No one will ever turn around and ask you to justify your claim — be it with a load tester or anything.  Simply say these magic words and your enemies will cower before you.  Anything cool — like reflection, say — will cause a certain amount of performance degradation.  This is normal of course.  In software there are always tradeoffs, and exchanging performance for other advantages such as robustness and decoupling are the norm.  Unless, of course, you make trade offs impossible.  The magic phrase “It’s not scalable” instantly makes any trade off seem impossible.  It’s very well, after all, to lose 5 milliseconds on a transaction, but what happens when you have a gazillion transactions?!!!  That’s 5 milli-gazillion units of time that you have cost the company, and time is money!  That’s 5 milli-gazillion dollars you’ve cost the company!   By golly, this solution is not scalable!

3. It will push us beyond our deadline.

“The solution you have provided is all well and good, and I mean neither to question your integrity nor your intelligence, but given the fact that it is not maintainable and not scalable, I fear that trying to implement it will push us beyond our deadline.”  I’ve never worked on a project that wasn’t “time sensitive” and rarely on one that wasn’t needed “yesterday”.  There’s no better way to kill an idea, even when it comes out of  the mouth of someone who refuses to say definitively when a project will in fact be completed, than to say that it will push us past our deadline.  I’ve seen this used when determining which architecture to use.  I’ve even seen it used in determining which textbox control to use.  If you ever find yourself in a position where you have an idea that is competing with someone else’s idea, you can quickly sweep your adversary’s idea aside by invoking this occult phrase: It will push us beyond our deadline.

Why are these magic phrases never tested?  Why are they impervious to standards of verifiability traditionally expected in other fields?  The reason is simple.  Software development is always seen, from the outside, as a kind of magic, and any successful project has at its heart some secret sauce, some magic code, that makes it all possible.

This is the magic unicorn principle.  At the heart of any successful application stands a magic unicorn.  You feed it data, no matter how disorganized or moldy, and it comes out the other end a rainbow.  Data in.  Rainbows out.  It’s beautiful in its simplicity.

In my next post, I will demonstrate how to build a DIRO magic assembly.  Stay tuned …

Ajax AutoComplete Extender with WCF

blackstone

The problem with conjuring tricks is that they lose practically all their glamour once you find out how they are done.  It’s very cool to see David Blaine walk down the street, do a few passes over his hand, and resurrect a fly which proceeds to flee.  It’s rather disappointing to do a google search and discover that in order to prepare for this trick, the first requirement is that you freeze a fly.

My trick is to make an autocomplete extender from the Ajax Control Toolkit call a WCF service instead of an asmx service.  For this recipe, I assume that you are already familiar with the autocomplete extender, and that you are using Visual Studio 2008.  I warn you in advance — my trick disappoints.  It is so trivially easy that, once the technique spreads, it is very unlikely to impress your colleagues at work, much less get you a date with a supermodel.

Start by creating a new web project called AutocompleteWCF.  Add a reference to the AjaxControlToolkit.dll.  Open up the default aspx page that is generated with your project, and add the following code to:

    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
            <asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
            <ajaxToolkit:AutoCompleteExtender
                runat="server" 
                BehaviorID="AutoCompleteEx"
                ID="autoComplete1" 
                TargetControlID="myTextBox"
                ServicePath="Autocomplete.svc" 
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="0" 
                CompletionInterval="1000"
                EnableCaching="true">
            </ajaxToolkit:AutoCompleteExtender>
    </div>
    </form>

 

This is the standard demo code that is shipped with the Ajax Control Toolkit Sample Website.  I’ve simplified it a bit by removing the animations.  The only significant change I’ve made is to change the ServicePath from Autocomplete.asmx to Autocomplete.svc, the latter being the extension for a WCF service.

The next step is to create our service and add a GetCompletionList operation to it.  The easiest way to do this is to go to Add | New Item and just select the Ajax-enabled WCF Service item template, but this would be so easy that it is hardly worth doing.

Instead, create a new WCF Service using the WCF Service Item Template and call it Autocomplete.svc.  Visual Studio will automatically generate a service interface for you.  Delete the interface.  We don’t need it.  (To be more specific, I don’t know how to get this to work with an interface, so I’m just going to ignore that it is possible.)

Again, I am going to rip off the ACT sample app and just borrow the code from their webservice and place it in our WCF service.  The WCF service class (Autocomplete.svc.cs) will look like this:

    [ServiceContract(Namespace = "")]

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    public class Autocomplete

    {

 

        [OperationContract]

        public string[] GetCompletionList(string prefixText, int count)

        {

            if (count == 0)

            {

                count = 10;

            }

 

            if (prefixText.Equals("xyz"))

            {

                return new string[0];

            }

 

            Random random = new Random();

            List<string> items = new List<string>(count);

            for (int i = 0; i < count; i++)

            {

                char c1 = (char)random.Next(65, 90);

                char c2 = (char)random.Next(97, 122);

                char c3 = (char)random.Next(97, 122);

 

                items.Add(prefixText + c1 + c2 + c3);

            }

 

            return items.ToArray();

        }

 

A few things worth noting:

1. Autocomplete does not implement the IAutocomplete Interface.  Even though this is generated automatically, with the WCF Service item template, you should remove it.

2. The service contract has a blank Namespace explicitly declared. 

3. The ASPNetCompatibilityRequirements attribute must be added to our class.

 

This takes care of the code that calls the WCF service, as well as the service itself.  We now have rig up the web.config file.  If you’ve been working with WCF for any length of time, then you know that this is where the problems usually occur.  Fortunately, the configuration is fairly simple.  You need to set up an endpoint behavior for your service that enables web scripting (much the way asmx web services must be decorated with the ScriptService attribute in order to be called from client-script).  You also will need to turn AspNetCompatibilityEanbled on for the hosting environment.

 

    <system.serviceModel>

        <behaviors>

            <endpointBehaviors>

                <behavior name="AjaxBehavior">

                    <enableWebScript/>

                </behavior>

            </endpointBehaviors>

        </behaviors>

        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

        <services>

            <service name="AutocompleteWCF.Autocomplete">

                <endpoint address="" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" contract="AutocompleteWCF.Autocomplete"/>

            </service>

        </services>

    </system.serviceModel>

 

And that is all you need to do make the AutoComplete Extender work with a WCF service instead of an asmx web service.  I told you it would be unimpressive.

Of course, using a WCF service for Ajax has all the limitations that using an asmx file for Ajax did.  First of all, you can’t call a service that is in a different domain than the page which hosts your client-code.  This is a security feature, to prevent malicious code from redirecting your harmless javascript to something nasty on the world wide web.

Second, you can’t call just any service from your client-side code.  The service must be explicitly marked as something that can be called from client code.  In asmx web services, we used ScriptService for this.  In WCF services, we similarly use EnableWebScript binding property.

Now I feel like I’ve wasted your time, so here’s a YouTube video of David Blaine to make up for it.  And remember, David Blaine is to Chris Angel what Daisy Duke was to Alexis Carrington.  It’s an existential thing, and at some point, you’ve just got to pick sides and stay put in a way that will determine who you are for the rest of your life.

Are you a David Blaine/Daisy Duke kind of person or are you a Chris Angel/Alexis Carrington sort?  Do some soul searching and please let me know what you learn about yourself.