2005 2006 2007 2008 2009 2010 2011 2015 2016 2017 2018 aspnet azure csharp debugging docker elasticsearch exceptions firefox javascriptajax linux llblgen mongodb powershell projects python security services silverlight training videos wcf wpf xag xhtmlcss

JavaScript Graphics Development Updated



For all those interested in learning some introductory concepts some lesser known features of JavaScript, I just updated my e-chapter on JavaScript Graphics Development. This an introduction to using JavaScript and Ajax concepts to do manual graphics development. It also touches briefly on concepts involving interactive graphics and widget creation.

Anyhow, here's the link:

Base64 PNG Server

In my mind, one of the coolest things tht modern web browsers can do is deal with base64 PNG images. PNG images are the "new standard" in web images. They can be very small in size or they can be larger as true color images depending on your needs. They don't replace everything, but they do replace a lot.

A base64 PNG image is a PNG image encoded as base64. Base64 encoding is a way to encode non-printable characters (stuff you can't see, but the computer can read) into printable characters (things like letters and numbers).

Base64 PNG images (which are text) can actually be read by modern web browsers as real images. In fact, it's one of my qualification requirements for being a modern web browser (actually there are MANY requirements in my mind). You can actually use base64 PNG images directly in CSS. Here's an example...

background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAABkCAYAAABaQU4jAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAC6ZJREFUeF7t3c1xHLkZBuC9++Lj+iD55AScgCNQBM7AGTiFra2ltso3xcAkmMUmQ3qABjBfY4D+IcUy5Xm2iiWJ09M/TzeJd4EPmJ9+8h8BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBDyHw+feXv4++/vLr898+xAmePIlPvz3//Pm35399+vr87/zn5d9Hd1Hfd3T7tN2f//Pyp+SX/jzzPtv+bwTq/Tpy9Lrtj/qzcOQabUOAAAEC7yCQg9XXl5fp18PzHymovMOh32WXnx6ef/l8Oef2la4t/fvr8z/3DvjXh5d/ZIfL9nvbxtdzkLu870dyOnN9/2/b1vuVnv29a2vbPjw/7W3rdQIECBAg0ARawCpBKjUo7evh+XEJJ5fwcAkuH50tNoa11yqHpnIN6e9b13DZ7knA+uh3+e3nJ2C93dAeCBAgQGBHIASs4f+h59dLj9BHx6zn2Q8Jpt6rEhK/za7hEiC/1SCmB+uj3+m3nZ+A9TY/7yZAgACBAwJ7ASvtovXsTIZUcs1TqOPaq3lK9Sxx+73TjNvP9l2H9y5B6XG0v3S8WR3N5T1fliHSSxB7RZicDRH2x6zXfBMAi91enc9Z53zvwn1J/66W06AZ7uXe+fT737vv/TFj3drWeZ15Vo6c0yxgRd96rmHY2BDh3g+q1wkQIEDgKnAwYOWappFbCjSt56fWcqXhxkHQyY1oHYaLdV+TGqnSe7YM2+3suzWal6L2M/c3FzEv55t7t75rwFrC2uX8S3BbX8OX3KB3HvU8+ms445zem0NjGRoNdk/te4OwPDnG06hWKXvf7n9432eBt9at5d7DahPOK004mBxjOFxdhoNHz8uq53IUsFpPbQna9Zzrz8csuJ951mxLgAABAncksBWwUgCojd+oBis3yEt91rdVD1ZpMPuw0LZPjXPtWQm9RrEHpISxXP+VG9qyfWuMu6Lj2MvWGv/SG7VVfF5DRZ0B+A4BK4fTfE7pGtK11ML7EkRTMNiqFTvr3OxKcE3HTfuv+8nH7wJW9Yv3MtS0/RHvTezVyX/v7s0sJMYfq1j7VwNuOl67D8Eph8VyDeE8VyFr73mJ59QHrBqyay/m6DxNYLijX4oulQABAt9DYDWLMM6+q38vAWrYC1F6aDZeW/V6lfByM9RSZv49xSGpFgYGPVItZIXXQoF67qVJ25SgVQvXb45bw05qwFuPxfccIpwU18cws2rMS6joG/OZ26zHrdqNivpHw71tiLP04g3PKfRIhu2bW+41Kz1ypwPWoDetBt1R71nt1Tr6vPS1eX3AuvYi3s40bT1YP9BM2u/xe8E+CBAgQOCNAl1PQgon8astdzDqwdo69KgnqA33HBjG2+pJGtXFxIDVr0fVeuFCI1nCQBsafLeANZjePwo5OSyVJTPOWE+dJ0O6o2PX781qrvpjxNmaR+q0hgG8XusguOzV0+VA3i2LsfW89PVd9fzXQ4rjZTwErDf+gvF2AgQI3KvAXg3Wuk7othEqw4hp7amlvif0fKW/R9faMIYhsqf0vb6R3gl9SwDs1quahZZ0/NzAdtv3Q4MfKWCla+mfx6POe/dzErCWodh1uF4H7cvr9T7VcNrXxR1Za6w5bwSsvXXF+gC2d803lmXdshb4L9e2tYRH7hHVg3WvvyJdNwECBF4ncKRxms2kirPuUuMc19Ca9SiUWqDrkgiluDkWER8KWOl4YdhqK2Dl3qEw9BeGBh9X637Vwu2wJtgR1ekswskQ6l4PVh+wzjjv3c9XBqwctm6C8FKEfi2cP7Go61bP0F7A6q9x75qnAaus71bD5exe52fnQK/rkWfFNgQIECBwJwJHGqcYeCpL7BWa1snsrIie9xFmitWhsbDvw1Pj27DVZMX2GLCu226sYH9iRff3DFhnnffu5zRg7dyrvR+HFpwPuh0KWJPFbUNAXmZ+1k8jOLjaej/jtA05zo6XAtaBVd/3jLxOgAABAnckcKRxqgt1xp6VUOg8nDLf92Cluqj0ntFQzKSmapl9N/gcwTxclod5rkOWW3U7fWCrny/XZjLGz2KsQ5zle0cehfcMWGed+966/vxHAes6u3Bch1R7+eq+tj6vca8nse1jY4hwL2C3SQ7h/m/VYNXzrbV5w2UaJhMSjtx/2xAgQIAAgRuBrYCVa21WazhdG+CwOvrNwp5xev+gx+u2vqh+ll/oQdia2TaaRViCRVkDaR0URg3y7FHYaqhn73nPgHXWOZ3jqKg/+5QV7ftlGmLAvVkEtc5sjLMIy/Ic/bBZW+7gQG/YXvF4C2pdj2R+32CmZ+iFWq95tcxsXK3jNgpYeSmIUocW77MPe/ZLkwABAgReJXBkmYbZx8y0IuFafxU/aHkwVNSCzrKMwi+5Z6Q21pfv9bP/YjF73T587yaoxbWQ+mUaYr3WFtRHC1itR6o0/sXs+oHWI+caKsoSG73zaB2s7t7kJS7ivYn1V53zUsdW7/3BD73eC1iTYyy1e8vzs1oiYhWw++exWzx0FLBWwXQQ9Pu6uFf9sHkTAQIECNyPQFtdfTKDLDVG04+YqQuRhtmDqaFO26fGeRRqcuPWzThM7+nDVb0DpUYrzlDMxfTT3qTROZ2YATY7781QVou9u0Losq+bzz/MYWZQNF7vRXo9Hq8t+HrCud6DEEgeV8sSjFdy/1JnV4b3fRsN0/b7L9uniQc3wWdk1567jeLxyXU/bi0NUZ6v62zWZTLE6pzqM9Xvp82YTe8pQ9N12/6e3M9vCFdKgAABAgQIZIFaWzbiqOH27OcGoiVAgAABAgQI3LVAHUYdri+2sfr+XaO5eAIECBAgQIDAlkD4vMM8nJp6tNrQ2VKXdWgYjzIBAgQIECBAgEAQaOuLleUHztZIwSRAgAABAgQIENgQsEimx4MAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgU2B/wJmPk0do+6gLAAAAABJRU5ErkJggg==);


Well, it's not SUPPOSED to be small! It's supposed to be embeddable. And it is. But think for a moment. You can take an image (not just PNG mind you, GIF can do this as well) and turn it into Base64. Now, can't you dynamically load images on the client? Well, yes you can... All you have to do is do a remote call to somewhere which will send the Base64 stream back.

One you get the stream back all you have to do is prefix the base64 stream with "data:image/png;base64," and assign the entire value to the src property (attribute) of an img object.

Here's an example I put together a few months ago of how you can do all this... Firefox users only please! IE6 won't get NEAR base64 images.

PNG Client/Service Example

Actually, this is also a great example of how to work with web remoting (I just CAN'T call it Ajax, that's too weird) and how to dynamically work with XML files.

Minima Blog Engine February 2007 CTP Released!



Over the past few months I've been getting various requests for portions (or all) of my blog engine. The project was not open or shared source… until now. Having had enough requests, I figured I should finally go back through my code and do the refactoring I've been putting off for quite some time now. I went ahead and did my cleanup, added a few more features, streamlined the API, simplified the code tremendously, fixed up the database a bit, and made a sample application to ship with it. Now I'm finally ready to release this blog engine under the name Minima as a February 2007 CTP. The files are listed below. One file is the Minima solution and the other is the database (yes, RAR only-- I don't do ZIP).

As far as licensing… it's a shared source project. Meaning, I'm going to continue development on it and release new CTPs as time goes on. I have a list of things I want to implement in future releases and I'll be shipping those in future CTPs. The license does however allow for modifications… as that's the entire point! This is a template for you own blog system and you can add to it add to it as see fit. However, please be warned that I'll be releasing new versions in the future. So, you may want to keep track of your changes or communicate with me about them. You really don't want to get into the situation where you say "Oh man… he released an assembly to do exactly what I wanted… uh oh… I rebuilt this entire section… this is going to get sloppy!" Just be careful with your changes. Furthermore, no matter how much you change it, you must put somewhere on your blog that your blog either uses Minima or is based on Minima. Lastly, the disclaimer is the typical disclaimer: neither myself or my company will be liable for any usage in any way, shape, or form of either this application or derivatives of it.

By the way… this is why my blog was flaky lately. I've been doing constant deployments to production, which caused all kinds of problems as this web site was my QA system.

Now, here are the release notes as seen in the ReleaseNotes.xml in the MinimaLibrary project in the RAR. Please pay special attention to the "Technology" and "As a Training Tool" sections as it explains the technology in this application, which I think will serve as an example for each of us in many areas. This is why I'm labeling this entry with so many labels.

Purpose

Minima is designed to give developers a minimalistic template for creating a feature rich alternative to Blogger, Wordpress, and other large-scale blogging systems in manner consistent with the technologies and design paradigms of ASP.NET 2.0, XHTML, CSS, ECMAScript, and the Framework Design Guidelines.

Minimalistic?

Minima is minimalistic in a number of respects. First, does not overload itself with every possible feature in the known universe. Next, it's designed to put extra features as add-ons in an effort to keep the code somewhat maintainable. Furthermore, the primary way of interacting with Minima is a single facade (a class designed to make interaction with the internal mechanics easier) with very understandable methods. This facade is actually the API exposed as a WCF service. Finally, in this release there is no client application; however, as I say, there is a very easy to use API. It should cover most everything you need.

There are also other dimensions to it's minimalism. For example, I put in my mini-exception monitoring system, which notifies me of any exceptions thrown from the web site. I could have used the Application Blocks, but I went the more minimal route instead Be clear on this: I'm a complete minimalist and purist. I refuse to have multiple computers, never put two toppings on my ice scream, hate putting anything on my sandwiches, I never use MODs for games, NEVER wear shirts with logos, and never wear more than 2 colors at a time. I hate stuff that gets overly complex. So, I'm a minimalist and this fits me.

Blog Management Application?

There is no management application in this release. I personally use is a small interface I wrote in WPF, which communicates via WCF to the primary server. It was my first real WPF application I wrote and I wrote it before I deeply understood XAML, so I wrote the entire thing using C#. (Those of you who were ASP/PHP masters before learning ASP.NET and therefore wrote your first project in pure C# without any markup will know what I mean) I'm rebuilding it now in mostly XAML with a little code here and there for WCF interaction.

Having said all that, you can very easily write your own tool. Even still, I find SQL Server Management Studios to be one of the best front-ends ever made.

Windows Communication Foundation

The primary way to communicate with Minima is the MinimaFacade class. This class is used internally to get the information for the web site. It's also what you should use when writing your own management tool. Looking at the class you will ask yourself "Why in the world isn't this thing static!?". I didn't make it static because I wanted to apply a ServiceContract interface to it thereby giving it exposure as a potential WCF service. The web site, however, does use it statically via the MinimaFacadeCache class. Anyway, the point is, you can easily write your own remote management application using WPF, Winforms, or ASP.NET 2.0 by using WCF. Of course, if you want a secure channel with WCF… that you will have to add on your own as I didn't have an SSL certificate for testing purposes.

Potential Future Changes

There are some things I would definitely like to change in future CTPs of Minima. I have an entire list of things I want to either change, fix, or add. More information is forthcoming.

Primary Features

