Sunday, October 28, 2007

Give LINQ a REST

We recently upgraded to FogBugz 6, which sports a new REST styled API.  I decided to play with it by writing a simple .NET client using VS 2008, and take LINQ-to-XML for a spin.  The center piece of LINQ-to-XML is the new XDocument class, which is yet another way to work with XML data in .NET:

 

return XDocument.Load(urlForXmlData);

 

What makes this differ from XmlDocument, XmlReader, etc., is that a LINQ provider has been written around it:

 

var cases = from c in doc.Elements("cases").Elements("cases")

            where c.Element("sTitle").Value.StartsWith(searchText)

            select c;

 

Beyond that, it’s plain easier to use, in my opinion:

 

if (responseElement.Element("error").Attribute("code").Value == "2")

 

With that, it’s fairly easy to come up with a method to send commands and read XML:

 

private XDocument SendCommand(string commandFormatString, params object[] parameterValues)

{           

    var commandUri = this.FogBugzApiUrl.ToString();

    commandUri += String.Format(commandFormatString, parameterValues);

    return XDocument.Load(commandUri);

}

 

This method can then be used to work against the REST API:

 

public bool LogOn(string email, string password)

{

    var responseElement = SendCommand("cmd=logon&email={0}&password={1}", email, password).Element("response");

    if (responseElement.Element("error") == null)

    {

        this._token = responseElement.Element("token").Value;

        return true;

    }

    else

    {

        return false;              

    }

}

 

Where it gets interesting, though, is using LINQ and inline initialization to new up strongly-typed wrappers around the responses:

 

public IEnumerable<Case> GetCases(string search)

{

    var response = SendCommand("cmd=search&q={0}&cols=ixBug,sTitle", search);

    var cases = from c in response.Elements("cases").Elements("case")

                select new Case() { Id = int.Parse(c.Element("ixBug").Value), Title = c.Element("sTitle").Value };

    return cases;

}

 

Hopefully, you can see how powerful LINQ and these other new features in .NET 3.5 are.  In a few lines of code, we can query a REST API and return strongly-typed wrappers around the content.

No comments: