At the end of the day yesterday one of my peers at my client came over and asked me how to randomly select an item from a SharePoint List. She was retrieving the list using jQuery and only wanted to display one item from the list, but she wanted that item to be random each time the page was loaded. She felt it would ultimately be the simplest solution to do this on the client, and I agreed. Our problem really came down to our personal limits using JavaScript, neither of us had done anything with random yet. I knew there had to be some pseudo-random number generator available, I have not met a modern language that does not have something to offer random yet.
Turns out JavaScript does have a random function that is a member of the Math object. I looked at a few uses of this function and decided using it with Math.floor() would produce the result we were after.
First, Math.random produces a ‘random’ value between 0 and 1. But we needed to randomly select an array item, which would be an integer index between 0 and the length –1. So multiplying the random result by the array’s length will almost produce the index value desired. Passing the value to the Math.floor method will round the result down to the closest integer value. Now we have a ‘random’ integer value that can be reliably used to select an item from the array of items. The following code is an example of how to test this methodology:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
var temp = ['1', '2', '3', '4', '5', '6'];
$("#container").html((temp[get_random(temp.length)]));
});
function get_random(max) {
if (undefined === max) {
max = 5;
}
var ranNum = Math.floor(Math.random() * max);
return ranNum;
}
</script>
So back to the original problem. My co-worker is retrieving a SharePoint list from the web service APIs. This list should be represented as an array of object literals (assuming it is not a simple list of strings) in JavaScript. So instead of an array of strings she will be selecting an object literal and displaying values from that object. I am sorry I don’t have a full blown demo of deserializing a SharePoint list, but if you refer to my recent post on
using jQuery to communicate with WCF services you can see how to consume a list of objects in the example to retrieve a list of active contacts from the server.
Now that I have covered the basics of calling a WCF service using jQuery’s AJAX functionality with JSON its time to deal with bugs. Yep, we all create them and have to troubleshoot them on a daily basis. Even if you are not actually coding the WCF service you need to know how to deal with any exception that may be bubbled back to the client when you call a service API method.
If you remember there were a few items I referenced in the previous post on the jQuery side of this transaction to deal with errors. The first is a DIV element to hold any error messages you may want to display to the user called AJAXError. In the jQuery Ready method I told this element to response to the global ajaxError event handler by displaying some diagnostic information to the user.
$("#AJAXError").ajaxError(function(event, request, settings) {
$(this).append("Error requesting page " +
(settings.url) ? settings.url : '' + "<br/>http Status Code: " +
(request.status) ? request.status : '' + "<br/>http Status:" +
(request.statusText) ? request.statusText : '');
});Now in production I do not recommend displaying a message like this to the end user. I will discuss ways to handle this more gracefully later.
The next item included in the sample code is a generic OnPageError method that is executed in the .ajax error callback method. You can either call this directly or inside a more custom error handler. I want to point out there are three parameters it processes, one for the XMLHttpRequest object, the is a string that describes the error and finally an exception object if any.
The following code snippet shows a basic error processing event handler. The showErrorMsg method in this example is designed to display an appropriate message to the user. But in reality the OnPageError method should be much more complex to process all sorts of scenarios
function OnPageError(xhr, errorMsg, thrown) {
if (typeof xhr == "string") {
showErrorMsg(xhr);
return;
}else if (typeof (xhr.responseText) == "string" && xhr.responseText != "")
{
showErrorMsg(xhr.responseText);
} else {
showErrorMsg("Unknown error occurred in callback.");
}
}An example of a custom error callback that eventually calls the OnPageError method is below, it closes the processing message to make the page available again. You may need to clean up some things depending on your needs like the example below. This is why I like creating a custom callback method instead of passing the OnPageError method directly. Click the image below to see the detail of the XMLHttpRequest object when a typical exception is thrown.

One thing you need to realize is JavaScript is very flexible and when an error is thrown in the AJAX process you may not get all these parameters, it might just be the errorMsg parameter or the thrown (exception object) parameter. This is why you need to build out an even more robust routine to process the parameters. A more robust method would process an exception object. If an exception is bubbled up through the WCF service it will be serialized, in our example it will be a JSON object. This means we can parse the exception object and handle it more gracefully.
function OnPageError(xhr, errorMsg, thrown) {
if (typeof xhr == "string") {
showErrorMsg(xhr);
return;
}
else if (typeof (xhr.responseText) == "string" && xhr.responseText != "") {
var err = JSON2.parse(xhr.responseText);
switch (err.ExceptionType) {
case 'System.Exception':
showErrorMsg(err.Message);
return;
default:
showErrorMsg(xhr.responseText);
return;
}
} else {
showErrorMsg("Unknown error occurred in callback.");
}
}
Since it is a JSON object you can simply use the JSON2.parse method to hydrate the object and then process it as if it were on the in the .NET code you are use to working with.
error: function(xhr, errorMsg, thrown) {
$.unblockUI();
OnPageError(xhr, errorMsg, thrown);
}
Great now you can gracefully handle exceptions for the user, what should you do now to figure out the bug and squash it? First realize an exception could be thrown in one of two places; the client or the server (inside the web service). The first order of business is to determine what side of the request the issue resides.
The first place to look is the Http Status code sent from the server. If you have a 500 value it was the server. If you don’t have a value or it is 200 or another non 500 series value the odds are it is in the client code. I make a lot of typos when I am typing from scratch, so those have gotten me quite a bit in my learning process. Often it was simply an improper case since JavaScript is very strict when it comes to casing. So knowing if it is in the service or the JavaScript is real important to solve the issue.
I primarily work in Internet Explorer, so the first place I tend to look is the development tools and take advantage of the fantastic debugging facilities built into the browser. I reviewed these techniques in a previous post. If you are working in FireFox Firebug is your friend. Other browsers may their own idiosyncrasies, so you may need to look into the debugging tools for that specific browser if you get real desperate.
Another tool I use to track down errors or just unexpected behavior with AJAX is Fiddler. Remember when working against the localhost you must place a period before the port directive in the URL like this: http://localhost.:23168/errorDemo.aspx. The Fiddler Inspectors tab gives you keen insight to see the exact messages being passed back and forth between the browser and the server.
Finally you can always set break points both in the JavaScript and your server-side code in Visual Studio and step through your code.
Above I show a basic OnPageError event handler, the sample application has a page that deliberately creates an exception in the AJAX call. The service method just throws a new Exception with a custom message, nothing fancy for the demo. The error callback is invoked by the JQuery ajax method. It passes an instance of the XHttpRequest object, an error message and if it was thrown.
function BlowUp() {
wjBlockUI();
ContactServiceProxy.invoke({ serviceMethod: "BadMethod",
callback: function(response) { ProcessBlowReturn(response) },
error: function(xhr, errorMsg, thrown) {
HandlerBlowUpError(xhr, errorMsg, thrown) }
});
}So I hope you have a little more insight into how to troubleshoot errors you may be having in your AJAX development. If you have other suggestions I invite you to share them in the comments.
Yesterday’s post reviewed how to setup a WCF web service to work with JSON from top to bottom. Today I am going to review what needs to be done to use JQuery to work with those WCF end points. If you have not already done so please download the example code so you can really follow along. This demonstration shows a simple web site with a contact form, an admin type page to display a list of contacts and a full contact upon selection. It also contains a page to demonstrate how exceptions can be handled. The exception page will be explained in a future post.
Lets get right to it by opening the ContactUs.js file. At the very top there is a ContactInfo object defined. The members of this object match the members of the corresponding ContactInfo class in the class library we reviewed yesterday. The default value for each member is also define to an empty string.
var ContactInfo = {
FirstName: '',
LastName: '',
Address1: '',
Address2: '',
City: '',
State: '',
PostalCode: '',
Business: '',
PhoneNumber: '',
EMail: '',
Comment: ''
}
The reason I defined this object at the top and on a ‘global’ scope is because it will be used in multiple functions later and I do not want to repeat the code over and over.
Before I go any further in the file I want to point out the dependant files for this script to actually function. First I decided to use the latest JQuery 1.4 library. It was just released and I felt this would be a great opportunity to test it out. All the code should work with the previous release to my knowledge. I am not doing anything in this script that has not worked with v 1.3.x in the past.
The next important dependency is the JSON2.js library created by Douglas Crockford and modified by Rick Strahl. It makes working with JSON objects a breeze in JavaScript. A quick side-bar here; Internet Explorer 8 and the latest version of FireFox have native JSON serialization built into their JavaScript engines. Unfortunately I do not like to be locked into the browser specific things like that so I rely on the JSON2 library. In the future, once all the relevant browsers have this ability we will probably change, but I bet we will need an abstraction layer even then.
Rick updated the original JSON library create by Crockford to handle odd date formatting issues created by MS AJAX library.
Other JQuery plugins include the BlockIU, to display Please Wait messages, and the validation and masked input. I have review the latter two last year.
I am going to skip around the ContactUs.js file for now, so bear with me. First the Ready function, it defines some basic setup functionality like input masks, table striping and default buttons etc. Below that it defines some behavior to display some stock messages for global JQuery AJAX events.
The ajaxError event handler gives you the ability to ‘hook’ into the pipeline to define your own actions to take when an exception is thrown by the server or any other instance where there is an Http Status code of 500 generated by the server or a request timeout occurs. For this demonstration I have simply created a DIV to hold these error messages.
$("#AJAXError").ajaxError(function(event, request, settings) {
$(this).append("Error requesting page " + (settings.url) ?
settings.url : '' + "<br/>http Status Code: " +
(request.status) ? request.status : '' + "<br/>http Status: "
+ (request.statusText) ? request.statusText : '');
});
var ajaxLog = $("#ajaxLog");
ajaxLog.ajaxStart(function(evt, request, settings) {
var dt = new Date();
$(this).append("<br/><hr/>Starting request... " + dt.toLocaleString());
});
ajaxLog.ajaxComplete(function() {
var dt = new Date();
$(this).append('<br/>Triggered ajaxComplete handler.' + dt.toLocaleString());
});
ajaxLog.ajaxSuccess(function() {
var dt = new Date();
$(this).append('<br/>Triggered ajaxSuccess handler.' + dt.toLocaleString());
});
I also added an ‘ajaxlog’ DIV to the site’s master page. The code above builds a log of when an AJAX request is initiated, completed and successful. This is done with a simple timestamp.
<div id='container'>
<div id="AJAXError" class="Error-Message-Area">
</div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<br />
<hr />
<div id="ajaxLog">
</div>
</div>

