Significant figures bug in C# and .NET in general


Presently, I am working on a scientific application, and have been creating some data tables. A request was made to me to ensure that some data columns be rounded to 3 significant figures e.g.

10.1234 becomes 10.1

10.7335 becomes 10.7

1.1003 becomes 1.10

I thought through this request with nonchalance at first, but was surprised just how difficult and time consuming it turned out to be to fulfil. After trying out many examples on the interwebs, including some lengthy code libraries, the solution was simplicity itself, using the .NET string format modifier G0 where the number after G is the number of significant figures desired,  so

Console.WriteLine((10.12345).ToString(“G3″));

Will give you a result of 10.1

This works fine and as expected, but the bug is when you have 10.0, what is output to screen is 10

After traipsing through numerous articles, the result was that this behaviour was “by design”. After communicating this “by design” feature to my boss (and numerous scientists), their retort was that it was a bug and ought to be corrected. The reason why they were so annoyed was because the missing trailing zero indicates a level of accuracy that is an unacceptable omission in their field, thus I was advised to prefer two decimal places instead.

One of the first rules you are taught as a new programmer, is that numbers in computer programs are zero based i.e. you start counting at zero because zero is a number, so why in this case are the .NET framework designers ignoring the zero? One must say that one concurs with this being a bug, and wish the framework library team could correct this behaviour, to save developers polluting their codebases with conversions to strings and back to numbers, just so one can present data in a way that is meaningful to mathematically based users.

Should I use DevExpress WPF controls for a new project?


Firstly, I must draw attention to the fact that my intention is not to spew bile, or communicate zealot-ism of any shape or form. My intention is to try and provide a fair, concise and balanced view, relative to personal experience that may hopefully assist anyone looking to answer this question.

Presently, I am now nearly six months into a Greenfield project, written exclusively using DevExpress WPF controls. Over the last few months, I have come to know their WPF API’s particularly well, and will continue to use the controls for the lifetime of the project simply because it is too late. A definite consideration is that it is often impossible to change anything major as a third party software suite you are developing on top of midway, for all sorts of reasons, the most notable being expense and time/delay to finish. WPF is such a flexible platform, I would advocate getting the business logic and functionality of an application thrashed out first, then look to a design team or third-party suite right at the end the end or during the process, rather than automatically restricting oneself from the offset with a third party suite. This, however, is seldom practicable, as the product owner/customer will need to be interacting with the software as time progresses, and they want to see something pretty, there is hardly ever any flexibility here, the application has to look stunning very soon into the start of the project, in order to gain their confidence (and settle their nerves) and continue in this vein.

There is nothing like hindsight, a trite but often unavoidable word when reflecting on a projects progression, It is always harder to be objective at a later date, because quite often, a quite different set of circumstances and considerations result due to the fact that time has moved on, and better ways of dealing with technical challenges and vendors present themselves. the steps required to solve particular problems become perspicacious.

One also must accept that projects must commence at some point, and utilise the best that is available at the time, otherwise no-one would ever start anything, because a better suite of components are just around the corner. Invariably, there have been profuse technical challenges along the way, as the application is a scientific one, but that is the essential stimulus for me personally,  yes, not fun some days, and you have good days and bad ones, but the overwhelming sense of achievement in surmounting the obstacles are what makes one do it again and again. Attention to minute detail is of unparalleled importance.  For all intents and purposes, it is about minutiae!

I think it important to take note that this is not a typical forms over data application but of a scientific bent, and thus far, their controls have proven very hard, if not impossible to customise to meet our technical requirements and specifications with ease and eloquence. Over the last month or so, I have been writing code that I quite frankly feel embarrassed to ever admit that I checked in…why?

The biggest problem is that DevExpress developers completely misunderstood WPF when they developed their WPF controls. I really cannot impress upon you sufficiently well just how much of a displeasure it is using their controls. I feel absolutely terrible (almost guilty) about talking about a vendor with such negativity, but they have made a serious mistake in their WPF suite, it has been a singular source of the most abject frustration for me in about a decade of developing software. WPF was built to allow developers to be flexible, and to build components with ease, using DevExpress controls cuts your flexibility by about 90% (and that is not a guesstimate).

