Friday, March 30, 2012

Rubber Duck Debugging

If Wikipedia knows it, it’s official; Rubber Duck Debugging is a new tool in my developer toolset!

I first heard about this technique here: http://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html.

An extract from the original story:

Bob pointed into a corner of the office. "Over there," he said, "is a duck. I want you to ask that duck your question."

I looked at the duck. It was, in fact, stuffed, and very dead. Even if it had not been dead, it probably would not have been a good source of design information. I looked at Bob. Bob was dead serious. He was also my superior, and I wanted to keep my job.

I awkwardly went to stand next to the duck and bent my head, as if in prayer, to commune with this duck. "What," Bob demanded, "are you doing?"

"I'm asking my question of the duck," I said.

One of Bob's superintendants was in his office. He was grinning like a bastard around his toothpick. "Andy," he said, "I don't want you to pray to the duck. I want you to ask the duck your question."

I licked my lips. "Out loud?" I said.

"Out loud," Bob said firmly.

I cleared my throat. "Duck," I began.

"Its name is Bob Junior," Bob's superintendant supplied. I shot him a dirty look.

"Duck," I continued, "I want to know, when you use a clevis hanger, what keeps the sprinkler pipe from jumping out of the clevis when the head discharges, causing the pipe to..."

In the middle of asking the duck my question, the answer hit me. The clevis hanger is suspended from the structure above by a length of all-thread rod. If the pipe-fitter cuts the all-thread rod such that it butts up against the top of the pipe, it essentially will hold the pipe in the hanger and keep it from bucking.

I turned to look at Bob. Bob was nodding. "You know, don't you," he said.

"You run the all-thread rod to the top of the pipe," I said.

"That's right," said Bob. "Next time you have a question, I want you to come in here and ask the duck, not me. Ask it out loud. If you still don't know the answer, then you can ask me."

"Okay," I said, and got back to work.

I do think it’s useful for the same reason I like buddy reviews and teaching concepts to others. By explaining a problem to someone else, you get new insights, learn new stuff and discover things you forgot.

Next time you see me talking to a rubber duck, don’t think I’m crazy. I’m just debugging my code… Glimlach

Thursday, March 29, 2012

Optimizing for happiness

A must watch for every developer oriented organization(and I hope my boss will read this too Knipogende emoticon). Tom Preston-Werner(one of the founders of GitHub) talks about the balance between optimizing for happiness and optimizing for money.

If this will not help to inspire your people…

Wednesday, March 28, 2012

Enable net.tcp binding support in IIS 7.5

To optimize the performance of a WCF service I built, I decided to change the binding from wsHttpBinding to netTcpBinding.  So I added a second endpoint in my WCF configuration configured to use the netTcpBinding. After deploying the updated application to IIS I got the following error:

“Could not find a base address that matches scheme net.tcp for the endpoint with binding MetadataExchangeTcpBinding. Registered base address schemes are [http].”

Starting from IIS 7.0 other protocols then HTTP are supported. As I was using IIS 7.5 this couldn’t be the problem.

I found out that one extra step is required: you need to add the net.tcp binding to the binding of the application in IIS.

How can we do this?
  • Open the Internet Information Services Manager.
  • Right click on the virtual directory/application in IIS.
  • Choose Manage application -> Advanced settings.

image

  • In the Enabled Protocols part add net.tcp(separated by a comma) and that’s it.

image

Tuesday, March 27, 2012

Rolling out TFS 11: Update your SQL Server first

Last week I finally had some time to start migrating our TFS 2010 environment to the TFS 11 beta. The first time I tried to do the migration it failed because I didn’t had the latest updates installed for SQL Server 2008 R2. The installation procedure mentions that you need at least SQL Server 2008 R2 with SP1 and Cumulative Update 1 installed.

So to get everything working, first install SP1: http://www.microsoft.com/download/en/details.aspx?id=26727

Afterwards you can download and install the Cumulative Updates(I think Cumulative Update 4 is the latest version): http://support.microsoft.com/kb/2633146.

Don’t try to mix the order, in that case you’ll end with the following error message(or something similar) during installation:

The version of SQL Server instance MSSQLSERVE does not match the version expected by the SQL SErver update. The installed SQL Server product version is 10.50.1600.1, and the expected SQL Server version is 10.51.2500.0.

Monday, March 26, 2012

WCF Performance Tuning