Now scroll down almost to the bottom of the ContactUs.js file till you find the object definition for serviceProxy. I am going to defer a detailed explanation of how this object functions to Rick Strahl since he has already written about the serviceProxy helper object. I did enhance it a little by allowing you to pass in a set of options and defaults to define how an AJAX call is made.
// *** Call a wrapped object
this.invoke = function(options) {
// Default settings
var settings = {
serviceMethod: '',
data: null,
callback: null,
error: null,
type: "POST",
processData: false,
contentType: "application/json",
timeout: 10, //Not Preferable, but needed for now.
dataType: "text",
bare: false
};
if (options) {
$.extend(settings, options);
}
This makes the invoke method more flexible by letting you define custom settings depending on your needs. In my case I realized the application I was working on had some non-optimized methods that were causing timeouts the first time they were run. Instead of wasting time chasing these issues on the client end I decided to extend the timeout setting to 2 minutes (I know super long, but it was needed). Normally I would set this value to 10 seconds or less. So as I add new method calls I set the value appropriately.
Before I go on you may be wondering why Rick chose to create a serviceProxy object instead of just calling the JQuery.ajax method directly. Well by creating an object you only have to create one instance of the object and it can retain common variables during the lifetime of the page. This especially comes in handy when you are calling more than one service on a page.
There are really two members of the serviceProxy object you need to be aware of; the ServiceURL value and the invoke function. The ServiceURL value is the URL to the WCF service you are calling.
var ContactServiceURL = "ContactUs.svc/";
var ContactServiceProxy = new serviceProxy(ContactServiceURL);
The invoke method, which I showed the top part above, actually makes the AJAX call based on the options you passed to the method. The $.ajax() success option is a callback function that is executed when the service responds to the client. In the case of serviceProxy a function is executed. It does some error checking before it executes the actual callback method you may have defined in your options. It calls the JSON2 parse function to deserialize a JavaScript object and passes the object to your custom callback.
success:
function(res) {
if (!settings.callback) { return; }
// *** Use json library so we can fix up MS AJAX dates
var result = JSON2.parse(res);
if (result.ExceptionDetail) {
OnPageError(result.Message);
return;
}
// *** Bare message IS result
if (settings.bare)
{ settings.callback(result); return; }
// *** Wrapped message contains top level object node
// *** strip it off
for (var property in result) {
settings.callback(result[property]);
break;
}
}
Below is a code snippet from the example code where the serviceProxy invoke method is called to retrieve a ContactInfo object. Three parameters are set in the call, serviceMethod, data and callback. If you do not need to pass an object to the service, for example GetActiveContacts the data does not need to be set. The serviceMethod value should be set because it is the name of the method being called, otherwise you will not get the response you expect.
ContactServiceProxy.invoke({ serviceMethod: "GetContact",
data: { request: request },
callback: function(response) {
...//Do Work Here
}
The next key thing I need to discuss is how to deal with the data once you have received it on the client. This is where John Resig’s parseTemplate function comes in real handy. I found it looking around for templating solutions and sort of fell into a chain of three Blog posts by Stephen Walther –> Rick Strahl –> John Resig.
The parseTemplate plugin/function accepts one parameter, data. this is your deserialized object. It magically merges the object into a template you define.
dContactDlg.empty().html($("#ContactInfoDlg").parseTemplate({ contact: response.ContactInfo }));
Where does this template reside? For this demonstration I decided to create script objects in the HTML. This is a little trick I learned from the above posts. You can even place loops and other scripting conventions in the templates, which is really cook for tabular data (see GetActiveContacts). You just need to place a merge tag for your object and property like this <#=contact.FirstName#> in your template and the parseTemplate function will merge the value into the template and create the string of markup with your values in place.
<script id="ContactInfoDlg" type="text/html"> 1:
2: <ol>
3: <li>
4: <label id="lblFirstName">
5: First Name :
6: </label>
7: <#=contact.FirstName#></li>
8: ...
9: <li>
10: <label id="lblComment">
11: Comment or Question :
12: </label>
13: <#=contact.Comment#>
14: </li>
15: </ol>
</script>

The last thing I want to touch on is error handling. Even though I placed a global $ajaxError handler in the .ready function, I use a custom error handler for each AJAX call. The error setting of the .ajax function is a function that receives three parameters. I followed the example set by Rick again and have an OnPageError event handler function, but often I need to place some clean up code in the handler. In the following example I close the ‘Processing…’ message I display using the BlockUI plugin. Otherwise it would remain on the page. I can’t just assume it was displayed either and close it in the general handler, so I need to deal with it for each call.
error: function(xhr, errorMsg, thrown) {
$.unblockUI();
OnPageError(xhr, errorMsg, thrown);
}
I will go into more detail on dealing with AJAX exceptions in my next post. So keep an eye out for that post. I also have posts planned for AJAX debugging techniques and unit testing examples.
Saturday I gave a presentation for the first time at the Southern California Code Camp on how to use JQuery to perform AJAX operations against a WCF Endpoint. Today I want to review how to create a WCF service that supports JSON and how to properly create messages that can be serialized to and from JSON.
The first step is to add a WCF Service to a web site, typically this will be your actual web site but it does not have to be. Your architecture will vary by application requirements and network security rules. Even behind the firewall you may have cross domain scripting restrictions, etc. Adding a WCF Service to the site in Visual Studio gives us a .svc file, but it also creates content we need to remove.
Visual Studio 2008 and .NET 3.5
Since Visual Studio 2010 is just around the corner I want to try and break the two experiences apart. I have a follow up post using Visual Studio 2010 planned in a few days. Select ‘WCF Service’ from the Add new Item dialog. This adds the .svc file to the web site, but it also adds two files and some unneeded sections to the web.config file as well.
First the files, a code file (.vb or .cs) is added to the project that defines the interface implemented by the service. It also includes some minimal attributes to tell WCF how to use the service. A code-behind file is also added to the .svc that implements the service. Both of these files can be used as is, however I like to remove these files. Instead I prefer to create a class library containing the code for both the interface and class implementation. In the long run this is a much cleaner way to manage the code for your WCF services. First it makes it easier to create unit tests for the code, which I will cover in another post. Second it gives you a certain flexibility to add another provider that implements the service interface. As you will see this does not make life any harder for us, it just requires the service’s web site to reference the class library.
The web.config file has also become polluted because unneeded behaviors, services and endpoint sections have been added to the system.serviceModel section. The following is example configuration that was added, it can simply be removed from the file.
<behaviors>
<serviceBehaviors>
<behavior name="Web.TestsvcBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="Web.TestsvcBehavior" name="Web.Testsvc">
<endpoint address="" binding="wsHttpBinding" contract="Web.ITestsvc">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="basicHttp" maxReceivedMessageSize="2147483647">
<security mode="None"/>
</binding>
</basicHttpBinding>
</bindings>
Ultimately this comes down to the configuration of the services and I am not bashful to admit I know very little about WCF configuration. I have people for that
. So here is where I am going to punt and say just trust me this works great.
The only thing left is to update the actual .svc file to use the correct service implementation and factory. This is an example of the directive in the default .svc file.
<%@ ServiceHost Language="C#" Debug="true" Service="Web.Testsvc" CodeBehind="Testsvc.svc.cs" %>
The following is an updated version of the file that points the Service to the service implementation class. It also tells the service to use the WebScriptServiceHostFactory, which tells WCF to use web protocols and adds the JSON serialization we need to make our service work with JQuery AJAX.
<%@ ServiceHost Language="C#"
Service="WCFJQuery.ContactBLL.Implementation.TestSvc"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
The Class Library
The next step is to add a class library to actually implement the service if you do not already have one. I like to organize the files into folders describing their purpose. You can organize how you would like, it is all a matter of personal productivity. I like to have a Contracts folder that contains the service interfaces, I use the plural here because often you will have more than one WCF service in your application.
The WCF attributes depend on a reference to the System.ServiceModel dll, so you should go ahead and add it up front, unless you are using a tool like R# that will add it for you when you add the first WCF attribute. The first file to add is the service interface. The example I use in my presentation is a simple contact form, so the service is called ContactUs. The corresponding interface is IContactUs.cs.
If you remember the attributes included with the interface file you deleted in the web site, the class was adorned with a ServiceContract attribute. This time we will define the full namespace of the interface, the name of the service, SessionMode and ProtectionLevel. For our purposes the following work for my service.
[ServiceContract(Namespace = "urn:WCFJQuery.ContactBLL.Contracts",
Name = "ContactUs",
SessionMode = SessionMode.NotAllowed,
ProtectionLevel = ProtectionLevel.None)]
Now we can add the members of the service interface. For the sample application there are 4 methods; PostNewContact, GetContact, GetActiveContacts and BadMethod. Each method has a definition like the following:
[OperationContract(IsTerminating = false,
IsInitiating = true,
IsOneWay = false,
AsyncPattern = false,
Action = "PostNewContact",
ProtectionLevel = ProtectionLevel.None)]
PostNewContactResponse PostNewContact(PostNewContactRequest request);
Now we can add the class to implement the service. I place this file in the Implementation folder because this file implements the service. We will add some more files here in a second. The ContactUs.cs file contains this file. The ContactUs class implements the IContactUs interface, it also has a ServiceBehavior attribute adorning it. In this demo the IncludeExceptionDetailInFaults property is set to true. This means exception messages will be bubbled through the service using the proper serialization for the client request. In this case it means our JQuery will get a JSON data object it can parse for us.
The class members don’t require any attributes. You can quickly auto implement those by either using the SmartTag on the interface name or with a tool like R# or CodeRush.
At this point you should have a bunch of references to classes that don’t exist yet. We need to create them. They are also added to the Implementation folder. This is where things get highly customized to your particular needs. By that I mean each one of these classes is a message class. It contains the body of the message, which typically is the contents of the request or the response.
Before I loose you here, this is something that took me a bit to comprehend at first. WCF and SOA architecture is about messaging and passing objects around. Typically each service method accepts a request object and returns a response object. In the case of GetActiveContacts it does not accept any request object.
I always like to get a response object back to check on the client. This is where I differ from some who focus on the WCF side of the application. The first situation I found myself wanting this was on a method that added a new object to the data store. The author of the service method did not return any confirmation value, or any value at all, just a null value. His reasoning was if it did not work it would have thrown an exception. I think this is a bad practice for any code, you should not rely on just bubbling an exception to the client. Instead you should catch the error and return something meaningful to the client. You can read more about that in Brad Abrams book.
Lets get back to the code at hand by examining the request object for retrieving a specific contact record. The service method requires a ContactId, which is the business key for a contact object.
Another side-bar here, notice I am not referring to a contact record, this is because modern application are querying a data model and not the database anymore. So think Entity Framework, oData or nHibernate. An actual contact object may be composed of values contained in several tables such as person, address, phone, email etc.
The GetContactRequest has to be serialized by the WCF engine, thus we need to add a a DataContact attribute to the class and DataMember attribute for each member. In this attribute the name of the member is defined. It could be anything we want, just remember it is the name you need to reference on the client. Next we need to specify this value is required, otherwise we would make the request without specifying the record we want. Finally the Order is set to 0. This tells the serilizer to add this value first or to the 0 index of the serialized object.
using System.Runtime.Serialization;
namespace WCFJQuery.ContactBLL.Implementation {
[DataContract(Namespace = "urn:WCFJQuery.ContactBLL.Implementation",
Name = "GetContactRequest")]
public class GetContactRequest {
[DataMember(Name = "ContactId", IsRequired = true, Order = 0)]
public int ContactId { get; set; }
}
}
On to the response object; GetContactResponse. Again you need to reference the Serialization namespace and add the attributes. This class also only includes a single object; a ContactInfo class.
using System.Runtime.Serialization;
namespace WCFJQuery.ContactBLL.Implementation {
[DataContract(Namespace = "urn:WCFJQuery.ContactBLL.Implementation",
Name = "GetActiveContactsRequest")]
public class GetContactResponse {
[DataMember(Name = "ContactInfo", IsRequired = true, Order = 0)]
public ContactInfo contactInfo { get; set; }
}
}
The ContactInfo class also needs to be serialized. So again you need to add attributes to manage this process. The ContactInfo class contains more than one member this time, some required, some not required. This time you will notice the index of the value increasing from 1 to 11.
using System.Runtime.Serialization;
namespace WCFJQuery.ContactBLL.Implementation {
[DataContract(Namespace = "urn:WCFJQuery.ContactBLL.Implementation",
Name = "ContactInfo")]
public class ContactInfo {
[DataMember(Name = "ContactId", IsRequired = false, Order = 0)]
public int ContactId { get; set; }
[DataMember(Name = "FirstName", IsRequired = true, Order = 1)]
public string FirstName { get; set; }
...
[DataMember(Name = "Coment", IsRequired = true, Order = 11)]
public string Comment { get; set; }
}
}
The process for the remaining request and response objects is the same. Remember any objects that are being passed in or out need to have serialization attributes defined. You are not required to add your contact or implementation classes to a class library, but as you will see in future posts it makes it much easier to test your code.
At this point we have a fully functioning WCF web service that will naturally accept and return JSON objects that can be used on the client. So in the next post I will review the infrastructure and patterns for making AJAX calls using JSON to a WCF service.
Source Code
What a wonderful showing yesterday at the SoCal Code Camp in Fullerton for both of my sessions. One thing I definitely learned is making AJAX calls to a WCF service with JQuery is in high demand and 60 minutes does not do it justice! Thanks for all the great interactions and sorry I did not have a chance to get my code and slide deck posted before the session, but I finally found some bandwidth that does not block the FTP port :).
For those of you not at the Code Camp session yesterday my first presentation was on making AJAX calls to WCF service methods using JQuery. This involves configuring your WCF service correctly, leveraging the JSON2 library, John Resig’s micro-Templating function and some JQuery and JavaScript magic dust.
I will post some write ups on what is going on in the code as the week progresses. I have just been too pressed for time lately to get things written, but should have time tomorrow. But for now you can download the source code for accessing WCF services using JSON via JQuery from here. The slide deck is on SlideShare.com, I will most likely be updating that over the next month now that I have given the session once and gotten great feedback.
Again thanks for everyone with the SoCal Code Camp, it was well worth the trip across the country to hang out with ya’ll.
Last week I wrote about voting for my MIX sessions, and if you have not voted for me, then why not? Go now and vote, you can come back afterwards and keep reading, I’ll wait. Meanwhile I wanted to publish my upcoming speaking dates. I am going to be at the Southern California Code Camp the weekend of Jan 30th at Cal St Fullerton. Next month I am speaking at the South Florida Code Camp in Miramar FL. Finally in March I am planning on speaking at the New York City Code Camp, they just announced a call for speakers last week so that is still in the works. And of course, if you vote for my sessions MIX!
So Cal Code Camp - Jan 30-31st
South Florida Code Camp – Feb 27th
NYC Code Camp – March 6th
And of course I will be attending the MVP Summit next month and MIX in March, but still vote for me!
This year MIX is letting you, the community, determine some of the content available during the conference. I, along with many others submitted different sessions to be voted on by, well anyone! You can choose up to 5 sessions. Voting closes on January 15, 2010 and you can read more about the MIX Open Call on their web site. I submitted three sessions to the mix, Lightweight WebForms, JQuery and WCF: Going Beyond the UpdatePanel, Throwing Out Your Tables: CSS Layouts for Developers, Playing Small Ball: Making ASP.NET Sites for Mobile Phones. Each of these sessions are brand new for me and inline with areas I want to focus this year or spent a lot of time on in the recent months. I think they are all about user experience development and areas we as ASP.NET developers need to learn more about to be competitive going forward.
This session will be all about doing table less layouts. I will focus doing page layouts, navigation and tricks of creating good form layouts that can be repeated over and over.
Mobile devices, phones, etc are all over the place now and it is time we start making our web sites render in a usable format for these devices. I am making this a priority to learn over the next year. In this session I am going to review best practices for creating sites to work nicely on smaller screen devices.
If you followed my Thin ASP series over the past year you saw how I used custom httpHandlers with my JQuery AJAX calls. I am going to take it to the next level by showing how to easily integrate WCF services and true messaging patterns with JQuery AJAX.
So vote early!!! There are lots of great sessions and speakers to choose from, just choose my sessions :)
Happy New Decade!!! Its hard to believe I have reached my 4th decade here on Earth, but I have. The last decade was full of challenges, good times and many bad. New Years morning I received confirmation I have received the ASP.NET MVP award for the third straight year, which is a great thing! I feel honored to receive this award each and every year, not because I think I deserve it, but because it is an appreciation from Microsoft for a lot of unpaid work I and many others put into community and all around sharing. Generally MVPs do not participate merely to get the award, but do so because they have a passion for their technology and share it with others, both the good and the bad.
With that out of the way, I have plans for 2010 already in place. I really see three things being my primary focus this year, Mobile Web Sites, CSS and JQuery and how to build the best user experiences on the ASP.NET platform. I have a realistic plan I have drawn up over the Christmas break that I believe is achievable. I will start posting some blogs on these topics soon. I have already started with CSS and JQuery in 2009, but a focus on the mobile platforms will be new. Other things I foresee learning more about and using is ASP.NET MVC and WCF.
The main reason I see my plans as being achievable is due to the philosophy I am enjoying with my new company, Tellago. I started as a full-time employee in early November and have been positively surprised every week. Jesus Rodriguez, Don Demsak, Pablo Cibraro and the rest of the team have just been nothing but a pleasure to work with. Not only are they smart and good at what they do, they are really helping me learn things about SOA development I just never contemplated. But more than that they see value in my personal pursuit of the things I am good at and enjoy as well as their own. I cannot explain the night and day difference I am having with Tellago over what I had at my previous consulting firm (and I use that term lightly). Tellago is a rapidly growing company, with a clear plan for the next year and has the talent and collection of driven people to achieve our plans and probably more in 2010.
The other day I gave an intro to JQuery Lunch and Learn to my client’s development team. I walked them through creating a simple JQuery Plugin to create a character remaining feature like Twitter has on its web site.
The ingredients for this plugin involved a textarea field (but you could just use an input field if you really wanted) and assigning the plugin to the textarea.
<script src="jquery.limitcharacters.js" type="text/javascript"></script> 1:
2: <script type="text/javascript">
3: $(document).ready(function() { 4:
5: $('#txtWhatAreYouDoing').limitCharacters(); 6:
7: });
</script>
<textarea id="txtWhatAreYouDoing" name="txtWhatAreYouDoing" cols="50" rows="3"></textarea>
The plugin itself is composed of what I think of as 3 segments. The first allows you to define options, which as then mapped to an internal JavaScript object called settings with default values defined.
// Default settings
var settings = {
charLimit: 50,
showRemaining: true,
remainingClass: 'remainingChars',
remainingWarnClass: 'remainingCharsWarn'
};
if (options) {
$.extend(settings, options);
}
The next section simply appends a SPAN to display the remaining characters as the user types in the field.
this.after("<span id='CharsLeft'></span>");
Now the real guts of the plugin! It intercepts the keyup event of the textarea and counts the number of characters used. If the number of characters is over the limit (settings.charLimit) it truncates to the maximum number of characters.
this.keyup(function() {
var len = $(this).val().length;
if (len > settings.charLimit) {
this.value = this.value.substring(0, settings.charLimit);
}
...
}
Next it gets the number of characters left and sets the value of the SPAN added earlier.
var charsLeft = settings.charLimit - len;
if (charsLeft < 0) {
charsLeft = 0;
}
$('#CharsLeft').text(charsLeft + " characters left");
Finally it sets the style of the remaining character SPAN by determining if there are fewer than 10 characters remaining. It does this by leveraging the hasClass, addClass and removeClass JQuery utility methods.
if ((settings.charLimit - len) > 10) {
if (!$('#CharsLeft').hasClass(settings.remainingClass)) {
$('#CharsLeft').addClass(settings.remainingClass);
}
if ($('#CharsLeft').hasClass(settings.remainingWarnClass)) {
$('#CharsLeft').removeClass(settings.remainingWarnClass);
}
} else {
if (!$('#CharsLeft').hasClass(settings.remainingWarnClass)) {
$('#CharsLeft').addClass(settings.remainingWarnClass);
}
}
The CSS classes used look like this:
.remainingChars
{
font-family: Arial, Helvetica, sans-serif;
font-size: 2.5em;
font-weight: bold;
color: #666666;
}
.remainingCharsWarn
{
color: #660033;
}
Putting it all together gives us a nice little plugin.

The full plugin source:
jQuery.fn.limitCharacters = function(options) {
if (this.length == 0) return;
// Default settings
var settings = {
charLimit: 50,
showRemaining: true,
remainingClass: 'remainingChars',
remainingWarnClass: 'remainingCharsWarn'
};
if (options) {
$.extend(settings, options);
}
this.after("<span id='CharsLeft'></span>");
this.keyup(function() {
var len = $(this).val().length;
if (len > settings.charLimit) {
this.value = this.value.substring(0, settings.charLimit);
}
var charsLeft = settings.charLimit - len;
if (charsLeft < 0) {
charsLeft = 0;
}
$('#CharsLeft').text(charsLeft + " characters left");
if ((settings.charLimit - len) > 10) {
if (!$('#CharsLeft').hasClass(settings.remainingClass)) {
$('#CharsLeft').addClass(settings.remainingClass);
}
if ($('#CharsLeft').hasClass(settings.remainingWarnClass)) {
$('#CharsLeft').removeClass(settings.remainingWarnClass);
}
} else {
if (!$('#CharsLeft').hasClass(settings.remainingWarnClass)) {
$('#CharsLeft').addClass(settings.remainingWarnClass);
}
}
return this;
});
}
If you have been using JQuery I hope you have started using the JQuery UI library. I use the JQuery UI Datepicker plugin to left users select a date from a calendar when they enter a date input field. The plugin works great, but an issue was raised by a user this morning that I had to also solve on with my previous client.
The customer is in the process of migrating from an old school main frame terminal to the more modern web application we were building them. Their normal user experience means tabbing between input fields. The user pointed out that once they selected the date from the datepicker the TAB focus was reset to the top of the DOM. This was not good because the user’s normal flow was broken at this point.
The solution was to set the focus of the page back to the input field in the Datepicker’s onClose event handler.
$(".datePicker").datepicker({ showOn: 'button',
buttonImage: '../Images/Calendar.png',
buttonImageOnly: true, onSelect: function() { },
onClose: function() { $(this).focus(); }
});
The focus from the input field was lost because once the user clicked the date in the calendar the immediate DOM element went from the input field to the calendar, which is not actually part of the form. It is just another page element that is removed from the DOM once the selection is made. Once the calendar is removed from the page, the browser now sets the immediate focus to the top actionable element in the DOM, thus interrupting the user’s process flow. Intercepting the onClose event gives us the flexibility to reassert focus to the input field and the user can continue as normal.
Finally, notice how the showOn setting is ‘button’. When the showOn setting is either ‘focus’ or ‘both’ the calendar is displayed as soon as the user enters the field. It also means setting the focus back to the input field when the calendar closes will cause the calendar to be redisplayed. I tried a few work arounds to correct this, but could not find a way to fix it. Alas I think to make it a true fix will require fixing the plugin itself to meet this user requirement 100%.
I am a tightwad when it comes to money and I am proud of it. I listen to Clark Howard and Dave Ramsey all the time, you should too; Rice and Beans Beans and Rice FTW!! Anyway, I love to travel, which is why I love speaking at Code Camps and User Groups. I have not had much budget for real travel though, but have made a lot of events in the past few years. I have been asked how I manage to do this several times recently, so for the benefit of the .NET community I thought I would share my secrets.
Driving
I typically drive to every event I go to, lets face it flying is expensive if you are paying out of your pocket. That does limit my radius, but I have flown to some events, but I will cover that later. Currently I live in Raleigh, which is a 5 hour drive (for me) to Atlanta and 6-7 hours to NJ and Philly (depending on DC traffic). I have determined that it takes about 4-5 hours to fly to Atlanta and actually get to where I want to go. Plus most .NET community events are not on MARTA, so that means renting a car to get anywhere.
It takes 30-45 minutes to get to the airport in Raleigh, another 30 minutes to park, shuttle, security and wait for the flight. Parking is $5-12 a day (depending on how close I am cutting it). Airfare to Atlanta is super high for some reason. The flight is roughly 75 minutes. Then deplaning getting a bag, if I checked one, renting a car (ca ching) and driving to the hotel (another hour or 2 right there depending on their traffic).
So that was around 4 hours of travel right there. Remember it takes me 5 hours to be to the Atlanta Perimeter from my house. That includes stopping for gas in Florence and Augusta. It actually takes a tank and a half, but gas is super cheap in those cities. Also note, I did not drive through Greensboro and Charlotte, it takes 7 hours that way, but is only 7 miles shorter…ah hah…traffic my friend.
Financially I have spent around $30 to get there and of course another $30 to get home. The drive down is very calming too, absolutely NO TRAFFIC till Atlanta. I am there about an hour later than if I had flown. I just checked on Fare Cast for a weekend flight 4 weeks from now $169 (connecting in Charlotte before taxes, bag and airport fees BTW). Normally the fare is around $300. So I am already way ahead even after getting an oil change a week earlier than normal.
Now notice I stopped in Florence, SC and Augusta, GA for gas. It is just much cheaper there than home or Atlanta or even Columbia. North Carolina has a very punitive gas tax of $0.44 a gallon, it is about half that in SC and GA. I know where gas is cheap thanks to a great ASP.NET set of sites and their heat map, http://www.georgiagasprices.com/Price_By_County.aspx?state=GA&c=usa. I am in South Florida as I write this, gas is $0.50 cheaper in GA than here FWIW.
Going North on I-95 I stop at Virginia exit 104, there are about 4 large truck stops and several other gas stations there. So the competition keeps the prices very low. I also stop in Newark DE. New Jersey also has very cheap gas prices, but you can’t pump gas yourself, so it takes longer. Stopping in Newark is also a way I get around a toll book too thanks to a simple cut across to Elkton MD :).
Speaking of tolls, if you are in the North East or some other place with those annoying toll booths, get an EZ Pass or the equivalent. You will save a little money, but more importantly time. I hate having to slow down to 10 MPH on the interstate for anything, but it is so much better than stopping, rolling down the window and handing someone $2-4 in 20 degrees and windy or 95 and humid.
Also remember, you can get reimbursed for your mileage at $0.55 a mile if you are doing company travel. I am incorporated, so speaking is a company expense!
I have actually beat someone flying from RDU to the same place in NJ and I left 15 minutes after them! So keep that in mind when you plan your trip. Driving also gives you much more flexibility on when you leave on both ends. I like being in control of things as much as I can. Yes there are benefits to flying too, but you pay for them.
Food
This is easy, I make sandwiches when I leave the house and eat them in the car. I also take bottled water and Capri Suns with me too. I do like Micky Ds a bit much, but try to avoid fast food if possible.
I am waiting on a flight right now and I made two sandwiches for the trip and brought them with me in my computer bag. I have found this to be very important when flying. Making connections can provide a very short window to get to the next plane, restroom and stand in a very long line to get dinner or lunch. Having my own food saves me $$ and time. Plus I know they are not messy and something I like. Cookies, chips and crackers are also staples for my travel, just not today. Security rules mean you have to buy an overpriced drink in the terminal though, get that before you board is my suggestions.
Hotels
I have background here, I worked in a hotel in High School and my parents managed several back in the 80s and 90s. I have never stayed in a $100+ a night hotel that has ever impressed me. I have only really had one hotel that did not meet my expectations in the same are for less money. That was in Atlanta for TechEd a few years ago. The AC unit was broken and it was summer, you do the math.
When I need a hotel I use either HotWire.com or Expedia.com. I typically have two requirements, free WiFi and something for breakfast. I really like Holiday Inn Expresses with their breakfast, but you really pay for it. So when you are considering hotels hear each other and there is a $40 difference between hot breakfast and muffins, a $5 trip to Micky Ds is your friend. Now that I have a Sprint WiFi card I am going to worry about that less and less.
I go to HotWire.com when I do not see rates to my liking. Many times I can find a better deal there when I could not otherwise. I saved over $700 for a week last summer in DC when I taught a class there over what the client recommended. Yes I needed to drive an extra 10 minutes each morning, but well worth it. I also saved about $150 over the hotel everyone stayed at the first Code Stock in Knoxville and was actually in a nicer hotel than they were. I was just one exit down.
Something you have to be cautious is booking fees with several of the online sites. FareCast.com charges $6 for hotel booking. I have also seen up to $11 as well. A lot of online booking sites have dropped these fees, but I did get hit with one last month on FareCast.com so beware of those. This will hold true for air fare as well.
Flying
I love to fly, just not when I can drive for cheaper in the same time frame. I am waiting on a flight right now, but I would have about a 20 hour drive in front of me if I was not flying, so well worth it. Here is where FareCast.com just shines for me. The Price Predictor makes it stand head and shoulders above the rest IMO. They will tell you when to buy and when to wait and how sure they are. There is also a fare history to visualize how the fares change for that route.
The only complaint I have is Southwest is not included in their results and I fly Southwest a lot because it is very convenient for me. I also really enjoy the filtering features on Fare Cast, it is a very responsive site and Microsoft owned by the way. One of the best examples of AJAX UX done right.
Speaking of Southwest, one of the reasons I really like them is they are geek friendly. In all of their terminals they have either what I call geek stations with power and even USB hookups. Often they have nice chairs as well. The BWI airport just rocks for this. I am also odd because I like the general admission because it lets me get the seat I want, either the exit row or the last row. Why you ask? Well if the flight is not full then I get a seat with no one sitting next to me, which happens about 70% of the time.
In the terminals though I tend to stay away from paying for anything as much as possible. It is overpriced, no matter what it is. If you need souvenirs go to Wal Mart before you leave. You will save a lot of $$$ there too. For example I was in Maui and stopped by the K Mart on the way to the airport and got some stuff, it was 2.5 Xs the price in the airport or the tourist trap gifts shops on the islands.
Car Rental
I really do not have much to say here other than limit it as much as possible and don’t buy the insurance. Your credit card will typically cover it for you and it is free. If you can ride the subway or bus go for it. When I go to Redmond I ride the bus from the airport for $2.50. It has free WiFi and it is fast WiFi. A cab ride from the airport to Microsoft is around $65 from what I hear and only gets you there about 20 minutes faster. I think for about $10 you can get a pass for the entire week and go anywhere in King county you want. Other large cities have the same type of system in place. The Metro in DC is pretty good inside the Beltway and of course New York Citiy’s subway, etc. Heck I rode the train between Arlington (my parents) and the Dallas TechEd for a week back in 2003. So much money and timed saved by doing that!!
Summary
I hope this helps you out. I am sure I have more things I do that I forgot. Please feel free to share your ideas in the comments!!! Thanks for Chris Eargle for encouraging me to share this post. I know it is out of the norm, but sometimes you have to step outside your comfort zone.
Earlier this year I wrote an application that allowed the user to fill in a username as part of the registration. I thought I would add a creature comfort to the form by making a non-intrusive validation of the username against the ASP.NET membership provider. My goal was pretty simple, see if the username was available and let the user know but not impede them from continuing the form. I decided to use JQuery and a simple HttpHandler.
The markup for the username line of the form contains a Label and an Input field for the username to be entered. It also contains a couple of Span tags, one for the indicator the username is being checked (usernameLoading) and one to indicate the results (usernameResult).
<li>
<label id="lblUserName" for="txtUserName">
User Name :
</label>
<input id="txtUserName" name="txtUserName" class="fillout required" type="text" maxlength="20"
value="<%=UserName %>" /><em><img src="images/required.png" alt="required" /></em>
<span id="usernameLoading">
<img src="images/indicator.gif" alt="Ajax Indicator" /></span> <span id="usernameResult">
</span></li>
The JQuery for the process assigns a ‘blur’ event handler for the txtUsername field. When a user leaves the field the blur event handler will fire. A function definition is defined in the handler that first displays the spinning Ajax indicator, then posts the value of the txtuserName field to the checkusername.ashx HttpHandler. The post method also defines a function to handle the handler’s response which fades the usernameResult Span result out if its already displayed. It then calls a custom function 400ms later, finishAjax(…).
$(function() {
$('#usernameLoading').hide();
$('#txtUserName').blur(function() {
$('#usernameLoading').show();
$.post("checkusername.ashx", {
username: $('#txtUserName').val()
}, function(response) {
$('#usernameResult').fadeOut();
setTimeout("finishAjax('usernameResult', '" + escape(response) + "')", 400);
});
return false;
});
function finishAjax(id, response) {
$('#usernameLoading').hide();
$('#' + id).html(unescape(response));
$('#' + id).fadeIn();
} //finishAjax
The finishAjax function hides the Ajax processing image, sets the html of the usernameResult Span and fades it in.
The checkusername.ashx contains the code to see if the username is available. You could implement any sort of code you want in this method to perform validation on the username, password or just about anything else. In this case it simply checks to see if a user exists for the username, if so it returns some HTML to indicate the useraname is Unavailable, otherwise it lets them know it is available.
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Dim mu As MembershipUser = Membership.GetUser(context.Request("username"))
If Not IsNothing(mu) Then
context.Response.Write("<span style=""color:#f00"">Username Unavailable</span>")
Else
context.Response.Write("<span style=""color:#0c0"">Username Available</span>")
End If
context.Response.Flush()
context.Response.End()
End Sub
When the handler returns the resulting HTML the progress indicator is faded out and the result is faded into view. Now the user knows their username is valid and can continue with the form or choose a new username. This technique can be used to do just about any sort of client-side/server-side validation without impeding the user’s progress.
Over the last year I have been spending a lot of time re-learning how to use CSS. Since ASP.NET was released the use of Web Controls had made me CSS and HTML ignorant. With the advent of ASP.NET MVC and JQuery combined with the increasing demand for richer user experiences I knew I had to tackle this deficiency immediately. Hence my adventure into my Thin ASP.NET series. It took me a while because I just did not understand how CSS selectors actually work. When I started using JQuery it finally popped for me and I really started to get it. There are three fundamental CSS selectors that just about anyone that has done any web work understands, type, class and DOM Id.
The Type Selector
This should be the most obvious selector because it sets the default rule to be followed for the specified element (I really call them element selectors, but that is not technically correct, they are Type selectors). For example the following rule designates the text contained within a <P> element will be the size of the containing element’s font size definition and the text’s color will be black.
P
{
font-size: 1em;
color:#000;
}
This is a good start. Today, sites that follow CSS best practices define a CSS Reset in the top of the file. Basically this is a set of rules that define the default layout behavior of those elements in the page. The driving reason behind this technique is to take control over the default rendering rules from the browser, hence eliminating many of the frustrating differences between browsers. Personally I have decided to adopt the YUI CSS Reset from Yahoo as my default reset, but there are many others available and of course you can define your own.
The Class Selector
This rule defines a CSS rule for any element that defines the class be applied. I see this technique almost abused at times by ASP.NET developers as we desperately try to overcome deficient ASP.NET control rendering. Like the previous example I can define a CSS class to enforce the same rendering logic:
.defaultText
{
font-size:1em;
color:#000;
}
A CSS class is defined with a ‘.’ prefix and can be named anything you want. To apply this rule to any HTML element all you need to do is include the class attribute and set it equal to the class name. Something I learned in the last year is the ability to define multiple class rules for an element in the class attribute. This comes in real handy when assigning JQuery plugins.
<input type="text" id="txtFirstName" class="defaultText textField"/>
For an ASP.NET web control you assign any class rules in the CSSClass property, which ultimately renders the class attribute with those values.
<asp:TextBox runat="server" id="txtFirstName" CSSClass="defaultText textField"/>
The ID Selector
The last selector type finds a DOM element by Id or the assigned name of the element. So in the examples above you can define a rule for the specific input element. The Id selector is prefixed with a ‘#’ in the rule definition.
#txtFirstName
{
font-size:1em;
color:#000;
}
This time instead of needed the class attribute there is no need to set this value. The CSS Rule will just be automatically applied. In this example you most likely do not want to define a rule just for the txtFirstName element because this is too specific because the CSS rule would most likely need to be applied to many other elements as well. But there is nothing saying you cannot do this and I will show you some tricks to define the same rule for multiple selectors later in the post.
Combining Selectors
This is where I see CSS novices lose the effectiveness of CSS selectors on their page. Instead of leveraging the real power of CSS selectors they will litter their markup with class attributes that are duplicated over and over in a page. The following example is a simple login component with E-Mail and Password input elements. I am defining the class attributes for both in a very inefficient way by duplicating the effort.
<ul>
<li>
<input id="txtEmail" type="text" class="loginText"/>
</li>
<li>
<input id="txtPassword" type="password" class="loginText"/>
</li>
<li> {Buttons}</li>
</ul>
The markup uses the class rule to ensure both the inputs look similar. But we have some wasted code here. What if I defined an id for the <ul> and combined a few element selectors for a CSS rule? That could be very efficient because I would just need a simple name and rule. In this case this is known as a descendant selector because it specifies this rule be applied to any INPUT element that is a child of a LI that is the descendant of a UL element called loginElements.
ul#loginElements li input
{
font-size:1em;
color:#000;
}
The markup could now look like this:
<ul id="loginElements">
<li>
<input id="txtEmail" type="text"/>
</li>
<li>
<input id="txtPassword" type="password"/>
</li>
<li> {Buttons}</li>
</ul>
That is ultimately less text being sent to the browser on each page request and a more specific rule. It also helps us out by applying the same style to any other input fields we might want to add, think about adding an OpenId field or maybe a third identifier. This really comes in handy on longer forms.
The ability to combine multiple selectors can also be done with class names as well, in fact you can combine as many selectors as you want in just about any combination you can dream up. It does take a little practice but you can get real specific with your selectors and that ultimately gives you surgical precision to define how an element will render.
In the login form example I might not reference the element id, but maybe define class to follow in the <ul> element. In that case the CSS rule might look like the following:
UL.loginElements LI INPUT
{
font-size:1em;
color:#000;
}
This is all well and good, but I forgot something! There are no labels in the form to tell the user what to enter, so lets add them.
<ul>
<li>
<label for="txtEmail">E-Mail</label><input id="txtEmail" type="text" class="loginText"/>
</li>
<li>
<label for="txtPassword">Password</label><input id="txtPassword" type="password" class="loginText"/>
</li>
<li> {Buttons}</li>
</ul>
Now I need a CSS rule to define how the labels are going to render. No problem, I can define a similar rule as the input rule. In fact I am going to use the exact same rule by stacking the selectors on the rule.
UL.loginElements LI LABEL,
UL.loginElements LI INPUT
{
font-size:1em;
color:#000;
}
I call it stacking because I think it reads better when they are stacked on top of each other. The official term is Grouping. But this is not good enough for me, I think I still need to define some more CSS rules for the label and the input elements to make them layout nicely. The following rules cause the labels to be 75 pixels wide and float left, meaning they will all line up along the left side. The text also aligns left.
UL.loginElements LI LABEL,
UL.loginElements LI INPUT
{
font-size:1em;
color:#000;
}
UL.loginElements LI LABEL
{
width: 75px;
float: left;
text-align:left;
}
UL.loginElements LI INPUT
{
width: 100px;
float: left;
}
Now the form is starting to look better! And I demonstrated another feature with CSS selectors, the ability to define more than one rule for a CSS selector. There is no limit to the number of rules you can define. If you read my last post on the Development Tools built into IE 8 you have seen it give you a visual trace of the CSS rules that are applied to an element and what selector applied the rule.
Sibling Selectors
Now I am just going to get fancy with you and show off. One of the coolest things in CSS selector syntax is the ability to define rules to be applied to an element based on elements that are sitting right next to it, or its siblings.
The way to define a sibling selector is to place a + between the left sibling and the right sibling. So a sibling rule looks like A + B where B is the target of the rule.
h1 + p
{
background-color: #3399FF;
color: #000000;
font-family: Arial, Helvetica, sans-serif;
font-size: 1em;
}
Applying that rule to the following Markup renders a paragraph with a blue background. The H1 and P tags are siblings within the parent DIV tag.
<div>
<h1>
CSS Selector Demo</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tellus odio, cursus ...</p>
</div>

Unfortunately you cannot go the other way with siblings. So defining a rule for P + H1 will not allow you to define the style applied to an H1 tag that has a P next to it like the HTML above.
Similarly you can define descendant selectors where the first selector rule is immediately followed by a selector. So “DIV P” designates any paragraph within a DIV element. You could also designate “DIV > P” to select any paragraph that is the direct descendant of a DIV element.
Attribute Selectors
Attribute selectors are another pretty sweet selector trick I like to use. This gives you the ability to define a selector that applies to an element that contains an attribute meeting the criteria. You can define an selector that says the element just has to have the attribute defined [att]:
or an attribute with a specific value [att=val]:
or an attribute with at least one value matching a value [att~=val]:
Finally you can match values based on language specification [att|=val]. This one is special because the value must be followed by a –. So you would typically match on the lang attribute. So a style of P[lang|=en] would match all English language types.
Pseudo-Class Selectors
Pseudo-classes enable you to designate a rule for an element based on some attribute that is not part of the document tree. Well that depends on the way you interpret the document tree model I guess because you can designate styles based on position below an element with selectors such as first-child, etc. So taking the example from the sibling selector you could define a selector that would only apply to the first paragraph within the parent DIV like the following:
div > p:first-child {...}
This selector says apply the style rule to only the first paragraph that is a child of a DIV element. Any other rules for paragraphs that would be met will be applied to the rest of the paragraphs in a DIV.
Other pseudo-classes apply to <A> tags, :link, :visited. This gives you control over how links that have been visited differ from links that have not been visited by the user. These are probably pretty common to most web developers as are the :hover, :active and :focus pseudo-classes because examples of these have all been done for hyperlinks for as long as I can really remember.
They all give you more granular control over how style rules are applied to elements based on where the user’s mouse or focus is placed on the page. You should note that :hover should be placed after :link and :visited because the color property would be hidden otherwise. Also pseudo classes can be combined like a:focus:hover.
Psuedo-Element Selectors
Similar to the Pseudo-class selectors there are selectors that really extend the ability to control rendering based on the position of the content within an element, pseudo-elements. This is how you see things like a very large capital letter at the beginning of a paragraph or a different font or background image for the first line. The :first-letter pseudo-element allows a specific rule for the very first character.
Adding the following selectors to the example changes the first character and first line of the paragraph:
h1 + p:first-line
{
text-transform: capitalize;
color: #CCCCCC;
margin-bottom: 4px;
font-size: 1.25em;
font-family: 'Times New Roman' , Times, serif;
}
h1 + p:first-letter
{
padding: 2px 5px 3px 5px;
background-color: #0066FF;
color: #333333;
font-family: Arial, Helvetica, sans-serif;
font-size: 4em;
float: left;
margin-right: 8px;
}
Which produces the following effect when it is rendered:
Summary
With so much raw power at our disposal to control the layout and rendering of any page mastering CSS Selectors is a must have skill for any web developer. I hope this post can be used as a reference document for you going forward. And from now on I hope you have the confidence to control your layout with CSS and not control attributes or even worse inline style definitions. I think you will also find that your markup is much more maintainable. Changes to your layout will also be much easier to accomplish.
Look for another post on defining selectors to work with ASP.NET web controls and some of their quirks in the next few days.
Internet Explorer has been out for a while now, and I am very pleased with it, especially from a developer’s perspective. First I am more and more appreciative of the IE team getting CSS compliant, this is making it so much easier to create a consistent design across browsers. If you want to appreciate the differences between the last three versions of Internet Explorer Smashing Magazine did a great article earlier this week. The thing that has truly changed my experience with client-side development (think JQuery and CSS) is the Internet Explorer Development Helper. In fact I can not imagine doing client-side development without it or FireBug in FireFox.
The Development Helper can either be invoked by selecting it from the Tools menu, or as I always do pressing F12. This launches a new window with all kinds of wonderful client-side development tools. The first thing that stands out are 4 tabs located below the menu (more on that later); HTML, CSS, Script and Profiler. The HTML table gives you manipulative access to the HTML. The CSS tab lets you access the CSS files loaded by the page. The Script tab lets you see and debug any JavaScript the page relies upon. The Profiler let you trace the page request and subsequent running of the scripts while the page is loaded.
HTML
When I am working on CSS issues in my pages I spend a lot of time on this tab. The reason is the ability to see how style rules are applied to a specific DOM element and change that style applications real-time. There are 4 ways to view the CSS rules for an element; Style, Trace Styles, Layout and Attributes.
The HTML Style tab simple lists all the style rules in the order they are applied to the element. The rules are displayed in a tree hierarchy, with each selector having its rules displayed as child nodes.
If a rule is overridden by another selector rule, then it is displayed with a strike through. Beside each rule is a checkbox, indicating if the rule is applied to the DOM element. Unchecking a rule will automatically cause the next matching rule to be applied to all elements that match that selector. You also have the freedom to select a rule, say background-color, and change it to another value. This will cause it to be applied to all elements that implement that rule. This is so valuable because now I can make minor tweaks to rules, selectors, etc to see how a change will affect the page without having to make the change in the stylesheet, save the file and reload the page.
The Trace Styles tab works almost the same as the Style tab, but instead of a treeview of CSS selectors and rules being displayed the CSS rules are listed for the DOM element with the ability to expand the selectors that apply to the element. You can again turn them on and off and adjust values as described before. I use this view more than the Style tab because it is much easier to see what I can adjust.
The Layout tab is much different than the two CSS tabs because it visualizes the box model of the element. This means you get to see the real height, width, margin, padding and offsets of the element. This is a very useful view when you are trying to work on layout and placement issues. I find it invaluable to understanding how a form using tables actually renders for example.
Finally the Attribute tab lets you define element attributes at run-time. So you can add and set any attribute or style value at run-time. For the longest time I was very frustrated with the Developer Tools because I could not add style rules or change attributes (like table cell widths) without going back to the source, saving and reloading. So when I found I could do it here I was very happy. Working with FireBug in FireFox also allows this feature, so I was really happy learning how to do it in IE too.
Script
If you do any AJAX development you will spend a lot of time in the Script tab. In the past few years the debugging tools seem to have finally caught up to the need to adequately work with JavaScript. This has been the primary reason I stayed away from JavaScript development over the years, but now with JQuery and the IE Developer Tool I Love JavaScript Development.
The Script tab of the Developer Tool opens up a real debugging environment that you can set break points in your JavaScript and step through the code just like we are accustomed to doing in Visual Studio. It also has additional windows for watches (both local and developer defined), a Console and a Call Stack window.
Stepping through code works just like it does in Visual Studio. However if you have included a JavaScript file that has been minimized then you are going to have a very difficult time stepping through this code. If you are not familiar with minimizing JavaScript it basically means removing the unneeded whitespace characters that are ignored by the JavaScript interpreter, making it much more compact to send down the wire. If you are developing this can be problematic because stepping through the code now is very difficult. I relate it to trying to step into one of the .NET libraries you do not have source code access, it just gives you a class view in Visual Studio.
Setting a watch is pretty easy, you can right click on a variable a selector, $(‘#myelement’) for example, etc. and you can just add the watch from the context menu.
One thing to note is once you close the Developer Tools you will loose not only the breakpoints you have set, but also the watches you have set.
The Console window is pretty nice because it allows you to execute a JavaScript statement based on the current point you have set your breakpoint. By this I mean you can execute a statement and see the result in the window based on the current state of the client-side state. So if a JS variable has a value that is set after your breakpoint it will not be available, but you can ‘set’ that value in the console and maybe play some what if scenarios like I described above in the CSS tabs.
Call Stack if a nice idea, but in my experience not quite as useful because I tend to only see ‘anonymous JavaScript function’ listed. But it does sometime actually list the functions called on the way to the point of the breakpoint execution.
Profiler
The profiler is another invaluable tool, but its not obvious at first glance. The profiler monitors all the JavaScript execution during a monitoring session. To start profiling just click the ‘Start Profiling’ button then go back to the browser and use your web site. When you are done executing things return to the Web Development tool and click ‘Stop Profiling’.
You will then be able to view the results of the profiler in one of two ways; by function call or in an execution tree. The usefulness of the profiler is allowing you to see where bottlenecks and other inefficient code is located in your JavaScript. It tells you how many times a function was called and how long those calls took. It also tells you what file the function is located and what line it is located.
The results can be exported to a CSV file by clicking the third button from the left on the Profiler toolbar. Now you can view and manipulate the data in another tool if you want. The E-Mail form I am using for this demonstration is rather boring because it does not do much outside the JQuery framework. But just glancing over it I can see some potential optimizations I can make by reducing the number of times I make JQuery use the selector syntax for example.
Menu Options
So far I have just been talking about the tabs in the Developer Tools and have not even started with the menu options!!! So wait, there’s more ;) I am not going to cover them all, but want to write about the cooler features.
Disable
This menu option gives you the ability to turn off scripts the pop-up blocker and even CSS. This means the browser will not execute these items. This can be a good way to test your application for downlevel browsers (think Lynx) and to see how a search engine spider might see your site. I like to turn off the scripts so I make sure my page will work where JavaScript is turned off. Granted I do not do that very often, but it is a nice way to test it out.
View
The View menu option is another useful feature because it overlays information on the page for applicable elements such as the CSS class, Id, tab index and Access Keys. This is really nice because now you can just glance at your page and see what these values are from a user’s perspective. So its another way to see things without having to view the source and search through the markup to find these values and make sure you are on the right element.
Outline
The Outline menu lets you turn on ‘outlines’ to visualize where a table, div or any other DOM element’s box is actually located on the page. When working on a new layout this is very helpful in determining where containers begin and end. In the screen shot shown here (click for a larger view), the DIVs are indicated with a thin green line. Images are outlined by purple.
Images
This menu option lets you visualize information about images or just turn them off all together. Again overlaying this information on an image is very helpful in determining the dimensions and file sizes. One problem I have is on small images it overlays the information, but only within the boundary of the image itself, which means you just get a pink box covering the image with no useable information. I hope they fix this issue and allow you to roll your mouse over the image and have the information naturally expand to a viewable tooltip type metaphor.
In the image shown here you can see it is highlighted in pink and see it trying to write out the image dimensions. This needs to be corrected in the next version of IE.
Cache
The Cache menu can be a developer’s best friend at times because you can designate that all supporting files must be retrieved from the server each time the page is requested. You can also manually clear cookies and the browser cache related to the URL.
Tools
Under Tools you can Resize the browser window to different potential user dimensions. I have always targeted my sites for an 800x600 box, but that is quickly fading away with larger monitors quickly becoming the defacto standard. Uber Geeks tend to run at super high resolutions so you can set the browser dimensions to larger screens as well or a custom height and width.
The ruler is a very neat tool, but not quite obvious at first. But you can pick a point on the page and drag the mouse from it to another point. A ruler is drawn from point A to point B. The length is displayed in the Ruler window that is open above the page.
The color picker is very useful when you are trying to determine a color on a web page. This will launch a tool window over the browser with a eye dropper mouse cursor. As you pass over elements in the page the color is grabbed by the tool and displayed in tool window. Clicking over an element will lock the color for you. Now clicking the ‘Copy and Close’ button will place the color’s HEX value in the clipboard so you can easily use it in your CSS or Paint.Net, etc.
Validate
Using valid HTML code is critical to having a good web site, in my opinion. You can get by with bad markup and CSS, but you are actually hurting yourself in the long run. The Validate menu lets you send your markup or CSS to W3C for actual validation. Additionally you can check for accessibility compliance, which is really handy. Now this is not going to be the ultimate accessibility feedback you might get from a tool like JAWs. But I highly recommend using as much validation as you can. One drawback is the tool wants to send the URL to the W3C online validation tool instead of posting the markup to the tool. So you cannot send anything from your local development machine, it has to be a public facing web site. So I hope this gets improved in future version.
Browser Modes
IE 8 is a game changer when it comes to supporting CSS standards. Prior to IE 8 Internet Explorer was known for doing things its own way as far as how it implemented CSS standards. This causes many web developers and designers to pull out their hair every time they build a user interface. Now the real problem is there are so many web sites out there that only conform to IE 6 or 7 standards. Microsoft has even been offering bribes to get folks to upgrade from IE 6, and as a web developer let me say PLEASE STOP USING INTERNET EXPLORER 6!!!
Rather than allowing these poorly developed sites just not work in IE 8, they opted to let users click a button to the right of the address bar to have IE 8 use the IE 7 rendering engine to display the URL. The Web Developer takes this a step further because it allows you to select the browser and the browser mode you want the page rendered. It even offers Quirks Mode, which is used by browsers when it cannot determine what if any DOCTYPE the page uses.
Summary
The Internet Explorer 8 Developer Tools are an invaluable tool that every web developer should leverage in their day to day development tasks to make high value modern web sites. Understanding all the features available in the tool is very important because once you understand how to use the tools you will start seeing how to make your web sites’ user interface better. With the popularity of FireBug, this is a much needed tool for Internet Explorer that will help all of us develop better front-ends.
Trolling the ASP.NET forums again this morning, I know I do it a lot, I found a question trying to parse the paragraphs out of a series of text. So I knew I had to answer it. The regular expression needed is '(.+)'. This tells the Regular Expression object to match on a series of one or more word related characters. This means it will group matches for a paragraph, indicated by a line or carriage return. Code for this solution would look like this:
public static MatchCollection GetParagraphs()
{
using (StreamReader sr = new StreamReader(@"{Path To Sampel File}\SampleText.txt"))
{
string textFromFile = sr.ReadToEnd();
Regex rg = new Regex(@"(.+)");
return rg.Matches(textFromFile);
}
}
I thought I would extend this to get a word count as well as all the words. In this case the expression is '(\w+)'.
public static MatchCollection GetWords()
{
using (StreamReader sr = new StreamReader(@"{Path To Sampel File}\SampleText.txt"))
{
string textFromFile = sr.ReadToEnd();
Regex rg = new Regex(@"(\w+)");
return rg.Matches(textFromFile);
}
}
Calling the RegEx.Matches method returns a MatchCollection, which has a Count property, can be used to get the count of matches. It can also be enumerated through to get that actual matches.
public static void WriteMatchCollectionResults(MatchCollection mc)
{
Console.WriteLine(mc.Count);
foreach (Match m in mc)
{
Console.WriteLine(m.Value);
}
Console.WriteLine("...........................................");
Console.WriteLine("");
}