Twitter and Postmodernism

barthelme

That’s a pretty pretentious title. 

First, a word of clarification.  While most articles and even dissertations that use the snowclone “X and Postmodernism” attempt to explicate X through the prism of postmodernism, this post will move in the other direction and attempt to elucidate postmodernism with X.  By the end, I hope to convince you that not only is the title modest but that a more accurate title would have been something like “Twitter as the Fulfillment of the Postmodern Project.”

To accomplish this we just need to bring two Dons into juxtaposition: Don Browning and Don Barthelme.

 

Don Browning, an MCA architect and Director of Technology at Turner Broadcasting, made the following Tweet a few days ago:

“You know how people create books made up of blog posts, I want to put together a blog made up of tweets..”

It’s a fascinating idea.  The first successful instance of the blog-to-book genre I ever came across was Joel Spolsky’s Joel On Software book, which is the tree unfriendly version of his popular tech blog.  He quickly followed this up with – naturally enough – More Joel On Software.   Other exemplars of the genre include Chris Anderson’s The Long Tail, Christian Lander’s Stuff White People Like and Jay Louis’s Hot Chicks with Douchebags.

Why would someone want to pay for articles they can already look at for free on the Internet?  And why would an author not feel dirty about repackaging his day-to-day musings and then charging for it?

Turning a blog into a book is a cultural uptrade.  A blog is a lowbrow version of the traditional book of essays. Being asked to convert one’s blog into a book is like being told that what one had been doing all that time one thought one was blogging was, in actuality, merely literary slumming in an alternative medium – one was always writing a book but just didn’t realize it.  The book form is the cultural recognition of this fact.

Cultural legitimacy comes at a price.  What makes a book a book and confers cultural legitimacy upon it is the not that trees were killed in its production but rather that people must pay money in order to own it.  A book is a commodity in a way that a blog is not.  People are used to paying for the privilege of reading something in their hands, while they resent paying for permission to read it on the Internet.  We all accept that we get what we pay for as well as the corollary that while there is value in a bargain, there is no ‘real’ value in something that is free.

The difference between a picture of a soup can and Andy Warhol’s picture of a soup can is that someone will pay millions of dollars for the latter.  Andy Warhol’s soup can is “art” because it has a price.  It has cultural value — rather than, say, use-value – because of its price tag.

soup

Without the price tag, what is the difference between a blog and the book version of that same blog?  The book version is less convenient to read while the content is basically the same.  The only justification for — the only value added of — paying for the book form of something one could read for free appears to be simply that: the privilege of paying for it.

This is, of course, also the strange world of Twitter, the plan for monetizing which is currently still in research, according to the official FAQ:

“Twitter has many appealing opportunities for generating revenue but we are holding off on implementation for now because we don’t want to distract ourselves from the more important work at hand which is to create a compelling service and great user experience for millions of people around the world. While our business model is in a research phase, we spend more money than we make.”

Twitter is currently a mechanism for not generating revenue, though it is so good at this that there is a lot of buzz about its potential value. 

According to TechCrunch:

“Some analysts have suggested that Twitter has moved past and consumed RSS at the center of the information machine. As newspapers and other print vehicles appear to collapse, the common concerns expressed about the permanent loss and funding of the fourth estate ignore the rise of a superclass of information creation. What some call the fallow ego-driven spew of the Warholian elites is more likely to be seen in the rear view mirror as something more akin to body painting and ultimately jazz.”

. . .

“What’s exhilirating is that the vague assumptions, arrogant exploits, twinkling of an ephemeral joke, they all are being ratified in a swirl of innovation that is dazzling in its ability to masquerade as superficial and childish.” [sic]

The coming fourth estate, however, is made up of disjointed observations about what one had for lunch and, occasionally, the sorts of “inarticulate grunt or roar” that William Rehnquist would argue is not protected speech.

John Scalzi (who, by the way, published his first science fiction book online and has now been nominated for the 2009 Hugo Award) provides a good description of Twitter which, though not the first, has the distinction of at least being the latest:

“[I]t’s even better than blogging for quite a lot of people, because when you’re limited to 140 characters, you don’t have to feel bad about not having all that much to say.

“That most Twitter communication is aggressively banal should also not come as a huge surprise. First, news flash: people are banal. Yes, all of us, even you (and especially even me). Even the great minds of the world do not spend all their time locked in the contemplation of the mysteries of the universe; about 90% of their thoughts boil down to ‘I’m hungry,’ ‘I’m sleepy,’ ‘I need to poo,’ ‘Check out the [insert secondary sexual characteristics] on that [insert sex of preference], I’d really like to boink them,’ ‘I wonder what Jennifer Aniston is doing right now, John Mayer can no longer tell me on his Twitter feed’, and, of course, ‘Look! Kitty!’ That the vast majority of Twitter posts encompass pedestrian thoughts about common subjects like food, music, tech, jobs and cats is entirely unsurprising, because this is what people think about.”

One could have a lot of fun coming up with ways to describe the banality of Twitter but unfortunately we’re all already too good at doing it.  Thanks to Twitter, it is a private joke that is being shared with millions of your Twitter friends. 

The social experiment for which Twitter lays the groundwork is to see how we can collectively uptrade Twitter’s cultural status.  Can the acknowledged irrelevance of Twitter be made relevant?

Returning to Don Browning’s opening comment about aggregating individual tweets and presented them as a blog — something like this has already been done by Don Barthelme, the postmodern literary figure, back in the sixties.  He developed a technique for amalgamating fragments of conversations into a literary form which he perfected in a 1969 short story called The Viennese Opera Ball:

“The judicial form contemplated in the agreement is that of a free trade zone to be transformed gradually into a customs union.  As Emile Myerson has said, ‘L’homme fait de la metaphysique comme il respire, sans le vouloir et surtout sans s’en douter la plupart du temps.’  No woman is worth more than 24 cattle, Pamela Odede B. A.’s father said.  With this album Abbey Lincoln’s stature as one of the great jazz singers of our time is confirmed, Laura La Plante said.  Widely used for motors, power tools, lighting, TV, etc.  Generator output: 3500 watts, 115/230 volt, 60 cy., AC, continuous duty.  Max 230 V capacitor motor, loaded on starting – 1/2 hp; unloaded on starting – 2 hp.  Control box mounts starting switch, duplex 115 V receptacle for standard or 3-conductor grounding plugs, tandem 230 V grounding receptacles, and wing nut battery terminals.  More than six hundred different kinds of forceps have been invented.  Let’s not talk about the lion, she said.  Wilson looked over at her without smiling and now she smiled at him.  This process uses a Lincoln submerged arc welding head to run both inside and outside beads automatically.  The rate of progress during the first stage will determine the program to be followed in the second stage.  The Glamour editor whose name was Tutti Beale ‘moved in.’  What’s your name girl?  she said coolly.  Carola Mitt, Carola Mitt said.  The Viennese Opera Ball continued.”

The story was published in a collection called Come Back, Dr. Caligari which you cannot buy on Amazon.com.  It was later republished in Flying to America: 45 More Stories which you can purchase for $10.85 plus shipping.  It has an Amazon sales rank of 76,601*.

Louis Menand, the Critic at Large for the New Yorker, recently wrote in his analysis of Donald Barthelme’s career that there are two senses of postmodernism.  According to the first, postmodernism is an acknowledgement that modernism was so successful that we are now all modernists.  Postmodernism, in this sense, means accepting that we are living in the age of modernism as initiated by James Joyce and Picasso (who, it is said, used to pay for his meals after he became famous by scrawling on napkins and handing them over in lieu of cash) and simply making sense of their linguistic and visual experiments. 

In the second, modernism was a failure and we are all now doing something else.  Instead of trying to make culture more erudite and less accessible, the goal of postmodernism is to remove the artificial boundaries between “high” and “low” art.  This can be accomplished in two ways: either by kicking high culture down or by kicking low culture up.

Kicking high culture downwards requires an unmasking.  Someone accomplishes the difficult task of being accepted into the vaunted ranks of culture and then proclaims that they were just faking it.  This is actually the easier of the two paths, and you’ll see that it happens quite often if you just look for it.

The second, kicking low culture upwards,  is the harder path and the holy grail for most postmodernists.  Making shit look interesting — and then making a convincing case for it — is harder than it looks.

Menand cites jazz as the epitome of this cultural upkick.  It fails to fulfill the postmodern project in two ways, however.  The first is a technicality – chronologically it developed before the postmodern movement was an inkling in anyone’s eye.  It lacks the ironical self-awareness of itself as a postmodern art form.  The second is a more substantial problem, though perhaps only in retrospect – despite its lowly and popular origins in clubs and bordellos, it has both visceral and intellectual merit.  The form lends itself both to the easily hummable tunes of Dave Brubeck as well as the challenging mathematical complexity of Thelonious Monk.  It was always potentially high art, in this sense, whether we realized it or not.

To fulfill the postmodern agenda, the low culture platform targeted for uptrade must lack these qualities.  It must be so clearly lowbrow that it survives transformation into a high culture artifact without anyone relinquishing this ironical awareness of its cultural banality.  If Twitter is the long anticipated postmodern medium, Twitter must succeed without losing the qualities that make it Twitter.

There are currently rumors of Google interest in purchasing access to the wealth of grunts and roars that is Twitter.  Twitter, in turn, has already turned down Face-book’s offer of half-a-billion dollars, and seems to be valuing itself at well over twice that. 

A billion dollars, of course, buys one a lot of cultural legitimacy.

 


* By way of comparison, Joel Spolsky’s book Joel On Software has a current Amazon sales rank of 22,865.  Hot Chicks with Douchebags ranks at 12,809.

Presenting at CodeStock 2009 dot dot dot question mark

CodeStock, which will be held on June 26th and June 27th in Knoxville, TN, has an interesting way of selecting speakers.  While a speakers committee ultimately decides who will speak at the event, all registrants (it’s $25 this year) also have a say in who they are interesting in hearing.

I’ve submitted two presentations this year but at the moment still have no idea if I’ll ultimately be delivering either.

The first is a version of the pleasantly successful REST-ful WCF presentation I did at Atlanta Code Camp, with additional material covering the release of the WCF REST Starter Kit 2.

The second is an overview of the MVC, MVP, and MVVM UI design patterns.  There are lots of good articles available on the net about how to use each one individually.  I want to give a more synoptic view of how they are related, and their advantages and disadvantages with regard to particular .NET platforms.

I don’t know anyone in Knoxville, so if you are planning on attending CodeStock this year, please drop me a line in the comments so I can make plans to meet up with you.

What kind of consultant are you?

A few Magenic colleagues  and I happened to be in the office at the same time today and were discussing what makes a good software consultant.  We arrived at the idea that there are certain archetypes that can be associated with our profession.  Consulting and independent contracting require a peculiar combination of skills which are not always compatible: leadership, salesmanship, problem solving, commitment, patience, quick thinking, geekiness, attention to detail, attention to vision, and so forth. 

