Yesterday I posted an entry on dealing with larger result sets that cause Fidder to create a ReadResponse() failed error. In that post I mentioned I turned on WCF Tracing to help debug the problem. This is a setting that when turned on causes the WCF stack to generate a couple of log files that can be used to see the details of what is going on. You can read more about the details of WCF Tracing on the MSDN site.
To turn on WCF tracing you need to add some sections to the web.config or app.config of your application:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Error,ActivityTracing"
propagateActivity="true">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener"
name="Default">
<filter type="" />
</add>
<add name="ServiceModelTraceListener">
<filter type="" />
</add>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging"
switchValue="Warning, ActivityTracing">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="ServiceModelMessageLoggingListener">
<filter type="" />
</add>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="tracelog.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
<filter type="" />
</add>
<add initializeData="messages.svclog"
type="System.Diagnostics.XmlWriterTraceListener,
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
<filter type="" />
</add>
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
<system.serviceModel>
<diagnostics>
<messageLogging logMalformedMessages="true"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="true" />
</diagnostics>
</system.serviceModel>
</configuration>
If you already have a serviceModel section you can just add the existing diagnostics section. Once you have these configuration sections in place WCF will start tracing all calls.
The tracing infrastructure creates two trace files. These files can be viewed using the Microsoft Service Trace Viewer.
The Service Trace Viewer breaks the trace report into a viewable representation of the data and much like fiddler gives you the ability to view the data in the raw XML format. If you notice at the bottom of the view (click the image to enlarge it to full screen) you will see the following error message.
There was an error while trying to serialize parameter urn:
[ProjectNameSpace].UI.WebSite.WebServices.ServiceContracts.[ServiceName]:FindOrdersResult.
The InnerException message was 'Maximum number of items that can be serialized or deserialized
in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. '.
Please see InnerException for more details.
Service namespace obfuscation aside this tells me what the real issue with my service call is. In this case the result set is larger than the default allowed. It also tells me I what I need to do, increase the MaxItemsInObjectGraph property. This allowed me to concretely make decisions to solve my problem.
So just like you can inject detail error error logging in the ASP.NET pipeline, like ELMAH, you have a built in tracing and logging solution that comes with WCF.
If you have found this Blog entry most likely you are seeing this response in Fiddler. It is accompanied by an HTTP status code of 504. ReadResponse() failed: The server did not return a response for this request is not very helpful and in fact fairly useless in debugging the problem, well short of looking up the exact phrase on Bing or Google to find this blog :).
Successful Response
ReadResponse() failed
I hit this error when trying to return an extremely large set of records via a WCF service today. In fact back at the New York City Code Camp I was asked if WCF could serialize a large dataset into JSON and I started playing at the time. I had sort of forgot about this over the past few months.
Diagnosing the problem involved turning on WCF Tracing and verifying my suspicion that I had hit a default limit. Well the WCF DataContractSerializer has a limit of 65536 object in the object graph. So I did the match on my demo data I was using to work through this issue and yes, I was over that limit in the number of objects. I had a 13 property object and crossing the 5041 record limit caused this issue to surface.
Now back to the ReadResponse() failed issue when using Fiddler. This is my suspicion at this point, so take it for what it’s worth. Based on things I read Fiddler creates this error message in response to a network error, hence the HTTP 504 status code, which is NOT an IIS generated code. It is actually a proxy generated status code and since Fiddler is a proxy this is why you get a 504.
My deduction is the large record set pushes some sort of limit on the network packets and an end of file is missing. Hence Fiddler cannot complete processing of the file stream coming in and promptly throws the proxy error.
Now, how do you deal with large sets of data in the context of JSON, AJAX, WCF, jQuery, etc? Well my suggestion is you don’t. Yes I said it, you don’t. Here is my rational. If you intend to page, sort and filter data in the browser you are wasting your time. It is NOT designed to do this. Yes you can do all that with great performance for small, reasonable sizes of data. But databases were designed to perform these tasks on data, not a JavaScript array sorting algorithm. Instead drive your users to define a much better set of criteria to narrow down the result set. This will give you the ability to reduce the to a manageable size.
I guess how you limit your set of data is up to you. Two strategies that I like are checking the potential size and throwing a ThisIsNotGoingToHappenException to the user so you can let them know they need to do something more to limit the results more. The next is limiting the results to say 500 or 1000 or some other manageable arbitrary size of your choosing and letting the user know there might be more. Either way I think its a good idea to let the user know there is more available, just be more specific. Of course you will have to give them a way to reduce the set.
If you are not having an issue with large responses being sent from the server and you still get the ReadResponse failed error from Fiddler, there is most likely something that is causing a corrupt stream to be sent from the server to the client, Fiddler in this case.
If you normally read this blog you may be wondering why I am posting it, trust me it needs to be done. Setting up an e-mail account in Outlook is one of the simplest tasks to do on the Internet. First open Microsoft Outlook, next open the tools menu as shown here:
Next either create a new account or select the account you need to edit:
The next step is to setup your account information and your login information to check your e-mail. For my mail server this is your full e-mail address and the password you setup through the web client.
The final step that needs to be done is to click the More Settings button on the bottom right corner of Change E-Mail settings dialog. This will open a 4 tabbed dialog. Chose the Outgoing Server tab. Here you need to set up the authentication for your SMTP server. Again for my mail server it is your full e-mail address and your password. It is always a good idea to remember your password.
There is nothing more or nothing less you need to do.
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.
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!

So go forth and create great custom jQuery selectors.
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 © 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.

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.
Last 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.
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.
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.
Earlier 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.

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.

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;
}
I 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>

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.

This is where I will leave this application for now. I will be adding database support in the next post.
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.
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.
Tuesday 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.
After 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.
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!
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.
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.
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.

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.

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.

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.

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.

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.

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.

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.

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.

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 
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).
The 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.”