Reinventing the wheel


One of  the most significant challenges as a developer – especially when working as a consultant (though not mutually exclusive) -  is the need to understand a completely alien software system very very quickly, and to be productive in adding new functionality to that system, consequently value, to whatever the project may be. One must cultivate procedures and practices that allow for the rapid addition of development requests that are fit for purpose.

Probably the biggest hindrance in all software development is developers that suffer from “not invented here, I didn’t write it” syndrome. Frequently, I encounter developers that cannot work on a piece of code without completely re-writing it, frequently either ending up with exactly the same functionality as the code they replaced or reinventing a square wheel i.e. one finds that one is actually are worse off from a code maintainability standpoint.

The role of any Software Architect or Team Lead, is primarily to ensure that the overall architecture of  a software system is sound i.e. well designed and robust, lending itself to the addition of new functionality without breaking or changing existing code. This is by no means easy, and the challenges of building software systems are well known, but software architecture is now no longer in the dark ages, established design patterns that resolve most system issues are abundantly available. This most important part of any software application, I cannot but help but to draw attention to that fact, getting this wrong, with the knowledge that you will have developers of varying abilities and skills during the lifetime of the application, is all but a recipe for failure.

Design

The architecture of the application must be a policy and this must be enforced. The architecture must make it difficult for developers to just do what they want by requiring that they have to either take a few extra steps in their algorithm or think differently (but the same for everyone else) in resolving whatever they are tasked with. This however, must be a justified design decision, and not loose coupling just for the sake of loose coupling i.e.using interfaces between layers for example, usually forces composability from developers where they would usually use direct call backs. I have seen systems quickly turn into big balls of mud because of this, and the larger the system that bigger the ball of mud.

 

7299iuz6qug2mn

Since the overall architecture has been formalised, what remains is in adding the functionality of different rooms. The Drawing Room in the home above, must have all the features and components that allow it to function as such. This is analogous to any feature in a software system. It is difficult for your typical programmer to see a software system in its completeness like the house above, so it is the Architects responsibility to ensure they are aware of what is required of them. Most developers don’t like being restricted in how they are allowed to solve a problem, because most developers are not Architects, and are seldom able to design a coherent and robust system. Rewriting code someone else has written for the most part is usually an exercise in absolute futility. One cannot count the times that programmers habitually duplicate functionally that already exists, and how negatively this impacts a projects progression. It is very easy to lose weeks and even months of development time, all because developers were unable to augment existing code that was already working.

Sawdust

If you task a typical programmer to design and develop a piece of functionality in an application, that has specific functionality, the results are often surprising. Requirements for software usually result in a single piece of functionality, lets take a chair for example.

11151bguz98uw24

I am certain the audience knows what the prime functionality of a chair is so I shall not elaborate, why should software be different? The objective for any programmer is to get the requirements realised in as short a time, but as functional as possible. Most programmers never create a chair that is simple and functional but end up with this.

9481t87166dxi7

Really skilled developers will give you something like a Futon

product_detailed_image_29785_21

Most developers spend and incredible amount of time creating sawdust, separating logic and creating loosely coupled components when a lot of the time this is not required. Developers often try and use their glass ball imagining future use cases and try to always create components that can be extended to have dual or many other uses e.g. the Futon above. This is wrong! Oftentimes, all you want is a chair. All the requirements in the software specification ask for is a chair and the developer ended up creating a Futon, then are perplexed when they receive lukewarm responses or even complaints that they have designed something that was not required.

Single responsibility is frequently misunderstood, and is a prime reason that programmers rewrite existing code a lot . Usually the argument is that “I had to split the code into this class, and that class, and the other class because I wanted to create a software component where single responsibility was as clear as possible”. The result almost always is sawdust, and fine grained sawdust at that, because well architected software systems usually just need software components like the chair. It is sometimes hard for intelligent developers to accept that a lot of the code they write at times can be solved very simply, their overactive minds end up creating a software system that is bloated with classes and code that will never ever be used because you aren’t going to need it.

The Graduate

It seems almost unfair to include graduates as prime candidates for reinventing wheels, but they almost always are the people that do this the most, including Masters up to and including PhD students.

21585e5556z58a1

In any software team, you need bright and talented individuals, especially where you are solving domain specific problems. Their importance cannot be overstated here, but with this comes a lot of baggage. It can be very challenging managing a team of incredibly gifted developers. Inexperienced developers of any academic background can also be a drain in resources. A simple problem is usually solved by using the most complex algorithm, when something simpler was required. It seems inconceivable, but most of the hardest problems to manage in complex software systems are usually a result of the smartest people in a teams undue influence. If people are very smart they are hardly ever questioned to justify their choices. I have encountered software where you are told that users hate using the application because “you require a PhD to use the software”. This complexity invariably stems from the source code, thus, it is important to accept that smart individuals always find ways of solving the most difficult problems, but can also be the reason why some problems in complex software systems are difficult to solve because simplicity is seldom a prerequisite in resolving issues.

The long-and-the-short-of-it is that the goal of any software is for people to use it, and most success is based on simplicity and easy of use, which also is true for maintainable software systems. Working software seldom needs to be completely re-written because it works. Improvements can always be made to any software because there are no perfect software systems, so save yourself the time and effort by learning other peoples code rather than rewriting it, this will allow you to solve more problems, add more features and provide real value to a project.

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?

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: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


Edit 22AUG2017, since the initial source on CodePlex is about to be shut down, I have moved this project to git available here: https://github.com/lukhezo/wpf-burner

I have also modified the theming a little

 

 

 

 

 

 

 

 

 

Original Post:

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