As a consultant, one is often both the salesman and the product being sold, and it requires a bit of a split personality to pull both off well.  Most consultants are able to do well with certain aspects of consulting but not others.  It seemed to us, however, that if we could identify certain “types” of consultants rather than try to identify the particular skills that make up a consultant, we would arrive at something approaching a broad spectrum of what consulting is all about.

After a bit of work, Whitney Weaver, Colin Whitlatch, Tim Price-Williams (who needs a blog because he knows too much about the entity framework not to share)  and I came up with the following list of consulting archetypes and the qualities that exemplify each one. 

For our unit test, we then tried to match consultants we know first with who they think they are and then with who they actually resemble.  It worked out pretty well, and so we thought we’d turn the idea loose.  (I turned out to be a weird mix of MacGuyver and the Jump-To-Conclusions-Guy, though I also have a savior complex.)

See if any of the following archetypes matches people you know.  And if you think we’ve left an important archetype out of our catalog, please let me know in the comments.

 

jack

Jack Bauer

Jack is the ultimate get-things-done guy.  This is in part because he takes the full weight of any project on his own shoulders.  He is admired by everyone he encounters for his dedication and competence. 

He also comes across as a bit harsh, however, so we can’t really say he has good soft skills.  Some consider consultants like him to be a bit too good to be true.

 

house

House

House is great at diagnosing any problem.  He is methodical and thorough while at the same time he is able to think well outside of the box. 

He is also a bit of a dick and will turn on you when you least expect it.  On the other hand, when he throws you under the bus, at least you’ll know it wasn’t personal.

 

TOP GUN

Maverick

Maverick is charismatic as well as intensely competitive, though his arrogance tends to put people off.  If you think a task will take two weeks, he’ll claim it can be done in two days.  If you estimate that something will take two days, he’ll insist he can do it in two hours.

He always manages to be successful though no one is sure how. 

 

sarah_connor

Sarah Connor

Sarah thinks quickly on her feet and is an extraordinary problem solver.  She has a great mix of soft and technical skills. 

Sadly, she tends to get the people around her killed.  Consultants with skills like hers seem to take on a lot more risk than the rest of us would, and we all reap the consequences.

 

don_draper

Don Draper (Mad Men)

Don has infinite charm and is a perennial winner.  Women love him and men want to be his friend.

He is also clearly hiding something from everyone, and is haunted by the notion that he is ultimately a fraud.

 

neo 

Neo

Neo can re-program reality.

Some consider him to be wooden.  He also has a bit of a savior complex.

 

terminator3

The Chick from Terminator 3

Pros: She’s smokin’ hot.

Cons: She will kill you at the drop of a hat.

 

macguyver

MacGuyver

MacGuyver is a jack-of-all trades, the kind of consultant you want on any project.  He also has great hair.

He tends to be a bit of a one-man-show, however.

 

kramer

Kramer

Kramer has the “vision” thing.  He’s the one who will envision and lay out the entire architecture of the project in the first few days despite other people’s misgivings.

Unfortunately Kramer has poor follow-through.  You’ll be living with his architectural decisions long after he’s moved on to bigger and better things.

 

ben

Benjamin Linus

Ben has excellent soft skills.  He is a master manipulator.  He can turn any situation to his own advantage.  In a tough negotiation, he’s the consultant you want at your side.

On the other hand, he is pure EVIL and cannot be trusted.

 

baldwin

Alec Baldwin in Glengarry Glen Ross

“Second prize is a set of steak knives.”  Alec is a motivator.  Other people quiver in his presence.  We all know that sometimes you have to be an asshole to get things done.  Fortunately a consultant like Alec loves that part of the job.

We can assume that he will eventually flame out, as people of this type always do.  Sadly, no one will really feel sorry for him when this happens.

 

cartman

Cartman

Eric Cartman has strong survival skills and is highly self-confident, both of which enable him to accomplish his sometimes overly ambitious schemes. He also aways has a private agenda.

Because of this, he tends to make himself a bit of a target, while his single-minded pursuit of his own ends can cause serious problems for other consultants.

 

george

George Costanza

Everything always seems to blow up on George.  He is also high maintenance.

On the upside, he is generally considered non-threatening, which can sometimes be a very good thing in consulting.

 

jump_to_conclusions_guy

The Jump-To-Conclusions-Guy

This guy is eternally optimistic.  He considers himself to have excellent people skills.

He does not have excellent people skills.

 

 vanilla_ice

Vanilla Ice

Vanilla Ice is the archetypal one-hit wonder. 

He did something important back in 1990 and has been living off of that one success ever since.  Then again, not everyone gets even that one success, so don’t judge him too harshly.

 

lumburgh

Lumbergh

Lumbergh is the anti-Jack Bauer.  He is a human deflector shield, and while you’re not looking he’ll manage to blame you for his screw ups.   When he throws you under the bus, you’ll know that it really was in fact personal.

The best that can be said of Lumbergh is that you don’t run into too many Lumberghs in software consulting.

 

 

We are so happy with this catalog of consulting types that we are thinking of using it in our local vetting of new-hire candidates.  Given the broad range of technical skills people can have, it seems rather unfair to try to label new-hires as “senior” or “junior” or anything like that.  What we’re looking for, after all, is a good fit for our local office, and the best way to do this is to, say, determine that we need another Maverick or a Sarah Connor or a Neo, and to try to find the right person following the guidelines above.

Moreover, when we tell our clients that we are sending them our A-Team, we can mean it literally: they are getting one Alec Baldwin, one Don Draper,  a MacGuyver and a Jump-To-Conclusions-Guy.  On the other hand, if someone wants the cast from Seinfeld, we can fill that order, too.

William James and the Squirrel

  squirrel

 

