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.

 

 



			

All rational people will agree …

squareOfOposition

In the Critique of Pure Reason, Immanuel Kant argues that moral actions are the actions of an autonomous will, and that an autonomous will is a will that is determined by reason alone.  Moral actions, additionally, follow the form of being universalizable, hence Kant finds in rationality a confirmation of the Golden Rule: when you do unto others as you would have them do unto you, you are behaving in a manner that can be universalized for all mankind.

In the years following Kant’s death, the notion that all rational people, when they are being rational, will consistently agree with certain propositions has fallen somewhat into disfavor.  This has reached the point that Habermas, perhaps one of the last post-modern defenders of some form of Kantian morality, argues that while it was presumptuous for Kant to make claims about what rationality looks like, we should still work towards some sort of ideal speech community which removes all biases and personal ambitions from the process of communication; this would de facto be the closest thing we can get to our ideal of pure reason, at which point we let them tell us what all rational people ought to believe.

And so you will not often see the phrase ‘all rational people agree’ in print much, these days, though back-in-the-day it was a commonplace.  Still, old habits die hard, and in its place we often find the phrase ‘most people agree’ in its place, with the implication that the “most people” we are talking about are the “rational people.”

I was recently trying to find a good article on Dependency Injection for a colleague and came across this one on MSDN, which unfortunately begins:

“Few would disagree that striving for a loosely coupled design is a bad thing.”

I assume that the author originally intended to say “Most would agree that striving for a loosely coupled design is a good thing.”   He then attempted to negate the statement for emphasis, but managed to over-negate, and failed to see that “few would disagree” is the apposite of “many would agree”, rather than its opposite.

In fact someone mentioned this to the author on his personal blog, but the author averred that this was just a Canadianism and not actually a mistake.

Be that as it may, it recalls a problem with logical quantifiers and natural language.  In the classic square of opposition (which sounds like a perverse political system but is simply a diagram that explains the complex relationship between universal propositions and existential ones) we are reminded that while universal affirmative propositions are contrary to universal negations, they are not contradictory.

If an A proposition, for instance ‘All rational people agree that X’, is true, then the contrary E proposition, ‘No rational people agree that X’ must necessarily be false, and vice-versa.  However, these are not contradictory propositions since both can actually be false.

The contradiction of A is the existential proposition (O), ‘Some rational people don’t agree that X’, just as the contradiction of E is I, ‘Some rational people agree that X.’  If A is false, then O is necessarily true; if O is false, then A is true; and either A or O must be true.

What cannot be easily resolved into logical formalism are the grammatical quantifiers ‘many’ and ‘few’.   Are ‘many’ and ‘few’ contradictory or merely contrary (or, God forbid, even subcontrary)?

What we can all agree on is the fact that english idioms are sometimes difficult to work with, and that this is particularly true when we attempt to formulate complex relationships between quantifiers.  Take, for instance, Abraham Lincoln’s famous epigram (which he possibly never uttered):

You can fool all of the people some of the time, and you can fool some of the people all of the time, but you can’t fool all of the people all the time.

I actually have trouble understanding the logic of this argument, and take exception with the first and second premises for the same reason that I take exception with statements about what all rational people agree on.  However I find myself so in agreement with the conclusion, as most people do, that I tend to overlook the manner in which we arrive at it.

Or take this one, from Tolkien’s novel:

I don’t know half of you half as well as I should like; and I like less than half of you half as well as you deserve.

It simply cannot be formalized into first-order logic.  Yet, remarkably, we manage to understand it — or at least most of us do.

In the movie Shrek the Third, there is this exchange, which plays on the difficulties of universal negation (O propositions brought to you by IMDB):

Prince Charming: You! You can’t lie! So tell me puppet… where… is… Shrek?
Pinocchio: Uh. Hmm, well, uh, I don’t know where he’s not
Prince Charming: You’re telling me you don’t know where Shrek is?
Pinocchio: It wouldn’t be inaccurate to assume that I couldn’t exactly not say that it is or isn’t almost partially incorrect.
Prince Charming: So you do know where he is!
Pinocchio: On the contrary. I’m possibly more or less not definitely rejecting the idea that in no way with any amount of uncertainty that I undeniably
Prince Charming: Stop it!
Pinocchio: …do or do not know where he shouldn’t probably be, if that indeed wasn’t where he isn’t. Even if he wasn’t at where I knew he was
[Pigs and Gingerbread Man begin singing]
Pinocchio: That’d mean I’d really have to know where he wasn’t.

In California, for safety reasons, the following law is apparently on the books:

The law says that nothing “shall be so designed and installed that it cannot, even in cases of failure, impede or prevent emergency use of such exit.”

H. L. Mencken provides several canonical examples of double negation in his book The American Language in order to demonstrate that it was once more common and better accepted, especially when English was closer to it’s inflected roots.  Thus Chaucer writes in The Knight’s Tale:

He nevere yet no vileynye ne sayde
In al his lyf unto no maner wight.

Shakespeare was no sloucher, neither, and Mencken cites several examples:

In “Richard III” one finds “I never was nor never will be”; in “Measure for Measure,” “harp not on that nor do not banish treason,” and in “Romeo and Juliet,” “thou expectedst not, nor I looked not for.”

At the same time, Shakespeare was also a genius at presenting universal negation in a manner fit to please Hegel when the Prince of Denmark soliloquizes:

To be, or not to be

while in King Lear,  in turn, the Bard’s use of universal affirmation is so fitting that any reasonable person would acknowledge it:

All the world’s a stage,
And all the men and women merely players:
They have their exits and their entrances;

RESTful WCF at Atlanta Code Camp

gullivers_travels

This past Saturday was the Atlanta Code Camp.  I want to be make a point of thanking Cliff Jacobson, Dan Attis, Doug Ware, Glen Gordon, Jeff Ammons and all the other organizers who made this a brilliant event.

My company, Magenic Technologies, presented at seven of the sessions this year. 

Sergey Barskiy, who was a developer on the CSLA-Lite team, presented on Building Silverlight Business Applications using CSLA.NET for Silverlight.

Whitney Weaver, another of our principal consultants and a master of all things data, spoke on What’s my data doing while I sleep? Tracking data changes in SQL Server 2008.

Colin Whitlatch presented an Introduction to ASP.NET MVC, and is planning to extend his presentation over the next few weeks on his blog, where he will be digging deep into ASP.NET MVC and helping others to do the same.

Jason Rainwater needs a blog, because he is currently one of the best WPF experts in Atlanta and there aren’t enough venues at this point for him to show off everything he knows.  He did two presentations this year: WPF Custom Controls and WPF DataBinding.

I presented on REST-ful WCF (the hyphen is a personal grammatical quirk rather than any attempt to make a philosophical point) and Mocking with Rhino Mocks and TypeMock: A Head-to-head Comparison.  I also got to make a short app-dev appearance in Tejas Patel’s Use of data mining controls with ASP.NET presentation.

As promised to the attendees, I’m making the code samples and slide-decks available.  Please excuse the lack of organization in the code — it’s pretty much just what I was writing while I was on-stage, but should be helpful if anyone is looking for samples.  All the code uses Visual Studio 2008.  The mocking samples will require that you have the appropriate dll’s for Rhino Mocks, which is free,  and TypeMock Isolator, which has a 30-day trial.

I am indebted to Pedram Rezaei for getting me started on the WCF-to-Flikr sample.

The Rest-ful WCF slide-deck and code can be downloaded here.

The Mocking powerpoint and samples are available here.

On Culture

My wife and I performed a small experiment this weekend when we took our three children to the symphony.  According to Steven D. Levitt and Stephen J. Dubner’s book, Freakonomics, children who are taken to concerts and art museums are not statistically advantaged by this activity.  However, in an interesting twist on the theological debate between justification by faith and justification by works, the authors claim that children who are parented by the sort of people who take their progeny to cultural events and fill their homes with books are indeed statistically advantaged.  Taking this to mean that good intentions are at least of equal value to good works (and what more can you ask of the parents of three children), we exercised our good intentions at the ASO’s performance with Jennifer Koh.

Sasha, the oldest (10), found the whole performance to be a waste of time.  Paul (8) and Sophia (6) were quite taken with Wagner’s Liebestod from Tristan and Isolde.  They found Jennifer Higdon’s The Singing Rooms to be considerably more challenging, however, as did their father. 

Ms. Koh’s performance was magnificent, of course, but the center of attraction for us was the Stradivarius on which she played.  I’ve never heard one live before.  Paul kept asking why it was so special and all I could think to say was that the ex-General Dupont is almost three hundred years old.  This duly impressed my son.  What speaks more on culture’s behalf, after all, than it’s gray-haired hoariness.

Perhaps it is an indication of my low-tastes, but as I watched this performance I kept thinking about how much I enjoyed the last performance I had seen at Atlanta Symphony Hall, Cirque de la Symphonie.  The music at that concert tended towards the romantic, from Saint-Saëns to Ravel.  While the orchestra performed on their instruments, the acrobats plied their art on their bodies by defying gravity in the air as well as defying basic physiology through acts of contortion.  Two acts stood out especially. 

Jaroslaw Marciniak and Dariusz Wronski entered the stage bald, in loin-cloths, and painted gold from head to toe.  They proceeded to lift, pin and balance off of each other in what I took to be an extended demonstration of Euclid’s 47th proposition, with each brief suspension being a prelude to the final revelation. 

Even more impressive was Elena Tsarkova’s contortion and balancing act.  All of it was remarkable, but at one point she stood on her head with her legs extended upward.  She then spread her legs out to be almost perfectly perpendicular to the rest of her body.  At this point something uncanny happened, but so quickly that I had to ask my wife if she had just seen something.  We couldn’t quite put words to what we had witnessed, and the best I could come up with was “ululation”.  There was an ululation in her legs which looked like the small wave some people can make with their shoulders.  It was breathtaking.

Following the Higdon performance came the intermission.  We took advantage of this natural break to sneak out and hunt for a decent milkshake in Atlanta.  The kids had earned it.  They behaved extremely well at the symphony.