Configuring WCF can be a daunting task. So a lot of people just use the WCF default settings and change as little as possible. However changing these defaults can dramatically improve the service performance, so it’s really worth the effort.
Let’s have a look at the most used binding in enterprise environments; the WsHttpBinding.
By default the following setttings are used:

<wsHttpBinding>
 <binding name="BadPerformanceBinding">
  <security mode="Message">
   <message clientCredentialType="..."
   negotiateServiceCredential="true"
   establishSecurityContext="true" />
  </security>
 </binding>
</wsHttpBinding>

There are 2 settings here that can have a negative impact on the performance:

negotiateServiceCredential

This setting determines whether the clients can get the service credential using negotiation with the service. When this setting is set to "true" a bunch of infrastructure soap envelopes are sent on the wire before the client sends its request. When set to "false" the client needs to have the service credentials out of band.

The trade off here is better performance (using "false") versus more convenience (using "true").

establishSecurityContext

This setting determines whether WS-SecureConversation sessions are established between the client and the server. A normal secured web service request requires one asymmetric encryption. Respectively, normal N requests require N asymmetric encryptions. Since asymmetric encryption is very slow, setting up a secure conversation is usually a good practice: It requires a one-time asymmetric encrypted message exchange in order to set up a session; Further calls in the session use symmetric encryption which is much faster.

But most of the time a user sends only one request.In that case set establishSecurityContext to "false".

Remark: As with all performance considerations, measure first!

Friday, March 23, 2012

CruiseControl and TFS:Unable to perform the get operation because it is writable

To integrate CruiseControl with TFS, we are using the TFS CCNET Plugin project on CodePlex. The plug-in works great will all versions of Team Foundation Server(although there is no official support for TFS 2010).

However last week, after importing a specific project, we got the following error message from CruiseControl:

ThoughtWorks.CruiseControl.Core.CruiseControlException: Warning AssemblyInfo.cs - Unable to perform the get operation because it is writable

What happened?

During the build, we update the AssemblyInfo.cs class to include the build number in the assembly information. Therefore we remove the readonly attribute from the file and add the build information to the file. The problem is that TFS tries to be smart about your workspace usage based on the fact that your files are readonly(although this has changed in TFS 11). So it doesn’t like that it finds some files that are not readonly inside your workspace.

As CruiseControl does not remove the workspace by default, the next time you trigger a build, the tfs get operation will fail.

How can we fix this?

Use the following settings inside your CruiseControl TFS plugin configuration:

  • deleteWorkspace=true
  • autoGetSource=true
  • cleanCopy=true

If you combine these 3 properties, the workspace is removed on every build and all existing files are deleted.

That’s it!

Wednesday, March 21, 2012

Internet Explorer 9: JavaScript window.onerror event

For a web application we are building, I added some global error handling behavior using the window.onerror event

But when debugging the application I noticed that the onerror event was never called. I lost a lot of time until I discovered that it was an IE9 only issue.

This fact brought me to the this forum post(Error Handling in IE9) where I found the following information:

“In IE9 when debugging is enabled the window.onerror listener does not get fired as the error was essentially passed to the debugger. The only workaround is to disable debugging. Alas there isn't a work around for this and so far we haven't received any servicing requests for a patch, but if you need one please do contact support / your MS account rep.

In IE10 the behavior was reverted back to the IE8 behavior and onerror should will always be called.”

So if I run the application without a debugger attached, it should work fine. Always fun, this browser specific behavior…

Tuesday, March 20, 2012

Updated DemoMates for Visual Studio 11 ALM Demos

Brian Keller announced the availability of updated DemoMates for the Visual Studio 11 Beta.

A DemoMate is a Silverlight-based rendering of a software demo which can be used to easily learn a demo or show it to an audience (albeit in a strict, linear format).

You can run these DemoMates online, or if you plan on using these in an environment where you might not always have Internet access then I suggest installing the offline version.

Online:
Agile Project Management in Team Foundation Server 11
Building the Right Software - Generating Storyboards and Collecting Stakeholder Feedback with Visual Studio 11
Diagnosing Issues in Production with IntelliTrace and Visual Studio 11
Exploratory Testing and Other Enhancements in Microsoft Test Manager 11
Making Developers More Productive with Team Foundation Server 11
Unit Testing with Visual Studio 11 - MSTest, NUnit, xUnit.net, and Code Clone

Offline: (gets installed locally on your computer)
Agile Project Management in Team Foundation Server 11
Building the Right Software - Generating Storyboards and Collecting Stakeholder Feedback with Visual Studio 11
Diagnosing Issues in Production with IntelliTrace and Visual Studio 11
Exploratory Testing and Other Enhancements in Microsoft Test Manager 11
Making Developers More Productive with Team Foundation Server 11
Unit Testing with Visual Studio 11 - MSTest, NUnit, xUnit.net, and Code Clone

Monday, March 19, 2012

IIS 7.5: Could not load type 'System.ServiceModel.Activation.HttpModule'

On an IIS 7.5 I wanted to deploy a .NET 3.0 WCF application. As no handler was registered for *.svc extension on the CLR 2.0, I ran the servicemodelreg.exe tool available in at C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation.

However this broke all my existing .NET 4.0 WCF services. The .NET 4.0 svc mapping was replaced by the .NET 2.0 version. As a consequence, every service call resulted in the following error message:

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

This error occured because I installed the 3.0 version of the WCF Http Activation module is installed after installing IIS and .NET Framework 4.

How did I fix this? 

Running the servicemodelreg.exe for .NET 4.0(available at C:\Windows\Microsoft.NET\Framework\v4.0.30319) had no effect.

In the end I found that I had to use the ASP.NET IIS Registration Tool (Aspnet_regiis.exe) to register the correct version of ASP.NET.

Don’t forget to add the –iru parameters when running aspnet_regiis.exe.

Friday, March 16, 2012

ASP.NET MVC 3: ViewContext.FormContext

ASP.NET MVC 3 introduced the concept of unobtrusive client validation. Based on data annotations on top of your model,  the HTML helpers render markup with validation info using the HTML5 data attribute:
<input data-val="true" 
data-val-required="The ProductName field is required."
id="ProductName" name="ProductName" type="text" />

These data attributes are picked up by the jquery.validate.unobtrusive library that constructs the correct validation rules for jquery.validate.

ViewContext.FormContext
In our project, we load some parts of the user interface dynamically based on some user actions. We noticed that the MVC framework didn’t render the data attributes in that case.


What’s the reason? We found out attributes with validation rules are rendered only if the ViewContext.FormContext property is initialized. It could be done with Html.BeginForm() method called in the beginning but, as in our case there was already a form on the page, so we set the FormContext manually:


if (ViewContext != null && ViewContext.FormContext == null)
{
 var dummyFormContext = new FormContext();
 ViewContext.FormContext = dummyFormContext;
}

Thursday, March 15, 2012

ASP.NET MVC 3: A Potentially Dangerous Request.Form Value was Detected From The Client

Last week, our users reported a bug that they got the following error back when  submitting some data inside the ASP.NET MVC application we are building:

“A potentially dangerous Request.Form value was detected from the client.”

ValidateInputASPNETMVC

 

This is caused by the ASP.NET request validation. Request validation is actually a good thing since it keeps people from injecting script tags in our application for Cross-Site Scripting ( XSS ) attacks. OK that’s fine, I understand this from a security perspective. But what if the user should be able to enter some special characters in some fields?

AllowHtmlAttribute

Let’s introduce the AllowHtmlAttribute, a property attribute that we can include on model properties to disable request validation on a property by property basis. Now we can turn off request validation just on the properties we want by adding the [AllowHtml] Attribute to it:

public class Order
{
public string Description{get;set;}

[DataType(DataType.MultilineText)]
[AllowHtml]
public string Remarks {get;set;}
}

Wednesday, March 14, 2012

Automapper Array mapping issue

For a project we are using Automapper to map our domain model to our WCF DataContracts.

Last week a bug was logged that a DTO with an array property was set to a zero-length array, although the source instance has the property set to null. We expected that the destination value would also be null. As all our DataContracts are validated against our XSD schemas, an error was thrown.

On the GitHub Automapper site we found that this was already reported as an issue. As a result a new configuration option was added.

If you didn’t download the latest version from the GitHub site but are using an official release, you can get around the issue by using the following code:

Mapper.CreateMap<Order, OrderDTO>()
.ForMember(o => o.OrderLines, opt => opt.ResolveUsing(o => o.OrderLines== null ? null: o.OrderLines));


Tuesday, March 13, 2012

Microsoft adds Mocking/Isolation support to Visual Studio 11