Frequently, it is possible to get off to a bad start in any project, even with experienced developers. It is the fresh ideas and perspicacious vision that allow younger developers for the most part to escape the nebulous approach experienced developers tend to exhibit. In my experience developing WPF applications over the last three years or so, one of the most poisonous components to introduce to a new  WPF application, is a dyed-in- the-wool Windows Forms developer. One feels however that one must communicate extensive and comprehensive experience as a Windows Forms developer, but  somehow I managed to shake off any misdirection in solving WPF problems after witnessing just how bad approaching WPF from a C++ and Windows Forms mentality is. On some projects, I have witnessed resplendent software engineers and architects commit the gravest mistakes in implementing WPF projects, simply because they could not and would not start looking at things from a different direction. It is this scourge that has been eminent in the procurement for DevExpress WPF controls, that much is irrefutable.

Recently, after speaking with a colleague, we arrived at the conclusion that their WPF API’s have been written top down by Windows Forms developers. It is that, and their overwhelming success as Third Party Windows Forms Vendors where things have gone horribly wrong. Using their controls in most instances, places asphyxia on whatever problem you are trying to resolve, because most of their API’s are just so hard to get to do what you want them to do, because they failed to grasp what WPF developers expect in their components. Frequently, I consult my rather extensive library of code to solve problems that I find cropping up again and again, but it is almost impossible to use any of my  existing WPF code with their controls, because of the way they have implemented their API’s. That is a sad indictment of the API’s. A simple application that you write in WPF and bind to in an items control or List Box in WPF, is impossible to migrate to their Grid controls for example because of their horrendous implementation.

One of the key components in every WPF project that I have worked on is Model View View-Model (MVVM) proficiency. This has been an essential and sought after skill when dealing with customers. As I write today, you will find plethoric requests for MVVM support for their WPF controls, and hitherto there is none. There are no code samples or examples on their numerous websites, so typically you will confront a problem, and find that their controls are specifically written to handle events in the code-behind and not commands. You will also find that they adore the decade old version of ADO.NET that is datasets. I have not worked on a single WPF application that has not used MVVM or POCO’s, finding anything in their documentation or code samples using POCO’s is as likely as finding a hen with teeth, speaks French, and tells jokes.

Their WPF Ribbon is a prime example of being a complete dog to work with. It is incomplete, non-MVVM compliant, and when customers say their want an Office 2010 Application Menu for example, your sat left wondering, why you paid the money for the controls. Using it in your applications is a factory for writing tightly coupled hard to modify code, and if you do create workarounds you find that you have a polluted codebase, trying to get a MVVM application that is easily testable. Whilst we are on the subject of testing, try to find a single example of a WPF component of theirs in a test situation, I will save you the time, and regrettably advise you that there are no code samples, nor do their components help one build testable code. DevExpress almost obstinately choose to ensure that you develop the hardest to maintain and poorly separated code, by creating components that cultivate bad practices. If you are a design oriented software team or company, you will find that DevExpress only supply asphyxiation to your ability to progress, you can take out the ”express” and replace it with “Dev-Stress” or “Dev-Stressed”

What I cannot however fault, is their support, this is certainly a redeeming feature, because their have an absolutely brilliant support system, and their staff are a joy to work with. They almost always find a solution for a query, though sometimes one is left wondering why  you needed to consult someone to perform what are mostly basic functions.If you are thinking of using their controls then you must be prepared to accept that you are for the most part, a paying guinea pig, because most of the issues you will have have either been reported by other customers, or your problem will be used to resolve other peoples problems in the future, as their websites and forums are pretty useless, they seem to take little care in preparing helpful documentation and code samples that reflect real world usage for their customers, pretty much every example is an example on how not to write quality software.

Another big issue I have found is with their release cycle. They generally have two big releases every year, and lots of incremental ones. If you find a bug, it is always tempting to update to their bug fix versions, but I have found this to be an endless source of hair-loss. Pretty much every time I have upgraded to solve an issue, it has been partially fixed, or ended up creating bugs or their have renamed and changed things that break things. The Visual Studio way of releasing software seems the best for developing complex projects, where over the period of a year or so, you can concentrate of solving the domain problems, rather than bug-riddled releases. It may sound as If I am being harsh or truculent, but this is the reality of using their software.

If you are thinking of using DevExpress WPF controls, you really have to try and assess whether you fall into their 90% use case, or their 10% oddities, but even if you do fall into their 90%, their API’s will assist you in writing a lot of hard to test, inelegant and expensive to maintain code, as they have been written to work best using the paradigm of the technology they are meant to be replacing (Windows Forms). If you have worked with WPF for any amount of time, it is almost unbelievable just how restrictive their controls are to use. Presently, even as one writes, befuddlement  continues to present itself, as to how or why their controls work the way they do? The Microsoft WPF control library is such a flexible system, why asphyxiate you and your organisations software development efforts by people that still write software components as if it was a decade ago?

Writing better code


A key factor to being a successful developer is writing good, solid, maintainable, error free code. It seems like a pretty obvious – albeit innocuous – statement, so why state the obvious? When you check code into the main branch of the source code for your organisation, you immediately expose your abilities and disabilities as a developer to the people you work with and for. If you check in a bad bit of code that contains bugs, it usually isn’t you that first notices the bug, but a colleague and you can look inept, especially if it is a silly mistake (and you have made a few of them – your boss may start thinking you are inapt to continue in your role in the company).

Writing good code is very difficult, especially when the code base is changing rapidly so you as a developer need tools that can make your life easier. The more experienced you become as a developer, the more you look to ways of making your life easier. Jetbrains have a visual studio add-in called ReSharper that is a little like FxCop, which the smarter developers amongst us use. If you are wondering why some developers seem to produce very clean code consistently that omits silly bugs (even on a Friday afternoon), you will more than likely find that they are using ReSharper.

I don’t doubt that a lot of people may dislike the fact that this takes over your IDE (this really is for the better though), in fact, If I recollect correctly I tried ReSharper a few times, then removed it (after a few word of mouth trials) every time because my IDE was less responsive, and because I was impetuous. It was only when I released a test application to a customer a few months ago (that kept crashing unexpectedly), when desperation set in, and drove me (frantically) looking for errors in my code. The main culprit  (in this specific instance) was a handful of null references in the codebase that had gone unnoticed, that ReSharper readily identified and I corrected, consequently achieving rapid application stability, over the course of a few days long code review. I’m not saying that all my problems were fixed, but most of the niggling issues were, with little to no effort.

It is not just null checks that ReSharper identifies, but a pretty comprehensive set of common coding mistakes that even the best programmers frequently make. The ‘Big Win’ is in that you get to correct problems there and then, as the code is written, before it becomes an issue. Visual Studio 2008 introduced background compilation that surreptitiously increases developer productivity by showing them errors as the code is typed, rather than waiting to press F5. ReSharper is orders of magnitude more helpful, if you use it correctly, you end up with a very clean codebase, with no unnecessary code, that has had common errors identified, giving you the developer confidence in your code.

To show a few basic examples

22-05-2010 15-16-47

Here I can remove the redundant delegate constructor call that the IDE generates. I can also remove the this keyword. The this keyword is rather abused in C# (Me in Visual Basic) and a lot of code samples (even from Microsoft) show developers misguided bliss with the word. One only ever needs to use the word when you have two variables named the same in a class (typically in a constructor) like this

22-05-2010 15-26-58

In most other cases it is redundant to use the word.

22-05-2010 15-21-35

In the sample above there are several issues. I have dead namespaces at the top, a poorly named control, two poorly named variables, that can also be made readonly. This is just an iota of the static runtime assistance that you get as a developer, and you can adopt the mantra of “writing a little code that does a lot”, rather than “writing a lot of code that does a lot”, with significantly less bugs.

I strongly encourage you to download this tool, acquaint yourself with it, and start working a little smarter (even on Friday afternoon).

Syntax Highlighting In Blogs/Websites From Visual Studio for C#, F#, Visual Basic, XML, XAML etc.


When time permits, I enjoy writing the odd article for my blog, and tend to post code samples pretty frequently. There are a number of syntax highlighting tools available (even as add-ons for Windows Live Writer that I compose all my blog posts in) that you find interspersed in blogs over the internet.

I ran into an issue where I was upgrading from Windows Vista to Windows 7 where the live writer add-in stopped working, and transmogrified my code in blog posts, and there was no way to retrieve code if it was a previous post in Windows 7 (used my Vista laptop). I resolved then to seek an alternative solution that emitted pure HTML.

After some trawling about the interwebs, I found the excellent CopySourceAsHtml on Codeplex. When you select code in Visual Studio and highlight it, there is an additional context menu option available to “copy the source as HTML”

copysourceashtml

Selecting this brings up the following form where you can format your code

options

Clicking on OK allows me to paste my code as HTML in C#, Visual Basic and F# thus;

C#

   17     /// <summary>

   18     /// Interaction logic for Window1.xaml

   19     /// </summary>

   20     public partial class Window1 : Window

   21     {

   22         public Window1()

   23         {

   24             InitializeComponent();

   25         }

   26     }

 

  Visual Basic 

    1 Class Window1

    2     Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

    3         MessageBox.Show("CopySourceAsHTML is cool")

    4     End Sub

    5 End Class

F#

   57 /// Compute the highest-common-factor of two integers

   58 let rec hcf a b =                       // notice: 2 parameters separated by spaces

   59     if a=0 then b

   60     elif a<b then hcf a (b-a)           // notice: 2 arguments separated by spaces

   61     else hcf (a-b) b

   62     // note: function arguments are usually space separated

   63     // note: ‘let rec’ defines a recursive function

There is however, a limitation in the Visual Studio 2008 version where you do not get the context menu option when trying to copy XAML. You could do a copy and paste of the .xaml into an .xml file, as the option is available there, but that can get a bit cumbersome.

The easiest “workaround”, is to create a Visual Studio keyboard shortcut. In Visual Studio select Tools then Options, which should bring up the following dialogue;

copy

If you start typing copysour as per arrow above, you should be taken to the CopySourceAsHTML.Copy command. Whilst this is selected, move mouse focus into the Press shortcut keys textbox and press CTRL+Shift+C on your keyboard (or whatever keystrokes you desire), and then press the Assign button. You should have the following;

Assigned

you should then find that if you are in XAML you can CTRL+Shift+C and copy the .xaml thus;

    1 <Window x:Class="SyntaxHighlightingExampleCS.Window1"

    2    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;

    3    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;

    4    Title="Window1" Height="300" Width="300">

    5     <Grid>

    6 

    7     </Grid>

    8 </Window>

Improve the quality of your code with NDepend


Before a parachutist, mountain climber or formula one driver undertake their tasks, a number of checks need to be undertaken. These checks will assist in deciding whether the parachutist for instance will even jump out of the plane. If a typhoon is on the way, all are likely to wait until it has passed, the type of climbing gear the mountain climber will choose, must depend on the type of mountain they are to climb. What all these checks result in, is less surprises, in computer programming this is analogous to bugs.

The Ironbridge Shropshire

I know that architecture is ubiquitously used to describe engineering software, but the comparison is indeed an irresistible one. Take the Ironbridge in Shropshire for example, every element of this engineering feat must have been stress tested. The materials must have been tested to see how they react to temperature changes, weight and so forth. You can even find out how many rivets they used, and the length of the steel used in the bridge, all wonderful and useful information. Shropshire bridge (as I’m sure your well aware) is not the only bridge in the world, as there are a great many others that come in different shapes and sizes and age. The design process for a lot of these constructions requires a similar set of circumstances and considerations. A formula one motor car for example, still has four wheels as does a mini cooper. Writing software is no different, and most if not all software projects entail a similar set of circumstances and considerations, whether massive, big or small, you still want to deliver a fast, efficient, reliable and effective application.

I have recently started using NDepend, to quote from their website;

NDepend is a tool that simplifies managing a complex .NET code base. Architects and developers can analyze code structure, specify design rules, plan massive refactoring, do effective code reviews and master evolution by comparing different versions of the code

NDependMain

If you prefer the ribbon, you can change the user interface to suit

Ribbon

The way I look at my code has been changed forever. What you get is an abundance of relevant and pertinent information about your code, that you never thought possible. NDepend is about assisting you the developer (whether a single man outfit or team) to ensure that you are producing the highest quality code possible. There is so much information at your fingertips, it is overwhelming.

The Model View Controller, Model View Presenter and Model View View Model design patterns for example, are all about separating the concerns of your code, and increasing the testability of your code base. NDepend is another necessary tool, in that when you perform code reviews, it becomes an indispensable tool. Architects for a project can set rules for the code base, and easily check to see that they have been adhered to from a quality point-of-view, and developers themselves can ensure that they remove any sloppy code they’ve written, and spot anomalies and problem areas before they check in their code.

Here I have just loaded an assembly for an application that I wrote a while ago. I have a pane (one of many) that furnishes me with information about the number of lines of code I have for instance, comments, methods, fields and types.

