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 11.0

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.

Saturation/Desaturation with HLSL/Pixel Shaders and WPF

Setup and Configuration

I have been working a lot with image processing applications recently, and encountered a problem a little while ago where there was a algorithm slowing a portion of an application down, due to it performing pixel by pixel transformations in C# code. I was advised to seek correction of the problem, and fervidly look into HLSL as a possible solution, and was fortunate enough enough to stumble upon the Shader Effects & Build Tasks project on codeplex. The reason that HLSL was suggested was because HLSL code executes on the graphics card, is supremely efficient, lightning fast and can even execute in parallel.

Downloading and installing Shader Effects BuildTask and Templates.zip (you can also download the source instead if you want) greatly simplifies ones ability to work with Pixel Shaders, as it allows for Visual Studio integration. Make sure you install the ShaderBuildTaskSetup.msi and most importantly read the readme, as this will direct you on the location for unzipping the required templates that you will need to do if requisite templates are to be available for you in visual studio (very easy, just copy a few zipped files to a location on your machine)

Projects

Now that the required components are installed, create a new WPF project/solution in Visual Studio (I am using 2010 Ultimate, but this should work with Visual Studio 2008, the Express Editions or Silverlight) and call it SaturateDesaturate.

Add another project to this solution, this time a Shader Effect Library (ensure the templates linked to above are installed) and call it ShaderEffects.

ShaderEffects

This new shader effects library hooks up the plumbing required to easily create pixel shaders. Again, I would advise you read the readme in this new .dll project. Right click the file that ends in .fx , select properties, you should have the following

BuildAction

When you installed the build tasks and templates above, this key component was added to this type of .dll, so whenever you add a new effect file, ensure that the .fx file has it’s build action set to effect or else things will not work.

Code Sample

Delete the automatically added Effect1.cs and Effect1.fx make sure you do not delete EffectLibrary.cs as this will be used by any effects that you add.

Add a new shader effect to the ShaderEffects project and call it DesaturateEffect.. For brevities sake , copy the following code into it;

 

using System.Windows;

using System.Windows.Media;
using System.Windows.Media.Effects;
 
namespace ShaderEffects
{
public class DesaturateEffect : ShaderEffect
{
#region Constructors
 
static DesaturateEffect()
{
_pixelShader.UriSource = Global.MakePackUri("DesaturateEffect.ps");
}
 
public DesaturateEffect()
{
this.PixelShader = _pixelShader;
 
// Update each DependencyProperty that’s registered with a shader register.  This
// is needed to ensure the shader gets sent the proper default value.
UpdateShaderValue(InputProperty);
UpdateShaderValue(SaturationProperty);
}
 
#endregion
 
#region Dependency Properties
 
public Brush Input
{
get { return (Brush)GetValue(InputProperty); }
set { SetValue(InputProperty, value); }
}
 
// Brush-valued properties turn into sampler-property in the shader.
// This helper sets "ImplicitInput" as the default, meaning the default
// sampler is whatever the rendering of the element it’s being applied to is.
public static readonly DependencyProperty InputProperty =
RegisterPixelShaderSamplerProperty("Input", typeof(DesaturateEffect), 0);
 
 
 
public double Saturation
{
get { return (double)GetValue(SaturationProperty); }
set { SetValue(SaturationProperty, value); }
}
 
public static readonly DependencyProperty SaturationProperty =
DependencyProperty.Register("Saturation",
typeof(double),
typeof(DesaturateEffect),
new UIPropertyMetadata(1.0, PixelShaderConstantCallback(0)));
 
 
#endregion
 
#region Member Data
 
private static PixelShader _pixelShader = new PixelShader();
 
#endregion
 
}
}
 
 

This essentially hooks up the WPF piece to the HLSL piece, with the PixelShaderConstantCallback receiving the value from the HLSL.

HLSL

Copy the following code into your .fx file

//————————————————————————————–
//
// WPF ShaderEffect HLSL — DesaturateEffect
//
//————————————————————————————–
 
//—————————————————————————————–
// Shader constant register mappings (scalars – float, double, Point, Color, Point3D, etc.)
//—————————————————————————————–
 
