Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
Add to Technorati Favorites


ASP Insider Follow Me On Twitter
Introducing SO-Aware, the WCF Management Tool Everyone Needs

Today is the day, Tellago Studios officially launches with our first software offering, SO-Aware.SO-Aware is a RESTful WCF Registry solution. So what does that mean? In short SO-Aware is a web based WCF management tool that also does monitoring and automated testing of WCF services.

If you are not sure how SO-Aware is unique from other governance solutions we have create a quick 5 Reasons Why SO-Aware is different from the competition.

  • Participatory governance
  • Centralizes metadata not messaging
  • Manages service artifacts like WSDL, Policies, but also includes WCF Specific artifacts like Bindings and Behaviors.
  • Provides for scheduled and on-demand testing.
  • Provides a simple, intutive and highly intenroperable REST Odata-based API model

To see SO-Aware in action Tellago Studios has created several SO-Aware how to videos to show all the create features. If you are a PowerShell guru, we even have a PowerShell Provider.

If you have a small set of services you would like to monitor or just try SO-Aware out, you can download the SO-Aware Express Edition for FREE!! Yes that is correct you can get SO-Aware for the low low price of FREE.

Next month Tellago will be hosting two webinars (August 4th & 25th) where you can see in real-time how to use SO-Aware to manage your WCF environment. These webinars will also give you live access to one of our staff members to ask questions.

I am not going to claim I am a WCF guru, but I do work with it each day as an AJAX developer. I experience some minor configuration issues from time to time. More importantly I see and feel the result of WCF management and integrity issues in the enterprise each day. As a developer and general IT enthusiast I know dealing with these issues is not pleasant and having great tools is the key to being successful as well as quality of life at work. So whether you are an IT pro that manages service implementations, a developer or architect that uses WCF I urge you to evaluate SO-Aware. If you want to know more about SO-Aware please feel free to contact Tellago Studios for more information. We have many friendly and knowledgeable folks here to help you out.

A Custom jQuery Selector to Retrieve Labels for Inputs

This afternoon @DamienGuard asked how to select labels that are associated with input elements. I think I have an answer for him, or at least something that should be able to get him on the right track. If not, oh well its still pretty neat.

One of the great features of jQuery extensibility is the ability to create custom selectors. This is how the jQuery Sizzle selector engine is able to extend the core CSS selector rules to allow some pretty slick, tight selectors. For example ‘:text’ can be used to return an array of all input with a type=text and textarea elements. If you review the list of jQuery selectors you will see many many more built into the core library.

$.extend($.expr[':'], {
mySelectorName: function (a) {

if(/*match*/){
return true;
}

return false;

}
});

Above is a custom selector framework. Here you extend the jQuery library with a custom expression ($.expr[‘:], …) Inside the expression definition you give the expression a name, which is actually a function. The function accepts a parameter, which represents the element to be evaluated. In this case I am using the variable ‘a’. Now you need to do your evaluation and there is no limit to what you can use for your evaluation, so shoot for the sky. If your filtering criteria are met, then return true, otherwise return false. If the filter is satisfied the element is added to the result set.

To solve Damien’s need I am going to create a label$input selector. Inside the selector logic I get the value of the element’s ‘for’ attribute. If there is a value, meaning it is defined and is not empty then I see if there is a matching input element. If the ‘for’ attribute is not available then it returns false to tell jQuery not to add the element to the matched set.

$.extend($.expr[':'], {
label4input: function (a) {

var iFor = $(a).attr("for");

if (iFor === undefined || iFor === '') {
return false;
}

return $("#" + iFor).length > 0;

}
});

The last step selects the a matching input field. Here I just use the value of the ‘for’ attribute with a ‘#’ prefix. If there is a matching element then the custom selector returns true, otherwise it is false.

For some test markup I create a simple form that uses a label as a legend as well as labels for a couple of input fields. If the selector works then I append the name of the input field to a DIV element.

<fieldset>
<ul>
<li>
<label>
This is a orphan label</label></li>
<li>
<label for="firstName">
First Name</label><input id="firstName" name="firstName" type="text" /></li>
<li>
<label for="lastName">
Last Name</label><input id="lastName" name="lastName" type="text" /></li>
</ul>
</fieldset>
<hr /><br />
<div id="labels"></div>

When the document is loaded the following jQuery is executed to list the matching elements using the custom selector.

$(document).ready(function () {
$(":label4input").each(function () {
$("<p>" + $(this).text() +"</p>").appendTo("#labels");
});
});

The result is a list of matching inputs!

jQuery Custom Selector

So go forth and create great custom jQuery selectors.

Intro To WebMatrix: Create a Contact Form Part 4 Adding A Master Page

In my three previous posts about using the Microsoft WebMatrix tool I showed how to create a form, add database interactivity and automated E-Mail functionality. Today I want to start making the site take a more usable form by adding a site layout.

The use of Master Pages or common site layouts go all the way back to the beginning of web development. Back in Classic ASP days we used to use include file to reference things like the header, footer and other common layout elements. This changed to ASP.NET user controls (.ascx) files when .NET was released. The release of ASP.NET 2.0 added a Master Page file, which made creating a common layout very intuitive.

With the Razor syntax the Master Page concept lives on, but in a slightly different syntax. Since Razor does not have the concept of Web Controls, but helpers, there is concept of sections.

Instead of adding a Master Page file to a WebMatrix web site you just need to add a .cshtml or .vbhtml file. In this file you add the markup to manage the layout you want to share across pages. This would include common references to CSS and JavaScript files.

Now I am going to get into some of my architecture theory. I like to define various sections in my common layouts that allow child pages to add additional values. For example in the HEAD element I usually set the page title in the page, not the master. I also add page specific CSS references, etc.

The Razor view engine allows you to define a section in your markup. In the example below this section is defined using the @RenderSection helper method. This is an overloaded function that requires a section name. You can also designate if the section is optional, if not defined the default value is false. If the section is required each page implementing this layout must define this section.


<head>
<link href="@Href("~/css/print.css")" rel="stylesheet"
type="text/css" media="print" />
<link href="@Href("~/css/screen.css")" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="@Href("~/css/ie.css")" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="@Href("~/css/main.css")" rel="stylesheet"
type="text/css" media="screen, projection"/>
@RenderSection("Header", optional: true)
</head>

Notice there is no Title element in the head, rather I will utilize the Header section on each page to define this element. Below is a snippet of code on the contact page. First you designate the LayoutPage at the top of the page. He is a stupid little trick. it seems you can define LayoutPage anywhere in your page’s markup, I have tried to place it several places in pages and it always works. While you can define the LayoutPage multiple times, the reality is only the last value counts, meaning the last time you set the property designates the layout used to render the page.