The primary features in Minima are just the ones that I just HAD to have. If I didn't absolutely need the feature, I probably didn't add it (but may in the future!) A few things I needed are: "fake" paths or archives and labels, "fake" URLs for each blog entry, multiple "fake" URLs for each blog entry (some times I have a typo in a title of a blog entry, but by the time I find out the blog entry is already popular--so I can't merely fix it-- I need two URLs to point to the same thing), almost completely database driven (including URL mappings), labels (not folders!, I wanted many labels per blog entry), pure CSS layout and style, pure XHTML structure, and the ability to add, remove, or change a major feature on a whim! Now that last one is very important… if I want to change something, I can. This ability came in handy when I went from blogger to my own engine and in the process lost my automatic technorati ping. That's something I quickly added though.

Technology

The DAL was generated using LLBLGen using Self-Servicing template in a two-class scenario. Everything was written in C# 2.0 using ASP.NET 2.0 with a few bits of custom AJAX functionality (I didn't want to use Atlas on this one). All style and layout is CSS as only people who are in desperate need of getting fired use tables for layout. The technorati ping functionality is based on an abridgement of my XML service framework. The RSS feed creation abilities is actual a function of the RSS.NET framework. I would have added Atom, but I've had majors problems with the Atom.NET framework in the past. Finally, the database is SQL Server 2005 (Express in my case), using one stored procedure (which I would like to refactor into LLBLGen).

As a Training Tool

One of my intentions regarding Minima is to use it as a sample application for .NET training. For example, this is a great way to demonstrate the power and capabilities of HTTPHandlers. It's also a good example of how LLBLGen can be effectively utilized. Furthermore, it also demonstrates how you can quickly and efficiently use WCF to turn a simple facade into a multi-endpoint service. It also demonstrates manual AJAX, CSS themeing, HttpWebRequest, proper use of global.asax, framework design guidelines, and type organization.

The API

For now, just look at the MinimaFacade and everything should become apparent. I'll be posting API samples in the future. See the Samples section below for some examples on using the API.

Update: Minima is now in the NetFXHarmonics Subversion respository at http://svn.netfxharmonics.com/Minima/tags/.

XmlHttp Service Interop - Part 1 (Simple Service Creation)



This entry is the first is a series on XmlHttp Service Interop.

In my day job I am constantly making diverse systems communicate. I make classic ASP talk to the .NET 2.0 Framework, .NET systems talk with Java systems, a Pascal-based system communicate with a custom .NET mail server, and even make .NET components access systems from the stone age. I love interop, but I'm finding that many people don't. From what I see, it seems to be a lack of understanding more so than a lack of desire. It's actually some pretty cool stuff and you can find great books on various interop topics.

While I do work a lot with COM, ES, and web service interop, my favorite communication mechanism is via straight XmlHttp calls. It's just so easy to do and support for it is just about universal. You can take JavaScript and make a call to ASP.NET, go to a VBS WScript and make a call to a web service, or force the oldest, nastiest product in your company to communicate with WS-* services. In this part of the series, we are going to discuss XmlHttp in general and see a call from JavaScript to a manually created service endpoint.

To start off with lets make it clear what we are and are not talking about. We are not talking about sockets or direct TCP calls nor are we talking about a service framework. XmlHttp is a way to transfer XML over HTTP. However, even though we talk about XML, in your using XmlHttp you'll find that this isn't a requirement at all, so, at root what we are doing is making simple HTTP calls.

To see what we're talking about in action, lets create a simple XML service endpoint that accepts a well-defined XML format to allow the sending of e-mail. Then, lets access the service via JavaScript. This is very similar to something I recently created to allow a very old system to send e-mails using the .NET Framework. Of course, in that situation I used the programming language of the system in question (Pascal), not JavaScript.

To begin with lets create the client. I know it seems a bit backwards, but lets look at this from the standpoint of a framework designer: look at how it will be used first, then implement mechanics. Now, the first thing we need to do this is a simple "htm" document. I want the page to be "htm" for the sake of this demonstration, simply to show that there is no server-side processing at all in this page.

Next, we need a way to access our endpoint. I'm not going to get into severe detail about how to do this in every single browser in the world, but, rather, I'm only going to show the standardized way. You can quickly do a search online to see how to extent this behavior to IE5 and IE6.

Skipping the lame setup and stuff many 6th graders can do, let's get right to the core of what we are going to do. The full implementation of everything seen here is in an accompanying VS2005 solution. It would probably be a good idea to have that open as you go through this.

To send a request to a server, simply use syntax similar to the following:

var xmlhttp = new XMLHttpRequest( ); xmlhttp.open('POST', ' Service.aspx', true); xmlhttp.onreadystatechange = function ( ) { if(xmlhttp.readyState == 4) { alert(xmlhttp.responseText); } }; xmlhttp.send(data);

This syntax works in any version of Firefox, the newer versions of Opera, and IE7 (or what I like to call " IE6.5"). Basically, what's happening here is this: you are creating a new instance of an HTTP requestor, giving it some connection information, setting a callback function, and sending some data to the service.

The part that you should look at closely is the XMLHttpRequest::open (note: my double colon syntax is from C++ and simply means Class::Member)function. This obviously takes three parameters: the HTTP method, the HTTP endpoint, and a boolean stating asynchronous communication. I want this to be an asynchronous call, so I'm setting the third parameter to true. I'll come back to the HTTP method in a moment and the HTTP endpoint is just the service address.

After that we see that the property XMLHttpRequest::onreadystatechange is being assigned a JavaScript anonymous function. If you are unfamiliar with these, just think of them as anonymous delegates in C# 2.0. This is the function that's going to be called when the state of the XmlHttp call changed. When inside this function, there are a few parameters you can look at when this function gets calls, but here I'm only testing one: readyState. This property basically states the status of the call. Notice the XMLHttpRequest property is called "onreadystatechange", not "oncomplete". This function is actually called when the state of the HTTP request changes. When I test for readyState == 4 I'm looking for round trip completion. Frankly, you probably never touch the values 1, 2, and 3 though you could check for 0, which means that the XMLHttpRequest::open function has not yet been called. In this situation, if the readyState is 4, then I want to display a message box showing the response content, which is accessible via XMLHttpRequest::responseText. One other very important property you will definately be using a lot is the XMLHttpRequest::status. This property gives values like 404, 415, 500, and so on. If the request did a successful round trip the status will be 200, so that's something you'll probably be testing for quite a bit.

Finally we see the XMLHttpRequest::send method. This simply sends a set of data to the service... well, kind of. In the XMLHttpRequest::open, the first parameter, the HTTP method, is very important. Depending on what you want to do you will either set it to GET or POST. If you are calling a pre-existing page that has no idea what a HTTP stream is, but knows about querystrings, then you will want to use GET. In this situation, you will want to put parameters in the querystring in the HTTP end point, that is, in the second parameter of XMLHttpRequest::open. However, if you are creating your own service, you may want to use POST instead as using POST makes the development on both the client and service simplier. On the client, you don't pack stuff in the querystring (though you still could) and on the server, you can access the data via a stream rather than via parsing the URL or doing any iteration. As that last sentence implies, by using the POST method you send the data you want to submit to the HTTP endpoint as a parameter of the XMLHttpRequest::send function. For those of you who understand WCF terminology, you can think of the HTTP method as being analogous to the WCF binding and the HTTP endpoint as being analogous to the WCF address. The only thing analogous to the WCF contract is the XML schema you use to create your data stream.

Now, since we are sending the information in the data variable to the service, we need to put something in it. For this service, I'm using the following XML, though it doesn't have to be XML at all.

var data = ''; data += '<Mail>'; data += '<ToAddresses>'; data += '<ToAddress>johndoe@tempuri.org</ToAddress>'; data += '</ToAddresses>'; data += '<CcAddresses>'; data += '</CcAddresses>'; data += '<BccAddresses>'; data += '</BccAddresses>'; data += '<FromAddress>no-reply@tempuri.org</FromAddress>'; data += '<Subject>XmlHttp Service Interop - Part 1</Subject>'; data += '<DateTime>03-08-07 2:26PM'; data += '</DateTime>'; data += '<Body>This is the message body.</Body>'; data += '</Mail>';

Given proper event management in JavaScript, you have everything you need to have a fully functional client. Now onto the server.

As we saw when we looked at the client code, the service endpoint is Service.aspx . To help us focus on the task at hand, we aren't going to do anything fancy like using URL aliasing (aka URL rewriting) to make it look cooler, though in reality you would probably do that.

In the code behind for the Service.aspx, we have code that starts like this:

XmlDocument doc = new XmlDocument( ); doc.Load(Request.InputStream); XmlNode documentRoot = doc.DocumentElement; XmlNode mailRoot = documentRoot.SelectSingleNode("//Mail");

Here what we're doing is creating a new XmlDocument and loading the data streamed from the client into it. Then we are getting the root of the document via XPath. The rest of the code is in the accompanying project and simply consists of a bunch of XPath queries to get the information from the document.

After we found all the values we needed in the XML document, either via XPath or another mechanism, we can do whatever we want with what we found. The important point is this: all we have to do is a simple Response.Write ("") to send data sent back to the client, which in turn changes the readyState in the previously seen JavaScript to 4, thus allowing the client to display the output in the alert window. It's really just as simple as this: the client sends stuff to the service, the service does something and sends stuff back.

Now, we could beef this up a bit by adding some HTTP headers. This is something you may find yourself doing often. To do this, use XMLHttpRequest::setRequestHeader to set a key/value pair on the connection. Here's an example.

xmlhttp.setRequestHeader('X-App-Source', 'My Client');

That 'X-App-Source' was completely made up. You could use 'My Awesome Service Caller' if you wanted. That doesn't matter, what does matter however is that you put this after the call to XMLHttpRequest::open or else you will seriously want to throw something across the room, because it's a painfully subtle error that will cause the call will fail every time.

On the server side, to access a header, simply do this:

String xAppSource = Request.Headers["X-App-Source"];

I know. You were expecting something a bit more profound. Okay, I can satisfy that need. If you have many headers and you want them all, here's what you can do.

foreach (String header in Request.Headers) { // Do whatever you want... }

Whatever you do, try to fight the temptation to do this:

Dictionary<String, String> headers = new Dictionary<String, String>( );
foreach (String header in Request.Headers) {
    headers.Add(header, Request.Headers [header]);
}

As nice as that looks, if you really want to have a headers key/value pair collection, you can just do this:

NameValueCollection headers = Request.Headers;

Regardless of what you do with the headers, remember that they are there for a reason and if you do a lot of service calls, you will find yourself using HTTP headers a lot. This is something you will see in the next part of the series.

So, that's a quick overview of XmlHttp. Please see the solution provided with this post for the full code. The next part of the series discusses making manual XmlHttp calls to WCF.

Materials

Object Range Selection and Emulating Word 2007's Formatting Box



Say you're working on a text driven web application and you want to get the selected text in order to see what was selected. With JavaScript that's easy enough, but what if you wanted to know what strongly-typed text was selected in order to recreate the selection later? This would come in tremendously handy if you want to have text annotation capabilities in your application. But, why stop there? If you are going to do that, why not add a nice pop-up window over your selection to give easy access to appropriate toolbox options? That's exactly what Word 2007 gives you and you can do the same in your JavaScript applications.

Implementing these two things involves the following tasks: assign each word (or letter if you want really fine grained control) a container span with an id and then watch for hovering over an object. When an object is hovered over, start a timer counter for the time of the hover. If hovering ends, reset the timer. When a specified amount of hover time has elapsed, see if they is a selection and if the object currently hovered over is in the selection. If so, show the toolbox. The first word and he last word selected are saved in the browser's Selection object as the 'anchorNode' and 'focusNode' objects of the selection, respectively.

Here's the meat:

// Get all spans and iterate through them making sure each REALLY exists and
// making sure each as an id.
var b = document.getElementsByTagName('span');
for(var a in b) {
    if(b[a] && b[a].id) {

    <span style="color: rgb(0,128,0)">// Only use those with an id starting with 'wid'.

if(b[a].id.substring(0, 3) == 'wid') {

        <span style="color: rgb(0,128,0)">// Set the event that is called at each interval.

b[a].timercall = function(evt){

            <span style="color: rgb(0,128,0)">// It there is a saved object (see onmouseover event below), 

// then continue… if(gHoverObject) {

                <span style="color: rgb(0,128,0)">// Increment counter.  When there are 4 timer intervals, 

// then get the object information and show the hover box. hoverCounter++; if(hoverCounter > 3) {

                    <span style="color: rgb(0,128,0)">// Get the text selection

var selection = window.getSelection( );

                    <span style="color: rgb(0,128,0)">// Does the selection contain the object the cursor is currently over?

// false means that the object the cursor is over must be fully selected. // That is, half the word being selected won't cut it. if(selection && selection.containsNode(gHoverObject, false)) {

                        <span style="color: rgb(0,128,0)">// Save the first object id selected and the last object id selected

toolboxObj.start = selection.anchorNode.parentNode.id; toolboxObj.end = selection.focusNode.parentNode.id; toolboxObj.style.display = 'block'; toolboxObj.style.left = parseInt(gHoverObject.x) + 'px'; toolboxObj.style.top = parseInt(gHoverObject.y) + 'px'; } } } };

        b[a].onmouseover = <span style="color: rgb(0,0,255)">function</span>(evt) {
            <span style="color: rgb(0,128,0)">// When the object is hovered over, save the object.

gHoverObject = this; gHoverObject.x = evt.pageX; gHoverObject.y = evt.pageY;

            <span style="color: rgb(0,0,255)">this</span>.timer = setInterval(<span style="color: rgb(0,0,255)">this</span>.timercall, 150);
            hoverCounter = 0;
        };

        b[a].onmouseout = <span style="color: rgb(0,0,255)">function</span>(evt) {
            <span style="color: rgb(0,128,0)">// Destroy the object so the algorithm doesn't run.

gHoverObject = null; clearInterval(this.timer); hoverCounter = 0; }; } } }

The provided proof-of-concept demonstration also demonstrates how to setup regular text to be strongly typed. This is simply done by splitting the text by a space and putting each word into a span, then putting each span into a parent object and finally putting that parent object before the original text and deleting the original text. You can view all this happening and see the resulting structure using Firebug for Mozilla Firefox.

The proof-of-concept demonstration provided is for Mozilla Firefox only.  Internet Explorer does NOT have the abilities to do this.

Important Disclaimer: it's not my intention to teach anyone JavaScript. This information is not for someone to simply copy/paste into their own applications. A solid understanding of the DOM, JavaScript syntax and dynamics, and XHTML is required before any true application can be built. So, please do not ask me any "how do I..." questions. When I get those I merely explain the basics and tell the person to figure it out on their own. In other words, I won't do your homework for you.

Links

Converting JSON to XAML



For reasons beyond human comprehension, the world felt like making an huge deal about Microsoft "revealing" SilverLight even even though WPF/E has been known about for some time now and even though nothing technical has changed even in the slightest with the simple change of a name. Having said that… it will probably be an awesome technology and I'm sure I'll be marinating many of my future applications in it. Editing XAML in notepad is much more appealing to me than being forced to use the overpriced and overly complicated Flash.

As cool as that is, however, since most of the work I do involves pure Ajax/JavaScript clients with almost all .NET coding at the service level, I definitely find JSON (which IS a JavaScript object) easier to manage than XML (which CAN BE a JavaScript object). So, in one of my applications I have the service that provides graphical information to Silverlight in the form of JSON serialized XAML, which will then be converted into XAML.

Here is an example of something the service would provide:

var jsonElement1 = {
        'Ellipse': {
        'Canvas.Left': '130',
        'Canvas.Top': '130',
        Height: '200',
        Width: '200',
        Stroke: 'Red',
        StrokeThickness: '10',
        Fill: 'SlateBlue'
    }
};

No, it's not human readable like XML is, but it's what JavaScript loves to see and it's what my service creates. Also, no, this is done for for efficiently purposes. This doesn't lower the service "message" size in the slightest, but it does however help to keep a consistence programming model across all my service calls. Furthermore, given that the data was in a database and not in XAML on the server, there's no real overhead. If, however, the data was in XAML on the server it would be a sign of pure stupidity for me to convert that to JSON and then back to XAML.

The parsing for something like this is actually really simple: just iterate through the JSON objects and arrays and creating an XML tree from it. As a reminder or reference, with regard to XML in a web browser, Firefox uses document.implementation.createDocument for XML while IE uses the MSXML2.DOMDocument COM object. Furthermore, Firefox is more strict in its usage of XML than the more familiar COM model that IE uses.

Here is an example of what I mean:

var doc = null;
if(DOM.implementation && DOM.implementation.createDocument) {
    doc = DOM.implementation.createDocument('', '', null);
    Xaml.ScanJSONElements(doc, data, doc);


<span style="color: rgb(0,0,255)">var</span> xmlSerializer = <span style="color: rgb(0,0,255)">new</span> XMLSerializer( );
<span style="color: rgb(0,0,255)">return</span> xmlSerializer.serializeToString(doc);
} else { doc = new ActiveXObject("MSXML2.DOMDocument"); Xaml.ScanJSONElements(doc, data, doc); return doc.xml; }

As you look through the Xaml.js file provided, you will also see that Firefox is very explicit about it's namespaces, while the COM model figured you will take care of them. There's nothing wrong with either approach, it's just something you will want to be aware of if you ever create XML in JavaScript.

Links

JavaScript Repeater Data Binding



In a previous post, I wrote about a way to convert JSON to XAML. The sample I provided with that post didn't really stop with a simple conversion example, but it also demonstrated how to create an use a simple JavaScript data binding repeater. It's just something I threw together in two minutes to bind an array of objects to a div to basically do in JavaScript/XHTML what ASP.NET does with the Repeater control. I think many people will be interested in this technique to see how they can bind data to a browser in a more efficient way.

As far as my requirements, I wanted this to be like ASP.NET in that the data is bound from a data source matching the fields in the data source objects to the data fields declared in this repeater and after all is said and done, the original declarative code should disappear. As far as the data source, I wanted it to be a series of the same type of object… kind of like a generic List.

So, to start off with, I simply declared the code that I wanted to write as the client. Some people call this the 'Sellsian' method (after Chris Sells at Microsoft), though I simply call it… common sense (as I honestly suspect Chris would too!). So, here is the declarative code I wanted to write for my data binding:

<div id="rptData">
    <h2>Title</h2>
    <div id="title" class="bind"></div>

<h2>XAML Output </h2> <div id="output" class="bind"></div> </div>

In this situation the data source fields are matched to element with the bind class and the element id. This is much like <%#Bind("") %> in ASP.NET.

On the other side, I would like my data source to be in JSON format and I would like to be able to bind in a way that 'feels' like a static class. Here is what I decided on:

var dataSource = [{
        title: 'Ellipse',
        output: Xaml.CreateXamlFromJSON(jsonElement1)
    }, {
        title: 'Rectangle',
        output: Xaml.CreateXamlFromJSON(jsonElement2)
    }, {
        title: 'Canvas',
        output: Xaml.CreateXamlFromJSON(jsonElement3)
    }
];


DataBinder.BindTextRepeater(D('rptData'), dataSource);

In the sample above you can see that I have a data source with 3 objects with the object being defined with the interface of a string field named 'title' and another string field named 'output'. Furthermore, I wanted to call the method what it is: a text repeater, not a fancy object repeater (though building that shouldn't be much more difficult), so my static method is called BindTextRepeater and accepts the declarative repeater object and the data source as parameters. In my examples I use the D('id') syntax where D is simply an alias for document.getElementById. I know some people use a dollar sign for that, but that just looks really weird to me.

Now onto the code. Here is the basic shell:

var DataBinder = {
    BindTextRepeater: function(obj, ds) {
}
}

The first thing we do in this situation is look at the data source and see what the objects look like. For this we simply need to create an array to record what fields we are looking at and iterate through the object to record it's fields. Put another way... we simply need to do simple JavaScript reflection and record the object interface, something that's incredibly simple in JavaScript.

var fields = new Array( );
for(var f in ds[0]) { fields.push(f); }

Now that we know what the object looks like, let's iterate through the datasource and bind each field to it's proper place in the repeater. This is what the rest of the method does and it should be fairly self explanatory, except for the following things:

First, I said that data is bound to fields with the 'bind' class. What if you had your own class on it? That's not a problem. JavaScript classes are a bit like .NET interfaces (where as JavaScript ids are a bit like .NET classes), so you can "apply" (or implement in .NET) a few of them. So, if you wanted the apply the class "message-log" to the bindable element, you would simply have the following:

<div class="bind message-log"></div>

In this case this is possible because I'm simply checking to see if the class STARTS with "bind", rather than simply checking to see if it IS "bind":

if(obj.childNodes[e].id && obj.childNodes[e].className && obj.childNodes[e].className.substring(0, 4) == 'bind') {
    /* ... */
}

Second, if the element if found to be bindable, the method looks through the fields array to see if that element has data for in the specified data field. If so, it binds. If not... there's not much it can do (though ideally you would throw an exception). One thing to note about this is that it replicates the element and binds the text as a child. This is seen by the following line:

var bindableObj = obj.childNodes[e].cloneNode(false);

When you clone a node, you can say true, which means to clone it's children, or you can say false, which means to clone only that particular element. In this case, we don't need the children as this is a text repeater and we are going to put our own text as a child. If we were to say true, we would have to go out of our way to remove the children.

If the element is not found to be bindable, it copies the element and it's children as can be seen as the cloneNode(true).

Third, after the data object is ready you have a duplicate of the original repeater, but now filled with data from the data source. This data object is then bound to the browser's DOM as a element immediately before the repeater template. After all data objects have been bound, the original repeater is removed. Thus, you replaced the repeater template with data bound controls and you're done.

Here is the final implementation of the BindTextRepeater method:

var DataBinder = {
    BindTextRepeater: function(obj, ds) {
        var fields = new Array( );
        for(var f in ds[0]) { fields.push(f); }
    <span style="color: rgb(0,0,255)">for</span>(<span style="color: rgb(0,0,255)">var</span> r <span style="color: rgb(0,0,255)">in</span> ds) {
        <span style="color: rgb(0,0,255)">var</span> outputObj = DOM.createElement(<span style="color: rgb(163,21,21)">'div'</span>);


        <span style="color: rgb(0,0,255)">if</span>(ds[r]) {
            <span style="color: rgb(0,0,255)">var</span> d = ds[r]
            <span style="color: rgb(0,0,255)">for</span>(<span style="color: rgb(0,0,255)">var</span> e <span style="color: rgb(0,0,255)">in</span> obj.childNodes) {
                <span style="color: rgb(0,0,255)">if</span>(obj.childNodes[e].nodeType &amp;&amp; obj.childNodes[e].nodeType == 1) {
                    <span style="color: rgb(0,0,255)">if</span>(obj.childNodes[e].id &amp;&amp; obj.childNodes[e].className &amp;&amp; obj.childNodes[e].className.substring(0, 4) == <span style="color: rgb(163,21,21)">'bind'</span>) {
                        <span style="color: rgb(0,0,255)">for</span>(<span style="color: rgb(0,0,255)">var</span> i <span style="color: rgb(0,0,255)">in</span> fields) {
                            <span style="color: rgb(0,0,255)">if</span>(obj.childNodes[e].id == fields[i]) {
                                <span style="color: rgb(0,0,255)">var</span> bindableObj = obj.childNodes[e].cloneNode(<span style="color: rgb(0,0,255)">false</span>);
                                bindableObj.appendChild(DOM.createTextNode(d[fields[i]]));
                                outputObj.appendChild(bindableObj);
                            }
                        }
                    }
                    <span style="color: rgb(0,0,255)">else</span> {
                        outputObj.appendChild(obj.childNodes[e].cloneNode(<span style="color: rgb(0,0,255)">true</span>));
                    }
                }
            }
        }
        obj.parentNode.insertBefore(outputObj, obj);
    }


    obj.parentNode.removeChild(obj);
}
};

Using this same approach of templating XHTML elements and reflecting JavaScript JSON data sources, you could actually create a full scale data binding solution for all your client-side data binding needs. Furthermore, since we used a JSON data source we can now bind data directly from JSON services accessed via Ajax techniques. Lastly, as I hope you can see, there wasn't really much magic in this example and absolutely no proprietary technology. It's simply a usage of what we already have and have had for many, many years.

Links

Minima and Data Feed Framework Renamed and Explained



As of today I'm renaming any of my CTP releases to simply… "releases". That is, my Minima February 2007 CTP is now "Minima - February 2007 Release" and my Data Feed Framework February 2007 CTP is now "Data Feed Framework - February 2007 Release".

The motivation behind these is different for each. With regard to Minima, I knew it wouldn't be a long term or real production project, so announcing it as a CTP was a mistake on my part. Not a big deal. Lesson learned. Furthermore, I knew from the start that it would be more of a training tool than anything else. With regard to my Data Feed Framework (DFF), after using it in various areas I realized that my initial release was sufficient for most scenarios.

As a reminder… what is Minima? Minima is an ASP.NET 2.0 blog engine built using a SQL Server 2005 database and an LLBLGen Pro 2.0 DAL that provides the base functionality that most technical bloggers would need. Since it's initial release I've added some functionality to my own instance of Minima and have used the February 2007 release as a training tool numerous times. Moving forward I want to make it very clear that Minima is primarily a training tool and a such, it's a blog template that people learning ASP.NET can enhance and upgrade to aide in their own personal learning. Having said that, Minima is a full fledged blog engine and it does have features such as labels and the ability to have more than one URL point to the same entry. In any case, if you want something to help you learn the various components of ASP.NET, please feel free to take Minima and use it as you please (see attribution/licensing note below).

By using Minima as a training tool you can learn much about base ASP.NET technology as well as manual Ajax prinicples, CSS theming, HttpWebRequest, proper use of global.asax, framework guidelines, and type organization. Furthermore you can use it to learn WCF, the power of HTTPHandlers, and how to effectively utilize LLBLGen Pro. I will try to release versions of Minima to demonstrate the new technologies of the day. For example, when ASP.NET Ajax matures a bit (I find it slower than a dead turtle right now), I'll be adding portions to demonstrate ASP.NET Ajax. However, I will not be adding new functionality for the sake of functionality. If the functionality can be used as a training tool, then I will add it. Also, Minima is a great way of learning WPF. How so? I deliberately did NOT include a client! Why? Because I would rather you use whatever you want to use to create a simple form to access the API via WCF. The client I use a very basic WPF client that calls the Minima WCF service. So far, Minima has been a very effective learning tool and I hope you will find it useful as well.

As far as my Data Feed Framework (DFF). What is it? It's a self-contained framework that converts SQL statements into RSS feeds. I've used this in a number of places where creating a manual RSS feed and MANAGING the RSS feeds would just be too time consuming. For example, say you have a ASP.NET 2.0 e-commerce website and you have new products released at various intervals. Well, it would be AWESOME if you had an RSS feed to announce new products and sales without having to send out an ethically questionable e-mail blast. With DFF, you simply write something like "select Title=ProductName, Description=ProductDescription from Product where ProductDate > '7/11/07' order by ProductDate desc" and BAM you have an RSS feed. Since an RSS feed is simply a select statement in a column in a row in a SQL Server table, you could also use it to dynamically create a custom feed for each person who wants to monitor the price of a certain product. It's very flexible. RSS feeds are accessible via their name, their ID, or you can use a "secret feed" to force a feed to be accessible via GUID only. DFF also includes some templating abilities to help customize the output of the RSS feed. In addition to the DFF SQL to RSS engine, DFF also includes an ASP.NET 2.0 control called an InfoBlock that allows you to consume any RSS feed and display it as an XHTML list. You can see an example of how to use an InfoBlock my looking at my blog. The boxes on the right are InfoBlocks which allow me to manage my lists using a SQL Server table (the DFF database contains a Snippet and a SnippetGroup table to store autonomous information like the information in these lists--please see the documentation for more information). DFF is creating secret RSS feeds that my own personal version of Minima then consumes. With this as an example, it should be easy to see how DFF can be used in portals. My DFF demonstration video shows a bit more of that.

For more information regarding my Data Feed Framework (DFF), please skim the concise documentation for Data Feed Framework linked below. It would also probably be a good idea for you to watch my short video documentation for DFF as well. Please note that even though DFF is designed to be a production framework, it too can be used as a training tool. The most obvious thing you can learn is how to create data-bound server controls for ASP.NET 2.0 as this is exactly what an InfoBlock is.

You may use either the SQL->RSS engine or the InfoBlock portion or both. It's up to you. Also, as with all my .NET technologies that I create, the source and database files are included for extensibility and so you may use these as training tools (for yourself or for others). Lastly, for both Minima and Data Feed Framework, please remember to keep the license information intact and make it very clear that your work either uses or is based on either whichever product you are using.

Minima - Links

Data Feed Framework - Links

NetFXHarmonics SolutionTemplate/E-Book



Recently I started putting together my standard .NET solution template for public release. This template contains the base architecture and functionality that all my projects need. This template is also organized in a very clear way that clearly separates each type of element into it's own section to maximize expansion and ease of development.

In order to make sure that the solution is understandable by many different types of developers, there are commentaries in each file in the solution. In addition to this, many of the files have full chapter-length lessons on a development topic contained in that file. For example, in the Code/SampleDomManipulator.js file, I wrote a rather extensive introduction to JavaScript browser dynamics through DOM manipulation. Because of these lessons, this solution template is also living .NET e-book.

Here is a list of some of the topics I've written about in this first release of my solution template, some of them are simple explanations and others are lengthy detailed lessons.

  • HttpHandler Creation
  • HttpModule Creation
  • HttpHandlerFactory Creation
  •  
  • Custom Config Section Creation
  • .NET Tracing
  •  
  • MasterPages Concepts
  • Global.asax Usage
  •  
  • CSS Theming, Management, and Media-Specific Sheets
  •  
  • JavaScript Namespaces
  • JavaScript File Consolidation
  • Firefox Console Usage
  • JavaScript Anonymous functions
  • JavaScript Multicast Event Handling
  • DOM Element Creation
  • DOM Element Manipulation
  • DOM Element Deletion
  • JavaScript Event Handling with Low Coupling
  •  
  • JavaScript GET/POST XmlHttp Service Interop
  • Manual XmlHttp Service Creation
  •  
  • JavaScript/CSS/ASP.NET/C# Code Separation
  • Highly Cohesive Type Organization

This solution template could be used for the basis for production projects or as a training utility for people new to ASP.NET, people new to JavaScript, DOM Manipulation or AJAX or people who just want to learn how to organize their projects more effectively.

As with all my projects, but much more so with this one, I will be updating the solution template over time to account for more AJAX techniques and .NET technologies. I will also continue to expand the commentaries and lessons to the point where this solution itself becomes a case study, a sample application, and book all wrapped up in one.

Links

Creating JavaScript objects from ASP.NET objects



If you have worked with ASP.NET for any length of time you probably know that the ASP.NET ID you set on a control on the server-side changes when it gets to the client side.  For example, if you have a textbox with an ID of "txtUsername" in ASP.NET, you will probably have a textbox with an ID of something like "ctl100_txtUsername".  When working only with server-side code, this is fine.  However, I'm a JavaScript programmer as well as a .NET programmer.  Most of my applications are heavily Ajax based and sometimes the entire application through all of its screens and uses will have ZERO postbacks.  So, it's important for me to have the correct ID on the client.  So, I need to be able to access controls on the client-side.  Not only so I can access the ID from a JavaScript functions, but also so I can set loosely-coupled events on objects.

Typically the way people get around this is with simple, yet architecturally blasphemous techniques.  The first technique is to break a foundational rule of software architectural (e.g. low-coupling) by putting an event right on the element itself.  That is, they hard code the event they want to raise right on the control itself.  This is a very strange technique as the .NET developers who do this technique are usually thos wwho would never put a server-side event on a control using OnServerClick.  Somehow, they think that putting an even directly on a client-side control by OnClick is less wrong.  This is obviously a case of extremely object coupling, an extremely poor architectural practice.  In case you can't picture it, here's what I'm talking about:

<asp:TextBox id="txtUsername" runat="server" Text="Username" OnClick="ClearBox( );"></asp:TextBox>

A much, much better way of getting around this is to use the ClientID property of an ASP.NET control to assign a multi-cast JavaScript event to that button.  However, we must be careful with this technique as it too could lead to design problems.  The most obvious problem is that of spaghetti code, the mixing of two or more languages in one same file.  Professional ASP.NET developers know that to have a sound system, you must be using code-behinds.  The ASP.NET development model greatly improves the readability of code by making sure that the C# (or VB) code and the ASP.NET declarations are completely separate.  While reading one page, your brain doesn't need to be flipping all over the place trying to translate multiple languages at the same time.  To be sure, those of us from the PHP world know that with time you can become very proficient in developing in spaghetti code, but, on the other hand, those of us who have taken over a project from another person know the pains of trying to decode that slop.

The typical technique for applying loosely-coupled events (and for many other JavaScript functionality) is actually very strange.  Though the ASP.NET developers will insist on a separation for their C# (or VB) away from their ASP.NET pages, they have no problem throwing JavaScript in the midst of C# code.  This is almost as bad as putting ad-hoc SQL queries in your C# code (very bad) or coupling CSS rules to an element via the HTML "style" attribute, thereby making the solution absolutely impossible to theme and breaking any chance of debugging CSS problems (very, very bad).  JavaScript and CSS have had a code-behind model long before ASP.NET was around.  So, we need to respect the practices of code separation as much as possible.  To this end, we need a better solution than throwing a large block of JavaScript in to an ASP.NET page.

Here is an example of the old technique using legacy JavaScript (in contrast to Modern JavaScript shown in a bit):

<script type="text/javascript"> 
function ClearBox( ) {
    document.getElementById(<%=txtUsername.ClientID%>).value = ''; 
} 


document.getElementById(<%=txtUsername.ClientID%>).onclick = ClearBox;
</script>

Typically, however, you will see a TON of JavaScript code simply thrown into the page with no respect for code separation and with no possibility for multicast events.  (Furthermore, not only is this code raw spaghetti code, that function isn't even in a JavaScript namespace.  Please see my link below for more information on JavaScript Namespaces;  If you are familiar with .NET namespaces, then you have a head start on learning JavaScript namespaces.  Would you ever throw a class into an assembly that without putting it in a namespace?  Probably not... it's the same idea in JavaScript.)

Fortunately, there is a better model using a couple of JavaScript files.  The first JavaScript file (Event.js) is one of my standard files you will see in all of my JavaScript applications (update: I no longer use this-- now, I use prototype.js from the Prototype JavaScript Framework to replace a lot of my own code):

var Event = {
    Add: function (obj, evt, func, capture) {
        if(obj.addEventListener) {
            obj.addEventListener (evt, func, capture); 
        }
        else if(obj.attachEvent) {
            obj.attachEvent('on' + evt, func); 
        }
    },

    Remove: function (obj, evt, func, capture) {
        if(obj.removeEventListener) {
            obj.removeEventListener (evt, func, capture);
        }
        else if(obj.detachEvent) {
            obj.detachEvent('on' + evt, func);
        }
    }
};

This Modern JavaScript document, simply allows you to add or remove events from an object.  It's fairly simple.  Here's a file (AspNet.js) you will find in some of my applications:

var AspNet = {
    Objects: new Object( ), 

    RegisterObject: function(clientId, aspNetId, encapsulated) {
        if(encapsulated) {
            eval('AspNet.Objects.' + clientId + ' = $(aspNetId)'); 
        }
        else {
            eval('window.' + clientId + ' = $(aspNetId)'); 
        }
    }
};

This one here is where the meat is.  When you call the RegisterObject function you will actually register an ASP.NET control with JavaScript so that you can use it without needing the fancy ASP.NET ClientID.  Furthermore, it also allows you to use the object directly in JavaScript without relying on document.getElementById( ).  This technique is actually a cleaner version of the one I previously mentioned.  It does require you to put a little JavaScript in your page, but that's OK as it's ASP.NET interop code used to register itself with JavaScript; therefore, you aren't really breaking any rules.

In general, you should never, ever place JavaScript in your ASP.NET system.  There are of course some exceptions to this, but the exceptions are based on common sense and decades of interop research from the industry.  Two of the most common exceptions to never having JavaScript in your ASP.NET system are for control generation and for sewing code ("interop code").  Control generation would be when a server-side control creates that which a browser will use in order to protect users (the developers using the control) from the interop between ASP.NET and JavaScript.  That is, to hide the plumbing, thereby increasing the level of abstraction of the system.  The C++ guys deal with the pointers, protecting me from memory management and the ASP.NET/AJAX control creators deal with the JavaScript plumbing so other developers don't have to.  It's the same idea.  Continuing with this analogy, while C# allows unsafe pointers, they should only be used in extremely rare circumstances.  JavaScript in ASP.NET should be about as rare.  One example of this rarity is in reference to the other exception: sewing code.

Sewing code ("interop code"), on the other hand, is exactly what you are seeing this this technique.  It simply connects one technology to another.  One major example of sewing code in the .NET framework is where ADO.NET connects directly to SQL Server.  At some point there must be a connection to the external system and the calling system must speak its language (i.e. SQL).  In the technique here, the interop is between ASP.NET and JavaScript and, as with all interop, sewing is therefore required.  Mixing languages is a very strong sign of poor design skills and a lack of understanding of GRASP patterns.  Many excellent, genius programmers would take their systems to the next level by following this simple, yet profound time tested technique.  Martin Fowler, author of the classic computer science text "Refactoring: Improving the Design of Existing Code" (one of my core books right next to the framework design guidelines!), is often quoted as saying "Any fool can write code that a computer can understand. Good programmers write code that humans can understand."  That's, of course, contextual as people who are complete fools in software design are often 100x better hardcore programmers than the best software designers.

Now, to use the AspNet JavaScript namespace, you simply put code similar to the following somewhere in your ASP.NET page (or the Event.observe function in the Prototype Framework):

<script type="text/javascript">  
Event.Add(window, 'load', function(evt) { 
    // ASP.NET JavaScript Object Registration


    AspNet.RegisterObject('txtUsername', '<%=txtUsername.ClientID%>');
    AspNet.RegisterObject('txtPassword', '<%=txtPassword.ClientID%>');
    Initialization.Init( ); 
}, false);
</script>

Basically, when the page loads your objects will be registered.  What does this mean?  It means you can use the object as they are used in this Initialization.js file (another file in all of my JavaScript projects):

<script type="text/javascript">  
var Initialization = {
    Init: function( ) {
        txtUsername.onclick = function(evt) {
            if(!txtUsername.alreadyClicked) {
                txtUsername.value = '';
                txtUsername.alreadyClicked = true; 
            }
        };

        txtPassword.onclick = function(evt) {
            if(!txtPassword.alreadyClicked) {
                txtPassword.value = '';
                txtPassword.alreadyClicked = true;
                txtPassword.type = 'password';
            }
        };
    }
};
</script>

As you can see there is no document.getElementById( ) or $( ) here.  You are simply naturally using the object as if it were strongly typed.  The best part is that to support another ASP.NET page, you simply have to put a similar JavaScript script block in that page.  That's it.  Furthermore, if you don't want to access the control directly, perhaps because you are worried about potential naming conflicts you can send a boolean value of true as the third argument in the AspNet.RegisterObject function, this will put the objects under the AspNet.Objects namespace.  Thereby, for example, making txtUsername accessible by "AspNet.Objects.txtUsername" instead of simply "txtUsername".

There is one catch though: you have to assign events to your window.load event using multi-cast events.  In other words, if at any point you assign an event directly to the window.load event, then you will obviously overwrite all events.  For example, the following would destroy this entire technique:

window.load = function(evt) {
// Do something...
}

This should not be a shocker to C# developers.  In C#, when we assign an event we are very careful to make sure to assign it using the "+=" syntax and not the "=" syntax.  This the same idea.  It's a very, very poor practice to ever assign events directly to the window.load event because you have absolutely no idea when you will need more than one event to call more than one function.  If your MasterPage needs the window.load event, your Page needs the window.load event, and a Control needs the window.load event, what are you going to do?  If you decide you will never need to do multicast events on load and then get a 3rd party tool that relies on it, what will you do when it overrides your load event or when you override its?  Have fun debugging that one.  Therefore, you should always use loosely-coupled JavaScript multi-cast events for window.load.  Furthermore, it's very important to following proper development practices at all times and never let deadlines stop your from professional quality development.

Related Links

Brainbench AJAX Exam



Well, it's official: I took the position as role as principal author of the Brainbench AJAX Exam.  Now I need to turn my usual AJAX curriculum into something worthy of an exam.  Basically I need to create a suitable outline with about 7-9 topics and 3-5 subtopics and put 4-6 questions into each subtopic to come up with a grand total of 160 questions.  Since I've done this already with the C# 2.0 exam, it should be fairly straight forward!  Err, maybe…

What will the exam cover?  Well, the fundamentals of AJAX.  I'm working on a video series right now that will cover what I refer to as the three pillars of AJAX: Modern JavaScript, Browser Dynamics (a.k.a. "DOM Manipulation" or "DHTML"), and AJAX communication.  Modern JavaScript topics that will be covered are JavaScript namespaces, closures, multi-cast events.  The browser dynamics include topics such as DOM tree navigation, node creation and removal, interpreting node manipulation (e.g. moving a box, changing a color) as well as architecture decisions (e.g. "should this be a div or a span?").  Finally, AJAX communication topics will include XMLHttpRequest usage, result interpretation, performance concerns, JSON translation, and callback creation.  These are of course not all the topics, but just a sampling.  The point is that the exam will basically be the exam for the video series.

To be clear, I will not have anything vendor specific near the exam.  This is one of the reasons I took the position.  The last thing we need is an exam which tests you on two or three completely different frameworks.  Java developers won't have a clue about ASP.NET AJAX and ASP.NET developers won't have a clue about the other 100 or so frameworks in existence.  I also have absolutely no intention of asking about obscure AJAX techniques that almost no one would ever know (e.g. request queuing, animation).  So, really, my video series will cover more than the exam as I have every intention of relying fairly heavily on Firebug in the video series and , but that can't be on the exam.

Prototype and Scriptaculous



OK, it's time that I come out with it: I've switch to using the prototype and script.aculo.us ("scriptaculous") JavaScript/AJAX frameworks. For the longest time I've sworn my allegiance to manual AJAX/DOM manipulation as I've always found it to be the absolute most powerful way to get the job done correctly, but as it turns out prototype/scriptaculous provide an incredible level of simplification without taking any of your power from you.  It's the ONLY AJAX framework I found that didn't suck.  Though I'm a .NET developer, I can't  the Microsoft ASP.NET AJAX ("Atlas") extensions.  Except for it's awesome web service handling, which I use all the time, it's a slap in the face of AJAX development. It's bulky with hard to read source code that has an incredibly low usability.  It seems to be the opposite of the beauty of C# and .NET in general.  With those technologies, everything just falls together without ever needing to read a thing (assuming you are a qualified web professional who understands the foundational concepts of the system). Sure, you have to look up stuff in the docs, but you don't have to pour over book on the topic to be productive.  The same can be said for prototype and scriptaculous.

So, what is this thing? Actually are two frameworks, one, prototype, is a single JavaScript file and the other, scriptaculous, is a series of JavaScript files. Prototype is a foundational JavaScript framework that simplifies the existing client-side JavaScript API into something much more intuitive and that's also widely cross browser compatible. Finally! Cross browser compatibility without needing to support it!  That means we no longer have to do a zillion tests to see how we are supposed to get an element's height. I can just simply call $('box').getHeight( ) and be done with it! Prototype has classes (types) for Arrays (which including a very powerful each( ) function-- similar to .NET's ForEach method, Elements (which allows you to modify style, add classes, get ALL descendants -- not just the children), Events (instead of trying to test for addEventListener or attachEvent, just use Event.observe!), and classes for a ton of other things. To put it simply: prototype gives you a new client-side API. The source code is also incredibly each to read. It's just the same stuff most of us have already written, but now we don't have to support it.  If we build our applications on prototype, some one else has pre-tested a BUNCH of our system for us!

Scriptaculous is a different beast entirely. While prototype is a new general client-side API, scriptaculous goes more specifically into dynamics. For example, it allows you to turn a normal list into a sortable list with ONE line of JavaScript.  ONE.  Uno.  Eins.  It also allows you to Turn one div set into a series of draggable elements (products?) and another set of divs into containers that the items can go to (shopping carts?) There are also a very nice set of pre-built animations as well as other common things like an autocompleting textbox and an in-place editable label. These are I've normally built manually, but can use them without micro-managing code.  Code by subtraction RULES!  Scriptaculous is also VERY flexible. Everything you can do in scriptaculous is extremely customizable thanks to JavaScript's flexible dynamic object syntax and native higher-order function capabilities. That means, for example, that when you create a sortable list you can control exactly how it can scroll and set callback functions all in the same simple line of code. Also, note that scriptaculous uses prototype's API for it's lower-level functionality. This is why you will often see the two products named together, like the various books written on "prototype and scriptaculous".

What about some samples? Well, Prototype and Scriptaculous are both SO simple to work with I have absolutely no idea how someone can write a book on them. I go to various Borders bookstores about every day (it's my office), so I get to see many different books. When I flip through the prototype/scriptaculous books I get very confused. How can someone take hundreds of pages to write something that could be said in 20 or 30?  Verbosity sucks (yeah I know… look who's talking).  These framework are insultingly simple to work with.

Here are a few very quick samples.  For better samples, just download scriptaculous and view extremely well-documented prototype API online.

Prototype

Want to make a simple AJAX request?

new Ajax.Request('/service/', { 
  method: 'get', 
  onSuccess: function(t) { 
    alert(t.responseText); 
  }
}); 

No XmlHttpRequest object, no COM objects, nothing!

How about updating the content of an element?

Using this element...

<div id="myText"></div> 

...with this JavaScript...

$('myText').update('this is the new text'); 

... you get an updated element!  As you can see, it even uses the typical $ syntax (in addition to $$, $A, $F, $H, $R, and $w syntax!) Just look at the examples in the Prototype API to see more.  You will be shocked to see how easy it is to walk to DOM tree now.  You will also be amazed at how much easier arrays are to manipulate.

Script.aculo.us

Using this XHTML structure...

<ul id="greek">
<li>Alpha</li>
<li>Beta</li>
<li>Gamma</li>
<li>Delta</li>
</ul>

...with this SINGLE line of JavaScript...

Sortable.create('greek');

..., you have a sorting list (try that out-- you will also notice some nice spring-back animations happening too!)

Need callback when sort is completed? (well of course you do!)  Just give the <li> elements a patterned ID ('listid_count')... 
 

<ul id="greek">
<li id="greek_1">Alpha</li>
<li id="greek_2">Beta</li>
<li id="greek_3">Gamma</li>
<li id="greek_4">Delta</li>
</ul>

...and add a function callback and you're done.

Sortable.create('greek', {
  onUpdate: function( ){ 
    alert('something happened');
  } 
});

Ooooooooooooooo scary. IT'S THAT EASY! You don't need a book. Just use the docs and samples online.

Here's another one: want to move an item from one list to another?

Just use these elements...

<ul id="greek">
<li id="greek_1">Alpha</li>
<li id="greek_2">Beta</li>
<li id="greek_3">Gamma</li>
<li id="greek_4">Delta</li>
</ul>
<ul id="hebrew">
<li id="hebrew_1">Aleph</li>
<li id="hebrew_2">Bet</li>
<li id="hebrew_3">Gimmel</li>
<li id="hebrew_4">Dalet</li>
</ul> 

... with this JavaScript.

Sortable.create('greek', { containment: ['greek', 'hebrew'] });
Sortable.create('hebrew', { containment: ['greek', 'hebrew'] });

Want to save the entire state of a list?

var state = Sortable.serialize('greek');

Couple that with the simple prototype Ajax.Request call and you can very quickly save the state of your dynamic application.

Now close your jaw and stop drooling.  I haven't even shown the drag-n-drop, animations, or visual effects that Scriptaculous provides.  Also, get this: it's all FREE. Just go get it at the links below. Be sure to look over the docs a few times to get some more examples of the prototype functionality and scriptaculous usage. I've thrown out A LOT of my own code without looking back now that I have these amazing frameworks. This is good stuff.

AdvancED DOM Scripting Book

Oh, and as always... be very certain that you know your AJAX before you do this.  I know it goes without saying that you need to be a qualified professional to use powerful tools, but some amateurs and hobbyists (and men who get a hand crushed trying to fix the wash machine) think "Hey! This tool can do it for me! I don't need to know how it works!".  So, make sure you understand the three pillars of AJAX (AJAX Communication, Browser Dynamics, and Modern JavaScript) before you even bother with the powerful frameworks or else you will by flying blind.  Basically, if you can't recreate the Prototype framework (very easy to read code!), you shouldn't be using any JavaScript/AJAX framework.  If you aren't familiar with AJAX Communication, Browser Dynamics, or Modern JavaScript. Check out Jeffery Sambell's amazing book AdvancED DOM Scripting   It's an amazing guide covers all the prerequisites for AJAX development from service communication to DOM manipulation to CSS alteration.  It's amazing.  Even if you're an AJAX expert, buy this book!

Links

Web Application Security Presentation



Today I found a really nice web application security presentation by Joe Walker.  Honestly, almost none of it is common sense and I would therefore encourage all web developers to check this out.  Also on the same page as the presentation are a number of very good AJAX security links like the XSS (Cross Site Scripting) cheat sheet.

BTW, this type of stuff is touched on in the Brainbench AJAX exam.

Links

Prototype and Scriptaculous Book



Today I noticed the book "Prototype and script.aculo.us: You never knew JavaScript could do this!" and while you do not need a book to learn P&S, this book will definitely induce a good 6 months to a year of experience into your skill set.  The book is available on Amazon in print or on the book's website in PDF format.

If you only want to know the basics of P&S, then you'll be fine with looking over the Prototype documentation and script.aculo.us samples.  However, regardless of how deep you want to go, you should definitely check out the freely available source code for the book available on the book's website.

As always, let the tools do the work, but don't rely on them for everything.  It's critically important that you understand AJAX developer from a deep mechanical level before you start using JavaScript or AJAX frameworks.  If you aren't well-versed in JavaScript and AJAX development, then I highly recommend AdvancED DOM Scripting: Dynamic Web Design Techniques by Jeffery Sambell.

Related Links

Opera Sues Microsoft Over Web Standards



I'm not going to go into too many details here, but I just wanted to point out that Opera has filed a complaint with the European Union against Microsoft for "…tying its browser…to the Windows operating system" and for "…hindering interoperability by not following accepted Web standards."  The article goes into all kinds of the same old anti-trust stuff, but it also mentions that Microsoft's technology "creates a de facto standard that is more costly to support, harder to maintain, and technologically inferior and that can even expose users to security risks."

This is tremendous huge win for anyone who 1) has respect for the web, 2) don't like segmenting QA plans to including an entire segment to IE support testing, or 3) likes to have a little self respect left over after a pure-AJAX project.  For years I've been saying that someone needs to take the IE team up on war crimes, but this filing by Opera is definitely a step in the right direction.  Perhaps someday we web developers will have the freedom to create rich client-side applications without having to add special support for the world's most "special" browser.

It's just absolutely unacceptable that someone that can infuse such a product into the world's information infrastructure and think they can get away with it.  If the WCF team had the same quality-control standards as the IE team, then SOAP would never, ever communication with anything.  If the networking stack guys had the that low of standards, can you even imagine trying to communicate between a "Microsoft TCP/IP" client and and Apache server?  Microsoft is an excellent company with great products and amazing standards, but the IE team seems to be absolutely against these things.  Sometimes people seem to forget that the word "standards" isn't just a word meaning "common, same, or basis for comparison", but that it also refers to a certain level of quality.  I've said it before and I'll say it again: the IE team has no standards (I feel a bumper-sticking coming on!)

Do yourself and the world a favor by downloading and supporting Mozilla Firefox, Apple Safari, or Opera.  Each of these are proper 7th generation web browsers, unlike Intranet Explorer whose existence is analogous to those half dead, temporary batteries that sometimes come with your kid's toys.  They are meant to be replaced.  So, if you are getting someone a computer for Christmas, give them the gift of one of these web browsers so they don't have to drag their muddy feet all over the Internet.

Links

  • Mozilla Firefox - Great CSS support, absolutely unsurpassable JavaScript and DOM support, and the ability to write browser extension with just JavaScript and CSS.
  • Apple Safari - Great font anti-aliasing with support for many of the same shortcut keys as Firefox.  A little quirky on the JavaScript and DOM side, but it's constantly improving.  I love Safari.  I usually keep Safari up most of the day when I'm working on Firefox specific projects that require me to do a lot of restarting.
  • Opera - Great support for CSS and continually improving JavaScript support with an amazing set of user features.  A little awkward for people not used to it though.

IE8, CSS, and Other Critical Standards



Early this morning I read that there is an internal build of IE8 that supposedly renders the Acid2 test perfectly.  When hearing about this, I'm sure there were crowds of naive developers rejoicing and singing praise.  That's great, but I'm not one of them.  The reason is simple: CSS is only one standard.