float4 Saturation : register(c0);
 
//————————————————————————————–
// Sampler Inputs (Brushes, including ImplicitInput)
//————————————————————————————–
 
sampler2D implicitInputSampler : register(S0);
 
//————————————————————————————–
// Pixel Shader
//————————————————————————————–
 
float4 main(float2 uv : TEXCOORD) : COLOR
{
float3  LuminanceWeights = float3(0.299,0.587,0.114);
float4    srcPixel = tex2D(implicitInputSampler, uv);
float    luminance = dot(srcPixel,LuminanceWeights);
float4    dstPixel = lerp(luminance,srcPixel,Saturation);
//retain the incoming alpha
dstPixel.a = srcPixel.a;
return dstPixel;
 
}
 
 

This simple HLSL code will be applied to every pixel on the image using the graphics card and saturate/desaturate the image. In the MainWindow.xaml copy the following code;

<Window x:Class="SaturateDesaturate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:shaders="clr-namespace:ShaderEffects;assembly=ShaderEffects"
Title="MainWindow" Height="600" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Image Source="/SaturateDesaturate;component/Images/Jellyfish.jpg" Grid.Row="0" >
<Image.Effect>
<shaders:DesaturateEffect Saturation="{Binding ElementName=slider, Path=Value}" />
</Image.Effect>
</Image>
 
<Slider x:Name="slider" Minimum="0" Maximum="6" Value="1" Grid.Row="1" />
</Grid>
</Window>

If you add an image and compare the saturation with a program like Paint.NET you will see that you have saturation added to your WPF images with a very few lines of code, and best of all it is very fast. I would also recommend you search codeplex for a shader effects library that contains many more shader effects and will help you get started and understand how they work.

I would also advise you to ensure that you remember to freeze all pixel shader instances (in your effect .cs files) and remove any static references (especially static constructors and shaders), as they are a prime candidate for memory leaks.

Original Image

 

Original

Paint.NET

 

Paint.NET200

HLSL Example

 

HLSL

WPF Message Box

The default MessageBox in WPF looks rather ugly on Windows 7 and Windows Vista

Before

 

Before

After

 

After

In order to update the messagebox, add a new app.manifest file

addManifest

ensure you have the following dependency tag

    1 <?xml version="1.0" encoding="utf-8"?>

    2 <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    3   <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>

    4   <description>iDesign – Media Burner</description>

    5   <dependency>

    6     <dependentAssembly>

    7       <assemblyIdentity name="Microsoft.Windows.Common-Controls" version="6.0.0.0" type="win32" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />

    8     </dependentAssembly>

    9   </dependency>

   10   <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">

   11     <security>

   12       <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">

   13         <!– UAC Manifest Options

   14             If you want to change the Windows User Account Control level replace the

   15             requestedExecutionLevel node with one of the following.

   16 

   17         <requestedExecutionLevel  level="asInvoker" uiAccess="false" />

   18         <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

   19         <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

   20 

   21             Specifying requestedExecutionLevel node will disable file and registry virtualization.

   22             If you want to utilize File and Registry Virtualization for backward

   23             compatibility then delete the requestedExecutionLevel node.

   24         –>

   25         <requestedExecutionLevel level="asInvoker" uiAccess="false" />

   26       </requestedPrivileges>

   27     </security>

   28   </trustInfo>

   29 

   30   <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">

   31     <application>

   32       <!– A list of all Windows versions that this application is designed to work with. Windows will automatically select the most compatible environment.–>

   33 

   34       <!– If your application is designed to work with Windows 7, uncomment the following supportedOS node–>

   35       <!–<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>–>

   36 

   37     </application>

   38   </compatibility>

   39 

   40   <!– Enable themes for Windows common controls and dialogs (Windows XP and later) –>

   41   <!– <dependency>

   42     <dependentAssembly>

   43       <assemblyIdentity

   44           type="win32"

   45           name="Microsoft.Windows.Common-Controls"

   46           version="6.0.0.0"

   47           processorArchitecture="*"

   48           publicKeyToken="6595b64144ccf1df"

   49           language="*"

   50         />

   51     </dependentAssembly>

   52   </dependency>–>

   53 

   54 </asmv1:assembly>

   55 

