Archive for March, 2008

Calling a Static Method from an Object Instance in C#

The short answer: You can’t call a static method from an object instance in C#. It’s allowed in VB.NET, but in C# you must use reflection or delegates instead.

Of the two workarounds, delegates is the preferred option. Delegates perform faster, and you get compile-time errors rather than run-time errors.

But it’s Friday, and I’m feeling a bit lazy. Here’s the syntax for using reflection:


typeof(<type name>).GetMethod("<method name>").Invoke(null, new object[]{<list of parameters if any>});

If you want the long answer to why C# doesn’t allow static methods to be called from instances, you’ll need to read the posts and comments for parts one, two and three on Eric Lippert’s blog, Fabulous Adventures in Coding.

But maybe not on a Friday. :-)

REST for the Weary

Those of you with a technical background may have noticed a close correspondence between the Web 2.0 principles I described in our design series and Representational State Transfer, or REST. This is no coincidence. Gordon’s been a backer of RESTful approaches to web application design for some time now; I’m a more recent convert. More importantly, the REST architectural pattern fit what we were trying to do with our infovark project.

REST is a design pattern used to create Internet applications. It’s been growing in popularity, but hasn’t been fully adopted by any of the major vendors yet. (Microsoft’s efforts to lump REST into the Windows Communication Framework notwithstanding.) This is probably due to the fact that the World Wide Web Consortium, or W3C, put its weight behind an earlier, competing design philosophy called SOAP. (SOAP used to stand for Simple Object Access Protocol, but the “simple” part was dropped long ago.)

SOAP was designed to help loosely connected computer systems communicate with each other. Many previous frameworks and standards had attempted to do the same thing, but with so many different hardware and software vendors building systems, most were doomed to fail. SOAP is likely to stick around for a while due to its close association with with Web Services and Service Oriented Architectures. As a practical matter, however, the class of problems that SOAP solves are actually rather limited. Strike that; the class of problems that only SOAP can solve are rather limited. For most applications, there’s an easier web services alternative: REST.

An Illustration

Pardon me while I geek out for a moment.

When I was a kid, me and my friend Rajeev would dial each other up — yes, literally dial each other — with our 300 baud modems. I know, I know, you young ‘uns are thinking, “What’s baud? What’s a modem?” Suffice it to say that it was a slow way to get two computers to talk with each other. And when I say slow, I mean S… L… O… W. You could literally watch the letters appear one by one in your monochrome terminal window. If you can imagine sending a message via Twitter one letter at a time, you’ve got the idea.

It was so painfully slow that there really wasn’t much point in sending messages back and forth. Other than the nerd-cool factor of making two computers located in different parts of town communicate, there wasn’t much to do. So Rajeev and I hit upon an idea. We’d play a game online. Being nerds, we naturally picked Chess.

Chess was actually a great application for modem-to-modem communication. There was a well-known initial starting state in the traditional arrangement of the pieces. There was an established protocol: white moves, then black moves. And there was even a short messaging format: chess notation.

So we started playing Chess online. Each of us kept a small chess board by the computer. We slowly took turns typing out our moves to each other and updating our game boards: “P-K4″, “P-K4″, “Kt-KB3″, “Kt-QB3″ and so on. Not exactly riveting entertainment, but hey, we were doing something new and different.

Every now and then, we’d run into a problem. I’d get a message from Rajeev with a nonsensical move, or he’d get a message from me that moved a nonexistent piece. Then one or the other of us would see these letters slowly print across the screen: P… I… C… K… U… P… T… H… E… P… H… O… N… E.

We’d then try to figure out what had happened, based on the log of all the messages that went back and forth and the current position of the pieces on each of our game boards. Sometimes we were able to figure out the mistake. Sometimes we agreed to go back to the last time we picked up the phone to reconcile our respective chess boards. Sometimes we started over.

As you can imagine, this sort of troubleshooting got old fast. And it happened all the time. Eventually we gave up on trying to play by computer, and we just bugged our Moms to drive us over so we could play using the same board.

REST in a Nutshell

The point of the story above is not to establish my geek cred, but to offer an analogy.

In the early days of network computing, bandwidth was low, latency was high, and it was vitally important to make your messages as concise as possible. A wide variety of message formats and protocols evolved to respect the limits of early computers and networking technologies, all designed to get as much useful data packed into as little space as possible. It’s exactly like the chess notation Rajeev and I used. We could have sent snapshots of the chess board after each turn, but it would have taken hours to transmit a single move that way. All we really needed to know was which piece needed to move where. Using the shorthand, a single move — one procedure — could be described in just a few letters.

Though network computing technology has come a long way since then, the most common way for computers to talk with each other is still via Remote Procedure Calls, or RPC. Rather than describe the entire gameboard, computers just tell each other how to move the pieces.

If you’re wondering how computers handle mistakes or lost transmissions, well, a staggering amount of effort in computer science has focused on error detection and correction algorithms and secure transaction processing. Believe me, the last thing your credit card company and your bank want to do is pick up the phone to work out whose set of accounts is more accurate.