In the same lecture excerpted previously, William James provides an earthy example of what he means by pragmatism.  It involves squirrel.

Some years ago, being with a camping party in the mountains, I returned from a solitary ramble to find everyone engaged in a ferocious metaphysical dispute. The corpus of the dispute was a squirrel–a live squirrel supposed to be clinging to one side of a tree-trunk; while over against the tree’s opposite side a human being was imagined to stand. This human witness tries to get sight of the squirrel by moving rapidly round the tree, but no matter how fast he goes, the squirrel moves as fast in the opposite direction, and always keeps the tree between himself and the man, so that never a glimpse of him is caught. The resultant metaphysical problem now is this: DOES THE MAN GO ROUND THE SQUIRREL OR NOT? He goes round the tree, sure enough, and the squirrel is on the tree; but does he go round the squirrel? In the unlimited leisure of the wilderness, discussion had been worn threadbare. Everyone had taken sides, and was obstinate; and the numbers on both sides were even. Each side, when I appeared, therefore appealed to me to make it a majority. Mindful of the scholastic adage that whenever you meet a contradiction you must make a distinction, I immediately sought and found one, as follows: "Which party is right," I said, "depends on what you PRACTICALLY MEAN by ‘going round’ the squirrel. If you mean passing from the north of him to the east, then to the south, then to the west, and then to the north of him again, obviously the man does go round him, for he occupies these successive positions. But if on the contrary you mean being first in front of him, then on the right of him, then behind him, then on his left, and finally in front again, it is quite as obvious that the man fails to go round him, for by the compensating movements the squirrel makes, he keeps his belly turned towards the man all the time, and his back turned away. Make the distinction, and there is no occasion for any farther dispute. You are both right and both wrong according as you conceive the verb ‘to go round’ in one practical fashion or the other."

Altho one or two of the hotter disputants called my speech a shuffling evasion, saying they wanted no quibbling or scholastic hair-splitting, but meant just plain honest English ’round,’ the majority seemed to think that the distinction had assuaged the dispute.

On Pragmatism: some excerpts

wjames

Over the past ten years or so the software development world has split itself between two extremes of temperament.  One is pragmatic while the other, for lack of a better term, is purist.  This is a division which actually happens again and again from one year to the next, with members of one party sometimes becoming members of the other, and practitioners of one philosophy in one technical domain becoming practitioners of the other under other circumstances.

This is not a division of temperament unique to programming of course, though it perhaps gets a little more play there than in other fields these days.  As a matter of interest and of clarification, I thought I might provide some excerpts from William James’s work Pragmatism: A New Name for Some Old Ways of Thinking from 1907:

“The history of philosophy is to a great extent that of a certain clash of human temperaments. Undignified as such a treatment may seem to some of my colleagues, I shall have to take account of this clash and explain a good many of the divergencies of philosophers by it. Of whatever temperament a professional philosopher is, he tries when philosophizing to sink the fact of his temperament. Temperament is no conventionally recognized reason, so he urges impersonal reasons only for his conclusions. Yet his temperament really gives him a stronger bias than any of his more strictly objective premises. It loads the evidence for him one way or the other, making for a more sentimental or a more hard-hearted view of the universe, just as this fact or that principle would. He trusts his temperament.”

. . .

“Yet in the forum he can make no claim, on the bare ground of his temperament, to superior discernment or authority. There arises thus a certain insincerity in our philosophic discussions: the potentest of all our premises is never mentioned. I am sure it would contribute to clearness if in these lectures we should break this rule and mention it, and I accordingly feel free to do so.”

. . .

“Now the particular difference of temperament that I have in mind in making these remarks is one that has counted in literature, art, government and manners as well as in philosophy. In manners we find formalists and free-and-easy persons. In government, authoritarians and anarchists. In literature, purists or academicals, and realists. In art, classics and romantics. You recognize these contrasts as familiar; well, in philosophy we have a very similar contrast expressed in the pair of terms ‘rationalist’ and ’empiricist,’ ’empiricist’ meaning your lover of facts in all their crude variety, ‘rationalist’ meaning your devotee to abstract and eternal principles. No one can live an hour without both facts and principles, so it is a difference rather of emphasis; yet it breeds antipathies of the most pungent character between those who lay the emphasis differently; and we shall find it extraordinarily convenient to express a certain contrast in men’s ways of taking their universe, by talking of the ’empiricist’ and of the ‘rationalist’ temper. These terms make the contrast simple and massive.

“More simple and massive than are usually the men of whom the terms are predicated. For every sort of permutation and combination is possible in human nature; and if I now proceed to define more fully what I have in mind when I speak of rationalists and empiricists, by adding to each of those titles some secondary qualifying characteristics, I beg you to regard my conduct as to a certain extent arbitrary. I select types of combination that nature offers very frequently, but by no means uniformly, and I select them solely for their convenience in helping me to my ulterior purpose of characterizing pragmatism. Historically we find the terms ‘intellectualism’ and ‘sensationalism’ used as synonyms of ‘rationalism’ and ’empiricism.’ Well, nature seems to combine most frequently with intellectualism an idealistic and optimistic tendency. Empiricists on the other hand are not uncommonly materialistic, and their optimism is apt to be decidedly conditional and tremulous. Rationalism is always monistic. It starts from wholes and universals, and makes much of the unity of things. Empiricism starts from the parts, and makes of the whole a collection-is not averse therefore to calling itself pluralistic. Rationalism usually considers itself more religious than empiricism, but there is much to say about this claim, so I merely mention it. It is a true claim when the individual rationalist is what is called a man of feeling, and when the individual empiricist prides himself on being hard- headed. In that case the rationalist will usually also be in favor of what is called free-will, and the empiricist will be a fatalist– I use the terms most popularly current. The rationalist finally will be of dogmatic temper in his affirmations, while the empiricist may be more sceptical and open to discussion.