Passing the Acid2 test brings a great deal of weight of the reliability of a web browser, but as an AJAX specialist, my core technologies are the DOM and JavaScript.  This is why I could use Firefox 1.5 and 2.0 even though they were only somewhat close to passing the ACID2 test (though this didn't stop me writing writing Mozilla a letter or two!)

People seem to forget that JavaScript is also a standard (by ECMA-International, who also has C#-- ironic?)  Furthermore, the DOM is a standard.  I can easily deal with strange stuff going on in CSS by using more images in place of text or by using IE conditional CSS (a feature the other browsers need).  It's just one of the many standards required to be a proper web browser.  Honestly, I can even deal with their weak implementation of JavaScript, because it handles closures, namespaces, and higher-order functions fine.

The problem I hit… every… single… day… however, is their lack of strong DOM support.  There are just SO few things you can do with the DOM in IE!  I don't even mean the awesome stuff like being able to access a mouse selection is a safe way, but something simple and common like being able to use addEventListener instead of attachEvent.  Even the Silverlight team thought it was important to add support for that (in their first release too!)

In addition to the DOM, I should also mention that this is not the end of the standards list.  Firefox, Opera, and Safari all take HTML5, Canvases (part of HTML5), and SVG for granted.  IE has absolutely no support for these standards.  I'm sure more avid standards specialists could go on and on, listing even more standards that IE lacks and that others have had for a while.  We just can't forget about the other technologies.  We only complain about CSS because it's partially supported and therefore it reminds people of its sloppiness in IE, prompting us to talk about it.  Since we haven't seen them in IE, most don't consider than as important, but if we had them in IE, then we wouldn't have to complain so much about the CSS support.  We would have more standards-based visual technologies to help us get to the same end.

Lastly, I would like to mention again that "standard" not only means "common, same, or basis for comparison", but it also refers to a certain level of quality.  So, even if the IE team were to pass the Acid2 test, support JavaScript 1.5+, and add support for the addEventListener function, they would have to continually and consistently prove their integrity by releasing a major update either annually or bi-annually to keep up with the technologies.  It's very important to keep changing with technology and to keep going with the flow.  IE's lack of proper web technology support has held web technology back for way too long.

I don't think most people realize how significance of a technological boost Firefox 1.0 was when it first came on the scene!  It wasn't just a new browser or some neat piece of technology.  It was like someone dropped a Lexus LS 2008 into a local car in 1991.  It shouldn't have been that way though.  The IE team had the most power and with that power came the responsibility to lead the charge.  They failed.  To this day, the Firefox and Opera guys are very hard working people who are constantly putting out new updates and therefore are constantly proving that even though they aren't perfect, they are willing to stay with the times and provide regular updates.  The IE team has to prove themselves in the same way and I'm confident that myself and my fellow web developers will completely accept IE when it becomes a proper web browser.

Therefore, I'm not too excited about IE8 passing the Acid2 test; I was much more excited when Opera did.  It's awesome that they finally got that far, but the IE team has a TON of things that must be done before IE can start playing with the big boys again.  Personally, I think they should just do what Apple did with OS9 and just rewrite the entire thing from scratch.  I also think they should recreate the IE team with some of the best of the best from other portions of Microsoft.  The web browser is arguably the most used application on a PC today and it is therefore worthy of our best resources.  Microsoft could even rewrite the entire thing in .NET to prove to the world the amazing power and efficiency of .NET and feed two birds with one scone!

10 Things Most Developers Didn't Know in 2007



To end 2007, I thought I would make a list of things which I found that most developers didn't know.  To make things more interesting, this list is actually a series of 10 mini-articles that I wrote today.  Since this article has several sub-articles, here's a table of contents to help you out (these aren't really in any order of importance):

#1  SQL Server supports powerful subqueries as anonymous sets.

Many developers don't take the time to seriously look at T-SQL or SQL Server internals.  As such, they miss many of SQL Server's more powerful features.  In January 2007, when co-worker saw he write the following query, he about fell out of his seat:

select MemberName, m.MemberId, count() from (select 
    distinct MemberId, 
    VisitUserAgent 
    from VisitSession 
    where MemberId is not null) a 
inner join Member m on a.MemberId = m.MemberId 
group by m.MemberId, MemberName, VisitUserAgent 
having count() > 1 
order by count(*) desc 

For starters, the guy didn't know you could do a filter after a group by, but that's not my point.  He had no idea that SQL Server (2000) allows you to use subqueries or use subqueries as anonymous sets.  As you can see, you can select from the list as well as use it in a join.  This tidbit alone should toss many painfully slow cursor-based stored procedures into the trash.  It's a simple SQL feature, but it's a powerful one.

#2  Firefox has an operating-system style console for web application debugging.

It's incredibly hard to find an ASP.NET web developer who knows this one.  It's a feature that knocks people right off their seats.  Instead of throwing alerts all over your AJAX applications, you can use the Firefox console and the dump( ) function.  Did I mention this has been a native feature since Firefox 1.0?

Step 1 (start Firefox with -console switch)

Step 2 (add the boolean key 'browser.dom.window.dump' to the Firefox configuration an set it to true)

Then simply call dump( ), instead of alert( ) and you're done. Your output will go to the Firefox console window (which looks almost exactly like a cmd window).

With this technique you can entirely avoid any possibility of having an infinite loops of alerts.  Personally, I like to track all the output of my web applications.  This comes in very handy when I'm using event capturing or need to watch the progressive state of my application.  When I do this, I also like to write an output identifier to each data dump.  Here's a sample of what I usually use for debugging:

var Configuration = { 
    Debug: false
}; 


var Debug = { 
    counter: 0, 
    write: function(text) { 
        if(Configuration && Configuration.Debug) { 
            dump(text); 
        } 
    }, 
    writeLine: function(text) { 
        if(Configuration && Configuration.Debug) { 
            Debug.counter++;        
            dump(Debug.counter + ':'+ text + '\n'); 
        } 
    } 
};

Here's some sample output using the Debug.writeLine( ) abstraction:

Leaves alert( ) in the dust, doesn't it? You can actually learn more about this technique and others from my Firefox for ASP.NET Web Developer video series found on my blog.  These topics are crucial to your understanding of modern web development.

#3  JavaScript has natively handled loosely-coupled multi-cast events for years.

This isn't something just for the Firefox, Opera, Safari world.  Even IE6 has native support for this feature. I'm not sure why this is, but in September 2007 when I was designing the AJAX exam for Brainbench, not a single one of the reviewers knew that JavaScript natively supported loosely-coupled multi-cast events.  I actually comments from almost all of the reviewers telling me that I should "leave server-side questions out of the exam".

JavaScript loosely-coupled multi-cast events are one of the most important core features of AJAX applications. They allow you to quickly and efficiently attach multiple event handlers to the XHTML same element. This becomes critically important when you are with multiple AJAX components, each of which that want to have an event handler attached to the load event of the window object.

I wrote an article about this in September 2007, so I'm not going to go into any kind of details here.  You my also opt to view this file from my SolutionTemplate, which supplements that blog entry.

#4  Not all image formats are created equal.

A few months ago, I came in as lead architect about half way through a project.  After having a few people fired for absolute incompetence, I did find a few people (PHP guys) who were ready, willing, and actually able to learn ASP.NET.  Everything was going well until the designer came back with his new theme and my associate whom I was training implemented it.  Everyone thought the project was going fine until I stepped in the room.  It didn't take but 10 seconds for a red flag to go up.  Just looking at the web site I could tell that this theme implementation was a disaster.  I noticed that there were signs of JPEG compression all over every single one of the images.  However, being a scientist and part-engineer I knew that measurement was a major key to success.  So, I whipped out Firebug, hit refresh and felt my jaw drop.  The landing page was 1.5MB.  Ouch.

You absolutely can not use one single image format for ever image on your web site, especially not the deadly JPEG format which does little more than destroy your images.  There are rules which web developers must need to follow or else a project is doomed to failure.  First off, you need to be using PNG24s for the all important images, while comparing their file sizes and quality with PNG8 compression.  Using Adobe Photoshop's Save For Web feature is very helpful for this.  If the image is a photo or something with many "real life" colors and shades, perhaps you want to do a size and quality comparison against a JPEG version as well.  If you absolutely need to have transparent images for IE6, then you need to take extreme care and either make special PNG versions for each background or, if you don't care too much about quality and the image is small with very few colors, use a GIF with transparencies.  The same goes for Firefox and printing.  Firefox (as of 2.0) does not print transparent PNG images.  So, if you want to support printing in Firefox, then you need to either make special PNG images for each background or make low-quality GIF images.

Needless to say, the designers theme had to go under severe reconstruction.  Not just because of the image sizes, but because he felt the need to design special input box, textarea, and button controls.  His design would have worked well for a WPF application, but this is the web (... but don't even get me started on the fact that his design for a wide screen monitor at over 1300x800.  The design was useless anyhow!)  The next project I ran as lead architect went much smoother.  Because it was extremely AJAX intensive, everything was minimized to the absolute core.  Each page had the minimal default.css plus it's own CSS sheet and only included the JavaScript it needed.  The web site landing page included barely anything and even had it's own extremely stripped down version of the JavaScript files.  For this project, I went from 350K in development to 80k in production.

#5  Custom server controls are not esoteric, complicated, or take too long to create.

  This seems to be a very common misconception amongst ASP.NET developers.  The reality, however, is that creating server controls is often a very trivial task.  Yet, many developers will use a GridView or other canned control for everything.  The GridView is awesome for basic tabular in a very simple, data-driven applications, but I can rarely use it.  On the other hand, I love the repeater and rely on it for almost everything.  Actually, it and the Literal are my two favorite controls.  I have to rely on these two controls to ensure that my AJAX applications are extremely optimized.  One of the beautiful things about .NET is that every ASP.NET control is simply a .NET class, which means that you can programmatically reuse them, inherit from them, and override their internals.  Thus, allowing us to create some powerful and elegant custom server controls.

On the same project with the overly sizes image files, we had an interesting meeting about how to show a media play list on a web page.  There was all kinds of talk about using Flash to create a media play list.  The conversation was quickly giving me an allergic reaction.  So, after hearing all kinds of absolutely insane quotes of time for creating a Flash play list, I decided to take matters in to my own hands.  Two hours later I handed the client a complete play list from A to Z.  To be clear, I had built this one something I had already had, but the grand total of time was them about 3 hours.  It's amazing what you can do when you understand the .NET framework design guidelines and aren't afraid to follow best-practices.

Here is how you would use a similar control:

<%@ Register Assembly="Jampad.Web" Namespace="Jampad.Web.Controls" TagPrefix="j" %>


<j:Media id="media01" runat="server" />

In your code behind, you would have something that looked like this:

media01.DataSource = MediaAdapter.GetContent(this.MemberGuid);

Upon loading the page, the data was bound and the output was a perfect XHTML structure that could them be customized in any number of ways using the power of CSS.  How do you make something like this happen?  It's simple, here is a similar control (Media.cs) placed in a class library (WebControls.csproj):

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;


namespace Jampad.Web.Controls
{
    [ToolboxData("<{0}:Media runat=\"server\"></{0}:Media>")]
    public class Media : CompositeControl
    {
        private Repeater repeater;
    <span style="color: blue">public </span>Media( ) {
    }


    <span style="color: blue">private </span><span style="color: #2b91af">Object </span>dataSource;


    <span style="color: blue">public </span><span style="color: #2b91af">Object </span>DataSource {
        <span style="color: blue">get </span>{ <span style="color: blue">return </span>dataSource; }
        <span style="color: blue">set </span>{ dataSource = <span style="color: blue">value</span>; }
    }


    <span style="color: blue">protected override void </span>CreateChildControls( ) {
        <span style="color: #2b91af">HtmlGenericControl </span>div = <span style="color: blue">new </span><span style="color: #2b91af">HtmlGenericControl</span>(<span style="color: #a31515">"div"</span>);
        div.Attributes.Add(<span style="color: #a31515">"class"</span>, <span style="color: #a31515">"media-list"</span>);


        <span style="color: blue">try </span>{
            repeater = <span style="color: blue">new </span><span style="color: #2b91af">Repeater</span>( );
            repeater.DataSource = <span style="color: blue">this</span>.DataSource;
            repeater.ItemTemplate = <span style="color: blue">new </span>MediaTemplate(<span style="color: #2b91af">ListItemType</span>.Item);
            repeater.HeaderTemplate = <span style="color: blue">new </span>MediaTemplate(<span style="color: #2b91af">ListItemType</span>.Header);
            repeater.FooterTemplate = <span style="color: blue">new </span>MediaTemplate(<span style="color: #2b91af">ListItemType</span>.Footer);
            div.Controls.Add(repeater);
            repeater.DataBind( );
        }
        <span style="color: blue">catch </span>(<span style="color: #2b91af">Exception </span>ex) {
            <span style="color: #2b91af">Literal </span>error = <span style="color: blue">new </span><span style="color: #2b91af">Literal</span>( );
            error.Text = <span style="color: #a31515">"&lt;span class=\"error-message\"&gt;" </span>+ ex.Message + <span style="color: #a31515">"&lt;/a&gt;"</span>;
            div.Controls.Add(error);
        }


        <span style="color: blue">this</span>.Controls.Add(div);
        <span style="color: blue">base</span>.CreateChildControls( );
    }
}
}

Notice the use of the repeater control.  This is the same control we use in ASP.NET as <asp:Repeater />.  Since this is .NET, we can use it programmatically to create our own powerful controls.  Also notice the various templates that are being set on the Repeater.  These are the same templates you would set declaratively in an ASPX page.  In this case, I'm programmatically assigning to these templates an instance of MediaTemplate (in MediaTemplate.cs).  This MediaTemplate.cs is just another file thrown in a class library, in our case the same WebControls.csproj, though since it's just a class, it could be in a different assembly and namespace altogether. Here's what the MediaTemplate.cs looks like:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;


namespace Jampad.Web.Controls
{
    internal class MediaTemplate : ITemplate
   {
        ListItemType type = new ListItemType( );
    <span style="color: blue">public </span>MediaTemplate(<span style="color: #2b91af">ListItemType </span>type) {
        <span style="color: blue">this</span>.type = type;
    }


    <span style="color: blue">public void </span>InstantiateIn(<span style="color: #2b91af">Control </span>container) {
        <span style="color: #2b91af">Literal </span>lit = <span style="color: blue">new </span><span style="color: #2b91af">Literal</span>( );
        <span style="color: blue">switch</span>(type) {
            <span style="color: blue">case </span><span style="color: #2b91af">ListItemType</span>.Header:
                <span style="color: blue">break</span>;


            <span style="color: blue">case </span><span style="color: #2b91af">ListItemType</span>.Item:
                lit.DataBinding += new EventHandler(<span style="color: blue">delegate</span>(<span style="color: #2b91af">Object </span>sender, System.<span style="color: #2b91af">EventArgs </span>ea) {
                    <span style="color: #2b91af">Literal </span>literal = (<span style="color: #2b91af">Literal</span>)sender;
                    <span style="color: #2b91af">RepeaterItem </span>item = (<span style="color: #2b91af">RepeaterItem</span>)literal.NamingContainer;
                    literal.Text += <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">"&lt;div class=\"media-item\"&gt;\n"</span>);
                    literal.Text += <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">"  &lt;div class=\"media-item-inner\"&gt;\n"</span>);
                    literal.Text += <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">"    &lt;a href=\"{0}\"&gt;&lt;img src=\"{1}\" alt=\"Media\" class=\"media-thumb\" /&gt;&lt;/a&gt;\n"</span>, (<span style="color: #2b91af">String</span>)<span style="color: #2b91af">DataBinder</span>.Eval(item.DataItem, <span style="color: #a31515">"mediaPath"</span>), (<span style="color: #2b91af">String</span>)<span style="color: #2b91af">DataBinder</span>.Eval(item.DataItem, <span style="color: #a31515">"thumbPath"</span>));
                    literal.Text += <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">"  &lt;/div&gt;\n"</span>);
                    literal.Text += <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">"  &lt;div class=\"media-item-bottom\"&gt;&lt;/div&gt;\n"</span>);
                    literal.Text += <span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">"&lt;/div&gt;\n\n"</span>);
                });
                <span style="color: blue">break</span>;


            <span style="color: blue">case </span><span style="color: #2b91af">ListItemType</span>.AlternatingItem:
                <span style="color: blue">break</span>;


            <span style="color: blue">case </span><span style="color: #2b91af">ListItemType</span>.Footer:
                <span style="color: blue">break</span>;
        }
        container.Controls.Add(lit);
    }
}
}


Simply compile those to together and you're set.  You can even embed (hopefully tiny) images in your project to make things even more seamless.  Using this simple pattern, I've created all kinds of things.  You can see a real example of this, including image embedding, in my SQL Feed Framework (formerly known as Data Feed Framework).  It's InfoBlock controls follow this same pattern.  For much better examples, whip out reflector and start digging around the System.Web namespaces.

It's actually rather astonishing to learn of some of the attituted some developers have about custom controls. When I was one of the editors for an ASP.NET 2.0 exam last year, I noticed one of the questions ask which type of control was "harder" to create. The answers were something like "User Control", "Custom Control", and a few others. They were looking for the answer "Custom Control". Since "harder" is not only a relative term, but also a subjective and an abstract one, the question had no actual meaning. Custom controls aren't "harder" than user controls.

#6  Most developers I worked with in 2007 had never heard of an O/R mapper.

Why do most developers still absolutely insist on wasting their time writing a chain of SqlConnection, SqlCommand, and SqlDataAdapter?  Perhaps it's just an addiction to being busy instead of actually being productive that causes this.  I don't know.  I would, however, expect these developers have to have some curiosity that there may be an easier way.  ADO.NET is awesome stuff and it is the foundation for all .NET O/R mappers, but if I'm not throwing around 1,000,000 records at a time with SqlBulkCopy, I'm not interested in working with ADO.NET directly.  We need to have a system that allows us to get what we want instead of forcing us to screw about with low-level mechanics.  It's no secret that I'm a huge supporter of Frans Bouma's work with LLBLGen Pro and I also use LINQ in most of my .NET 3.5 applications.  For a corporate .NET 2.0 project, there's absolutely no excuse to not pay the $300 for LLBLGen Pro.  Managers!  Open the wallets!  It will save you money.

However, it's not always about the money.  Even if the developers knew about O/R mapping, and the company isn't from in a poverty-stricken 3rd world country, sometimes extreme pride, lack of personal integrity, and political alignment can destroy any chance of being productive.  A long time ago I worked at a company where I thought I would be productive.  Five or so weeks into the design phase of the project, we received a politically-focused project manager as big brother.  He was absolutely against the use of any modern technology and despised the idea of an O/R mapper.  He instead told us that we were to write a stored procedure for every possible piece of interaction that would happen.  He also wanted us to use Microsoft's data application block to access the stored procedures.  At one point he said that this was their O/R mapper, showing that he had no idea what an O/R mapper was.

A few days after his reign had started, I took an hour or so to write up a 12 page review document covering various aspects of LLBLGen Pro and how they would work on the project.  I thought it was a very convincing document.  In fact, one guy looked at it and was convinced that I took it from the LLBLGen web site.  The project manager, however, was beginning to be annoyed (this is not uncommon with me and old-school project managers!)  The project manager decided to call together a panel of his "best" offshore developers and put me in what basically amounted to be a doctoral defense.  Prior to the meeting I sent out my "dissertation" and asked everyone to read it before they arrived at the meeting so that they would be prepared for the discussion.  When it was time for the meeting, I was told to sit at one side of a large meeting table and the project manager and his team sat at the other.  Then the disaster began.  First off, not one single person on that team had read my document.  Secondly, for the next 45 minutes they asked me basic questions that the document would have answered.  Even after they admitted that I had answered all of their concerns to their satisfaction and being told by their team that LLBLGen Pro was obviously a very productive tool, they reached the conclusion that they still weren't going to use it.  It was a waste of my time and I still want those 45 minutes of my life back.

What was really interesting about my defense was the developer's code.  In the meeting, the developers had showed me their [virtually unreadable, anti-.NET framework design guidelines, inefficient, insecure] .NET project code and I was shocked to see how much time they wasted on writing the same stuff over and over and over again.  When they showed me their stored procedures, I about passed out.  It's a wonder how any of their systems run.  They were overridden with crazy dynamic SQL and cursors.  They even had most of the business logic in the data access tier.  The concept of N-tier architecture was not something that they understood at all.  I think that's the point where I gave up on my defense.  If a developer doesn't even understand the critical need for N-layer and N-tier architecture, there's just no way they will be able to understand the need for an O/R mapper.  It's actually one of the fastest way to find a coder hiding amongst professionals.  Their SQL/ADO.NET code was also obviously not strongly-typed.  This was one of the core points of an O/R mapper and these developers could not understand that.  They could not see the benefit of having an entity called Person in place of the string "Persno" (deliberate misspelling).

This project didn't really take off at all, but for what parts I was involved, I used the next best thing to an O/R mapper: a strongly-typed data-set.  Read this carefully: there is no shame in using a strongly-typed data set if you don't have an O/R mapper.  They are no where near as powerful, but they are often good enough to efficiently build your prototypes so that the presentation layer can be built   You can replace the data access components later.

The training of developers in the use of LLBLGen Pro and LINQ O/R mapping was one of the main reasons I publicly released both my Minima Blog Engine and my Minima 3.5 Blog Engine source code to the public in 2007.  You are free to use these examples in your own training as you see fit. 

For more information and for some example of using an O/R mapper, please some of my resources below:

#7  You don't need to use SOAP for everything.