@{
LayoutPage = "/_SiteMaster.cshtml";

...

}


@section Header {
<title>Simple Contact Form With WebMatrix</title>
}

The @section Header {} defines the area of markup or logic to generate content rendered for that section in the LayoutPage. Any markup and rendering logic not contained in a @section block is assumed to be the page’s body. It is rendered in the LayoutPage using the RenderBody() function. To my knowledge there is no limit to the number of sections you can define for a layout, however I have to believe the more you define the harder it will be to maintain and performance should suffer.

Now to the actual Layout or Master Page. For this demo I simply moved the layout markup from the contact form defined in the series’ first post. There are two optional sections defined, Header and Footer. It calls the RenderBody() function in the main-content DIV element. Notice there is no logic in my Layout. You can add logic code (C# or VB) just like a normal page. There is nothing preventing you from doing this. I will cover how to pass data back and forth between the Layout and content pages in another post.

<!DOCTYPE html>
<html>
<head>
<link href="@Href("~/css/print.css")" rel="stylesheet"
type="text/css" media="print" />
<link href="@Href("~/css/screen.css")" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="@Href("~/css/ie.css")" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="@Href("~/css/main.css")" rel="stylesheet"
type="text/css" media="screen, projection"/>
@RenderSection("Header", optional: true)
</head>
<body>
<div class="container">
<div id="header" class="span-24 last">
<div class="MainHeader">
<div class="span-16">
<h1>
WebMatrix World</h1>
<h2>
Where it does not matter if you choose the Red Pill or the Blue Pill</h2>
</div>
</div>
<div id="MainNav" class="span-24 last">
<div id="dMenu">
<ul>
<li><a href="@Href("~/")">Home</a></li>
<li><a href="@Href("~/Contact")">Contact</a></li>
</ul>
</div>
</div>
</div>
<div id="main-content">
@RenderBody()
</div>
<div id="Mainfooter" class="span-24 last">
<div id="footermenu">
<ul>
<li><a href="@Href("~/")">Home</a></li>
<li><a href="@Href("~/Contact")">Contact</a></li>
</ul>
</div>
<div id="footerCopyright">
Extreme Web Works &copy; 2010
</div>
</div>
</div>
</body>
</body>
<script src="js/jquery-1.4.2.min.js"
type="text/javascript"></script>
@RenderSection("scripts", optional: true)
</html>

Putting it all together, along with some additional CSS rules we get a pretty basic layout with a simple menu.

Web Matrix Master Page

With Layout Pages the WebMatrix, Razor experience gives designers and developers the ability to create and manage larger sites look and feel without duplicated effort.

Why I Love Working for Tellago

TellagoLast November I made the decision to join Tellago full-time. I was recruited by my friend Don Demsak for about 4-5 months before joining. It meant doing a lot of travel and essentially relocating to a South Florida the majority of time, a place I had only spent about 4 days visiting a decade prior.

As for the travel, I was in a point of my life where I really wanted to get back in the air again. I traveled a little prior to starting Extreme Web Works in the summer of 2000. I enjoy the lifestyle. I realize it is not for everyone, but for me it is a natural place. I like to explore the world. While I am not travelling the world, yet, I do a lot of commuting each week.

If you know much about my story over the past 3-4 years you know it is contains a series tragic events, including some extremely dishonest clients. I am not going to mention them here, I have done that enough amongst my close friends. In fact I think Ajilon was the only really good experience I had in that time frame and they were just fantastic. So I had a natural distrust of joining another consulting company. While everything is not absolutely perfect, it never is anywhere and I do not expect it to be perfect. There are so many things that outweigh the few negatives, which to be honest are dealt with pretty quickly if you just mention a problem.

Quality of Peers

My friend and MVP from New Jersey, Don Demsak recruited me to Tellago. My role is the UX/Web Guy. I am actually an architect by title. Don is our CTO which means he ordered my laptop LOL. But working with folks like Don is so valuable. He is sharp and not limited to just .NET/WCF knowledge. I also get to work with Jesus Rodriguez (the founder), Pablo Cibraro, Gustavo Machado and a few others just on my project. All are super skilled and super talented.

We push each other because we all have a natural drive to be the best we can be. The conversations we have makes it feel like a Code Camp or MIX every week. Several of my Tellago peers are MVPs or should be MVPs types. Many are community leaders, either here in the US or in Argentina. The core competency we own is a deep understanding of enterprise quality SOA architecture and implementation. Which is not the perfect fit for my background, but it has forced me to learn and relearn many things related to the enterprise environment. It has also given me a fertile environment to learn how to build a modern AJAX/ Service oriented application.

Encouragement to Extend Yourself

Sometime this month we will formally launch Tellago Studios, a separate company where we will promote our own products created in house. The first product is SOAware, which I will explain in a later post.

We also have our own CodePlex area, called Tellago DevLabs where we create open source projects that can range all over the place really. We already have a few projects available and I know a few more will be posted in the coming months. One of the latest projects is BizTalk Data Services, a RESTful OData API to interact with BizTalk.

The goal of Tellago Studios and Tellago DevLabs is to encourage us to explore and develop solutions to either share with the masses and even make extra income while getting famous. Ok, so fame may be limited, but the fact Tellago is wise enough to realize developers of this caliber are not satisfied with turning their minds off at 5PM (which I rarely leave before 6:30) or limiting their curiosities to just the project at hand. They foster an environment of exploring and sharing with each other and the community at large.

Encouraging a Real Life

Tellago does realize you do need to relax from time to time and we all have families. So they do as much as they can to encourage us to spend time doing normal things too. Jesus wants all of us to use our vacation time each year for example. Plus traveling so much gives you a lot of free travel.

We also have company dinners from time to time where we can just hang out and get to know each other. Some have even joined together to participate in a charity marathon, etc. Although I can't get Don or Jesus to join me for cheap cheeseburger night at MacDonald's, maybe one day.

Conclusion

I am thankful to be part of Tellago. As I survey the direction technology is going with cloud computing, HTML 5, mobile, BI and many other areas I see Tellago as a company positioned to be a leader going forward. Having the SOA/BI/Enterprise knowledge we posses should be vital to success in the next phase of the web. Can I call it web 3.0 or is that too cliché?

We are always on the lookout for great talent and seem to always have the need for someone new to join the team. If you are interested contact me, Don or Jesus.

I have wanted to post something about my Tellago experience for a while now. To be honest I was just so busy I did not have the time to invest in this post till now. I also wanted to give it some time till I felt like I could express my experience adequately.

Intro To WebMatrix: Create a Contact Form Part 3 Adding E-Mail Support

This is the third in a series of posts on using the new ASP.NET WebMatrix tool. Today we are going to add automated E-Mail functionality. Again the Html Helpers make this a very easy task.

Continuing where I left off after adding the database insert functionality lets add the code to manage an automatic confirmation response and notification E-Mail mechanism. Just following the database code added in the last post I added a couple of string variables to hold the body of the messages. One message goes to the user to let them know their request was received. The other goes to a site administrator type to let them know they have some work to do ;). Notice the use of the string.Format function to perform a simple merge with the data submitted in the form?

