enrich and simplify http coding

2007-07-09 @ 21:05#

one of my primary goals this year is to improve my http coding. note i said http, not html, not asp.net, but http. my point is that i've been spending a lot of time learning how http works (or should work) and how i can use my current code skills (C#, markup, etc.) to improve the way i write web-based stuff (pages, apps, feeds, etc.).

i've approached this in two ways: 1) improve the richness of my support for http (like caching, validated documents, etc.); and 2) reduce the number of lines of code i produce in general. since The Best Code is No Code At All, i've been working to do more with less and even just plain do less.

to that end, i've been distilling my code loops used to support POST and PUT and have got it down to a fairly tight set of lines. i use regex to parse out important bits of strings; XSD to validate my inputs; XSL to convert the inputs into valid T-SQL; and to convert db output into valid XML or XHTML to render back to the caller. below is a common example of my code for a POST of an XML document that includes solid validation as well as rendering the db return.

i'm not saying i invented any of this, but i am saying i'm pleased that i'm getting it narrowed down to a reasonable set of code to work with.

// validate the uri string id = Regex.Match(this.Context.Request.RawUrl, rex_url).Groups[1].Value; if (id != string.Empty) throw new HttpException(400, "bad uri"); // get the xmldoc from the entity XmlDocument xmlin = new XmlDocument(); xmlin.Load(this.Context.Request.InputStream); // validate the doc SchemaValidator sv = new SchemaValidator(); string sch_error = sv.Execute(xmlin, this.Context.Server.MapPath(add_xsd)); if (sch_error != string.Empty) throw new HttpException(400, sch_error); // validate html element string fragment = xmlin.SelectSingleNode("//notes/text()").Value; string html_errors = util.ValidateFragment(ref fragment); if (html_errors != string.Empty) throw new HttpException(400, html_errors); else xmlin.SelectSingleNode("//notes").InnerText = fragment; // transform xmldoc into sql command XslTransformer xslt = new XslTransformer(); string cmdtext = xslt.ExecuteText(xmlin, this.Context.Server.MapPath(add_xsl)); // execute sql and return results SqlXmlCommand cmd = new SqlXmlCommand(util.GetConfigItem("mamund_personal_db")); cmd.CommandText = cmdtext; using (XmlReader rdr = cmd.ExecuteXmlReader()) { xmlout.Load(rdr); } this.Status.Code = HttpStatusCode.Created;

code