This is one of the reasons I wrote my XmlHttp Service Interop series in March and May 2007.  Sometimes straight up HTTP calls are good enough.  They are quick, simple, and light-weight.  If you want more structure, you can simply use XML serialization to customize the smallest possible data format you can think of.  No SOAP envelope required.

Here are the parts to my series:

Also keep in mind that you don't need to keep JSON to JavaScript.  It's a beautiful format that could easily be an amazing structured replacement for flat CSV files.  RESTful interfaces using GET or POST with HTTP headers are also a great way to communication using very little bandwidth.  My AJAX applications rely heavily on these techniques, but I've also used them for some behind the scenes work as well.

One great example of how you can use RESTful services is by looking at the interface of the ESV Bible Web Service V2. In November 2007, I wrote a .NET 3.5-based framework to abstract the REST calls from the developer. By looking at my freely available source code, you can see how I'm interacting with the very light-weight REST service.

#8  A poor implementation of even the most beautiful database model can lead to a disast

Developers and Web Developers



(This is a sequel to my Coders and Professional Programmers article)

I'm fairly sure the year was 2001. It was before I did my transition from coder to professional, but it was long after I became a real web developer (1994).  This was the year that the web became severely corrupted by an influx of thousands of MFC/VB developers thinking they were web developers simply because they knew how to drag-n-drop a control onto a canvas and make something appear in a web browser. The influx was, of course, due to the release of ASP.NET. These people were not web developers and that same coder-mill continually throws out unprofessional after unprofessional today.  This was the year I got so upset with the pragmatic, unprofessional web developers running around taking my work that I retired for 3 years to go back to college.

So, what is a web developer?  Surely is at least one definition per person in the entire industry, but I must say that, at root, it's a person who understands and can proficiently interaction with web technologies.  What web technologies?  Today, these include, at a minimum, semantic XHTML, CSS, and Modern JavaScript.  In a sense, you could easily mark these as the pillars of web programming.  Without academic and hands-on knowledge of these technologies, there is no web devolvement (yes, both are required-- and despite what the pragmatists think, the former is critical). Furthermore, this technology list changes over time.  If I were to retire today, I have no right to come back in 5 years claiming to be a web developers.  To be a web developer at that time, I need to learn a new X, Y, and Z in including their guidelines and best practices.  You must keep up or be left behind.

Having said that, PHP, JSP, and ASP.NET developers often inappropriately call themselves web developers.  Not all PHP, JSP, or ASP.NET developers are like this, especially PHP developers! Respect, respect!  In any case, I can kind of see the confusion here, but even still, a quick realization of what these technologies are should have killed any thoughts of this a long time ago.  These people work with server-side technologies, not web technologies.  The same CGI model used 15 years ago is the same model today.  The only thing these people are doing is creating code that runs on a server and shipping the output.  Period.  That's not web development; this is the same work you would do if you were to build an Excel report.  It’s just work behind the scenes that may or may not touch a web browser.  Even then, just because it hit a web browser, doesn’t mean its web development.  There’s no client-side technologies involved at all. Without deeply interacting with client-side technologies, there is no web development.  In fact, the inanimate object known as a web server is more of a web development than server-side-only people.

Web development begins at the point when you begin to ponder the technologies and implementation from the perspective of the client-side.  I'm sure most people won't believe me when I say this, but I did web development for my 4 years of high school before I even knew that you could use server-side software to dynamically create pages.  Everything I did was in pure JavaScript and fancy frame manipulation.  This was web development.  I didn't need CGI or Perl.  PHP, JSP, and ASP.NET simply sends out a stream and it just so happens that a web browser may be the one making the request.  The output may be for a web browser, but that in absolutely no way makes it web development.  That's like going to a foreign country and using a translator device and saying because you have that device, you speak the language.  You in absolutely no way speak the language!  Worst, some people will defend, virtually to the death, the idea that they do speak the language simply because they know a few words to "fix" the translation!  We see this in server-side-only developers who, because they know a few HTML tags, think they know the technologies.

Most of the time, however, server-side-only developers really think they are web developers. So, this simple and obvious explanation won't do.  Therefore, we are forced to make a distinction between web 1.0 and web 2.0 developers.  We often think of web 2.0 as being quick, dynamic, and smooth client-side dynamics.  This is from a marketing perspective, but it's hardly a definition that satisfies the computer scientist.  The distinction I use is actually a bit more straightforward: web 2.0 development is development from the client-side perspective.  This definition actually reminds me of the definition of a series I learned in my Real Analysis class in college: a mapping from N to R.  How in the WORLD is that a series!? Isn't a series a set of entities or something?  Well, somehow it's a mapping from N to R (I've yet to hear another professor give this same definition, but the point is that "formal definitions" in mathematics rarely look like their application in reality).

When I talk about web 2.0 to a colleague or a client I'm talking about web-specific design and implementation from the perspective of the client. From this perspective calls are made to various services for interaction with outside data.  In other words, web 2.0 is a client-service model for the web.  In this sense, what is web 1.0?  Just the opposite: development from the server-side perspective.  This is ASP.NET development, for example.  When you are working with ASP.NET, you are working from the perspective of the server and you send data out.  In this model, you have a logically central system with entities accessing it. In reality, this isn’t web development—it’s development of something that may or may not do web development for you. Web 1.0 is a server-client model for the web (notice the word server, instead of service—as seen in the web 2.0 model)  If you are a deep Microsoft developer you recognize the web 2.0 paradigm: WPF/WCF allows you to easy create a client-service model bypassing the client-server model all together.  You create your client interfaces in WPF and access WCF servers as you need them.

In this perspective, what does this mean in terms of the actual technologies?  Well, almost all my web applications are done using the web 2.0 model.  That is, all my programming is done from the perspective of being inside the web browser.  I'll directly modify the DOM and access data via AJAX calls as required.  Some of my applications are pure-AJAX. That is, not single postback in the entire system (like meebo.com-- meebo is a prime example of a web 2.0; everything is from the perspective of the client with communication via AJAX services.)  In fact, my controls are very Google-ish.  Google is also deep into this model.  See their AdSense, AdWords, or Analytics controls; insert a declarative script and it does the rest from the perspective of the client.  As you can see here, you don't even need the XHR object for web 2.0!

What does ASP.NET AJAX bring?  In this model, ASP.NET AJAX is as web 1.0 technology that gives you the dynamics of web 2.0.  This was actual the entire point behind creating it.  Web 1.0 developers (who are often not web developers at all!) can use their existing server-side perspective and paradigms to implement dynamics on the remote system (in a web 1.0 model the client is the remote entity-- whereas in web 2.0 the services are remote).  ASP.NET AJAX very much allows for a web 2.0 model, but that's not how it's primarily marketed.  As a side note, I should mention that, this model for explaining web 1.0 and 2.0 is only a logical representation and therefore can not be right nor can it be wrong.  The fancy marketing representation kind of works too, but it's often too abstract to have real meaning.

Personally, I think the web 1.0 model of development is counterproductive and encourages sloppy priorities.  The user experience is the point of the system. Without that, the entire point of the web site is dead.  One of my problems with ASP.NET AJAX is how it's marketed.  The server-perspective model of development encourages development that seems backwards.  Furthermore, because of this, the aforementioned so-called "web developers" continue to spread their disease of pragmatism all over the world further aiding in the disintegration of quality.  As I've originally stated, most of these people don't understand even the basics of semantic XHTML, which is the single most fundamental aspect of web development, which can be seen in their use of div-soup or <br/> mania.  These people may be awesome server-side professionals putting my enterprise architecture skills to absolute shame and run circles around me in just about any algorithm or design pattern implementation, but they are only coders when it comes to the web.

After years and years of dealing with people like this, I've come to notice a few signs of web 1.0 coders:

  • If someone says "Firefox?  How's that better than IE?", it goes without saying that this person not only hasn't the first clue about web development, they don't even understand the tool which represents the core purpose of web development: the web browser.  People like this are almost always helpless.  You could try to explain the true power of CSS, the fact that SVG, HTML5, and Canvases are in every web browser except IE, or talk about how Firefox has the architecture of an operating system with its console, it's own registry (about:config), as well as the ability to install apps (extensions), but you're probably only going to get the same pragmatic blank stare of a coder. Fortunately, I haven’t heard say this in at least 3 years.
  • If someone says "I know CSS, here…" and shows you how they used font-size, color, and font-weight on a few elements contained in a table embedded in a table embedded in yet another table, then you have your work cut out for you, because you met a person who thinks HTML is the latest cool technology on the block and hasn't the first clue what CSS really means.  As I've stated in my article "CSS Architecture", CSS is not just a styling technology.  Furthermore, we web 2.0 developers realize that CSS is to be used in harmony with semantic XHTML and therefore understand the dangers of using a table.  These people obviously don't.  Of course, the minute their boss asks for mobile support, they come running to you because they now realize "DOH! Tables are too wide! AHH! Tables make the page size too big!" They will have to learn their lesson eventually.
  • If someone says "I know JavaScript, here… " and they show you a validation function, then you need to explain to them that JavaScript isn't merely a scripting language, but is rather a very powerful object-oriented/functional programming language which often puts strongly-typed languages to shame.  It includes closures, namespaces, an extremely rich object system, object-oriented access levels, multi cast events, and a boat load of core JavaScript objects.  Yet web 1.0 developers haven't the first clue. This problem isn’t nearly as bad as it used to be, though. MSDN magazine devoted some time to the topic in the May 2007 issue and the number of JavaScript experts in the Microsoft community is growing very rapidly.
  • If someone says "Hmm… I don't see the control you are talking about in my toolbox", then you know you are dealing with a coder.  Not only that, you're probably dealing with a person who has never, ever learned what semantic development even is.  Typically people like this will use the dead concept of a WYSIWYG designer to drag-n-drop controls and set properties with their mouse.  Clearly, these people focus more on how something seems to look at the moment, not how the page is actually built.  Pragmatists.  Personally, I’ve never designer support into anything, ever. If you can’t program it, don’t develop it! I personally find it extremely unprofessional to even allow designer-support. The target audience typically has absolutely no concept of the difference between a semantic <h1></h1> and a pragmatic <div id="myHeader"></div>.  Not only will their code cause problems down the road, your code will never integrate with it, which, of course, means you will be rewriting everything. Anyone who understands the importance of semantic XHTML understands the sheer severity of this problem.  You will break a page's structure by relying on a designer.  A designer should only be used by a professional who knows how to fix it's flaws.  Since only a professional would be able to fix the flaws, it follows that only a professional should do web development.  Duh?  For more information on semantic XHTML, see any modern web 2.0 book or my mini-article here (a quick note-- when I was formatting this post in WLW, every one of my list items would start a new list-- if I didn't understand semantic XHTML, I would have been completely stuck [also notice I'm using the semantic term "list item" not the syntactical term "<li />"-- focus on what things ARE, not what they DO-- try focusing on what something IS using a WYDIWYG designer!])

I know I've written about this topic before, but it's is just such a critically important topic.  Just because someone does something, that doesn't mean they are in that profession.  I change my own oil and change my tires, but this doesn't make me a mechanic.  A few months ago I was talking to a guy who actually said that he doesn't care about what he produces, because "it's just a job".  Just a job!?  Why don't you just get another one!  These people need to stop masquerading as web developers, stop undercutting my professional company by offering $3.75/hour unprofessional "development", start upping their own standards and start showing a little respect to us that were here first.  To a lot of us professionals this isn’t just a “job”; it’s actually become part of us! Unfortunately, I've learned years ago that people don't change.  Not for their marriage, not for their family, and especially not for their careers.  It's hopeless.  Moving on.

Dojo 1.0: Client-Side Web Development Framework



Recently I started a deeper study of the Dojo JavaScript Toolkit 1.0.  When I first got into Dojo, my reaction was something like "my goodness this is complicated", but then I woke up.  In reality, Dojo is not simply a JavaScript framework like prototype or an animation framework like script.aculo.us, but, rather, it's an entire client-side web development framework.  You can think of it as being a client-side version of the ASP.NET.  Because of this, I'm not going to compare it to prototype or script.aculo.us, products, which have completely different applications than Dojo.

Here is a simple break down of an example based on the hello world example found on the Dojo web site.  First let's add the dojo.js file:

<script src="dojoroot/dojo/dojo.js" djConfig="parseOnLoad: true" type="text/javascript"></script>

What in the WORLD is the djConfig attribute?  Well it's not in any XHTML DTD that's for sure.  This is something to tell Dojo to, obviously, parse the file on load.  Duh.  That's not really the fun part though.  Check this out, you actually use a PHP style "require" statement to load specific portions of Dojo:

<script type="text/javascript">
   dojo.require('dijit.form.Button');
</script> 

By doing this, now we can add the following control into our page structure:

<button dojoType="dijit.form.Button" id="hola">
  Hola Mundo!
  <script type="dojo/method" event="onClick">alert('Hola');</script>
</button>

This creates a simple button which alerts 'Hola' when clicked.  As you can see, it gives you a very nice declarative programming model.  I personally think this is incredible because 1) I believe that we should focus on web development from a client-side perspective and therefore create controls on the client, 2) I love declarative programming, 3) I don't want to build this thing myself.  With Dojo I get a declarative client-side programming model without having to architect the internals.  This is really awesome, since I'm a strong advocate of client-side perspective programming (a.k.a. web 2.0).

One interesting aspect of Dojo is that it loads only the files that you need for that specific page.  This is a rather nice compromise between the Prototype and mooTools methods.  Prototype loads the entire thing into memory and mooTools allows you to download each section you want.  Dojo, however, installs on the server as a set of files that are available for download and you retrieve them as you need them.  To add to this, you don't add them via the <script /> element, you add the dojo.js file that way, but you load the others by calling dojo.require( ).  What's nice about this is that you load modules, not files.  It also gives it a more native programming feel, but it also makes sure you don't load the same file twice.  Here's an example of what I'm talking about:

<script type="text/javascript">
  dojo.require('dojo.parser');
  dojo.require('dijit.form.Button');
  dojo.require('dijit.form.FilteringSelect');
  dojo.require('dijit.form.CheckBox');
</script>

Here you can see that I'm loading up four different modules.  What's interesting about this is that it's kind of similar to how we import .NET namespaces.  However, it's even more like how we load .NET assemblies.  Think of each one of these as being an assembly we need to reference.  In .NET, you add a reference, let fusion and it's buddies find and load the assemblies, and simply use the controls as if they were local; you don't care about "files".  This is very similar to the model presented in Dojo.  It's like you are adding a Dojo "assembly" reference, letting it load it for you, and you access it as it were local.  This is all in direct contrast to the model that PHP as well as most JavaScript/AJAX framework use.  In PHP and in these frameworks, you typically load "files" directly.  One of the hardest things for a PHP developer to do is make the mental transition from file files to "magically loading" .NET assemblies.  In .NET assembly names don't need to match their DLL names, in fact as assembly can span more than a single DLL file!  In the same way, Dojo's module names don't have a one-to-one module-to-file mapping and loads whatever physical files you need based on the logical name you request.  Very nice! The analogy isn't perfect and like I've already mentioned it's a bit like the .NET namespace import model as well.

Dojo contains a number of very nice controls as part of it's Dojo Widjet Library, also known as Dijit.  Many of these are controls that most of us have wanted for years, but just have never had the time to mess with.  For example, Dojo including a slider control, a dynamically expanding textarea, and a filtering select box.  There's a whole host of others, but these are the ones that I personally have wanted to see in a professional framework for a long time.  There's also a progress bar control and a dialog control for those of you who are into business apps.  Dojo actually provides a tooltip dialog control as well.  This control, as the name suggests, shows a dialog as a tooltip.  The only time ever seen a control like this used was on the Facebook login screen, specifically when you check "Remember me".  Another interesting thing related to controls is that Dojo gives you the ability to transform controls into a more beautified form.  It's able to do this because it ships with a few CSS files that give Dojo its initial look and feel.  Furthermore it also includes a number of themes.  You can see this in a few of the more basic demonstrations in the Dojo documentation.

Dojo also includes many layout controls including a split container, accordion, tab control and what is called a StackContainer.  This container shows a pane on the screen and gives you a next and previous button so you can go back and forth between panes.  There's also a rich text editor control.  That should get some people's attention right there.  As cool as that is though, I don't think anything beats the grid control.  The grid is like a combination of ASP.NET's GridView and WPF's Grid.  It allows databinding like GridView, but it also allows complex row and column adjustment like the Grid.  Technically it's not part of the core of Dojo, but it's incredibly amazing.  You can see a great example of a Grid with it's code, see this example.  The code for this Grid is so simple, that you probably won't even believe your eyes.  Even still, the author of that example writes about the example here.  The Grid really is one of the most powerful controls I've ever seen in a client or server technology.  Again, can you see how Dojo is like a client-side ASP.NET?

It should go without saying at this point, but Dojo also includes various validation controls.  You can actually put an <input /> element on the screen and set dojoType="dijit.form.DateTextBox" and you get an entirely new animal that loads a calendar control when you click in the textbox.  If you prefer to type the date out by hand, the field will be validated automatically.  You can also validate against money.  Look at this example from the Dojo documentation:

<input type="text" name="income1" value="54775.53"
  dojoType="dijit.form.CurrencyTextBox"
  required="true"
  constraints="{fractional:true}"
  currency="USD"
  invalidMessage="Invalid amount.  Include dollar sign, commas, and cents." />

That's seriously detailed.  The data is validated as the user types.  If you want to validate numbers that don't represent money, you can use the NumberTextBox Dojo control (also set via the dojoType attribute).  Or, if you want more powerful validation, use a ValidationTextbox and set the regExp attribute and validate directly against a regular expression.  Your regular expression doesn't have to be inline in the regExp attribute either.  Take a look at this example from the Dojo documentation:

<input type="text" name="zip" value="00000"
  dojoType="dijit.form.ValidationTextBox"
  regExpGen="checkForFiveDigitZipCode"
  required="true"
  invalidMessage="Zip codes after 5, county name before then." />

Here you can see that the JavaScript function (checkForFiveDigitZipCode) is called for validation.  To see these examples run and to see more information on validation in Dojo see the validation page in their documentation.

At this point I think I should mention something.  As many of you know, I'm a strong standards advocate and an extremely outspoken opponent of the mere existence of Internet Explorer.  Having said that, laws exist for a purpose and, frankly, only within the bounds of that purpose.  The purpose of standards are to give us a common ground and to help us have cleaner, more professional work (my "having higher web standards" thing I'm always talking about).  In terms of web browsers, each browser needs to continually keep up with the standards.  Why?  Obviously so web developers can ship out content and not want to change their career every single time they realize that browser X, Y, or Z doesn't support a specific feature.  With this in mind, there is absolutely nothing wrong with Dojo using custom attributes on types.  Dojo is requiring new functionality, but it's also providing that functionality at the same time.  That which is requires, it provides.  This is completely legal within the bounds of the purpose of standards.  So, there is no reason for anyone to start crying about Dojo adding custom attributes.  There was a time when I was a standards extremist (~2003), going so far as to even use a custom DTD on my pages where I would use custom attributes (set via JavaScript), but I've since realized that standard extremism is practically a cult and have ran from it.  Also, and you may want to sit down for this one, I think that Dojo holds nicely to semantic web principles.  Notice we aren't creating an input and procedurally making it do validation, rather, we are creating something that is a validation box.  It's not as semantic as a <validationtextbox /> would be, if it were to exist, but as with most things, semanticism (huh?) is a continuum.  If it weren't a continuum, <input type="hidden" /> shouldn't exist or ever be used (I would argue that this does in fact have some semantic value!)  Because of this, I don't see Dojo involving itself with the evils of pragmatism.  However, Dojo would be an evil pragmatic framework with little semantic structure, if it instead tried to setup some type of configuration system by setting class names.  Can you even imagine the chaos?  I've done this before as a standards extremist and it's really nasty.

Another thing that's insanely cool about Dojo is the event system.  As we ASP.NET developers know, events aren't simply things you use on visual controls.  No, you use events to notify entities of (...drum roll please...) events.  So, you could have multiple entities monitoring a centralized entity, perhaps a service and when that centralized entity sends out an update, all the other entities immediately receive the update.  It's the observer pattern, but you may know it as the publish/subscribe model.  Normally when you think of JavaScript events you think of events in terms of visual control events just as you would with ASP.NET.  With Dojo, however your event model gets an upgrade with a publisher/subscriber model.  Here's an example for you to ponder:

<script type="text/javascript">
  function Client (name) {
    this._name = name;
dojo.subscribe(<span style="color: #a31515">'update'</span>, <span style="color: blue">this</span>, update);

<span style="color: blue">function </span>update(args) {
  console.debug(<span style="color: blue">this</span>._name + <span style="color: #a31515">': ' </span>+ args);
}
} var Server = { sendUpdates: function(message) { dojo.publish('update', [message]); } }; var clientA = new Client('Client A'); var clientB = new Client('Client B'); Server.sendUpdates('event occured!'); </script>

One thing on which I would like to warn all my .NET colleagues is this: they use Java terminology.  They fire their events whereas we like our events and think they are doing a great job so we raise them.  Personally, I've never understood that terminology, especially in systems like the web that allow for event bubbling where events are RAISED to the top.  OK, enough rant.  Before moving on though, just think about what I keep mentioning : this is like a fully fledged client-side ASP.NET.  You must surely be noticing that by now.

Dojo, of course, also gives you a XMLHttpRequest abstraction layer so that you don't need to mess with all that browser detection nonsense.  The syntax is rather similar to prototype's very intuitive syntax.  This is fortunate, because not all frameworks have a nice abstraction layer.  I've given up on trying to figure out mooTool's abstraction layer a long time ago.  It's doable, but the complexity curve is very steep.  In Dojo, however, the complexity curve is relatively flat, like prototype's.  Here's an example based on a Dojo documentation example of a simple XHR call (if you like, you can set 'json' instead of 'text' in the handleAs).  This code isn't anything fancy, but that's kind of my point:

<script type="text/javascript">
dojo.xhrGet({
  url: '/file/1.txt',
  handleAs: 'text',
  timeout: 3000,
  load: function(response, ioArgs) {
    alert(response);
    return response;
  },
  error: function(response, ioArgs) {
    console.error('Status code: ', ioArgs.xhr.status);
    return response;
  }
});
</script>

As simple as this is though, you can do much more with Dojo's abstraction layer than what I've seen in any other framework.  For example, there's actually a dojo.io.iframe object to give you the ability to do iframe-based AJAX.  Dojo also includes the dojo.rpc object, which allows for incredibly poweful RPC calls.  Gone are the days of having to choose to either create your own end-to-end communication or to completely use a flawed product.  You now have a nice middle ground for your AJAX service access. In a sense it's kind of similar to .NET remoting, in how it's not SOAP, but it's not quite sockets either.  The dojo.rpc concept is amazing quite possibly my favorite Dojo feature.  You can expect me to write more about this feature in the future.  I'm been completely taken in by this incredible feature and can see an incredible number of applications for it.  If you want to see something else wildly awesome, check out the dojo.data data access layer.  The documentation needs to be developed a bit more, but it's wild.  Whereas dojo.rpc may be similar to .NET remoting, dojo.data is kind of like WCF binding.  You just connect to a built-in or custom data store and your can bind Dojo controls directly to it!  Bind directly to your Flicker.com datastore or write your own.  For a few good examples of using this feature, check out this blog entry.

There are also features which we would kind of expect from a client-side framework like drag-n-drop support, animation support (though barely documented-- here's a PDF of an example), and DOM node selection (see dojo.query).  It also gives you control over internationalization (and unicode encoding) and the power to handle the back button in AJAX applications (of course by using the # syntax).  There's also the ability to create object-oriented class with inheritance.  One downside to this feature is that Dojo went back to the days of C++ and impossibly complex object graphing by allowing multiple inheritance.  You may want to set a corporate guideline to stop people from doing this, lest your object graphs become completely unreadable.  In any case, you also have an abstraction for arrays (to help emulate JavaScript 1.6), cookies, strings and dates.  You are also provided a mechanism for converting the data of an entire form into JSON data.

As if that weren't enough, Dojo also provides a unit testing framework called D.O.H.  You can do anything from simple asserts to full test cases, including grouping test cases.  In addition to the unit testing, Dojo allows you to send informational and debug messages to the Firebug console.  The documentation is packed with more testing samples than you will know what to do with.  Most of them are for testing the Dojo framework, but these tests use D.O.H. and give you a world of insight into the variety of things you can do with Dojo.

As far as documentation, there is more documentation for Dojo than I have seen in all the other JavaScript/AJAX frameworks combined.  The online "Book of Dojo" is incredibly long.  In fact, some may say that it's too long.  The Dojo people thought of this though and allow you to quickly get ROI from their "Dojo for the Attention-Impaired".  This page demonstrates the basic idea behind Dojo by showing a quick Hello World example.  I would recommend you do skim through this page, do the demo, then skim through the rest of the book, doing demos as you go.  One thing I should mention about the documentation is that while there is a lot of it, it's very hard to read at times.  I had to read the event system documentation numerous times before I was able to get anything from it.  This is definitely something the Dojo guys should look into.

Another thing they should look into is their use of double quotes in their JavaScript documentation.  This is something most ASP.NET AJAX books do and it really makes the code hard to read and hard to manage (do you really want to escape every single double quote in your HTML controls? ouch!)  It's makes about as much sense as using double quotes in your T-SQL code (which, yeah, would require a setting, but that's my point-- it's lame).  The Dojo documentation seems to go between various authors who either respect for the JavaScript guidelines (') or who don't even realize it exists (").  To make things worst, at times they use single quotes in their HTML!  There doesn't seem to be any consistency here.  I'm glad they didn't try to mix their code with any type of server-side work.  I don't even want to try to read double-quotes JavaScript in the midst of PHP, Java, or C# code.  That would e painful to read.  Other than these two concerns, the documentation was fairly exhaustive.  Some developers, however prefer to learn by seeing.  If you're one of those, you can check out the official Dojo demos.

In terms of deployment, you actually don't even need to install Dojo.  It's on the AOL Content Delivery Network (CDN), so you can quickly just include the Dojo entry file from their server and be done with it.  If you really want to download it to your system, you can hit up the Dojo web site and download it from there.  You could also head on over the the Dojo web site that parodies the script.aculo.us web site: dojo.moj.oe.  Also, remember that everything you need is accessible from the single Dojo entry file (often dojo.js) and that you use dojo.require( ) statements to bring in functionality at a module level, not a file level.  Therefore, the AOL CDN method should be perfect for most people.

Dojo is currently in version 1.0, however, this is an open source 1.0, not a Microsoft 1.0.  When Microsoft has an alpha, it's a preview.  When they have a beta 1, it's pretty nice.  When they have a beta 2, I'm usually using it in production.  When it's RTM as v1.0, everything breaks and I end up removing it.  Google products as well as Firefox and Dojo on the other hand are hardcore and stable when they hit 1.0.  Their idea of 1.0 is like Microsoft's idea of an SP2.  Shall I remind everyone that Gmail is STILL marked as beta after all these years??  Dojo is a stable system that have been in development and testing for an extremely long time.

Dojo really is a fascinating client-side web development framework which can bring great elegance as well as a great declarative programming model to your AJAX applications.  Furthermore, given it's rich set of controls, Dojo is absolutely perfect for web-based business applications.  Dojo is also probably one of the great technologies of all time that are destined for completely misunderstanding as a product comparable and/or equal with products that don't even come close to it.  There are people living today that still try to compare Internet Explorer with Firefox, VSS with Subversion, Gimp with Photoshop (oh yes, I went there!), the Zune (which is a media player) with the iPod Touch (which is an Internet device)and Gmail with Yahoo! Mail or Hotmail.  Compare them and you will see there is no comparison.  As I said at the beginning, this neither replaces prototype or script.aculo.us, which would be used in more minimal environments.  Dojo is a different framework to be used when a project has different requirements.  Besides, you should never choose one tool as your end all be all for everything.  That's a naive way of thinking, unless you actually think it wise to cut your bread with a butter knife or spread your butter with a bread knife.  Rarely are things in life one-side-fits-all.  Frameworks are free; use them, but use them wisely.  Hopefully many of you will seriously consider using Dojo in your current or future AJAX and ASP.NET projects.

Links

March 2008 Web Technology Update



Recently a bunch of technologies have been released and/or updated and I would like to mention a few of them briefly.

First and foremost, Silverlight 2 Beta 1 has finally been released and you may download it immediately.  There is also an accompanying SDK.  You can find a nice development tutorial series on Scott Guthrie's blog.  If you are already familiar with WPF, you can just skim this entire series in less than 5 minutes.  Given that this technology isn't the same as the full WPF and given that it's designed for the web, there will obviously be differences.  It's important to remember that Silverlight 2 isn't simply WPF for the web.  I would call WPF 3.5's XBAP support for IE/Firefox "WPF for the web".  No, this is possibly the biggest web technology improvement since the release of Firefox 1.0, which in turn was the biggest technology release since the printing press.  Alight, alight… since .NET 1.1.  It's support for the dynamic language runtime is going to completely revolutionize our web development.

When reading through Scott's tutorial series (serious, at least skim it), it's interesting to note that Silverlight 2 allows cross-domain communication.  It does this by reusing the Flash communication policy files.  This is really awesome as it means that you can start accessing resources that Flash has been using for a while.  Being able to dynamically access resources from different domains is critical to the success of web architecture in the future.

Speaking of cross-domain communication, John Resig and I received a very depressing e-mail the other day telling us horrible news: cross-domain communication will probably be removed from Firefox 3 before it's official release.  Apparently a bunch of paranoid anti-architects were complaining about the dreaded evils of being able to access resources from different domains.  Um ok.  Fortunately, however, Firefox 3 has a feature called postMessage that allows you to get around this.  Malte Ubl has produced a library called xssinterface to demonstrate just this concept.  You could, of course, get around this completely with some iframe hacks or some other scripting magic.

Speaking of web browsers, I would like to bring people's attention to a technology that I've been following for some time now: Apple WebKit.  This is basically the brains inside Safari.  I absolutely love the Safari web browser.  It's by far and away the easiest web browser to use.  It also has the same keyboard short-cuts as Firefox, which is how I'm able to use it.  It's also incredibly fast, but I should mention that it uses even more memory than Firefox.  My last instance passed 500MB.  Given it's lack of an extension or configuration (i.e. about:config) system, it's obviously no where near the same caliber as Firefox though.  It is, however, my primary web browser as has been since October '07.

The reason I mention WebKit is because as very few people know, this is an open source project and has nightly binaries released on their webkit.org web site.  One of the most interesting thing about nightlies that you can actually watch the progress of development as time goes on.  About every month or so I like to get the latest Firefox nightly.  It's always interesting to see the major experiments that the developers try about 2 months after a major release of Firefox.  There's always some really awesome "teaser" feature in there that later grows into a fully grown technology.  The same can be said for WebKit.

None of that is, however, my primary reason for mentioning WebKit.  As, most web developers know, the Acid2 test has been the standard for checking a web browsers compatibility with the CSS standard.  I've been pushing this test for a long time, but I've never pushed it as the only test.  There are many things that a web browser must do and many features a web browser must have before it can be considered appropriate for use.  Merely focusing on CSS, while completely ignoring DOM support, JavaScript, and general user usability can lead a browser to be as impossible to use as Opera 9.

As I've said time and time again, I'm not a CSS specialist.  Part of the definition of being a professional web develop is that I have a solid understand of the inner workings of CSS including specificity, the various selectors, and how to merge absolute, floating, and relative position on the same elements, tasks "coders" see as nearly impossible to learn.  However, my focus is on AJAX interaction as seen from the JavaScript and DOM worlds.  Therefore, we need to have a test for browsers that goes beyond the simple Acid 2 test for CSS.  I'm not the only one thinking this way, because recently the Acid3 test was published and it tests CSS, JavaScript and DOM support.  This is the new standard for web browsers.

So far no web browser has even gotten close, with the lowest score from a web browser being 39% in Safari to the best score being 50% in Firefox 2.0.0.12.  However, in terms of non-released software, Firefox 3.0b3 has a score between 59% and 61%, depending on its mood (update: b4 is steady at 67%) and the latest WebKit nighty has a score is 90% (watch WebKit progress on Acid 3 at http://bugs.webkit.org/show_bug.cgi?id=17064).  That's phenomenal!  The newly released Internet Explorer 8 beta 1 has a score of 17%.  Those of you who have naively praising the IE team for being YEARS late on getting near the Acid 2 test need to wake up and realize this is 2008.  Time moves-- keep up.  Firefox has been close for the longest time and has always had the next-gen's next-gen JavaScript and DOM support, but has only recently completely passed the finish line of the Acid 2 test.  So, they are finally off my watch list there, but I will not stop bugging them until they pass the Acid 3 test.

For more information on the Acid 3 test, see John Resig's most entitled "Acid 3 tackes EMCAScript".  He's about as passionate as I am for web standards and Firefox and his blog is an invaluable resource for all things JavaScript.  His work is so good that I would like to take the time to plug his book he is currently writing: Secrets of the JavaScript Ninja.  I absolutely guarantee you that this book will redefine the entire world of JavaScript and will raise the bar incredibly out of the reach of "coders". To all of you coders who think you know JavaScript, do a view-source on the Acid 3 source code (you may want to bring a change of underwear with you).

Lastly, it's not necessarily a "new" technology, but it's so incredibly phenomenal that I need to mention it: Prototype 1.6.  It's amazing to me that people actually go out of their way to use ASP.NET AJAX 3.5 (I still find the ICallbackEventHandler interface more productive).  ASP.NET AJAX 3.5 is not nearly as bad as extremists think, but the design is still flawed.  Prototype on the other hand is absolutely incredible.  I've written about Prototype before, but this version 1.6 is even more powerful.  There a A LOT of changes from Prototype 1.5.  It's so good that I no longer call it "prototype/script.aculo.us".  Script.aculo.us is a great animation system, but, honestly, the main reason I used it was for the DOM abstraction in the Builder object.  Prototype now has an Element object to help create DOM objects, thus allowing me to remove Script.aculo.us from most of my projects (it's not as complete as the Builder object, but it allows object chaining-- which greatly increases code readability, conciseness and understanding!).  The Template object is also amazing as it gives you the ability to go far beyond simple String.Format formatting.  The new Class object for OOP is also great.  It's so much easier to use than Prototype 1.5.  Also, being able to hide all elements with a particular CSS pattern with one shot is very useful! (for example, $$('div span .cell-block').invoke('hide')).  It even allows you to use CSS 3 selectors on the most dead of web browsers.  It really makes developing for Internet Explorer 6 and 7 bearable!  Even if I have to use ASP.NET AJAX 3.5, I'll still including prototype.js.  If you do anything with JavaScript, you need Prototype!

 

Links

Cross-Browser JavaScript Tracing



No matter what system you are working with, you always need mechanisms for debugging.  One of the most important mechanisms a person can have is tracing.  Being able to see trace output from various places in your application is vital.  This is especially true with JavaScript.  I've been working with JavaScript since 1995, making stuff 12 years ago that would still be interesting today (in fact, I didn't know server-side development existed until 1998!) and I have noticed a clear correlation between the complexity of JavaScript applications and the absolute need for tracing.