//Send E-Mail Confirmations
var contactConfirm = string.Format(
"Thanks {0} {1} for contacting us. We will respond as soon as we can.",
firstName, lastName);

var mewContact = string.Format(
"A new contact request has been made by {0} {1}, {2}. Please respond ASAP!! \r\n{3}",
firstName,
lastName,
email,
comment);

After creating the body of the E-Mail messages its time to send them. If you have ever done automated E-Mail from a .NET application of any kind the following code will be second nature. I am not going to cover the ins and outs of how sending E-Mail actually works here, I have covered how to send E-Mail in .NET several times over the years and it has not changed.

In particular, I encourage you to review the articles I wrote on using Neptune SMTP server as a local SMTP server to test against. Because I am using Neptune I set the SmtpServer property to localhost. If you are trying to test against a non-local SMTP server please make sure you set this property to the address of your test SMTP server.

Next set the port, by default SMTP is port 25. If you have read the documentation that came with my version of WebMatrix it says the port number of 587. That is absolutely wrong. While it could be that is not the default well known port for SMTP.

Continue setting other properties as you need. You will need a from address for the message to originate. The final step is to send the messages. Here you will notice the use of dynamic parameters, a new feature to C# 4.0. If you have worked in JavaScript this will look very familiar to you. Here you can define a series of comma separated parameters and their corresponding values. Since each message has a unique destination, subject and body they are all set in the Send function.

// Initialize Mail helper
Mail.SmtpServer = "localhost";
Mail.SmtpPort = 25;
Mail.EnableSsl = false;
Mail.UserName = "clove";
Mail.From = "info@test.com";
Mail.Password = "pass@word";

// Send confirmation email
Mail.Send(to: email,
subject: "Contact Request",
body: contactConfirm
);

// Send alert email
Mail.Send(to: "test@test.com",
subject: "Contact Request",
body: mewContact
);

Now when the form is submitted it now adds a record to the database followed by sending a couple of notification E-Mails. Here is the entire page’s code and markup so you can see how it all fits together:

@{

var contact = new Contact();

if(IsPost){

contact.FirstName = Server.HtmlEncode(Request["FirstName"]);
contact.LastName = Server.HtmlEncode(Request["LastName"]);
contact.EMail = Server.HtmlEncode(Request["email"]);
contact.Coment = Server.HtmlEncode(Request["comment"]);

var db = Database.Open("Simple Contact");
db.Execute("INSERT INTO Contact (
FirstName, LastName, email, Coment) VALUES (@0, @1, @2, @3)",
contact.FirstName,
contact.LastName,
contact.EMail,
contact.Coment
);

//Send E-Mail Confirmations
var contactConfirm = string.Format(
"Thanks {0} {1} for contacting us. We will respond as soon as we can.",
contact.FirstName, contact.LastName);

var mewContact = string.Format(
"A new contact request has been made by {0} {1}, {2}. Please respond ASAP!! \r\n{3}",
contact.FirstName,
contact.LastName,
contact.EMail,
contact.Coment);

// Initialize Mail helper
Mail.SmtpServer = "localhost";
Mail.SmtpPort = 25;
Mail.EnableSsl = false;
Mail.UserName = "clove";
Mail.From = "info@test.com";
Mail.Password = "pass@word";

// Send confirmation email
Mail.Send(to: contact.EMail,
subject: "Contact Request",
body: contactConfirm
);

// Send alert email
Mail.Send(to: "test@test.com",
subject: "Contact Request",
body: mewContact
);

}
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Contact Form With WebMatrix</title>
<link href="css/print.css" rel="stylesheet"
type="text/css" media="print" />
<link href="css/screen.css" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="css/ie.css" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="css/main.css" rel="stylesheet"
type="text/css" media="screen, projection"/>
</head>
<body>

<form method="post">
<fieldset class="span-12">
<legend>Simple Contact</legend>
@if(!IsPost){
<ul>
<li><label for="FirstName">First Name:</label>
<input id="FirstName" name="FirstName"/></li>
<li><label for="LastName">Last Name:</label>
<input id="LastName" name="LastName"/></li>
<li><label for="email">E-Mail:</label>
<input id="email" name="email"/></li>
<li><label for="Comment">Comment:</label>
<textarea id="Comment" name="Comment"></textarea></li>
<li><button id="btnComment">Submit</button></li>
</ul>
}else{
<p>Thanks @contact.FirstName; @contact.LastName; for your comment</p>
<p>@contact.Coment;</p>
}
</fieldset>
</form>
</body>
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
</html>

Tomorrow I will a master page to the site and apply it to the contact form.

Intro To WebMatrix: Create a Contact Form Part 2 Adding Database Support

Yesterday I posted the first in a series on using WebMatrix to build web sites. The first post created a basic contact form and collected the submitted values. Now I am going to add a database and a table to store the site’s contact form submissions.

First, select the Databases node in the group navigation on the left-had side of WebMatrix. This is the accordion style tool if you are wondering, the Databases node should be close the bottom, just above the Reports node. After you have done this the main surface area in WebMatrix displays the following ‘button’.

Clicking this allows you to add a database. Caution there is no setup dialog to get in the way, the database is just simply added to the site. You can also add a new database by clicking the new database button in the ribbon bar. You can also add a connection to an existing database and add a new table to a database. The database will be named after your site, for my demo it is called Simple Contact, after the site. If you add another database it will be called Simple Contact1. Be careful adding databases to your site, I have not found a way to remove them after you add them.

Now add a new table to the database called Contact. You can either right-click on the Tables node under the database or click the button in the ribbon bar.

Now you need to add columns to the table. To do this you need to right click on the table and select Definition in the context menu. Adding columns to the table is a little different experience than using SQL Management Studio. Shown below you see the column names, but you cannot edit the values here. You need to select each column and in a lower pane you can set the properties of the column; Name, Allow Nulls, Data Type, Default Value, Is Primary Key and Length. Remember this is SQL CE, not full SQL Server so you do not get all the bells and whistles, which is not a bad thing.

Inserting a new record is pretty simple. You just need to add a few lines of code to the existing page. Now let me insert a quick disclaimer, I DO NOT LIKE INLINE SQL STATEMENTS anywhere in an application. But for now we are going to run with it here. I have plans on showing how to leverage good architecture later.

But for now lets follow along with the get it done strategy. The WebMatrix team has made communicating to the database really simple by giving us a Database object. This object has several public members to Open a database and Execute a SQL statement. To open the database just call Open and pass in the name of the database, nothing else and you now have a connection to execute statements. To execute a statement, just call Execute passing in a SQL string. As you can see below you can use the @n to set a placeholder for parameters that follow the statement. Now I do not know how it deals with SQL Injection, etc. I am going to assume there are safeguards in place.

@{
var firstName = "";
var lastName = "";
var email = "";
var comment = "";

if(IsPost){

firstName = Server.HtmlEncode(Request["firstName"]);
lastName = Server.HtmlEncode(Request["lastName"]);
email = Server.HtmlEncode(Request["email"]);
comment = Server.HtmlEncode(Request["comment"]);

var db = Database.Open("Simple Contact");
db.Execute("INSERT INTO Contact (FirstName,
LastName, email, Coment)
VALUES (@0, @1, @2, @3)"
,
firstName,
lastName,
email,
comment
);
}
}
 

That is pretty much it. Now when you fill in the form and submit it a new record is added to the Contact table.

As you can see the Webmatrix experience makes working with databases very easy. Again I do warn I am not a fan of the inline SQL, but remember this is not a true professional development tool. It is aimed at simple web development needs.

In my next installment we will add automatic E-mail capabilities to the site. From there I will add validation, master pages and other features that are important to have a fully functional web site.

Intro To WebMatrix: Create a Contact Form Part 1

WebMatrixEarlier this week Microsoft released a Beta version of WebMatrix, as web development tool aimed at new developers, hobbyist and those new to the Microsoft web stack. Today I am going to walk through building a standard contact form using WebMatrix. The form will collect a First and Last name, E-mail and Comment. The data will be stored in a database table and e-mail confirmations automatically sent. This is the first installment of three. Today We will build the basic form, tomorrow we will add the database component and finally the E-mail.

Step 1: Create the Site Foundation

For this tutorial I am going to lay an initial foundation we can build upon later. First, open WebMatrix and select Site From Template. In the dialog, and don’t you like the subtle AJAX style dialogs in WebMatrix, select the Empty Site Template.

WebMatrix

The next step is to add files to the site that will be used to build common features. This includes CSS and JavaScript files. For the CSS I have added 4 CSS files, the first three are Blueprint CSS and the fourth is the site’s actual CSS rules. The next is the jQuery library, which is simply the current release, 1.4.2 file.

WebMatrix

As for Blueprint CSS this is the first time I have used it here on this blog. I was introduced to it at the South Florida UX group this summer. I have heard of it before, just never had the time to work with it, till now. For now, if you want to learn more about how to use Blueprint CSS in your sites please visit the project Wiki.

Blueprint is a grid based CSS framework that breaks a page into vertical 24 columns. There are rules defined in the framework you can assign to your page’s layout elements. Again, I am not going into a Blueprint tutorial today, but the site needs some basic rules to define how the form will layout. The main.css file contains these rules. Simply put they define how the fieldset, legend, li, input and button elements will render.

fieldset{
margin:auto;
margin-top:2.5em;
}

fieldset.span-12{
margin-right: auto;
float: none;
}

legend{
text-align:left;
background-color:#cecece;
}

fieldset li {
display: inline-block;
width: 100%;
}

label {
float: left;
width: 8em;
margin-right: 1em;
text-align:left;
}

input {
float: left;
width: 12em;
margin-right: 1em;
}

button {
float: right;
margin-right: 1.25em;
}

WebMatrixI place the CSS and JavaScript files in the css and js folders respectively. I also created a folder to contain images. I am not going to use that for this tutorial, but eventually it will be used as I progress the site.

Step 2: Create the Form

Now to add the contact form. This is pretty standard, just use HTML markup to layout a form. For me this is an unordered list containing labels and inputs for each field. The HEAD contains references to the CSS files as well as the page’s title. The reference to the JavaScript file(s) are located at the bottom.

<!DOCTYPE html>
<html>
<head>
<title>Simple Contact Form With WebMatrix</title>
<link href="css/print.css" rel="stylesheet"
type="text/css" media="print" />
<link href="css/screen.css" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="css/ie.css" rel="stylesheet"
type="text/css" media="screen, projection"/>
<link href="css/main.css" rel="stylesheet"
type="text/css" media="screen, projection"/>
</head>
<body>
<form method="post">
<fieldset class="span-12">
<legend>Simple Contact</legend>
<ul>
<li><label for="firstname">First Name:</label>
<input id="firstName" name="firstName"/></li>
<li><label for="lastname">Last Name:</label>
<input id="lastName" name="lastName"/></li>
<li><label for="email">E-Mail:</label>
<input id="email" name="email"/></li>
<li><label for="Comment">Comment:</label>
<textarea id="Comment" name="Comment"></textarea></li>
<li><button id="btnComment">Submit</button></li>
</ul>
</fieldset>
</form>
</body>
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
</html>

WebMatrix

Now the form markup is defined we can start adding some code to make it do something. Now we get to the Razor syntax. Above the DOCTYPE tag add a code block, @{  }. Inside this block I added some variables to hold the values for each field. Then I added an if statement to check if the page was in a Post-Back state. Similar to the IsPostBack property of the traditional ASP.NET page the Razor View Engine has the IsPost property. When the page has been posted back you can access the posted field values just you have been able to do since Classic ASP days, Request[variable name].

@{
var firstName = "";
var lastName = "";
var email = "";
var comment = "";

if(IsPost){
firstName = Request["firstName"];
lastName = Request["lastName"];
email = Request["email"];
comment = Request["comment"];
}
}

Using the IsPost variable in the markup you are able to display a different set of markup based on the post-back state. For this demo I chose to display a simple confirmation message to the user.

@if(!IsPost){
<ul>
<li><label for="firstname">First Name:</label>
<input id="firstName" name="firstName"/></li>
<li><label for="lastname">Last Name:</label>
<input id="lastName" name="lastName"/></li>
<li><label for="email">E-Mail:</label>
<input id="email" name="email"/></li>
<li><label for="Comment">Comment:</label>
<textarea id="Comment" name="Comment"></textarea></li>
<li><button id="btnComment">Submit</button></li>
</ul>
}else{
<p>Thanks @firstName; @lastName; for your comment</p>
<p>@comment;</p>
}

Save the cshtml file. Now you can open it in a browser to take it for a spin. Fill in the fields and submit the form. After you submit the form you should get the conformation message in the fieldset.

WebMatrix

This is where I will leave this application for now. I will be adding database support in the next post.

Microsoft’s WebMatrix, The Simple ASP.NET Editor

