ViNull: This site is best viewed with VT100
tagged:
I hate seeing code mixed with markup.
Seeing a template page with <% if(show) { %> makes me want to claw my eyes out. Seeing String htmlTitle = "<h1>" + title + "</h1>" causes me to vomit up a little something in my throat.
Mixing code with markup is not a magic chocolate and peanut butter combination - it's a volatile cocktail of vinegar and baking soda waiting to explode your application to tiny Server 500 Error giblets.
The time comes however when we find ourselves needing to generate some well formed HTML in code, and I found myself in just such a position last night adding the agenda to the CodeStock website. (Less than one week away now!)
Background: On the CodeStock site, the speakers and sessions list lives in an XML file. The agenda page has a grid of session times and my task was to fill in each session "cell" with the session planned for that room and time. I wanted to link to the full session and also list the speaker's name in the cell. In the XML I have created Key elements that are used as HTML anchors in a link to a session. It's all very low tech, simplistic goodness. An example of the XML for a speaker:
<Speaker>
<Key>Brownell</Key>
<Name>Steve Brownell</Name>
<Website>http://enthusiasticprogramming.blogspot.com</Website>
<Photo>~/Speakers/SteveBrownell.png</Photo>
<Bio>
Steve is the manager for research and development at AllMeds in Oak Ridge, TN. Steve
has been programming one thing or another for over twenty years. AllMeds makes and
sells a commercial software product which is an electronic medical record system. We've
been .NET based since 2000. AllMeds is a VB.NET shop at heart, but the AllMeds system spans
many areas of Windows development.
</Bio>
<Session>
<Key>Hobbled</Key>
<Title>
The Hobbled: There And Back Again, or Code Automation: how I made it from the
presentation layer to the database and back.
</Title>
<Abstract>
Stop writing code, and start writing code that writes code. There's never been more
choices to help you automate the creation of the data object layers immediately above
the database. Writing class factories and data access classes is boring, time consuming
and wastes valuable time with expensive developer resources. This course will examine
two current approaches: using a template engine and programming with the CODEDOM. We'll
also briefly discuss other ORM techniques like LINQ to SQL Classes.
</Abstract>
<Level>200</Level>
<Technology>VB.NET, C#, LINQ, SQL</Technology>
</Session>
</Speaker>
(Steve was our CodeStock Speaker Idol winner, and I enjoyed seeing System.Codedom in action; something I'll be playing with and posting on in the future thanks to Steve!)
LINQ to XML, and the new "X" classes that come with it make working with XML as easy as it should have always been. Armed with LINQ, I decided that putting <%= SessionInfo("Hobbled") %> was something I could live with (had this been a larger site that needed to live longer than August 9th, I would have opted for a user control <CodeStock:SessionInfo Key="Hobbled"/>). My first LINQ expression looked something like the following:
var info = (from s in speakers.Descendants("Session")
where s.Element("Key").Value.Equals(SessionKey)
select new {
key = s.Element("Key").Value,
title = s.Element("Title").Value.Trim(),
speaker = s.Parent.Element("Name").Value
}).First();
This yields a very useful info object with just the information I need. *If* I was in a hurry, and didn't mind a little vomit, I would follow on with the following:
String hmtl = String.Format("<a href='{0:s}' title='{1:s}'>{2:s}</a><br />{3:s}",
new object[] { ExpandURL("~/Pages/Agenda.aspx", info.key),
info.title,
info.title.Length > 30 ? info.title.Substring(0, 27) + "..." : info.title,
info.speaker });
Why do I despise this so much? It's not easy to read, and it can become cumbersome to change. ASP.NET has a collection of server controls just for generating HTML, intended for use in user controls but they are not limited to user controls alone. To generate the html above would look something like this:
HtmlAnchor aHref = new HtmlAnchor() {
HRef = ExpandURL("~/Pages/Agenda.aspx", info.key),
InnerText = info.title.Length > 30 ? info.title.Substring(0, 27) + "..." : info.title,
Title = Title
};
HtmlGenericControl div = new HtmlGenericControl("div") {
InnerText = info.speaker
};
StringBuilder html = new StringBuilder();
using (StringWriter sw = new StringWriter(html)) {
using (HtmlTextWriter hw = new HtmlTextWriter(sw)) {
aHref.RenderControl(hw);
div.RenderControl(hw);
hw.Close();
}
sw.Close();
}
There are times when working with parts of the .Net framework I have wonder if some Java types didn't design the class. The mess here to render the HTML is one of those times. The lack of a RenderControl that returns a String is the problem - thankfully we now have extension methods to fix the framework, but that's another post. No matter how much I hate markup in the code, I cannot endorse this version over the vomit inducing first solution.
It occurs to me that HTML is (or was once) fundamentally XML, and I can return XML from my LINQ expression. In fact, this is what LINQ is about - not just getting the data you want, but getting it in the format you need. Here is the new LINQ query:
XElement info = (from s in speakers.Descendants("Session")
where s.Element("Key").Value.Equals(SessionKey)
let key = s.Element("Key").Value
let title = s.Element("Title").Value.Trim()
let shortTitle = title.Length > 30 ?
title.Substring(0, 27) + "..." : title
let session = new XElement("a",
new XAttribute("href",
ExpandURL("~/Pages/Agenda.aspx", key)),
new XAttribute("title", title),
shortTitle)
let speaker = new XElement("div", s.Parent.Element("Name").Value)
select new XElement("span", session, speaker)).First();
This may not seem to some as better. I myself have trouble looking at most LINQ expressions, but as I'm learning to Thinq Linq I'm seeing that writing the LINQ expression is where the power lies, not in the syntax. The mental dialog goes something like this:
"Okay, from my list of speakers I want a session where the session's key matches SessionKey. Now, let me grab some fields I need, first the key, then the title which I need to trim off excess whitespace, then let's make a short version of that title since Steve's title is so long - love that title though. I'll need an link tag for the session; set the href and title attributes, and then add the speaker's name in a div tag so I get a cheap line break. I'm really in XML not HTML, so I'll need a root node and a span tag will work without affecting layout, and I'll add the link and div tags as children."
Writing LINQ like this I feel much closer to the problem I'm trying to solve, and not bogged down by syntax. There is still some moments I'm thrust back to code, such as the use of First() to select only one result. I'd like to have a "select first" option in LINQ expressions instead of just the extension methods.
Is this something I'll be using now every time I have this problem? Not sure yet, but it's another "tool in the box" I'll keep around and use when it feels right.
tagged:

Update: The GiantBomb.com crew have made a video explaining the site!
A decade ago I would have no problem talking about the latest in gaming. Then I got into MMO's, and that led to me leaving gaming all together. There is something about realizing "gameplay" is a nice marketing term meant to cover up the fact you're just playing Diablo for $15 bucks a month to turn you off the industry completely.
Then came my Wii, and an XBox 360 followed. The Wii is great for games with groups and my younger daughters, but games like Legend of Zelda: Twilight Princess reminded me there was another class of games I used to play, before the MMO blight. Playing Mass Effect, Bioshock, and Gears of War on my 360 reignited my passion for gaming.
I've always hated the mainstream game review sites like IGN and GameSpot - the reviews never feel honest and I have to spend a good deal of time reading user reviews to gauge the game. I have many things going on in my life; I don't have time to waste on bad games. I started following Ars Opposable Thumbs and soon learned of the new site Jeff Gerstmann was behind.
Jeff was the editorial director of GameSpot, and was fired for giving bad reviews to games that publishers were advertising on the site. WikiPedia has some of the details, and Jeff himself doesn't talk about it, but it's pretty obvious what went on. The fact many editors left GameSpot in protest after the firing speaks volumes. I found Jeff's podcast, and became instantly hooked.
The "bombcast" is easily one of my top three podcasts - first just Jeff and Ryan Davis then later adding Brad Shoemaker and Vinny Caravella to the cast. These guys all hail from GameSpot, and are not your polished art critics, but gamers who speak about games the same way you and I would. They are honest, clear, and pretty damn funny. These four have also worked on launching a new game review site: www.giantbomb.com
The website is part news, part wiki. The search feature is slick, and the pages go beyond just the games and into the characters, developers, and concepts. The amount of user contributed content is staggering, considering the site has been live for little more than a week. If you haven't checked it out already, and are into gaming at any level, take a look at Giant Bomb.
tagged:
A few days ago I posted a question to the community, looking for a definition of the ASP.NET MVC framework that didn't depend upon faults in ASP.NET WebForms - after all, faults can be fixed. I also do not like the implication that ASP.NET MVC is for those looking to use the MVC pattern, as I've been using that pattern for a decade and I use it in WebForms today. Credit goes to Lucas Goodwin for helping me with the following definition:
ASP.NET MVC is the evolution of Classic ASP.
I've helped a number of developers move from Classic ASP to ASP.NET, and each one has said to me, "wow, this is nothing like ASP" once they groked it. This is true, and mostly because WebForms introduced an event based paradigm to ASP. Classic ASP had problems, but was the lack of events one of them?
Classic ASP's number one problem was lack of separation of concerns. This is the same reason I don't like PHP, my code is far to friendly with my HTML (gotta keep em' separated). True you can discipline yourself to provide a separation, but it's not something the framework designers gave much thought to.
WebForms fixed the separation issue, but at the same time brought in the event model. I liked this "magic controller" approach, because it saves me the time I used to spend wiring up controllers that just ended up back at the same template I started with. (For the record, I was mostly working with python before moving to WebForms, first with a framework called Albatross and later SnakeSkin) An event model is not required to have separation of concerns, and this forced an event model on to many Classic ASP developers. So I will add a bit to the definition:
ASP.NET MVC is the evolution of Classic ASP, adding an easier separation of concerns while not using an event based model like WebForms.
So do you agree or disagree? I like this definition because it's not claiming either approach is better, and I can look to the pros and cons of an event based model to guide me in selecting MVC or WebForms for a project. It also is less likely to cause rioting in the streets at your next user group meeting when the topic comes up!
tagged:
There is a bit of turbulence in the ASP.NET airspace over MVC (yes, I'm making this post while on the fight back from the ASPInsiders Summit). Even among the ASPInsiders, who are supposed to be at the cutting edge of ASP.NET, there is little agreement over what is MVC and what it's for.
MVC, or Model View Controller, is an age old pattern found in many places. ASP.NET providers follow the pattern, as does Service Oriented Architecture. The general idea to have some code called a Model that works with your data storage, other code called a View that displays the data, and last plumbing code that ties these two together, called the Controller. I call it a pattern because implementations differ in the details - the View may render a button, but when the user clicks that button should the click action be handled by the View or Controller? The Model and View should know nothing of each other, but is the Controller allowed to be tightly coupled to them both? (If your first thought above was the Controller should handle the button action, think now what this means about being loosely coupled between the View and Controller).
ASP.NET MVC is a framework in development that is intended to closely match the MVC pattern. The minefield lies in answering the pragmatic question of what does ASP.NET MVC offer over WebForms, and when would you use MVC? In taking with those excited by MVC the reasons range from supporting TDD, clean URLs and avoiding postbacks by sending actions to a controller, better control over HTML output (including getting rid of ViewState), and being closer to the http protocol.
TDD, or Test Driven Development, will always come up in any ASP.NET MVC conversation, but TDD itself isn't an explicit part of MVC. The MVC pattern is very amendable to TDD however, and thus the association. I generally support testable code even if there are no tests around the code. Testable code is much easier to maintain, enhance, refractor, and replace. I don't find the process of test-first development helpful, but I do write tests in the same session as the code when I know I'm writing some critical piece of functionality that needs to survive multiple versions of the software. As Hanselman noted, I'm like the "person who goes to church on Easter and Christmas" and I'm sometimes looked down upon by the congregation who attend weekly. I'm okay with this, but I have some reservations with MVC as a framework for TDD.
To say you cannot test WebForms is a strawman argument; there is no trouble in separating the Model and testing it thoroughly. Depending on how you go about it, you can also separate the Controllers and test them - I generally have very simple Controllers that pass user input into the Model as is, so testing the Controller is not that important to me. Testing the View in WebForms is very difficult - and this isn't specific to WebForms. My objection to claiming MVC has testable Views is the implied definition of testing. Verifying the output HTML of a View is not helpful at all - it's just string comparison. I want to write tests like Asset.JavascriptRunsOnSafariMac() and Assert.IE8RendersSameAsFireFox3(). If MVC could do that, then I would be switching to it today!
WebForms provides a very robust SiteMapProvider interface that makes it easy to clean up urls of dynamic content. Global.asax can be using to control routing of requests (in fact this is how MVC does it as well). The biggest problem I've had here isn't WebForms fault, but IIS6's inability to allow ASP.NET to handle requests without an ASP.NET extension in them: this is solved in IIS7.
You can get fine grain control of HTML in WebForms, ever with just the stock controls. There is also an entire collection of HTML server controls to match HTML tags to make it easy to generate HTML from code (I hate seeing tags hardcoded in source file, feels dirty and hackish). About the one thing that is hard to do in WebForms I deal with somewhat often is controlling the client side ID's, which can become quite long and fugly looking. For CSS you can just assign a class name instead of using ID references (and there aren't many places I'm using CSS IDs except for layout divs that aren't coming from ASP.NET controls anyway). Javascript is trickier; you need to inject a reference of Control.ClientID on the server in the client script, and the need is much more common than with CSS. If you have an external JavaScript file this can get worse, but I believe that an external JS method should take the ID of the control they work with as a parameter making it easier to read the external file without the need to reference the aspx code. At the end of the day however, I'm not willing to throw the "baby out with the bath water" and will lean more on Microsoft to fix this issue in WebForms rather than jump to MVC.
The last reason for MVC I mentioned, being closer to the http protocol and its stateless nature, I simply don't grok. Any application with a basic level of user interaction will need to mask the http protocol's implementation details to provide a positive user experience. Web programmers of all frameworks and languages have realized there are only a few methods to solve this problem; cookies, url parameters, and hidden fields. Any state solution will involve one or all of these - even if state is stored on the server's side. WebForms supports all of these methods, and you can disable things like ViewState (hidden fields) if desired. (I am aware there is also ControlState that will be still emitted if ViewState is disabled, but I'm willing to say that if these few bytes are an impact you are working on an edge case).
I'm not here to bash ASP.NET MVC - to the contrary I'm here to help by outlining the faults in the current arguments for MVC. If MVC is defined by the features in or not in WebForms, then it's going to be hard for those deep into WebForms to see value in MVC. It becomes a song of "anything you can do, I can do better (no you can't, yes I can)" and will deadlock when neither side is listening to the other. ASP.NET MVC need to be defined without claiming faults in WebForms, because that only says use MVC because WebForms is broken - leading one to say, "why not just fix WebForms?"
I wish I could end here with a new explanation of ASP.MVC meeting the requirements I've just stated, but I'm afraid I can't. This is a fault with me, and not the MVC framework - I'm too close and deep into WebForms to see a need for MVC I can't fill already. It's my hope and request that instead of seeking to pick apart this post, the supporters of MVC come out to define MVC without attaching that definition to the perceived faults (for that's the minefield) of WebForms.
tagged:
Let me start by saying while reading The Annotated Turing: A Guided Tour through Alan Turing's Historic Paper on Computability and the Turing Machine I encountered two other reviews worth note. The first review by Jeff Atwood focused on Alan Turing's personal life as a gay man in the first half of the 1900's and is light on reviewing the actual text of Turing. The second review is by Deirdre Sinnott and does cover the text in depth, but one must carry a certain level skepticism (however undue) toward Deirdre given her relationship to Petzold. I must also alert the reader to my own bias, as I have written well of Petzold in the past and was sent a (signed) copy of Turing. I did however purchase the book before I knew a copy was being sent to me.
For the impatient, busy, or otherwise opposed to reading what has become a lengthy review, I will save you the investment of time by saying now I highly enjoyed this book and would strongly recommend it to any programmer, mathematician, or person with an interest for numbers. I will qualify this recommendation with the disclaimer that if you do not have the time to devote to reading the remainder of this review, you may not have the time needed to read and understand the book's content. I found myself only able to read 10-20 pages a night of this scant 359 page book due to the amount of mental engagement demanded by the subject matter; which only worked to increase my enjoyment. Before we get into the content of the book however, let us take a moment to understand the actors involved...
Alan Turing is our hero in this tale, a brilliant young man who leads a troubled life and finds refuge in a love for numbers. Our narrator, Charles Petzold, shares a great many things in common with Turing, including this love of numbers and the mind to process these numbers in complex ways. I have read many of Petzold's books on Microsoft Windows programming and one constant is that his examples often use calculus or trigonometry equations in a way that the example itself teaches as much on mathematics as the API the text covers. Mathematics and computers, I'm learning, are tied much closer together than most would assume. The last character is myself, the reader, who poses only a basic understanding of college level mathematics (enough to meet CS requirements) and who once wrote a two page mathematical paper that was, in the words of the professor, "an amazing level of insight and effort, but 100% flawed and incorrect". I mention this because while I was not able to understand every formula and proof covered in Turning, this did not detract from my understanding of its significance to the material.
The events in Turing surround Turing's paper "On Computable Numbers, with an Application to the Entscheidungsproblem." I will probably offend true mathematicians with the following explanation of the Entscheidungsproblem (and again later in this review), but simply put the Entscheidungsproblem asks for a set of steps one can use to determine if a given formula has a solution (but not what that solution might be). Consider A² + B² = C², which we know is true because we can plug in 3, 4, and 5 and see that it works. What about A³ + B³ = C³? Before we start trying some random numbers it would be nice to know if there even is a solution - and this is what the Entscheidungsproblem is all about. (My method would be to try some random numbers, I'm sure a mathematician would start with a much more reasonable and fruitful approach.)
Turing proved that no, there is not a universal method for determining if a given formula has a solution. Turing was not the first to prove this: 6 weeks before Turing's paper was published in 1936, Alonzo Church published a paper that also proved there was no method for the Entscheidungsproblem. Turing's solution was so novel and unique in it's approach however, that it has the rare honor of also being published, and Turning added a proof to his paper that both methods are equivalent.
Truth. To normal folk truth has a somewhat soft definition, but to mathematicians truth has strong and rigid meaning. You may know something to be true simply through common sense, but in the world of mathematics something must be proven in concrete formula before it can be accepted as true; until then it remains unproven and will not even be considered worthy of assumption of truth in all but the most extreme cases.
To tackle the truth of the Entscheidungsproblem, Turning invented (on paper) a machine that could read a sequence of commands that expressed a method to calculate number and print it as the result. This allowed Turing to work with numbers like π without needing to calculate the exact value (something no easier in 2008 than it was in 1936). Further, Turing devised a method to give every possible sequence of commands a unique number, called a Description Number, or DN. The DN for a machine that computed π might be DN 314,257. Last, Turing invented a machine that could be given a DN and generate the sequence of commands that DN represented, then pass this sequence off to another machine to calculate the result. Turing's machines worked in binary, i.e. 0's and 1's only, so Turning then proved it was not possible given a DN to determine if the calculation machine would ever print a 0 as a result of calculation, thus proving there was no universal method to determine if a given formula had a solution.
Just reciting the list of actors and events doesn't convey the story, we must also discuss the meaning and impact. Much of The Annotated Turing is true to the title; Petzold presents the unmodified original Turing paper and provides annotations to help understand the material, while also citing related material and events. In this capacity, Petzold is unsurpassed - the bibliography for Turing cites over 90 books and papers (including a humble citation of Petzold's own Code) and one is given the impression Petzold read many more books not cited. Petzold's greatest contributing to Turing's work comes at the end however, when he explores the impact Turing had on the fields of mathematics, computer science, and philosophy.
Any developer reading above recognized that Turing machines are computers running programs. What may not have been obvious is that Turing's proof also means that no program can be written that will determine the output of another program. That we cannot break this limitation, and our new platforms, languages, and computers will "at best [...] only do jobs faster."
The philosophic impact is far greater, for we humans qualify as Turing machines. Other philosophers and mathematicians have come very close to a proof that the universe is fundamentally digital, can be expressed as 0's and 1's, and qualifies as a Turing machine. If true, this abandons our romantic notions of free will, for as a Turing machine in a digital universe our actions are calculable. Our perception of free will is merely the misunderstanding of the inability to predict the output of our own Turing machine, the mind.
I do not assert I've laid out a solid argument in the above paragraph - for that you'll need to read Turing and possibly the references cited by Petzold. Having just finished Turing hours before writing this review, and being a person who has rejected the idea of fate, I'm still a little uneasy myself. It's as if Alan Turing sat next to me on the airplane and said, "Oh fate? It exists, I have a mathematical proof here somewhere in my backpack I did last summer when I had some spare time." At least I don't have to tell the major religions of the world I was wrong about them too...
Last, I'd like to mention that in planning for CodeSock this summer, we were able to get Wiley Publishing (publisher of Turing) as a supporter. I requested and was granted 5 copies of The Annotated Turing to give away at the end of the conference.
tagged:
design web templates
Great source for web design resources
tagged:
.net provider programming
Example of creating your own provider in .Net
tagged:
writing blog for:captquirk
Seth Godin tells you why you need a blog.
Older Posts