Browsing Posts published by james

In this final (for now) instalment, let me ask a rhetorical question: Is managed code the right choice for every applications? Absolutely not! For example, .NET and Windows itself are not designed for use in real-time systems. There are no guarentees on worst-case latency during processing. i.e. If you’re writing software for a pacemaker or nuclear reactor – both hard real-time systems since failure results in loss of life – you have deadlines by which you have to complete computations and if you don’t make those deadlines, your system may fail. You might think it trivial to meet a deadline (e.g. worst-case length of computation / instructions per second), but consider the fact that any device connected to the system can raise an interrupt, which can result in your code being preempted so that kernel-level driver code can run. So figuring out worst-case latency involves considering the impact of all connected peripherals (and how they interact) in addition to other factors. Not an easy problem and the reason why there exists many operating systems specifically designed for real-time applications. How much software truly has real-time constraints? Very little, to be honest.

But I digress. I think you get the point that .NET isn’t appropriate for all software, but then again, neither is Java or many other commonly used languages and frameworks. However .NET is applicable to a broader class of software than you might imagine. What surprises many people is that .NET isn’t slower than unmanaged code in many cases. There are a lot of areas, such as raw numerical calculations, where the JITed MSIL code is essentially equivalent to what an optimising C++ compiler would produce. Games, which traditionally try to squeeze out the every last ounce of performance from your hardware, are starting to be written in managed code, and we’re not talking Space Invaders and Pacman. Arena Wars, a real-time strategy game, is built using the .NET Framework 1.1. (I’ve honestly never played this game, but it does go to show you that it is possible to write a real game using managed code.) Games are no longer requiring hand-optimized assembly language for critical loops. (For example, Quake by id Software was written in C with parts in
hand-optimized assembly. Quake 2 was also written in C, but contained
no assembly language. The slight performance gain of using assembly
language was not deemed necessary.)

Look at the performance characteristics of your code. If the bulk of your CPU time is spent in third-party frameworks (like DirectX, a physics engine, or an AI engine), it’s rather irrelevant what you write the code that drives the third-party framework, assuming the overhead of calling it isn’t too high. Imagine a situation where you have a sort and you naively use a bubble sort, which is known to be slow. Should this concern you? That depends on how much time is spent in the sort. If the CPU spends 1% of the overall application time in the bubble sort, speeding it up will result in at most a 1% performance gain. Not worth your time. If however the application spends 50% of its time in the sort, then even a factor of 2 speed-up would result in 25% faster execution. The same is true with the choice between managed and unmanaged code. If the time spent in your code is a small fraction of the overall execution time, it’s rather irrelevant what that code is written in. Pick a language/framework that allows you to develop quickly and with the fewest number of errors. But as I pointed out earlier, managed code doesn’t equate to slow code.

In summary, there are trade-offs in using managed code as there are with any runtime environment. You’re not going to get any faster than hand-optimized assembly (if you have infinite time to optimize), but who is going to write Windows applications in assembly language today? (I’m ignoring Steve Gibson for the moment. Amazing what one can do in assembly language these days, but not somewhere I want to live my developer life personally.) The key is to know your tools and know which ones are right for which job. With that in mind, I leave you with some links comparing managed to unmanaged code performance. I hope that they prove enlightening.

Episode 4: Life, the Universe, and Everything is complete. John and I hold down the fort in the latest episode of Plumbers @ Work. You can find the show notes here (as well as below) and podcast here. It will be posted to MSDN Canada Community Radio shortly.

Show Notes

  • Introduction
  • News Bytes: Renaming of Office “12” to Office 2007
  • News Bytes: Release Date for Team Foundation Server (TFS)
  • News Bytes: WSCF 0.6
  • Developer Destination: HanselMinutes
  • Discussion about Reflector
  • Discussion about SysInternals
  • Developer Destination: .NET Kicks
  • Developer Destination: DNR TV
  • Discussion about Screencasting
  • Calgary .NET User Group
  • Site Navigation in ASP.NET 2.0
  • WebParts in ASP.NET 2.0
  • Upcoming Speakers for Calgary .NET User Group
  • Discussion about AJAX and ASP.NET “Atlas”
  • Test Driven Development (TDD) in AJAX
  • Dan Sellers’ WebCast Series – Security on the Brain
  • Canadian Developers Blog
  • Discussion about WinFX
  • Overview of Windows Communication Foundation (WCF)
  • Overview of Windows Presentation Foundation (WPF)
  • Overview of Extensible Application Markup Language (XAML)
  • Overview of Windows Workflow Foundation (WF)
  • Discussion about Workflows and Activities
  • Windows WorkFlow Foundation (WF) versus BizTalk Server (BTS)
  • Overview of the Windows Shell (AKA, “Monad”)
  • Don Box’s Weblog Post on SOAP versus REST in WCF
  • Overview of SOAP and REST
  • Multi-Core CPUs and the Future with Concurrency

Running time: 56:34

Show References

Discuss this episode in the forums.

After I wrote Common Pitfalls When Handling Exceptions in .NET, I had a few questions about exception handling techniques when you’re writing a Web Service. Of course the common pitfalls still apply. The questions were more around how you should expose those exceptions to the client of a Web Service. Should you let them percolate up and allow the SOAP stack to transform them into SoapFaults? Or should you catch all exceptions in each WebMethod and manually transform them into appropriate SoapFaults? I would definitely recommend using the second technique of catching all exceptions and manually transforming them into SoapFaults. What difference does it make, you might ask? There are two main reasons – the first related to your “contract” and the second related to security.

Let’s talk about Web Service contracts. Your contract – what you are promising to clients of your Web Service – is anything that you expose to the outside world. Typically developers think of this as the methods, parameters, and return values of your Web Service, but it also includes any SoapFaults that your Web Service can throw. You don’t want to let your implementation details (i.e. exceptions that can be thrown) leak into your Web Service contract. Does your client care if the Web Service is written in .NET, Java, C++, or hand-coded assembly language? They shouldn’t. If you allow the SOAP stack to transform exceptions into SoapFaults, you are allowing your underlying implementation details to leak into the contract. Your clients may start depending on the fact that a particular exception is being thrown and transformed into a particular SoapFault. What happens if you want to switch implementations later – for instance switching from ASP.NET Web Services (aka ASMX )to Windows Communication Foundation (WCF)? You will end up breaking client code. Best case scenario (for you, the Web Service developer) is that all the clients update their code to handle the changed SoapFaults. Worst case scenario (from your point of view) is that the install base is too large and you have to replicate ASMX exception-to-SoapFault semantics in WCF.

The second concern is security-related. By allowing exceptions to escape your web service and allowing the SOAP stack plumbing to serialize the exception, you are exposing implementation details, such as stack traces, that could assist a hacker in abusing your service. A good practice is to catch all exceptions in the WebMethod and provide meaningful (and sanitized) SoapFaults to your clients, but record detailed exception information, such as stack traces, using your favourite logging framework.

Don Box provides a succint summary on the whole SOAP vs. REST debate. I couldn’t agree with him more!

Something that I’ve always liked about the Windows NT platform and the .NET Framework is their excellent support for Unicode. Historically programming has been (and continues to be) very English-centric. This is not a problem for me as my native tongue is English, but I’ve learned a smattering of other languages over the years… French – I’m Canadian, eh!, Latin, I’m a geek, eh!, American Sign Language, that’s just cool, eh! I consider myself a multi-cultural person and can only imagine the huge language barrier that software development must present for non-English speakers. Abhinaba has an example of using Hindi variable names in a simple C# progam to show that the C# compiler supports Unicode. This looks so foreign to my Anglophone eyes, but is cool nonetheless. I like his idea of localizing the C# language itself by modifying the C# tokenizer in Mono. This would open up the world of programming to a much wider audience.


For the true geek, consider this… there is a mapping of Klingon to the Private Use Area of Unicode. With suitable modification of the C# tokenizer, you could write an awesome first-person shooter in Klingon. Unfortunately Klingon# (or K# for short) would only compile applications involving serious bloodshed and gratuitous violence. Any other applications would result in a compiler error.

We’ve just released Episode 3: Powered by Infinite Improbability Drive. So that we can get you, our loyal listeners, the episodes more quickly, we’ll be hosting on both MSDN Canada Community Radio as well as on the Plumbers @ Work site. You can find the show notes here, photos here, and podcast here. It will be posted to MSDN Canada Community Radio shortly.

Show Notes

  • Introduction
  • Around the Horn with the Plumbers
  • Security March with Dan Sellers
  • Microsoft Blacklisted C++ Libraries
  • SHA-1 Discussion
  • Team Foundation Server (TFS) Release Candidate (RC) 1
  • Public Release of Internet Explorer (IE) 7.0 Beta 2
  • Various Issues with IE 7.0 Beta 2
  • Development of IE versus Development of Firefox
  • The Browser as a User Experience (i.e. AJAX)
  • Really Simple Syndication (RSS) in IE 7.0 and Outlook (AKA, The Ultimate Pull Application)
  • Information Overload (AKA, Organizing Information)
  • Upcoming Canadian Conferences: VSLive! and DevTeach
  • Half-Time
  • .NET Framework 2.0 Adoption
  • ASP.NET 2.0 Adoption
  • PetShop 4.0 Discussion and Highlights
  • .NET Nuke 4.0
  • Old Microsoft Reference Applications (AKA, “Different Strokes” or “ALF”)
  • Enterprise Library 2.0 Highlights
  • Windows “Live” Highlights (i.e. Domains, Favorites, and Messenger)
  • Other “Live” Projects (Office “Live” and Visual Studio “Live”)
  • Windows OneCare Beta
  • The Realities of a “Secure” Operating System
  • Windows Vista Favourite Features
  • Running as Standard User/Non-Admin on Windows Vista
  • Event Viewer in Windows Vista
  • Windows Calendar (WinCal) in Windows Vista
  • What’s Coming Up for the Plumbers
  • Upgrading to Community Server 2.0
  • John Still Doesn’t Have a Xbox 360

Show References

Rory Blyth and the Ewok
The SharePoint Show
Alberta .NET User Group
Calgary .NET User Group
Dan Sellers’ Blog
MSDN WebCasts
Saying Goodbye to an Old Friend (Michael Howard)
Bruce Schneier
SHA-1 Broken (Bruce Schneier)
KeyLength.com
Michael Howard’s Blog
Team Foundation Server (TFS) Release Candidate (RC) 1 (via Jeff Beehler)
Rob Caron’s Blog
Jeff Beehler’s Blog
Team Foundation Server (TFS) Go-Live License
TFS Blog
Internet Explorer (IE) 7.0 Beta 2
Scott Hanselman’s “Running Internet Explorer 7.0 Beta 2 without installing it.” Post
DevConnections
VSLive! Toronto
DevTeach
MSDN Article for Petshop Migration
.NET Nuke
Enterprise Library 2.0
Windows “Live”
Microsoft Gadgets
Windows “Live” Domains
Windows “Live” Favorites
Tuscany (AKA, Visual Studio “Live”)
Windows OneCare Beta
Windows OneCare Pricing Announcement
TopDesk
UntitledNet (Xbox 360 Locator Application)

You can post comments in the forums. As always, feedback is more than welcome.

When reviewing code, I often encounter problems in the way that exceptions are handled. I’m not going to cover guidelines for designing your own exception hierarchy or whether you should derive from ApplicationException or Exception for custom exceptions. (You should derive from Exception, if you must know. There is really no reason for ApplicationException and was a design goof by the BCL Team, as noted in .NET Framework Standard Library Annotated Reference Vol1.) Here’s five code samples showing improper exception handling and how to fix it. We’ll start from the most severe and go to the more cosmetic…


Code Sample #1:


try {

    // code

} catch (Exception e) {

   // better do something here

}

 

Whoah!!! We’re losing the exception completely. This is also known as swallowing the exception. This is really bad. If an exception is ever thrown, we’ll never hear about it. Even with the best of intentions, it’s too easy to forget to go back and fill in these types of placeholders. If you want to note that an exception handler needs to be implemented, I would recommend the following code instead:

 


try {

    // code

} catch (Exception e) {

   // TODO: better do something here

   throw;

}

 

The TODO will highlight this code in the TODO list in Visual Studio. The throw repropagates the exception so we don’t lose it. We can remove the throw later if we actually handle with the exception.

Code Sample #2:



try {

    // code

} catch (ApplicationException e) {

   if(e.Message.StartsWith(“Some custom error message thrown by another piece of code”)) {

      // Handle the exception

   } else {

      throw;

   }

}

 

YIKES!!! This code is wrong for so many reasons. Simplest is that your error handling code will fail if you correct (or introduce) a typo in your other code’s error message and you don’t get any compile-time checking. It also breaks horribly as soon as you internationalize your error messages. If you need to handle a particular type of exception, derive a new exception type. If you’re using Visual Studio 2005, there is even a code snippet for new exception types. Simply create a new file, delete the class definition, and type “exception-TAB-TAB”. Presto new exception type. You can then explicitly catch that exception as follows:

 



try {

    // code

} catch (CustomException e) {

   // Handle the exception

}

Code Sample #3:



try {

    // code

} catch (Exception e) {

   throw new ApplicationException(“Some useful message about what we’re doing: ” + e.Message);

}

 

Whoah again. We just lost a lot of information about the original exception, including its stack trace and any inner exceptions it contained and made our debugging lives a lot harder. I would recommend the following code instead:

 


try {

    // code

} catch (Exception e) {

   throw new ApplicationException(“Some useful message about what we’re doing”, e);

}

 

This code propagates the original exception as the innerException so that we can see the exact origin of the failure.

Code Sample #4:



try {

    // code

} catch (Exception e) {

   // do something like logging

   throw e;

}

 

This naively looks like reasonable code to repropagate an exception, but it contains a subtle flaw – you’re killing the stack trace. The correct code is:

 


try {

    // code

} catch (Exception e) {

   // do something like logging

   throw;

}

 

A simple throw causes the current exception to continue to propagate including stack trace. You have to watch that your logging or other operations don’t throw an exception that can kill the current exception.

Code Sample #5:



try {

    // code

} catch (Exception e) {

   // Execute code, but never use e, which causes a “variable, e, never used” warning

}

 

This is minor as it only produces a warning, but if you’re not going to use the variable, don’t declare it! The following code has exactly the same behaviour, but does not produce the compiler warning resulting in easier to read build output.

 



try {

    // code

} catch (Exception) {    // We don’t need to refer to Exception, so don’t give it a name

   // Execute code

}

 

or alternatively:

 


try {

    // code

} catch {    // We don’t need to refer to Exception, so don’t give it a name

   // Execute code

}

 

This is just a sampling of common problems with exception handling code that I’ve encountered during code reviews. Please feel free to add any additional ones in the comments. Happy exception handling!

Bil Simser has a great blog post on getting Windows SharePoint Services v2 and SharePoint Portal Server 2003 set up for development in your favourite virtual environment. Given that I’m just doing the install dance with WSS v2, this is great info. I’m taking a twist and seeing if I can get things going with VS 2005 compiling to .NET 1.1 using some MSBuild tricks. I’ll report my success/failure in a few days time.

Bil Simser is looking to upgrade from his current status as SharePoint MVP to the world’s first ever Notepad MVP. Support his cause and wish him luck! You go, boy!

Our second episode is live! John, Bil, and I had a blast talking tech, as usual. Unfortunately Dan was unable to join us, but he was there in spirit. What you’ll get in this one-hour, action-packed episode:
  • Introduction
  • The Plumbers are In – Bil, James, and John Report; Dan is MIA
  • Living the 2005 Canadian Launch Tour
  • The Performance “Gardener” Has Left the Building
  • CTP Hell is Over
  • WPF, WCF, and WF! Oh My!
  • “Office 12”
  • MSDN and TDD
  • Google Analytics
  • Marketing BizTalk Server 2006
  • ASP.NET Web Administration Tool
  • James Gets Excited about Virtual Server 2005 R2
  • Half-Time
  • WinFX, Part Deux: Visual Designers
  • Clemens Vasters’ “Soccer Anywhere” Project
  • Microsoft Application Verifier (Bounds Checker on the Cheap)
  • PromptSQL: Intellisense for T-SQL
  • Visual Studio 2005 Add-Ins
  • SharePoint Adventures with the DSL Toolkit
  • Taming the “Wild” Corporate Developer with VSTS
  • SQL Server 2005 Service Manager and The Case of the Missing System Tray Icon
  • Orb.com
  • Xbox 360, Where Art Thou?
Without further ado, I present to you:
 
 
You can catch the RSS feed here. You can leave us feedback and suggestions on the podcasts at .NET Plumbers.