Remember the days of Classic ASP? You know when you could build an entire application in notepad and some simple VBScript? Then Visual Interdev came along and well 12 years later we have a mountain range of classes and Visual Studio 2010 along with other productivity tools to help us build web applications.

What if I said you could have all that simple freedom back to develop web sites? Well you can. Microsoft has just announced its latest web development platform and tool, Microsoft WebMatrix which utilizes the new Razor syntax.

There are several key audiences Microsoft is trying to appeal to with WebMatrix. In particular the PHP and Ruby crowds as well as new developers. The Webmatrix experience is designed to be a step up from the notepad development experience, but not overwhelming like Visual Studio can sometimes be.

WebMatrix

My initial impressions have been really favorable. As seasoned as I am with Visual Studio I really like the simple approach with WebMatrix. One thing that I do find to be missing is no intellisense or auto-completion. So be aware of those missing features professional .NET developers are typically accustomed to using.

For more initial information please visit Scott Guthrie’s WebMatrix announcement post. Download the Beta release of WebMatrix from Microsoft. You can also view WebMatrix videos and tutorials on ASP.NET. I have several blog posts almost ready to go at the moment on how to accomplish things with WebMatrix. So please come back each day for these to be released.

The query parameter '$format' begins with a system-reserved '$' character but is not recognized

Twitter oData WhiningTuesday morning I was ranting on Twitter, well really whining, about how WCF Data Services does not support JSON format out of the box. Fortunately I was shown the answer in replies to my rant. So I want to share this with you.

First, I made the mistake of learning to work against the oData specification, not WCF Data Services. Despite the marketing feel around oData and WCF Data Services, the latter does not completely implement the oData spec. In particular it does not support JSON out of the box. As a Web/AJAX developer this is sort of a big deal.

Trying to retrieve a WCF Data Service requesting JSON using the $format=json in the querystring results in the following being returned:

This is a screenshot taken in Fiddler. I had to do that because it just gracefully fails making the AJAX call using jQuery.

Yes, I set the Accepts header to application/json and got ATOM back. So finding a solution was very important to me.

Twitter oData WhiningAfter finally determining WCF Data Services does not support JSON out off the box I searched for a solution, one that did not require mush thought to be honest. The first solution I found was by Josh Eistein, where he created an HttpModule to support JSON. But this is WCF and HttpModules just don’t feel right.

Next Mike Flasko pointed me to a WCF JSONP Behavior Pablo Castro has posted on the Microsoft Code Gallery. You can download the sample code that contains the JSON behavior classes you need to add to your service. This is the answer to the problem. Once you add the JSONPSupportBehavior attribute to your service class it now supports the $format=json parameter.

[JSONPSupportBehavior]
public class SampleService : DataService<ContactsData>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
}
}

Now calling the service method using jQuery returns JSON, the easy to digest data format.
 
<script type="text/javascript">
$(document).ready(function () {

var query = "http://localhost.:32006/SampleService.svc/People?$format=json"; //Make sure you adjust your port #

$.ajax({
dataType: "jsonp",
contentType: "application/json",
url: query,
success: callback
});

function callback(response, status, xhr) {
alert(response);
}

});
</script>

Viola!!:

The more I understand how the sausage is actually made at Microsoft the more I understand why this was not included. But then again I have a hard time understanding why in this case. Its a pretty simple thing to implement on the surface at least.

Whatever the reason, this works for now and I am happy. Just wish I did not have to go through the hoops I did to make it work. So download the JSONPSupportBehavior source code and add it to your next WCF Data Service.

What Would You Select?

Software development is a collection of trade offs; performance for speed to market, quick & dirty vs. maintainable, on and on. Most tend to sacrifice user experience at some level for time to market, other do not consider maintainability, reliability. You can keep adding things you have experienced. Lately I have had a torrid relationship with the jQuery Masked Edit Plugin.

Like all love affairs you go through a cycle of sheer bliss where the new target of your affection is just awesome. This is soon followed by a period of time where you enjoy your time together, but there is nothing new being added to the relationship. Eventually you reach the real commitment or cut them loose point. If you really commit to each other you go through a tough time of really getting to know each other at a very intimate level. Ultimately you find ways to add real value to each others lives. If you cut them you go find another love of your life and repeat the cycle.

Often as developers we cut pretty quick, rinse and repeat over and over. But then eventually we find a great fit for us. And we get very attached, but more importantly we get very skilled at knowing exactly what our tool|control|plugiin etc really wants to do and how we can elicit the behaviors we need.

So I am at that very critical point with the jQuery Masked Edit plugin. I mean it is just awesome, really it is. But users, man they are fickle and they want what they want when they want it. So begins the part of my relationship with a control where it was great for a lot of things, but ultimately the user wants way too much and the control/plugin breaks under the pressure.

If you are not familiar with the masked edit plugin, it is simple way to provide the user guidance when entering data in a web form. For example instead of three input fields for a US phone number you can create a mask like (999) 999-9999 and the user can just type the number and the dashes will just appear in the correct places. I have fond all sort of places to integrate the plugin to make the user experience just that much better…or have I?

$(document).ready(function () {
$('input.PhoneMask').mask("?(999) 999-9999");
$(".orderQty").mask("?9999", { placeholder: "" });
$(".ZipPlus4").mask("?99999-9999", { placeholder: "" })
});

The more you work with the plugin as a user you eventually find the situation where you are switching between windows to get a value or where you must loose focus on the masked input field to make sure you are typing the value correctly. Just applying a phone number masked will cause the partial value to disappear when you return. This can be very frustrating, it’s even hard to take a screen shot of this happening!

Masked Edit Plugin Demo

Fortunately the masked edit plugin lets you define a place where a partial value is allowed. Changing the phone number mask to ?(999)-999-9999 instructs the plugin that any character to the right of the ? is optional. You can place the ? anywhere in the mask, it is just an indicator to the plugin and will not be render in the input field. Remember this is a mask, not a validator, so this could be a perfectly valid situation. You can apply the validation plugin for validation here and have a great combination.

Great so the problem is solved! But now we have another issue this has created. Funny how solving problem X begets problem Y when we are programming! Now the masked edit plugin struggles with caret positioning. When the plugin does not allow partials and you set focus to the input field the entire value is selected. Once the partial indicator is applied the plugin is not quite sure what to do here. So it just puts the cursor at the beginning, not the end, not where you point the cursor when you click your mouse pointer.

Optional Masked Edit Plugin Demo

Another side-effect I found is the plugin does not let go of a value when you do select the entire text and delete it. It simply deletes the first character. So by designating the mask to allow partial entry you have solved one user problem, but create two, probably worse UX problems.

