2005-04-21

Gems of the .NET Framework

Sometimes I think the .NET Framework is overengineered. There is just a ton of stuff there, and I have the sneaking suspicion that ninety percent of it is never going to be used by more than maybe ten developers. Be honest. When was the last time you found yourself using objects from the System.EnterpriseServices.Internal namespace?

But then again, there are some really nice side effects of such a dense pack of APIs, some of them very easy to overlook. I've written before how HttpWebRequest is a very easy way to converse with HTTP servers without having to go through the typical "do it yourself" hoops inherent in the C language: make a socket, connect, create some HTTP headers, write the headers, read the response. HttpWebRequest, along with its wonder twin HttpWebResponse, turn getting HTTP data into about six lines of C#. HttpWebRequest is a Good Thing.

When faced with some minor problem, I start looking through the .NET Framework for a good method to solve it. Sometimes I find one, sometimes I don't. In some cases, the solution is a lot easier than I make it out to be, and that's no one's fault but the people who maintain the .NET documentation on msdn.microsoft.com.

In this case, I have a string that I want to digest into the parts of a URL. Say, turning "http://www.cnn.com/" into a protocol, a host, and a local file component. Respectively, "HTTP", "www.cnn.com", and "/". How can this be done? It's gotta be some complicated thing buried in System.Net, right? Lord! You'll probably have to get into the basics of parsing XML!

Nope. Not at all. The .NET Framework handles this problem for you, in the Uri class which is — get this — in the base System namespace. Smack my forehead and call me retarded.

Here's a really straight-forward method of instantiating a Uri:

string url = "http://www.host.dom/some/file/somewhere.txt";
Uri uri = new Uri(url);
Wasn't that easy? You may now create a new WebRequest using "WebRequest.Create(uri)" and go about your business.

No comments: