Mike Taulty's Blog
Bits and Bytes from Microsoft UK
Simple LINQ and an HTTP Handler

Blogs

Mike Taulty's Blog

Elsewhere

All that messing with WCF and POX and so on left me feeling a bit battered and bruised so I thought I'd have a bash at an Http Handler using LINQ as a bit of a rest.

Really quite enjoyed doing this;

public class DataHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        
        context.Response.ContentType = "text/xml";

        NorthwindDataContext ctx = new NorthwindDataContext("server=.;database=northwind");

        var query = from c in ctx.Customers
                    where c.Country == "UK"
                    select c;

        var xml = new XElement("customers",
                      from c in query.ToList()
                      select new XElement("customer",
                        from p in c.GetType().GetProperties()
                        select new XElement(p.Name, p.GetValue(c, null))));

        xml.Save(context.Response.Output);
        
        context.Response.Flush();                                                                        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

It's a bit naughty because it's using reflection to turn the Customer type (generated by the LINQ to SQL diagramming tool) into element-centric-XML but it makes it nice and short.

The only other thing I'd say is that if you take out the;

query.ToList();

just to leave query then you get a peculiar error;

Queries with local collections are not supported

Essentially, what I think is happening is that at the point where we enumerate the SQL query we're trying to combine it with the other bits around it. Haven't probed deeply enough to work exactly what's going on but I think that's the theme of it.


Posted Fri, Jun 8 2007 10:40 AM by mtaulty

Comments

Christopher Steen wrote Link Listing - June 10, 2007
on Sun, Jun 10 2007 8:13 PM
Give it a REST! [Via: Anil John ] GWT a Year Later: Was it the correct level of abstraction? [Via: Dietrich...