Burning and Erasing CD/DVD/Blu-ray Media with WPF

Some time ago I worked on a project where I needed a DVD burner/formatter, and came across an open source version by Eric Haddan. The only problem with that excellent solution was that it was written in winforms ,and I was working on a WPF application. I have now ported that application to WPF using MVVM.

burneru

You can download the free WPF burner at http://wpfburner.codeplex.com/. Just select the downloads tab and save the source code.

If you are on XP then you will need Image Mastering API v2.0 (IMAPIv2.0) for Windows XP if you don’t have this already (this is included in Vista SP2 and Windows 7). To burn a Blu-ray you will need Windows Feature Pack for Storage 1.0 if you are not using Window 7.

Common sense lost with MVVM

I am a big fan of using MVVM in WPF applications, but am finding, increasingly,  that even seasoned developers frequently dispose of very good habits, in order to stay true to the pattern.

One such occurrence is is not using message boxes. A  cardinal sin in MVVM, is ensuring that message boxes are never used in View Models. The end result is that one starts to see code like this.

delete

If you don’t have a logging system for your exceptions then you should have, if you do then always ensure that you log the exception. During development, one instinctually starts to determine brittle code, and events where errors can occur and use try-catch blocks. The worst thing you can do here is nothing. It is better not to use the try-catch at all, and just let the application blow-up, because at least you know that there is a problem, and go about fixing it.

I really cannot sufficiently impress upon thee just how much of a bad practice this is, and the amount of time you or other developers that work on your project will spend trying to find obscure bugs that occur because you are swallowing exceptions, just because MVVM stipulates that message boxes should not be used, means they shouldn’t, they should!

Free WPF Ribbon with source code and MVVM samples

Finally after about 2 years as a CTP, Microsoft have released the WPF ribbon. Due to the delay, one can be certain that they were allowing their third party software vendors as much traction for users that needed a ribbon, but some brilliant open source versions including Fluent Ribbon Control Suite have been developed.

ribbon

The best thing about the release, is that the Office Fluent UI licensing is now no longer a requirement. This allows people to download the software straight away, without having to go through the cumbersome process of logging into the Office website, signing the licensing, then spending half a day trying to locate the installation because it was hidden in a way that made you think they don’t want anyone to use it.

The download for the ribbon is available here. Please ensure that you also take the time to install the source and samples if you want to build MVVM compliant applications with the ribbon (you should be doing this in WPF anyway) . The MSDN documentation is available here.

The installation notes say that this is not supported on XP, but on vista upwards but I have not tested this. If there are issues then you should be able to use another vendor.

After installing the MSI you should have the following template in Visual Studio

project

There is no information on the installation templates for the express editions, but I would hazard a guess as to them never being available, as building applications with a Ribbon is not something a learner ‘typically’ does. If you are using express, then you should be able to add the requisite .dll thus. If you look in my Tree View below in Visual Studio, you will find that there is a reference to RibbonControlsLibrary. This is located at; C:\Program Files (x86)\Microsoft Ribbon for WPF\v3.5.40729.1\RibbonControlsLibrary.dll

tree

Note:  If you installed the source and samples as well, a .zip file with both is available at the same location. Copy this, and unzip it in a location of your choosing

source

The code behind for my window has the following code, so inherit off RibbonWindow

ribboncode

Finally your XAML should be defined so, and you’re good to go!

xaml

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

Windows Phone 7 – The Real Game Changer

 

Excitation

I am really exited in the direction Microsoft has taken with Windows Presentation Foundation and Silverlight, in that they have really demonstrated that they see these two technologies as the future of their user interface based aspects in their software by making significant investment in the technology. For a start, they have used WPF to great effect in Visual Studio 2010. Frequently, I spend 10 to 12 hours in Visual Studio and it is an absolute joy to use the 2010 version as the previous user interface that had not changed for a decade was showing its age. The number of enhancements in Visual Studio is plethoric, and includes automatically generated UML diagrams all done in WPF, but that really is another subject in itself.

A brief history