A lot has changed on the testing front inside Visual Studio 11.(If you want to know a good overview of all the changes: http://www.peterprovost.org/blog/post/Whats-New-in-Visual-Studio-11-Beta-Unit-Testing.aspx). One interesting feature I noticed in this long list of changes is the introduction of their own isolation framework:

The Visual Studio Fakes Framework

“Microsoft Fakes is an isolation framework for creating delegate-based test stubs and shims in .NET Framework applications. The Fakes framework can be used to shim any .NET method, including non-virtual and static methods in sealed types.”

Wow! As it also will support to fake both non-virtual and static methods, I can finally isolate some of the harder to (unit)test parts of the .NET ecosystem.

The Fakes framework helps developers create, maintain, and inject dummy implementations in their unit tests. It provides two ways to do this:

  • Stub types Stub types make it easy to test code that consumes interfaces or non-sealed classes with overridable methods. A stub is realized by a distinct type which is generated by the Fakes Framework. As a result, all stubs are strongly typed. 
  • Shim types Shim types allow detouring of hard-coded dependencies on static or non-overridable methods. A shim of type T can provide an alternative implementation for each non-abstract member of T. The Fakes Framework will redirect method calls to members of T to the alternative shim implementation.

Creating Fakes is as easy as right-clicking on one of your project references and choosing Add Fakes Assembly.

Read more about the Visual Studio Fakes Framework in the MSDN Documentation.

Remark: I didn’t add any sample code, as the syntax could still change.

Monday, March 12, 2012

Team Foundation Server Licensing changes

Microsoft introduced some interesting changes last week regarding the TFS licensing requirements.

What’s changed?
  • Team Explorer Everywhere: You no longer need to purchase Team Explorer Everywhere separately. Before today, Team Explorer Everywhere users had to purchase both a Client Access License (CAL) and the Team Explorer Everywhere software, whereas Visual Studio Team Explorer users only had to purchase a CAL – the Visual Studio Team Explorer software has always been a free download (TE 2008, TE 2010, TE 11 Beta) for users who had a license to access a TFS server. Now the story is the same for Team Explorer Everywhere (TEE 2010 with SP1, TEE 11 Beta).
  • Team Foundation Server Reporting – Microsoft removed the TFS CAL requirement  for viewing reports in TFS. This addresses a long standing concern that it was not reasonable to require a CAL for the occasional stakeholder who wanted to check a report to see progress or issues.
  • Using TFS from within Microsoft System Center Operations Manager – With the upcoming release of System Center 2012, you will be able to connect your operations team to your development team, allowing them to better collaborate on production issues. Operations Manager 2012 includes the ability to escalate tickets and all the associated diagnostic data to development by connecting it to Team Foundation Server. The licensing is updated to enable your Operations Manager users to take advantage of this integration without also needing a TFS CAL.

More information and all the details here: http://blogs.msdn.com/b/bharry/archive/2012/03/08/even-better-access-to-team-foundation-server.aspx

Friday, March 9, 2012

ASP.NET MVC 3: Configuring unobtrusive validation

ASP.NET MVC 3 ofeers client side validation through the unobtrusive javascript and jQuery validation plugins. Most of the time the default behavior is fine, but what if you want to tweak the validation configuration?
Only validate the form fields when the form is submitted:
$(function() {
 var validationSettings = $.data($('#formToValidateId').get(0), 'validator').settings;
 validationSettings.onkeyup = false;
 validationSettings.onfocusout = false;
});

As you can see, it’s possible to change some settings through the  validator settings object. By setting  the onkeyup and onfocusout properties to false, the validation on blur and key up will be disabled.
Disable the validation on input fields with class ignore.
$(function() {
 var validationSettings = $.data($('#formToValidateId').get(0), 'validator').settings;
 validationSettings.ignore = '.ignore';
});


Setting the ignore property of validator settings object to .ignore will tell the jQuery validation plugin to ignore all input elements with class ignore during validation. 


Of course there are a lot more options you can configure. For a complete list of jQuery validation options have a look here.

Thursday, March 8, 2012

HTTP status codes database

Looking for a good cheat sheet with all the available HTTP status codes?

Have a look at httpstatus.es. It contains a list of all HTTP status codes with their IETF and Wikipedia descriptions.

image

Wednesday, March 7, 2012

ASP.NET MVC 4 Beta issues

After installing ASP.NET MVC 4 Beta, I was experiencing some strange behavior. Attempting to cut and paste a line inside the cshtml/vbhtml editor resulted in a wait of about 20 seconds. I had the problem in all my Razor files both for ASP.NET MVC 3 and ASP.NET MVC 4. After removing the ASP.NET MVC 4 Beta, everything was back to normal.

Anyone who has a good solution?

Note: I found this post(http://blogs.msdn.com/b/webdevtools/archive/2012/02/27/vs2010-sp1-mvc4-beta-workaround-for-cshtml-vbhtml-editor-s-long-pause.aspx) by a Microsoft employee, but the workaround he suggested(compiling the project) did not solve the issue for me.

Tuesday, March 6, 2012

Responsive Web Design

Today, there is a huge range of devices to think about. I have a 24” inch screen at home, a 15” laptop screen at work, a cell phone and a tablet. So instead of designing your web application for one resolution (what makes it a compromise for all other screen formats), the new trend is responsive web design.There are a multiple definitions available but essentially it means creating a site that will dynamically adapt to different screen sizes by resizing and reformatting its constituent elements.

A great example of response web design is http:// responsivewebdesign.com/robot, a site created by Ethan Marcotte, the author of Response Web Design.

This is how the site looks on my 24” screen:

image

And this on my 15” laptop screen:

image

And this on my mobile phone:

WP7Screenshot

Monday, March 5, 2012

Visual Studio 11(beta) ALM Virtual Machine and Hands-on-Labs/Demo Scripts

My shortest post ever Glimlach.
With the beta release of Visual Studio 11, the Visual Studio 11 ALM Virtual Machine has also been updated, along with all of the hands-on-labs and demo scripts.
Get the updated VM here!

Friday, March 2, 2012

WCF: Whitespace after ampersand disappears

We noticed a strange problem when trying to read the contents of an WCF Message into an XmlDocument. The contents of the message body looks like this:
<Customer> 
    <Name>Laurel &amp; Hardy</Name> 
</Customer> 

The code for the reader looks like this:

XmlDocument bodyDoc = new XmlDocument();
bodyDoc.Load(message.GetReaderAtBodyContents());
XmlReaderSettings settings = new XmlReaderSettings();
XmlReader r = XmlReader.Create(new XmlNodeReader(bodyDoc), settings);

However after saving the results into the database, we’ll see the following information:
<Customer> 
    <Name>Laurel &Hardy</Name> 
</Customer> 

So we lost a whitespace after the ampersand.

The solution is to change the XmlDocument properties and add the PreserveWhitespace option:

XmlDocument bodyDoc = new XmlDocument() { PreserveWhitespace = true };

Thursday, March 1, 2012

NHibernate eager fetching

NHibernate supports the concept of eager fetching for a long time. However there are some things to consider when you start using this with the out-of-the-box NHibernate Linq provider.
Let’s first look at the obvious way:
var customers = session
.Query<Customer>()
.Fetch(c => c.Orders)
.ToList();

This will return the customer and all the customer’s orders in a single SQL statement.
Rule #1: Fetch() statements must always come last.
If you want to mix Fetch with other clauses, Fetch must always come last. The following statement will throw an exception:
var customers = session
.Query<Customer>()
.Fetch(c => c.Orders)
.Where(c => c.CustomerId == "ABC")
.ToList();

But this will work fine:

var customers = session
.Query<Customer>()
.Where(c => c.CustomerId == "ABC")
.Fetch(c => c.Orders)
.ToList();

Rule #2: Don’t fetch multiple collection properties at the same time.
Be careful not to eagerly fetch multiple collection properties at the same time. The following statement will execute a Cartesian product query against the database, so the total number of rows returned will be the total Subordinates times the total orders.

var employees = session
.Query<Employee>()
.Fetch(e => e.Subordinates)
.Fetch(e => e.Orders)
.ToList();

Rule #3: Fetch grandchild collections using FetchMany.
You can fetch grandchild collections too.  The following statement will throw an exception:

var customers = session
.Query<Customer>()
.Fetch(c => c.Orders)
.Fetch(c => c.Orders.OrderLines)
.ToList();

But if you use ‘FetchMany’ and ‘ThenFetchMany’ it will work fine:

var customers = session
.Query<Customer>()
.FetchMany(c => c.Orders)
.ThenFetchMany(o => o.OrderLines)
.ToList();