This is why data replication is such a huge problem. If you only transmit the moves to each other, you have to start from a known initial state. The chessboard at Rajeev’s house and my house had to match at the start of the game. It’s also why synchronization is a big deal. If the moves are sent out of order, all sorts of problems occur.

If, on the other hand, you could send pictures of the game board back and forth, a seasoned player could probably reassemble the images in something close to the right order. Better yet, if both players could look at the same board at the same time, then you’d never get out of synch.

This is the essence of the REST architectural pattern. It’s a little less respectful of network resources, but by transmitting the current state of the game at any point in time, you can simplify the amount of work you need to do to get two players to agree. Most of the transaction issues and handshaking protocols become unnecessary. The World Wide Web — hypertext over HTTP — works in a RESTful way, and it’s the most successful computer application ever built.

Enterprise 2.0 is about applying the lessons from the Web to the enterprise, so it makes sense that we should start with the core design principles.

WCF, WebHttp Binding, and Authentication

If you’re trying to build REST-enabled services with WCF, you’ll want to use the webHTTP Binding.

This binding defaults to anonymous handling, so if you’re planning on doing any authorization you need to change the binding configuration.

This took me ages to figure out, largely because the webHttp binding is new and not well documented.

To change the binding to support NTLM or Windows authentication, add the following node to the system.servicemodel in your app.config:

  1. <bindings>
  2. <webHttpBinding>
  3. <binding name="varkBinding">
  4. <security mode="TransportCredentialOnly">
  5. <transport clientCredentialType="Ntlm"  />
  6. </security>
  7. </binding>
  8. </webHttpBinding>
  9. </bindings>

Note that you can supply one of five values to the mode attribute: None, Basic, Digest Windows, NTLM, and Certificate.

Once you’ve picked the one you want, in your service definition, specify your new binding from the bindingConfiguration attribute:

  1. <service behaviorConfiguration="SyndicationBehavior"
  2. name="Yourapp.Yourservice">
  3. <endpoint address="http://localhost:8000/url"
  4. behaviorConfiguration="SomeBehavior"
  5. binding="webHttpBinding" bindingConfiguration="varkBinding"
  6. contract="YourContract.IYourService" />
  7. </service>

And all calls to your REST service should be made with a valid windows network identity.

In your serviceCode, you can retrieve it from the System.ServiceModel namespace:

  1. ServiceSecurityContext.Current.WindowsIdentity

Oh, and if you’re not comfortable with editing the XML files, or you’d like to explore the dizzying array of other available options in WCF, I also discovered the Microsoft Service Configuration Editor (possibly someone had discovered it before me. ) It lives at C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcConfigEditor.exe. It gives you a simple(ish) visual way to edit WCF Configuration files.

UPDATE: JustinJSmith over at The Cybertopian Chronicle points out that it’s even easier to invoke the config editor – you just right click on your app.config, and select “Edit WCF Configuration” (duh…)

Using XmlConvert for DateTime Strings

James Newton-King, developer of the JSON.NET project, notes that it gets harder to be a .NET developer with every release. He reposted a chart from Brad Abrams showing the growth of the number of types in the Microsoft .NET framework.

More Types in Microsoft.NET Every Year

We’ve run into this problem all the time developing infovark. Often, it’s not the sheer size of the framework that proves challenging, but finding just the right method to do just the right thing.

A case in point was a recent problem I had in converting a DateTime object into a string properly formatted for XML. Normally you’d do something like this:

string theDateString = myDateTime.ToString();

This gives you a string in the .NET format, but that’s not the correct format for XML Schema (XSD). No problem, you think, I’ll just pass a format argument to the ToString method. So you look up the available string formatting options on MSDN. There’s lots of choices here, from the “based on ISO 8601″ format to the “RFC1123Pattern” to the “UniversalSortableDateTimePattern”. But it turns out that none of these formats work for XML if you want it to validate against your XML Schema. What gives? Do you have to provide a custom formatting string to get the date pattern you want?

It turns out that you’re looking in the wrong place entirely. These aren’t the string formats you’re looking for. Move along.

What you want is in the System.Xml namespace. You want the XmlConvert class. The XmlConvert class lets you convert from native .NET types to valid XML and back. The code looks like this:

string theDateString = XmlConvert.ToString(myDateTime);

It’s not only the size of the .NET framework that’s daunting. It’s the fact that functionality can be duplicated — or worse — made just slightly different across all of those classes. It puts developers in an awkward situation. Do they spend time researching to figure out exactly which method of which class in which namespace ought to be used in a given situation? Or do they roll their own (possibly buggy) implementation? It’s a tough call.

Personally, I’d like to see more guidance from Microsoft — perhaps through their code analysis tools — as to the preferred way of doing common tasks.

Welcome Underground

Thanks for stopping by!

The Infovark Underground is a new blog where Dean and I can unleash our inner nerd, and share some of the technology and experiences we run into as we build Infovark (Yes, we call our product Infovark. It’s got the same name as our company, because we’re all about making things easy to remember and share..)

Unlike our Infovark blog, which details what we’re doing, the underground will get into much more technical detail about how we’re doing it — discussing programming, development and tools.

If that sounds like the kind of stuff you might be interested in, feel free to add our feed to your readers!