I decided to move the focus of my development over a year ago to WPF after spending a number of years in Windows Forms, before that it had been Delphi, before that C/C++ and domain specific languages primarily used in the medical, banking and defence industries. It was a bit of a gamble, because if you live outside of London (I am in Manchester), then WPF jobs are few and far between, as most business that required investment in software to gain the competitive edge has already done so. The opportunities with WPF and Silverlight usually arise in start-ups, of which I am involved in one at present. The exciting thing is not being tied to a codebase that is many years old, with a license to use the latest and greatest software. I moved the project I was working on to .NET 4.0 the day it was released, without needing endless meetings deliberating about the why, that what and the what for. It is beginning to look as the gamble I took has paid off, as I have overnight become a Windows Phone 7 developer. This included being a Silverlight developer as well.

Windows Phone 7

I, like many people use my mobile phone daily, and cannot imagine what it would be like not to have a mobile phone. I have been a little sceptical about the real usefulness of iPhone applications, as most of them presented themselves as bubblegum to me. Taste sweet for five minutes, then endlessly insipid afterwards. I have also been put off by having to learn objective C and the Apple implementation. The only Apple product I have owned was a G4 some years ago, but it ended up unused as it was not suited to the kind of development I needed to do at the time. My current mobile phone contact is up in a months time, I had resigned myself to getting an iPhone, simply because it is one of the best phones on the market, with a breadth of applications, something my current phone lacks.

I watched the announcement at Mix for the Windows Phone 7 with glee, and with the leaked images of a Dell phone (courtesy of Engadget) I resolved that I would have to wait till Christmas using my current phone as I had become a Windows Phone developer overnight

04-21-10lightningg4

Tools

I would say the chief issue that determines whether I do something or not now is how long it will take me. My time is very limited, so anything that requires a steep learning curve without a significant return of investment for that time usually means that I won’t look twice at it. this is also true for Microsoft release CTP’s so frequently it can be hard to keep up. I decided to download the CTP for Windows Phone 7, as a release that integrates with Visual Studio 2010 RTM has now been made available here. The installation was quick and polished enough to give me the confidence that it should not break my Visual Studio  installation. What you get is a version of Visual Studio Express (seems to me only C# at the moment, so I hope a Visual Basic version is available or is in the pipeline) that included the following template (also installed into Visual Studio 2010)

30-04-2010 08-49-09

After choosing the Windows Phone Application you get what looks more like a WPF application rather than a Silverlight application

30-04-2010 08-55-36

Press F5 and you get an emulator for the phone that contains a working version of Internet Explorer and the eye catching transitions between pages

30-04-2010 09-01-51

looking at the nuts and bolts of the thing, they are using the Navigation pattern that is so familiar to me, it seems like I am writing a WPF application. I will dig deeper into how one can leverage their existing skills to create a simple application for Windows Phone 7

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"

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

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

    5     <Grid>

    6 

    7     </Grid>

    8 </Window>

Free WPF Themes

Update 1/10/2010 : Reuxables have now released some free themes including a lightweight version of Gemini (below) that has just the two colours. I have a sample application here showing the theme in an application I have just released.

Update : As rightly pointed out by a reader, Reuxables have stopped their free offer as they are now concentrating on the new .NET 4.0 controls and themes, including the elegant Gemini to be released soon.

Gemini

It seems the only freely available themes are the ones one codeplex. These were originally designed by the reuxables team, but I have lost faith in them with the withdrawal of the free themes they had available.

I think the best free themes at the moment are the Silverlight 4 themes, but they are yet to be ported to WPF.

Original Post

A little while back I noted that reuxables were gathering steam. Slightly earlier that year, we were all wowed by the Lawson Mango application

lawson_m3_cs_1

as this was a clear illustration that WPF could offer a vector based visual experience that left your ‘jaw on the floor’. Reuxables have now released a free version of the above theme called Inc

inc

I have been using this in my WPF applications, and have grown rather quite fond of it, principally because WPF themes can be a bit ‘too much’ for applications that one uses daily. You can get the theme here (there is also a free Metal theme [below] if that takes your fancy)

Metal

Follow

Get every new post delivered to your Inbox.