So here is the decision to be made, forgo the partial data entry, deal with the crazy side-effects or become truly insane and write your own plugin to solve the problem for each and every mask field?

I guess it depends on your situation to be honest. If you are rushed for time decide what feature is the most optimal for your target users. If you have enough time then by all means create your own plugin solution. Once you have done the first one, the second comes much easier. Eventually you will have a very robust masked edit plugin that will be pretty close to the one in question here.

The next option is to tell the author what you want and hope they eventually get around to it in their spare time. Remember, except for the Microsoft jQuery plugins there is not really author being paid to develop the code. You of course could try to update the plugin with the functionality you need, then share it with the author, etc.

Finally you can just ship it in a broken state and fix it later of course. We all know how that intention ends though.

In the end software development is not really different than any other aspect of our lives. Decisions must always be made and that involves trade-offs. You must evaluate where you are and what you can reasonably do. I really like the jQuery Masked Edit plugin, I use it all the time. But as with any love affair you eventually find your lover’s flaws and either learn to live with them, help improve them or abandon and start over. For now I am going to live with them. As time permits I hope to improve them. Ultimately I probably will not leave the masked edit plugin, its been good for me.

10 Ways to Debug JavaScript in IE 8

I know, I know use FireBug and FireFox. I hear it all the time. I say meh, everyone does that. As I wrote last year, in IE 8 press F12 and Bazinga!!! You get the IE Developer tools. Read more about using the IE developer tools in my old post. But I show this in my CodeCamp sessions and folks are just amazed the tools are there and they work quite nicely.

Now that I spend a majority of my web development in the JavaScript layer debugging my scripts is very important. If you are working in the corporate world chances are you are targeting IE (version 8 I pray). So lets look at 10 ways to debug your JavaScript in IE 8.

Set Breakpoints

Any good debugging experience has to allow you to set a breakpoint, or designate a place in your code to stop execution and allow you to examine variables and process flow. The IE Developer tools are no different. Just like Visual Studio you can view your JavaScripts in the Script Tab.

Across the top of the tab there is a toolbar, the ‘Start Debugging’ button and the dropdown to the right are the most important items. More about the button in a moment. The dropdown is a list of scripts and markup pages, i.e. resources that can contain JavaScript. Clicking the dropdown list reveals a list of possible scripts, selecting an item opens that script in the tab.

The script window is a viewer, not an editor, which I can understand. There are many instances where it would not have rights to edit anyway because the scripts are loaded through a web server, etc. The line number is displayed to the left, which is important to locate code to actually edit in Visual Studio later.

set breakpoints

Setting a breakpoint is very straight forward. Place your cursor on the line you want to set a breakpoint and press F9. In the right-hand pane there are several action buttons on the right, which are basically tabs they just don’t look like it. Selecting the Breakpoint option shows a list of breakpoints. There is a checkbox to the left of each breakpoint. Unchecking the correlating checkbox disables the breakpoint. You can also delete individual or all the breakpoints as well.

To enable debugging mode the ‘Start Debugging’ button needs to be pressed. This changes the button to a ‘Stop Debugging’ button, which make sense, right? Now when you load the page, or cause script to be executed the debugger watches the execution and if it hits a breakpoint it stops execution to allow you to evaluate the code.

Just like other IDE (i.e. Visual Studio) conventions convey for stepping through code. F10 goes to the next line in scope, F11 steps into a function, etc. F5 even starts the debugger and lets you continue execution from a breakpoint. You can even set breakpoint conditionals. That is where you designate a condition where the breakpoint actually executes.

View Local Variables

Now that you have hit a breakpoint there are two things you need to do, see what variable values are and of course step through the code. Back over to the right-hand pane there is another button called ‘Locals’. Pressing this button reveals, well nothing really, until you hit a breakpoint. Once you hit a breakpoint in a script you will see all the locally scoped variables on the left and their values on the right. If a variable is an object literal you can expand it to see the values of each property. You can expand properties too if they are objects.

view local variables

Add Watches Directly From Your Code

Additionally you can also add custom watches. These can be viewed by pressing the ‘Watch’ button on the toolbar. Custom watches can be added in two ways. First by selecting a variable or expression in the script, right-clicking and selecting ‘Add Watch’. The selected variable or expression is now added to the Watch window.

Add Custom Watches Directly in the Watch Tab

You can also add a watch by hand by clicking on the last row in the watch window. Here you can just start typing in the variable name or expression to watch. This is extremely useful when you are trying to see things like what a different selector references or a modification of an expression. You can also edit any watch by clicking it. Then you just start editing it as needed.

custom watch

Step Through Your Code

Stepping through code is a breeze as well. F10 to step to the next line. F11 steps into a function. Be careful stepping into functions, if you step into a minified script (like the jQuery framework) you will most likely feel lost and it may be somewhat difficult to get back up to your code because the flow goes through so much framework code.

set breakpoints

Change a Variable Value

Just like working in Visual Studio you can change the value of a variable in the watch window as you are stepping through code. You can do the same in either of the IE Developer Tools Watch windows. Simple double-click the current value and change it accordingly.

edit variable value

Drill Into an Object

I mentioned above you can expand an object in either of the watch windows. If a variable is an object literal you will see a + icon to its left. This indicates it can be expanded to view the child properties. One you do this you can manipulate their values and expand them as well.

view local variables

Use the Console To Test Code

The console is just like the Console window you never use in Visual Studio the IE Developer tools allow you to type expressions for evaluation. You can think of this is sort of a scratch pad to try ideas out. If your script hits an unhandled exception you will also see the error messages here.

Console

You can also use the console object in your script to echo information to the this window during the execution of your test.

Use the Console to Reveal Syntax Issues

I mentioned above if there is an unhandled exception in your script it will be logged to the console window. This is true if you have a syntax error. When the browser loads your script and there is a syntax error, think missing ; or closing } etc, you typically see a little warning icon in the bottom-left corner of the browser. Viewing the console window will tell you what the issue is. It also allows you to click a link on the message to take you to the line of code in the script window to the left. This feature has really helped me out a lot over the past few months.

Profile Your Code to Find Inefficiencies

Finally, Another tab on the main toolbar is Profile. This is very useful to track down bad code.

Profiler

To profile code press the Start Profiling button. Then run your script, interacting with is as necessary. Once you are done, press the same button to stop profiling.

Profiler

Now you can see how many times a function is called and how long it executes. You can now track down inefficiencies in your script and make it better.

So the next time you are debugging an AJAX application targeting IE, do not fire up FireFox to debug it, just use the browser you are targeting. If you were at MIX this year I hope you attended the mini session on the IE 9 developer tools. The toolset only gets richer. It even bakes in a mini version of Fiddler. Speaking of Fiddler stay tuned for my next post