ProjectLines

In another pane, you have information pertaining to code quality, methods that are too big, methods that are too complex, methods to refactor, methods with too many variables, methods with too many parameters, the list goes on and on. Each point an important code quality concern.

CodeQuality

In the same pane under design, you have suggestions that stateless types in the code could be changed to static types, or that a class without a descendant should be sealed, and again a myriad of other code quality issues that need to be addressed.

Design

Why should it be sealed? The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.  You have 5 classes here that can be changed to Structs, improving performance as they are now value types and not reference types from a .NET runtime standpoint.

You have Visual studio integration, Reflector integration and a wealth of other features.

VSIntegration

An issue any Software architect or Developer always runs into is performance and trying to ensure that their code is as optimised as possible, ensuring that their end users have the best possible experience when they use an application. I have always used this article every once in a while to ensure that my applications are structured correctly, and refer to it every now and again (most of the article is relevant to Silverlight and WPF as well). Clearly by using NDepend you will end up with better performing applications, and also more maintainable codebases, because all the ‘gremlins’ are ‘found out’ soon and the more you review your code with it, the better quality your code will be as a result.

NDepend is an essential new development tool, that I will blog about more, once I understand it better.

The .NET Framework Client Profile


In a previous post, I discussed the benefits of the .NET Client Profile, but this was still beta and had not been released (though it has now been released in Visual Studio 2008 SP1).

Presently, this is only of benefit to XP machines, but its function will certainly be beneficial to Vista or future Windows versions, as the .NET versions increase. Essentially, all the server or developer specific libraries are removed, leaving application specific libraries only (why was this not thought of sooner?). If one is thinking of deploying a .NET 3.5 SP1 application today on XP, an installation of .NET 2.0, 3.0., 3.5. and associated service packs is required. The resultant package, is a download or install that is hundreds of megabytes large (or so it seems).

The .NET Client Profile is designed to be installed via the Microsoft Website. If installation is required locally then a webserver must be created and one must go through a few tedious steps. My own thoughts are this was unwise of Microsoft, as there are loads of developers who just want to create a setup CD with all the necessary files, without creating a dependency on the Internet in order to deploy an application.

Nevertheless, create a new project (we’ll create a simple “hello world” application)

HelloWorld1

Drag a button onto a form, click the button to create a simple event handler

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HelloWorld
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello World, this is the new client profile");
        }
    }
}

The following code as you might guess creates the following program

HelloWorldMessage

Double click the properties folder in Solution Explorer, select the application tab and check the client profile checkbox

HelloWorld2

Select the publish tab on the left and click on prerequisites

HelloWorld3

Here you should find the following options pre-selected, if not, select them

HelloWorld4

Now create a c:\deploy folder (at the top) and click “publish now” at the bottom

deploy

You should now have your files in a folder called deploy on your c:\ drive

deployFiles

I have a test XP machine that I have copied the files to, and clicked setup.exe to install the program. You should see a dialogue to install the client profile

SetupOfPRofile

After accepting the license agreement, the client framework is installed

Installing

Once this has completed, you should be prompted to install the HelloWorld program

InstallProgram

You can then test the application to see that it works

Actual Program

So why go through the bother of doing this? If you click into the windows folder on the XP machine and right click the .NET framework folder you can review its size which is approximately 53 MB in size.

I have another test XP test machine (for comparison) that also just has XP service pack 3. I have selected to install the full .NET framework 3.5 using the bootstrapper

DotNetAgain

Here the download size is 60 MB but look what it installs

DotNetThreePointFive

What you get is 455MB of framework code, but beware! Size information in XP is misleading. If you look at the .NET framework folder in c:\windows, you soon see that the actual size is around 110MB

FullDotNet

If I look at the .NET framework folder in Vista the size is 129MB (and this is .NET 3.5 SP1)

VistaDotNet

I know code does get installed in other places but as you can see the code you need to install is at least halved with the client profile.

Absolutely Smashing


Smashing Magazine is a repository for graphics and contains loads of free graphics, icons and tutorials. It is quite possible to spend days there, as the talent on show is plethoric. Being rather design challenged (but not design ignorant), there really is a lot of high quality material available. Initially I just flicked through a few pages, but after spending some time there I am simply amazed at the high and even production quality material people make available.