Thus, a long, long time ago I built a tracing utility that would help me view all the information I need (and absolute no more or less).  These days this means being able to trace information to a console, dump arrays and objects, and be able to view line-numbered information for future reference.  The utility I've created has since been added to my Themelia suite (pronounces the-meh-LEEUH; as in thistle or the name Thelma), but today I would like to demonstrate it and deliver it separately.

The basis of my tracing utility is the Themelia.Trace namespace.  In this namespace is…. wait… what?  You're sick of listening to me talk?  Fine.  Here's the sample code which demonstrates the primary uses of Themelia.Trace, treat this as your reference documentation:

//+ enables tracing
Themelia.Trace.enable( );
//+ writes text
Themelia.Trace.write('Hello World!');
//+ writes a blank line
Themelia.Trace.addNewLine( );
//+ writes a numbered line
Themelia.Trace.writeLine('…and Hello World again!');
Themelia.Trace.writeLine('Another line…');
Themelia.Trace.writeLine('Yet another…');
Themelia.Trace.writeLine('One more…');
//+
//++ label
//+ writes labeled data to putput (e.g. 'variableName (2)')
Themelia.Trace.writeLabeledLine('variableName', 2);
//+
//++ buffer
//+ creates a buffer
var buffer = new Themelia.Trace.Buffer( );
//+ declares beginning of new segment
buffer.beginSegment('Sample');
//+ writes data under specific segment
buffer.write('data here');
//+ nested segment
buffer.beginSegment('Array Data');
//+ write array to buffer
var a = [1,2,3,4,5];
buffer.write(a);
//+ declares end of segment
buffer.endSegment('Array Data');
buffer.beginSegment('Object Data');
//+ write raw object/JSON data
buffer.write({
    color: '#0000ee',
    fontSize: '1.1em',
    fontWeight: 'bold'
});
buffer.endSegment('Object Data');
//+ same thing again
buffer.beginSegment('Another Object');
var o = {
    'personId': 2,
    name: 'david'
};
buffer.write(o);
buffer.endSegment('Another Object');
buffer.endSegment('Sample');
//+ writes all built-up data to output
buffer.flush( );

Notice a few thing about this reference sample:

  • First, you must use Themelia.Trace.enable( ) to turn tracing on.  In a production application, you would just comment this line out.
  • Second, Themelia.Trace.writeLine prefixes each line with a line number.  This is especially helpful when dealing with all kinds of async stuff floating around or when dealing with crazy events.
  • Third, you may use Themelia.Trace.writeLabeledLine to output data while giving it a name like "variableName (2)".
  • Fourth, if you want to run a tracer through your application and only later on have output, create an instance of Themelia.Trace.Buffer, write text to it, write an array to it, or write an object to it, then call flush( ) to send to data to output.  You may also use beginSegment and endSegment to create nested, indented portion of the output.
  • Fifth, notice you can throw entire arrays of objects/JSON into buffer.write( ) to write it to the screen.  This is especially handy when you want to trace your WCF JSON messages.

Trace to what?

Not everyone knows this, but Firefox, Google Chrome, Safari, and Opera each has its own console for allowing output.  Themelia.Trace works with each console in its own way.  Here are some screen shots to show you what I mean:

Firefox

Firefox since version 1.0 has the Firefox Console which allows you to write just about anything to a separate window.  I've done a video on this many years ago and last year I posted a quick "did you know"-style blog post on it, so there's no reason for me to cover it again here.  Just watch my Introduction to the Firefox Console for a detailed explanation of using the Firefox Console (you may also opt to watch my Setting up your Firefox Development Environment-- it should seriously help you out).

Firefox

Google Chrome

Chrome does things a little different than any other browser.  Instead of having a "browser" wide console, each tab has its own console.  Notice "browser" is in quotes.  Technically, each tab in Chrome is it's own mini browser, so this console-per-tab model makes perfect sense.  To access this console, just hit Alt-` on a specific tab.

Chrome

Safari

In Safari, you go to Preferences, in the Advanced Tab to check "Show Develop menu in menu bar".  When you do this, you will see the Develop menu show up.  The output console is at Develop -> Show Web Inspector.

Safari

Opera

In Opera 9, you go to Tools -> Advanced -> Developer Tools and you will see a big box show up at the bottom.  The console is the Error Console tab.

Opera9

Internet Explorer

To use Themelia.Trace with Internet Explorer, install Nikhil's Web Developer Helper.  This is different from the IE Developer Toolbar.

IEWebDevHelper

Firebug

It's important to note that, in many situations it's actually more effective to rely on Firebug for Firefox or Firebug lite for Safari/Chrome, IE, and Opera, then to use a console directly.  Therefore, Themelia.Trace allows you to set Themelia.Trace.alwaysUseFirebug to true and have all output redirected to Firebug instead of the default console.  Just try it, use the above sample, but put "Themelia.Trace.alwaysUseFirebug = true;" above it.  All data will redirect to Firebug.  Here's a screen shot (this looks basically the same in all browsers):

FirebugLite

There you have it.  A cross-browser solution to JavaScript tracing.

Links

Love Sudoku? Love brain puzzles? Check out my new world-wide Sudoku competition web site, currently in beta, at Sudokian.com.

kick it on DotNetKicks.com

Creating JavaScript Components and ASP.NET Controls



Every now and again I'll actually meet someone who realizes that you don't need a JavaScript framework to make full-scale AJAX applications happen… but rarely in the Microsoft community.  Most people think you need Prototype, jQuery, or ASP.NET AJAX framework in order to do anything from networking calls, DOM building, or component creation.  Obviously this isn't true.  In fact, when I designed the Brainbench AJAX exam, I specific designed it to test how effectively you can create your own full-scale JavaScript framework (now how well the AJAX developer did on following my design, I have no idea).

So, today I would like to show you how you can create your own strongly-typed ASP.NET-based JavaScript component without requiring a full framework.  Why would you not have Prototype or jQuery on your web site?  Well, you wouldn't.  Even Microsoft-oriented AJAX experts recognizes that jQuery provides an absolutely incredible boost to their applications.  However, when it comes to my primary landing page, I need that to be extremely tiny.  Thus, I rarely include jQuery or Prototype on that page (remember, Google makes EVERY page a landing page, but I mean the PRIMARY landing page.)

JavaScript Component

First, let's create the JavaScript component.  When dealing with JavaScript, if you can't do it without ASP.NET, don't try it in ASP.NET.  You only use ASP.NET to help package the component and make it strongly-typed.  If the implementation doesn't work, then you have more important things to focus on.

Generally speaking, here's the template I follow for any JavaScript component:

window.MyNamespace = window.MyNamespace || {};
//+
//- MyComponent -//
MyNamespace.MyComponent = (function( ) {
    //- ctor -//
    function ctor(init) {
        if (init) {
            //+ validate and save DOM host
            if (init.host) {
                this.host = init.host;
                //+
                this.DOMElement = $(this.host);
                if(!this.DOMElement) {
                    throw 'Element with id of ' + this.host + ' is required.';
                }
            }
            else {
                throw 'host is required.';
            }
            //+ validate and save parameters
            if (init.myParameter) {
                this.myParameter = init.myParameter;
            }
            else {
                throw 'myParameter is required.';
            }
        }
    }
    ctor.prototype = {
        //- myfunction -//
        myfunction: function(t) {
        }
    };
    //+
    return ctor;
})( );

You may then create the component like the following anywhere in your page:

new MyNamespace.MyComponent({
    host: 'hostName',
    myParameter: 'stuff here'
 });

Now on to see a sample component, but, first, take note of the following shortcuts, which allow us to save a lot of typing:

var DOM = document;
var $ = function(id) { return document.getElementById(id); };

Here's a sample Label component:

window.Controls = window.Controls || {};
//+
//- Controls -//
Controls.Label = (function( ) {
    //- ctor -//
    function ctor(init) {
        if (init) {
            //+ validate and save DOM host
            if (init.host) {
                this._host = init.host;
                //+
                this.DOMElement = $(this._host);
                if(!this.DOMElement) {
                    throw 'Element with id of ' + this._host + ' is required.';
                }
            }
            else {
                throw 'host is required.';
            }
            //+ validate and save parameters
            if (init.initialText) {
                this._initialText = init.initialText;
            }
            else {
                throw 'initialText is required.';
            }
        }
        //+
        this.setText(this._initialText);
    }
    ctor.prototype = {
        //- myfunction -//
        setText: function(text) {
            if(this.DOMElement.firstChild) {
                this.DOMElement.removeChild(this.DOMElement.firstChild);
            }
            this.DOMElement.appendChild(DOM.createTextNode(text));
        }
    };
    //+
    return ctor;
})( );

With the above JavaScript code and "<div id="host"></div>" somewhere in the HTML, we can use the following to create an instance of a label:

window.lblText = new Controls.Label({
    host: 'host',
    initialText: 'Hello World'
});

Now, if we had a button on the screen, we could handle it's click event, and use that to set the text of the button, as follows:

<div>
    <div id="host"></div>
    <input id="btnChangeText" type="button" value="Change Value" />
</div>
<script type="text/javascript" src="Component.js"></script>
<script type="text/javascript">
    //+ in reality you would use the dom ready event, but this is quicker for now
    window.onload = function( ){
        window.lblText = new Controls.Label({
            host: 'host',
            initialText: 'Hello World'
        });
         window.btnChangeText = $('btnChangeText');
         //+ in reality you would use a muli-cast event
         btnChangeText.onclick = function( ) {
            lblText.setText('This is the new text');
         };
    };
</script>

Thus, components are simple to work with.  You can do this with anything from a simple label to a windowing system to a marquee to any full-scale custom solution.

ASP.NET Control

Once the component works, you may then package the HTML and strongly-type it for ASP.NET.  The steps to doing this are very simple and once you do it, you can just repeat the simple steps (some times with a simple copy/paste) to make more components.

First, we need to create a .NET class library and add the System.Web assembly.   Next, add the JavaScript component to the .NET class library.

Next, in order to make the JavaScript file usable my your class library, you need to make sure it's set as an Embedded Resource.  In Visual Studio 2008, you do this by going to the properties window of the JavaScript file and changing the Build Action to Embedded Resource.

Then, you need to bridge the gap between the ASP.NET and JavaScript world by registering the JavaScript file as a web resource.  To do this you register an assembly-level WebResource attribute with the location and content type of your resource.  This is typically done in AssemblyInfo.cs.  The attribute pattern looks like this:

[assembly: System.Web.UI.WebResource("AssemblyName.FolderPath.FileName", "ContentType")]

Thus, if I were registering a JavaScript file named Label.js in the JavaScript.Controls assembly, under the _Resource/Controls folder, I would register my file like this:

[assembly: System.Web.UI.WebResource("JavaScript.Controls._Resource.Label.js", "text/javascript")]

Now, it's time to create a strongly-typed ASP.NET control.  This is done by creating a class which inherits from the System.Web.UI.Control class.  Every control in ASP.NET, from the TextBlock to the GridView, inherits from this base class.

When creating this control, we want to remember that our JavaScript control contains two required parameters: host and initialText.  Thus, we need to add these to our control as properties and validate these on the ASP.NET side of things.

Regardless of your control though, you need to tell ASP.NET what files you would like to send to the client.  This is done with the Page.ClientScript.RegisterClientScriptResource method, which accepts a type and the name of the resource.  Most of the time, the type parameter will just be the type of your control.  The name of the resource must match the web resource name you registered in AssemblyInfo.  This registration is typically done in the OnPreRender method of the control.

The last thing you need to do with the control is the most obvious: do something.  In our case, we need to write the client-side initialization code to the client.

Here's our complete control:

using System;
//+
namespace JavaScript.Controls
{
    public class Label : System.Web.UI.Control
    {
        internal static Type _Type = typeof(Label);


        //+
        //- @HostName -//
        public String HostName { get; set; }


        //- @InitialText -//
        public String InitialText { get; set; }


        //+
        //- @OnPreRender -//
        protected override void OnPreRender(EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptResource(_Type, "JavaScript.Controls._Resource.Label.js");
            //+
            base.OnPreRender(e);
        }


        //- @Render -//
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (String.IsNullOrEmpty(HostName))
            {
                throw new InvalidOperationException("HostName must be set");
            }
            if (String.IsNullOrEmpty(InitialText))
            {
                throw new InvalidOperationException("InitialText must be set");
            }
            writer.Write(@"
<script type=""text/javascript"">
(function( ) {
    var onLoad = function( ) {
        window." + ID + @" = new Controls.Label({
            host: '" + HostName + @"',
            initialText: '" + InitialText + @"'
        });
    };
    if (window.addEventListener) {
        window.addEventListener('load', onLoad, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onload', onLoad);
    }
})( );
</script>
");
            //+
            base.Render(writer);
        }
    }
}

The code written to the client may looks kind of crazy, but that's because it's written very carefully.  First, notice it's wrapped in a script tag.  This is required.  Next, notice all the code is wrapped in a (function( ) { }) ( ) block.  This is a JavaScript containment technique.  It basically means that anything defined in it exists only for the time of execution.  In this case it means that the onLoad variable exists inside the function and only inside the function, thus will never conflict outside of it.  Next, notice I'm attaching the onLoad logic to the window.load event.  This isn't technically the correct way to do it, but it's the way that requires the least code and is only there for the sake of the example.  Ideally, we would write (or use a prewritten one) some sort of event handler which would allow us to bind handlers to events without having to check if we are using the lameness known as Internet Explorer (it uses window.attachEvent while real web browsers use addEventListener).

Now, having this control, we can then compile our assembly, add a reference to our web site, and register the control with our page or our web site.  Since this is a "Controls" namespace, it has the feel that it will contains multiple controls, thus it's best to register it in web.config for the entire web site to use.  Here's how this is done:

<configuration>
  <system.web>
    <pages>
      <controls>
        <add tagPrefix="c" assembly="JavaScript.Controls" namespace="JavaScript.Controls" />
      </controls>
    </pages>
  </system.web>
</configuration>

Now we are able to use the control in any page on our web site:

<c:Label id="lblText" runat="server" HostName="host" InitialText="Hello World" />

As mentioned previously, this same technique for creating, packaging and strongly-typing JavaScript components can be used for anything.  Having said that, this example that I have just provided borders the raw definition of useless.  No one cares about a stupid host-controlled label.

If you don't want a host-model, but prefer the in-place model, you need to change a few things.  After the changes, you'll have a template for creating any in-place control.

First, remove anything referencing a "host".  This includes client-side validation as well as server-side validation and the Control's HostName property.

Next, put an ID on the script tag.  This ID will be the ClientID suffixed with "ScriptHost" (or whatever you want).  Then, you need to inform the JavaScript control of the ClientID.

Your ASP.NET control should basically look something like this:

using System;
//+
namespace JavaScript.Controls
{
    public class Label : System.Web.UI.Control
    {
        internal static Type _Type = typeof(Label);


        //+
        //- @InitialText -//
        public String InitialText { get; set; }


        //+
        //- @OnPreRender -//
        protected override void OnPreRender(EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptResource(_Type, "JavaScript.Controls._Resource.Label.js");
            //+
            base.OnPreRender(e);
        }


        //- @Render -//
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (String.IsNullOrEmpty(InitialText))
            {
                throw new InvalidOperationException("InitialText must be set");
            }
            writer.Write(@"
<script type=""text/javascript"" id=""" + this.ClientID + @"ScriptHost"">
(function( ) {
    var onLoad = function( ) {
        window." + ID + @" = new Controls.Label({
            id: '" + this.ClientID + @"',
            initialText: '" + InitialText + @"'
        });
    };
    if (window.addEventListener) {
        window.addEventListener('load', onLoad, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onload', onLoad);
    }
})( );
</script>
");
            //+
            base.Render(writer);
        }
    }
}

Now you just need to make sure the JavaScript control knows that it needs to place itself where it has been declared.  To do this, you just create a new element and insert it into the browser DOM immediately before the current script block.  Since we gave the script block and ID, this is simple.  Here's basically what your JavaScript should look like:

window.Controls = window.Controls || {};
//+
//- Controls -//
Controls.Label = (function( ) {
    //- ctor -//
    function ctor(init) {
        if (init) {
            if (init.id) {
                this._id = init.id;
                //+
                this.DOMElement = DOM.createElement('span');
                this.DOMElement.setAttribute('id', this._id);
            }
            else {
                throw 'id is required.';
            }
            //+ validate and save parameters
            if (init.initialText) {
                this._initialText = init.initialText;
            }
            else {
                throw 'initialText is required.';
            }
        }
        //+
        var scriptHost = $(this._id + 'ScriptHost');
        scriptHost.parentNode.insertBefore(this.DOMElement, scriptHost);
        this.setText(init.initialText);
    }
    ctor.prototype = {
        //- setText -//
        setText: function(text) {
            if(this.DOMElement.firstChild) {
                this.DOMElement.removeChild(this.DOMElement.firstChild);
            }
            this.DOMElement.appendChild(DOM.createTextNode(text));
        }
    };
    //+
    return ctor;
})( );

Notice that the JavaScript control constructor creates a span with the specified ID, grabs a reference to the script host, inserts the element immediately before the script host, then sets the text.

Of course, now that we have made these changes, you can just throw something like the following into your page and to use your in-place JavaScript control without ASP.NET.  It would look something like this:

<script type="text/javascript" id="lblTextScriptHost">
    window.lblText = new Controls.Label({
        id: 'lblText',
        initialText: 'Hello World'
    });
</script>

So, you can create your own JavaScript components without requiring jQuery or Prototype dependencies, but, if you are using jQuery or Prototype (and you should be!; even if you are using ASP.NET AJAX-- that's not a full JavaScript framework), then you can use this same ASP.NET control technique to package all your controls.

kick it on DotNetKicks.com