Still Stuck With IE 6? Consider Just Jumping to IE 9

Odds are if you are viewing this Blog with IE 6 you are in a large, slow moving corporation. I really doubt normal folks reading this Blog would still have IE 6 installed on their home or small business computers. If so, Bad Geek, Bad Geek, now go think about what you are missing. Seriously there is no good reason for anyone to use IE 6, it is a 9 year old browser (warning clicking that link may display a disgusting image).

Internet ExplorerThe Internet moves fast, really fast and standards, trends and techniques change almost daily. Well maybe not really that fast, but at least the way we as developers and designers learn to leverage HTML, CSS2/3 and JavaScript. In the past 9 years we have learned to build some pretty amazing applications. Just think about it, back then AJAX was still just a household cleaner!

The real culprit behind the continued use of IE 6? Well corporations of course! Chitcka did a survey of browser usage by the hour and determined the peak IE 6 usage hours were during the US work day. Why would the corporate world force their employees to use a less secure and less functional browser? Well they have built so many behind the firewall applications that are in a word, bad. Not bad in the fact they don’t work, but bad in the sense they were not written to have a forward life.

What is a ‘forward life’ you may ask, well its developing an application so that it cannot reasonably function in the near future as trends and standards progress. Think long Gevity.

Why Wait for IE 9?

With so much effort to get users to stop using IE 6 you may be wondering why I am espousing the idea of waiting for IE 9 as the natural upgrade path. The answer is two fold really, to avoid repeating yourself with IE 8 and to give you time to upgrade your applications.

Sadly the trend I am seeing in the corporate world right now is to upgrade to IE 7, again why? Well because most corporate IT directors have this long outdated mentality that you must wait 2-3 years for a release to be ‘stable’. This is modern day hog wash! These same IT decision makers probably drive a car built in the 70s I bet. Of course they don’t, they are probably already driving a 2011 model. Honestly there is no reason to not be using IE 8, or the latest FireFox or Chrome. So no, I am not going to advise IE 6 companies to plan a strategy to migrate to IE 8 specifically, but please do (like NOW). Just plan on moving to IE 9 next year as part of your plan. This really means upgrading your application to support the W3C standards, not a specific browser.

Time To Upgrade

IE 9 is set to release sometime next year, my guess is at MIX 11. Why, well Microsoft likes to use large events like MIX to make major releases. If you are not aware, MIX is Microsoft's web technology conference, an ideal place to launch a new browser. This year at MIX 10 Microsoft unveiled a preview look at IE 9, with demonstrations of its new functionality and performance improvements.

So that gives you roughly 10 months to get ready, so get moving. This means you need to upgrade all of those poorly written applications from 2000-3, but seriously, isn’t an update long overdue for those applications anyway?

How Can You Test Your Applications Upgrades?

That’s pretty easy, just write your application to the standards. That means know HTML 4+ and CSS 3 and apply it to your applications. You can test in IE 8, FireFox and Chrome. And I well make a sizable wager that Microsoft will release previews of IE 9 later this year. Currently you can see use the IE 9 Developer Preview. If not I am sure you will see it before it is actually released so developers can really test their apps. But as usual, they are really wanting to see if IE 9 works in the real-world and fix any flaws unearthed by Beta testers.

The Moral of the Story

Companies still forcing their developers to create applications to support IE 6 are just hurting themselves. They are telling their employees they really do not care about their security and quality of life. For their developers they are saying this is a dead-end place to work, you can never advance your career.

Web standards are a great thing. They allow developers to code against a common target, not a browser. The browser is only responsible for rendering the application according to these standards. The browser competition is to perform this task the best. So far IE 9 looks to be doing a great job executing these standards. FireFox and Chrome are already implementing many of the newer standards. By creating applications to the standards you give your users the freedom of choice to use what browser they like best.

By avoiding IE 6 support corporations only stand to gain by freeing their developers to spend more resources on more modern applications. Applications that really take advantage of the standards that are driving great user experiences everyday. Each day these standards are exercised further by developers all over the world and the bar is constantly being raised to create great user experiences that make companies run efficiently and profitably. The choice to stick with a 9 year old, out dated and insecure browser is a choice that screams”This is a dead company, run far away.”

JavaScript The Good Parts – Book Review

Over the past 18 months or so I have become a heavy jQuery programmer. You can say a lot about using jQuery, one thing I thought I would never say is I love working with JavaScript, er I mean ECMAScript. As you start working with jQuery and JavaScript you will eventually learn about Douglas Crockford, one of the driving forces behind JavaScript. His book BLOCKED SCRIPT The Good Parts is a staple of the JavaScript library.

JavaScript The Good PartsIf you really want a good explanation of JavaScript’s components this is the book to get. One word of warning you will need to read through the various sections more than once as well as apply the concepts explained on your own before you get some of the more advanced ideas.

The main reason I got this book was to help understand how to build better object oriented JavaScript, or at least better organized AJAX applications. The Good Parts explains various object patterns you can use to build applications. From the Object Literal to various functional patterns, he reviews them all.

But more importantly he covers a lot of key concepts that a JavaScript developer needs to understand such as how equality is actually determined in JavaScript. He also reviews Regular Expressions, Arrays and so much more.

Finally he reviews what he calls the Good Parts and the Bad Parts of JavaScript. I found this section to be extremely helpful in truly understanding how JavaScript works.

So if you are like me and really enjoying jQuery or just really want to know intimate details about JavaScript BLOCKED SCRIPT The Good Parts is for you. It really is a must have for any true web developer.

jQuery Tutorial: Validation with the jQuery UI Tabs Widget

This is so long overdue, but I told Dave Ward last Summer I would post this Blog and well I have not been so good on that commitment. If you want to validate a form that is organized using the jQuery UI Tabs widget you probably need to perform validation as the user switches between tabs. In fact there may be many times you may need to validate a section of a form or a page as the user navigates through various areas. This technique can be used in any of those cases.

Specifically when using tabs there you may need to validate user supplied data before they are allowed to change tabs. The classical case is a wizard where the user steps through each step to reach  a completed state. Typically the wizard will have buttons to go forward and backwards. The user may also want to manually select tabs (not covered here) so validation needs to be performed in both these instances. In this example I am going to assume you have basic familiarity with the jQuery UI Tabs widget and the Validation plugin.

First the wizard markup. This example will use a super simple wizard that collects a user’s name on the first tab and their phone number on the second tab. But you should be able to extrapolate the functionality to forms of any size. If you are not familiar with how the jQuery UI Tab widget works, I recommend reviewing the documentation.

The following markup is the form used in this example:

<form id="MultiTabValidation" action="MultiTabValidation.aspx" method="post">
<div id="tabs">
<ul>
<li><a href="#FirstTab">General Information</a></li>
<li><a href="#PhoneTab">Phone Information</a></li>
</ul>
<div id="FirstTab">
<fieldset>
<legend>User Information</legend>
<ul>
<li>
<label for="txtName">
Name</label><input type="text" id="txtFirstName" class="required"></input></li>
<li>
<button id="btnToPhoneNumber" name="btnToPhoneNumber" type="button">
Next ></button></li>
</ul>
</fieldset>
</div>
<div id="PhoneTab">
<fieldset>
<legend>Phone Number</legend>
<ul>
<li>
<label for="txtPhone">
Phone</label><input type="text" id="txtPhone" class="phone required"></input></li>
<li>
<button id="btnToGeneral" name="btnToGeneral" type="button">
< Prev</button>
<button id="btnSubmit" name="btnSubmit" type="button">
Submit</button></li>
</ul>
</fieldset>
</div>
</div>
</form>

The example requires both the First Name and the Phone number be supplied. It also requires the phone number to conform to a standard US phone number format. There is a forward button on the first tab and a backward on the second along with a final submission button. Just a simple demonstration form organized in a tabbed format.

If you are not familiar with the jQuery Validation plugin syntax the validation is mapped to the input fields by adding a CSS class to the input’s class attribute. The plugin ships with many common validation rules included, but you can extend them as you need for your application. This demonstration uses the require and phone rules. And as you should have guessed class=”required” tells the jQuery Validation plugin that field is required. Adding phone (class=”required phone”) tells the plugin the input is required and should be a valid US phone number.

Now reference the latest jQuery library however you like. You will also need to reference the jQuery Validation Plugin, I also reference the additional-methods.js file for good measure ;). I place all this at the bottom of the page as usual.

Finally I add a script block that contains a $(document).ready(function(){}); and a helper plugin called validateTab. In the page’s ready function I define the validation behavior, I will return to this later.

The validateTab plugin is where the cool stuff happens anyway. It accepts one parameter, toTab, which is the index of the tab to navigate if validation succeeds. But before navigation validation must be performed. An isValid parameter is defined and set === true. This is use to determine if navigation van occur at the end of the plugin.

You may be telling yourself I made a typo above, but no I did not. In JavaScript you can use === to test for real equality and !== real inequality. Using the traditional == or != only tests for what Douglas Crockford calls truthy, meaning in JavaScript it can produce false positives in many instances. So using === is the best practice to test for quality in JavaScript.

Next, since this is a plugin $(this) is the jQuery object reference to the DOM element (the current tab in this case) being validated. Calling the jQuery find() function passing in selectors to grab all form input fields (using ‘input, select’ should get references to all the user input fields). Chaining the jQuery each() function and passing in an anonymous function to check validation gives us a place to check for valid user input on each input element.

jQuery.fn.validateTab = function (toTab) {

var isValid = true;

$(this).find("input, select").each(function () {
if (isValid) {
isValid = $(this).valid();
} else {
$(this).valid();
}
});

if (isValid) {

if (!toTab) {
toTab = 0;

}

$("#tabs").tabs('select', toTab);
}
return false;
}

Inside the anonymous function $(this) refers to the input element to validate, not the tab. Since the page references the jQuery validation plugin you can simply call the valid() function against the input element like $(this).valid(); and it will return true if the input passes its associated validation rules, or false if it does not. If isValid === true then validation is performed and the result is set to the isValid variable. If isValid is already false then it is not set again. You have to do this incase you are looping through elements and one is invalid but followed by a valid element. You still should check validation even if you have crossed a bad value. You should always let users know just how much is wrong!

If all the elements on the tab pass validation (isValid === true) then you can programatically select the desired tab using the following line:

$("#tabs").tabs('select', toTab);

In the document.ready function there are click event handlers for any buttons that navigate between tabs. Each event handler calls the jQuery PreventDefault function to keep the form from doing its default actions. It also calls the validateTab plugin function described above, passing in the target tab’s index against the button’s parent tab.

$(document).ready(function () {

$('#btnToPhoneNumber').click(function (e) {
e.preventDefault();
$("#FirstTab").validateTab(1);
});

$('#btnToGeneral').click(function (e) {
e.preventDefault();
$("#PhoneTab").validateTab(0);
});


});

The nice thing about performing validation by hand is no other tabs have validation performed on them. This means you have more control over the entire process and that performing validation on tab 1 does not perform validation on tab n. If validation were performed on the entire page the user experience would be fairly low because as each new tab is displayed to the user it would be littered with a collection of validation messages.

You can fire individual element validation anytime you need, giving you the freedom to validate anything you need on the page whenever you want. One of the many, lesser known features of the jQuery Validation Plugin.

5 UX Resources for Developers

I have been getting more and more questions about resources I use for various things. Today I was asked about User Experience (UX) resources and to be honest I was just not ready for the question. I do not consider UX to be a component of design or development. It does not belong to AJAX, Silverlight or any other application framework. I really consider it almost a light-black art of understanding how to articulate your application so a user finds it as easy and intuitive to use as possible.

So with that here are 5 places I consider to be a good place for developers to refer when trying to build the all important layout of their application/site. They are in no particular order.

Quince

QuinceA collection of example design patterns done in a really nice Silverlight application managed by Infragistics. The gallery defines problems, how to solve them and then shows these concepts in action on real web sites. What I personally like about this is the examples are not over the top fantastic designs, but real life examples of useful UX design patterns.

Yahoo Design Patterns Library

Similar to Quince Yahoo has a nice gallery of UX design patterns. It also has the problem/solution arrangement.

BoagWorld

Boag WorldBoagworld is a collection articles and a regular podcast on design principles. They cover many topics more tilted towards design and marketing. I have just started checking this site out, so I will reserve a full editorial till later. It does come highly recommended to me from those more in the design world.

Jacob Nielson

I think it is safe to say this may be the Craig’s List of the User experience world. Jacob Nielson’s useit.com is his blog on user experience. He is one of the world’s leading experts on usability.

Twitter

Yes, I find twitter to be one of the best resources for just about anything. The key is to use the twitter search engine to monitor for what’s happening in a field on a daily basis. By following UX related terms you cant help but find twitter accounts that specialize if sharing UX information, like UXTweets.I find all sorts of great resources each day on ASP.NET, jQuery, marketing, UX, music and of course my friends. But first and foremost it is a professional tool for me. I currently use Seesmic’s twitter client because I can designate search terms to be followed so I can know in almost real-time what is hot each day.

UX Tweets

This is not a complete list, but a starting place. Please feel free to ad more references in the comments. Hopefully I can revisit this list in the future.

More Posts Next page »