“I will write these traits down in two columns. I think you will practically recognize the two types of mental make-up that I mean if I head the columns by the titles ‘tender-minded’ and ‘tough-minded’ respectively.”

THE TENDER-MINDED THE TOUGH-MINDED
Rationalistic (going by ‘principles’) Empiricist (going by ‘facts’)
Intellectualistic Sensationalistic
Idealistic Materialistic
Optimistic Pessimistic
Religious Irreligious
Free-willist Fatalistic
Monistic Pluralistic
Dogmatical Sceptical

 

“Pray postpone for a moment the question whether the two contrasted mixtures which I have written down are each inwardly coherent and self-consistent or not–I shall very soon have a good deal to say on that point. It suffices for our immediate purpose that tender-minded and tough-minded people, characterized as I have written them down, do both exist. Each of you probably knows some well-marked example of each type, and you know what each example thinks of the example on the other side of the line. They have a low opinion of each other. Their antagonism, whenever as individuals their temperaments have been intense, has formed in all ages a part of the philosophic atmosphere of the time. It forms a part of the philosophic atmosphere to-day. The tough think of the tender as sentimentalists and soft-heads. The tender feel the tough to be unrefined, callous, or brutal. Their mutual reaction is very much like that that takes place when Bostonian tourists mingle with a population like that of Cripple Creek. Each type believes the other to be inferior to itself; but disdain in the one case is mingled with amusement, in the other it has a dash of fear.”

And here’s the bait and switch portion of this post.  When we speak of being pragmatic today, we generally mean by it the items in the second column above.  For James, however, the term describes a way of looking at the world that resolves disputes between the possessors of these two temperaments.  It is the tertia via.

“The pragmatic method is primarily a method of settling metaphysical disputes that otherwise might be interminable. Is the world one or many?–fated or free?–material or spiritual?–here are notions either of which may or may not hold good of the world; and disputes over such notions are unending. The pragmatic method in such cases is to try to interpret each notion by tracing its respective practical consequences. What difference would it practically make to anyone if this notion rather than that notion were true? If no practical difference whatever can be traced, then the alternatives mean practically the same thing, and all dispute is idle. Whenever a dispute is serious, we ought to be able to show some practical difference that must follow from one side or the other’s being right.”

. . .

“It is astonishing to see how many philosophical disputes collapse into insignificance the moment you subject them to this simple test of tracing a concrete consequence. There can BE no difference any- where that doesn’t MAKE a difference elsewhere–no difference in abstract truth that doesn’t express itself in a difference in concrete fact and in conduct consequent upon that fact, imposed on somebody, somehow, somewhere and somewhen. The whole function of philosophy ought to be to find out what definite difference it will make to you and me, at definite instants of our life, if this world- formula or that world-formula be the true one.”

. . .

“There is absolutely nothing new in the pragmatic method. Socrates was an adept at it. Aristotle used it methodically. Locke, Berkeley and Hume made momentous contributions to truth by its means. Shadworth Hodgson keeps insisting that realities are only what they are ‘known-as.’ But these forerunners of pragmatism used it in fragments: they were preluders only. Not until in our time has it generalized itself, become conscious of a universal mission, pretended to a conquering destiny. I believe in that destiny, and I hope I may end by inspiring you with my belief.”

. . .

“At the same time it does not stand for any special results. It is a method only. But the general triumph of that method would mean an enormous change in what I called in my last lecture the ‘temperament’ of philosophy.”

It is a philosophy that requires us to ask, when given two temperamental approaches to the same problem, a very rude question. 

We would be required to ask “What practical difference does it make?”  On the other hand, in programming if not in other spheres, it would save an insufferable amount of time and effort were we simply to ask this a little more often.

Visual Studio 2008 Toolbox Crash Redux

crash

I had written a while ago about a quick way to resolve this issue by simply uninstalling Power Commands.

For some reason, the problem reappeared for me a few weeks ago — I think after installing an SDK — and I did not have Power Commands installed!  So I had to find an alternative solution.  It’s a little tedious, but it does the trick. 

Just to recap, the problem is that when the Visual Studio 2008 IDE reaches a certain state, attempts to Choose Items in the toolbox leads to Visual Studio shutting completely down, usually after a long and fretful wait.

1. To clear this peculiar issue up, you will want to run Visual Studio in safe mode.  To do so, open up a command line utility and run DEVENV /safemode.  Visual Studio should come up for you.

2. Right click on your toolbox and select Choose Items… from the context menu. 

3. Methodically select each tab in the dialog box that is presented.  Accept any recommendations or error messages that come up.

4. After this time consuming but effective process, you may close Visual Studio and bring it up again in normal mode.  All blemishes should be gone, and you can continue with your work.

How Will Battlestar Galactica End?

apollo

I’m such a loser.  Hours away from the BSG finale and I am still blogging about code.

So how will Battlestar Galactica end tonight?  I am hoping for a classic Dallas ending.  Apollo wakes up on the 1978 Galactica from a nightmare in which he is a sociopath politician named Tom Zarek on an alternate Galactica in which Dr. Z is never found and Earth is a wasteland.  It turns out that this is part of an evil plot devised by Count Iblis, but Starbuck, Apollo, Boomer, Lieutenant Zack and Muffit, Boxey’s Daggit, foil Iblis’s scheme and bring sanity back to the Galactica.  When Apollo tells Starbuck about their intimate relationship in his dream, it creates some awkwardness, but they work it out in a game of pyrimid and then go down to the gambling planet to get good and sloshed.

Can’t wait ’till tonight when I get to see how close I am.  It’s definitely a Crystal and Courvoisier kind of evening.

WCF REST Starter Kit 2: Calling Twitter

The great power of the WCF REST starter Kit comes from allowing programmers to easily call pre-existing REST services written on non-Microsoft platforms.  Of those, Twitter is probably the most popular and easiest to understand.  In order to use twitter, we need at a bare minimum to be able to read tweets, to write tweets, and occasionally to delete a tweet.  Doing this also showcases the core structure of REST calls: they allow us to perform CRUD operations using the following web methods: GET, POST, PUT and DELETE.

The following example will use GET to read tweets, POST to insert tweets, and DELETE to remove tweets.

Ingredients: Visual Studio 2008 SP1 (C#), WCF REST Starter Kit Preview 2, a Twitter account

Sample: download (10 KB)

In this tutorial, I will walk you through building a simple Twitter command line application — I know, I know, Twitter from a console is what we’ve all been longing for!

This tutorial will use the techniques from the previous Getting Started post on WCF REST and expand on them to develop a “real world” application.

The first stop is the documentation on the Twitter API, which can be found here.  Based on the documentation, we can see that we want to call the friends_timeline resource in order to keep up with our twitter buddies.  We will want the update resource in order to insert new tweets.  We will also want the destroy resource so we can immediately delete tweets like “I am testing my console app”, “testing again”, “still testing 3”, etc.

Reading our friends’ tweets is the easiest part of all this.  The basic code looks like this:

var client = new HttpClient();

 

//set authentication credential

NetworkCredential cred = new NetworkCredential(_userName, _password);

client.TransportSettings.Credentials = cred;

 

//set page parameter

var queryString = new HttpQueryString();

queryString.Add(“page”, page.ToString());

 

//call Twitter service

var response =

        client.Get(

        new Uri(“http://twitter.com/statuses/friends_timeline.xml”)

        , queryString);

 

var statuses = response.Content.ReadAsXmlSerializable<statuses>();

foreach (statusesStatus status in statuses.status)

{

    Console.WriteLine(string.Format(“{0}: {1}”

        , status.user.name

        , status.text));

    Console.WriteLine();

    Console.WriteLine();

}

Twitter uses basic authentication to identify users.  To insert this information into our header, we create a new Network Credential and just inject it into our HttpClient instance.  (_userName and _password are simply private static fields I created as placeholders.)  The service can also take a “page” parameter that identifies which page of our friends’ statuses we want to view.  This code uses the HttpQueryString type that comes with the Starter Kit to append this information.

The results should look something like this:

console4

Probably the trickiest thing in getting this up and running is using Paste XML as Types from the Edit menu in order to generate the statuses class for deserialization.  To get the raw XML, you will need to browse to http://twitter.com/statuses/friends_timeline.xml, at which point you will be prompted for your Twitter account name and password.  In my case, I then copied everything out of the browser and pasted it into notepad.  I then stripped out the XML declaration, as well as all the hyphens that IE puts in for readability.  Having too many status elements turned out to make Visual Studio cry, so I removed almost all of them leaving only two.  Leaving two turned out to be important, because this allowed the underlying Paste XML as Types code to know that we were dealing with an array of status elements and to generate our classes appropriately.  At the end of this exercise, I had a statuses class, statusesStatus, statusesStatusUser, and a few others.

Posting a twitter status is a little bit harder, partly due to the way the Twitter API implements it.  Here’s the basic code for that:

var client = new HttpClient();

 

//set authentication credential

NetworkCredential cred = new NetworkCredential(_userName, _password);

client.TransportSettings.Credentials = cred;

 

//fix weird twitter problem

System.Net.ServicePointManager.Expect100Continue = false;

 

//send update

if (p.Length > 140) p = p.Substring(0, 140);

HttpContent body = HttpContent.Create(string.Format(“status={0}&source={1}”

    , HttpUtility.UrlEncode(p)

    , “CommandLineTwitterer”)

    , Encoding.UTF8

    , “application/x-www-form-urlencoded”);

 

var response = client.Post(“http://twitter.com/statuses/update.xml”, body);

Console.WriteLine(“Your tweet was twutted successfully.”);

This took a bit of trial and error to figure out, and in the end I just opened my Twitter home page with the Web Development Helper to see what the message was supposed to look like.  The Expect100Continue is needed to handle a change in Twitter’s API that showed up sometime at the beginning of the year, and which is explained here, here and here.

In order to make delete workable in a console application, I have tacked the following lines of code to the end of the status update method:

var status = response.Content.ReadAsXmlSerializable<status>();

_lastTweetId = status.id;

which hangs onto the id of the successful tweet so the user can turn around and perform a DESTROY command in order to delete the previous tweet.

 

You will notice that in the above snippet, I am using a type called status instead of one the objects associated with statuses from the simple GET service call above.  It is actually identical to the statusesStatus type above.  I gen-ed the status class out of the response simply because I needed a class called “status” in order to map the XML element returned to a clr type.  An alternative way to do this is to add an XmlRoot attribute to the statusesStatus class in order to make the serialization work properly:

 

[System.Xml.Serialization.XmlRoot(“status”)]

public partial class statusesStatus

{

    …

This would allow us to write our deserialize code like this:

var status = response.Content.ReadAsXmlSerializable<statusesStatus>();

_lastTweetId = status.id;

The delete code finishes off this recipe since it will demonstrate using one of the methods one rarely sees in typical REST examples (the other being PUT) .  It looks like this:

 

if (_lastTweetId == 0)

    return;

 

HttpClient client = new HttpClient();

 

//set authentication credential

NetworkCredential cred = new NetworkCredential(_userName, _password);

client.TransportSettings.Credentials = cred;

HttpResponseMessage response = null;

response = client.Delete(

    string.Format(“http://twitter.com/statuses/destroy/{0}.xml”

        , _lastTweetId)

    );

In order to pull this all together and have a functioning app, you just need a simple processing method.  The main processing code here that interprets commands and calls the appropriate methods simply loops until the EXIT command is called:

static void Main(string[] args)

{

    if (!CheckArgsForCredentials(args))

        SetCredentials();

 

    var input = string.Empty;

    while (input.ToUpper() != “EXIT”)

    {

        input = ProcessInput(Console.ReadLine());

    }

}

 

private static string ProcessInput(string input)

{

    //INPUT = READ

    if (input.ToUpper().IndexOf(“READ”) > -1)

    {

        if (input.ToUpper().IndexOf(“PAGE”) > -1)

        {

            var iPage = GetPageNumber(input);

            ReadFriendsTimeline(iPage);

        }

        else if (input.ToUpper().IndexOf(“ME”) > -1)

        {

            ReadUserTimeline();

        }

        else

            ReadFriendsTimeline(1);

 

    }

    //INPUT = TWEET

    else if (input.ToUpper().IndexOf(“TWEET”) > -1)

    {

        UpdateTwitterStatus(input.Substring(5).Trim());

    }

    //INPUT = DESTROY

    else if (input.ToUpper().IndexOf(“DESTROY”) > -1)

    {

        DestroyLastTweet();

    }

    return input;

}

This should give you everything you need to cobble together a simple Twitter client using the WCF REST Starter Kit.  Mention should be made of Aaron Skonnard’s excellent blog. After spending half a day on this I discovered that Aaron Skonnard had already written a much more succinct and elegant example of calling Twitter using the HttpClient.  I also found this cool example from Kirk Evans’s blog explaining how to accomplish the same thing using WCF without the HttpClient.

The full source code (10K) for this sample app has the properly generated types for deserialization as well as exception handling and status code handling, in case you run into any problems.  In order to run it, you will just need to add in the pertinent assemblies from the WCF REST Starter Kit Preview 2.

Getting Started with the WCF REST Starter Kit Preview 2 HttpClient

Ingredients: Visual Studio 2008 SP1 (C#), WCF REST Starter Kit Preview 2

In Preview 1 of the WCF REST Starter Kit, Microsoft provided many useful tools for building RESTful services using WCF.  Missing from those bits was a clean way to call REST services from the client.  In Preview 2, which was released on March 13th, this has been made up for with the HttpClient class and an add-in for the Visual Studio IDE called Paste XML as Types.

The following getting-started tutorial will demonstrate how to use the HttpClient class to call a simple RESTful service (in fact, we will use the default implementation generated by the POX service template).  If you haven’t downloaded and installed the WCF REST Starter Kit, yet, you can get Preview 2 here. You can read more about the Starter Kit on Ron Jacobs’ site.

The sample solution will include two projects, one for the client and one for the service. 

1. Start by creating a Console Application project and solution called RESTfulClient.

2. Add a new project to the RESTfulClient solution using the Http Plain XML WCF Service project template that was installed when you installed the Starter Kit.  Call your new project POXService. 

The most obvious value-added features of the WCF REST Starter Kit are the various new project templates that are installed to make writing RESTful services easier.  Besides the Http Plain XML WCF Service template, we also get the ATOM Publishing Protocol WCF Service, the ATOM Feed WCF Service, REST Collection WCF Service, REST Singleton WCF Service and good ol’ WCF Service Application.

PoxService 

For this recipe, we will just use the default service as it is. 

[WebHelp(Comment = “Sample description for GetData”)]

[WebGet(UriTemplate = “GetData?param1={i}&param2={s}”)]

[OperationContract]

public SampleResponseBody GetData(int i, string s)

{

 

   return new SampleResponseBody()

   {

     Value = String.Format(“Sample GetData response:”   {0}’, ‘{1}'”, i, s)

   };

}

For the most part, this is a pretty straightforward WCF Service Method.  There are some interesting additional elements, however, which are required to make the service REST-y.

(In a major break with convention, you will notice that the default service created by this template is called Service rather than Service1.  I, for one, welcome this change from our new insect overlords.)

The WebGet attribute, for instance, allows us to turn our service method into a REST resource accessed using the GET method.  The UriTemplate attribute parameter specifies the partial Uri for our resource, in this case GetData.  We also specify in the UriTemplate how parameters can be passed to our resource.  In this case, we will be using a query string to pass two parameters, param1 and param2.

By default, the template provides a Help resource for our service, accessed by going to http://localhost:<port>/Service.svc/Help .  It will automatically include a description of the structure of our service.  The WebHelp attribute allows us to add further notes about the GetData resource to the Help resource.

You will also notice that the GetData service method returns a SampleResponseBody object.  This is intended to make it explicit in our design that we are not making RPC’s.  Instead, we are receiving and returning messages (or documents, if you prefer).  In this case, the message we return is simply the serialized version of SimpleResponseBody, which is a custom type that is specified in the service.svc.cs file and which does not inherit from any other type.

public class SampleResponseBody
{
    public string Value { get; set; }
}

3. Right click on the PoxService project and select Debug | Start New Instance to see what our RESTful service looks like.  To see what the service does, you can browse to http://localhost:<port>/Service.svc/Help .  To see what the schema for our GetData resouce looks like, go to http://localhost:<port>/Service.svc/help/GetData/response/schema .  Finally, if you want to go ahead and call the GetData service, browse to http://localhost:<port>/Service.svc/GetData .

(In the rest of this tutorial, I will simply use  port 1300, with the understanding that you can specify your own port in the code.  By default, Visual Studio will randomly pick a port for you.  If you want to specify a particular port, however, you can go into the project properties of the PoxService project and select a specific port in the project properties Web tab.)

<SampleResponseBody xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Value>Sample GetData response: '0', ''</Value> 
</SampleResponseBody>

4. Go to the RESTfulClient project and add a new class called SampleResponseBody.  We are going to create a type for deserializing our SampleResponseBody XML element.  We could write out the class by hand, and prior to Preview 2 we probably would have had to.  It is no longer necessary, however.  If you copy the XML returned from browsing our resource (you may need to use View Source in your browser to get a clean representation) at http://localhost:1300/Service.svc/GetData you can simply paste this into our SampleResponseBody.cs file by going to the Visual Studio Edit menu and selecting Paste XML to Types.  To get all the necessary types in one blow, you can also go to http://localhost:1300/Service.svc/Help and use Paste XML to Types.  As a third alternative, just copy the XML above and try Paste XML to Types in your SampleResponseBody class.  However you decide to do it, you are now in a position to translate XML into CLR types.

Your generated class should look like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute(“System.Xml”, “2.0.50727.3053”)]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace = “”, IsNullable = false)]

public partial class SampleResponseBody

{

 

        private string valueField;

 

        /// <remarks/>

        public string Value

        {

            get

            {

                return this.valueField;

            }

            set

            {

                this.valueField = value;

            }

        }

}

 

5.  Next, we need to add the Starter Kit assemblies to our console application.  The default location for these assemblies is C:\Program Files\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies .  The two assemblies we need for the client are Microsoft.Http.dll and Microsoft.Http.Extensions.dll .  (I happen to like to copy CodePlex bits like these into a folder in the My Documents\Visual Studio 2008 directory, to make it relatively easier to track drop versions).

6. We will now finally add some code to call call our GetData resource using the HttpClient class.  The following code will simply prompt the user to hit {Enter} to call the resource.  It will then return the deserialized message from the resource and prompt the user to hit {Enter} again.  Add the following using references to your Program.cs file:

using Microsoft.Http;

using System.Xml.Serialization;

  Now place the following code in the Main() method of Program.cs:

static void Main(string[] args)

{

    Console.WriteLine(“Press {enter} to call service:”);

    Console.ReadLine();

 

    var client = new HttpClient(http://localhost:1300/Service.svc/);

    HttpResponseMessage response = client.Get(“GetData”);

 

    var b = response.Content.ReadAsXmlSerializable<SampleResponseBody>();

 

    Console.WriteLine(b.Value);

    Console.ReadLine();

}

Both the Get request and the deserialization are simple.  We pass a base address for our service to the HttpClient constructor.  We then call the HttpClient’s Get method and pass the path to the resource we want (in true REST idiom, PUT, DELETE and POST are some additional methods on HttpClient).

The deserialization, in turn, only requires one line of code.  We call the Content property of the HttpResponseMessage instance returned by Get() to retrieve an HttpContent instance, then call its generic ReadAsXmlSerializable method to deserialize the XML message into our SampleResponseBody type.

While you could previously do this using WCF and deserialization, or even the HttpWebRequest and HttpWebResponse types and an XML parser, this is significantly easier.

 

console1

 

7. If you recall, the signature of the GetData service method actually takes two parameters, an integer and a string.  When translated into a REST resource, the parameters are passed in a query string.  To complete this example, we might want to go ahead and pass these parameters to our GetData resource.  To do so, replace the code above with the following:

static void Main(string[] args)

{

    Console.WriteLine(“Enter a number:”);

    int myInt;

    Int32.TryParse(Console.ReadLine(), out myInt);

 

    Console.WriteLine(“Enter a string:”);

    var myString = Console.ReadLine();

 

    var q = new HttpQueryString();

    q.Add(“param1”, myInt.ToString());

    q.Add(“param2”, myString);

 

    var client = new HttpClient(“http://localhost:1300/Service.svc/”);

    HttpResponseMessage response = client.Get(new Uri(client.BaseAddress + “GetData”), q);

    var b = response.Content.ReadAsXmlSerializable<SampleResponseBody>();

 

    Console.WriteLine(b.Value);

    Console.WriteLine(“Press {enter} to end.”);

    Console.ReadLine();

}

The first block asks for a number and we verify that a number was indeed submitted.  The next block requests a string.

The third block creates an HttpQueryString instance using our console inputs.

The important code is in the fourth block.  You will notice that we use a different overload for the Get method this time.  It turns out that the only overload that accepts a query string requires a Uri for its first parameter rather than a partial Uri string.  To keep things simple, I’ve simply concatenated “GetData” with the BaseAddress we previously passed in the constructor (this does not overwrite the BaseAddress, in case you were wondering).  We could have also simply performed a string concatenation like this, of course:

HttpResponseMessage response =

client.Get(string.Format(“GetData?param1={0}&param2={1}”,myInt.ToString(), myString));

but using the HttpQueryString type strikes me as being somewhat cleaner. 

If you run the console app now, it should look something like this:

console2

 

And that’s how we do RESTful WCF as of Friday, March 13th, 2009. 

To see how we used to do it prior to March 13th, please see this excellent blog post by Pedram Rezai from April of last year.