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.

Easing .NET Framework deployment for Windows Forms and WPF


One of the real pains with deploying a .NET 3.5 application on Windows XP (OS of choice for business) is the fact that you need to install .NET 2.0, .NET 3.0 and .NET3.5 frameworks. The first two are plus 100MB, and the last is around the 60MB mark (last time I checked). Windows Vista comes with .NET 3.0 pre-installed.

This does cause headaches for IT professionals trying to deploy a new application, or if you write a managed application distributed on the Internet, users need to download and install all the aforementioned versions before the application works. This is cumbersome, awful first impression and bad user experience when starting to use a new application.

With the forthcoming Visual Studio 2008 and .NET framework 3.5 service pack around the corner, a new feature called ‘client profile’ has been created. This, in a nutshell, removes all the extraneous libraries a client application does not use, like ASP.NET for example, and retains the most common client application libraries for both Windows Forms and Windows Presentation Foundation. A step by step tutorial is available here.

ClientConfigs_web_2

The total file size will be around 27 MB, which is tiny, and will please all the IT departments no end, that have to deploy managed applications either locally or distributed. Even if you have just a .NET 2.0 application, that is around 120MB in size, so you immediately shave off 100MB in the install. I must reiterate, that this affects both Windows Forms and Windows Presentation Foundation, and you can ease deployment for both presentation layers. You will reduce the install imprint of you application by at least 400MB and save at least 30 minutes at the start, while the client machine installs .NET 2.0 then .NET 3.0 and finally .NET 3.5 (with the restarts in the middle).

Free Dundas Charting Components in SQL Express 2008


The first Release Candidate (0) of the long awaited SQL Server 2008 has been made available on MSDN. One thing I did not know was that Microsoft purchased Dundas Charting last year, and their components are to feature in the forthcoming SQL Server 2008 release. You can find information on the changes here.

Since Dundas are the leaders in data visualisation, especially for business intelligence, this is most welcome. When you consider the cost of a single Dundas license is usually around the $700 mark, ouch! SQL Express users will not be ostracized either, as a special SQL express version with advanced services including reporting will be freely available. I hated the fact the SQL 2005 Express, or the Full version, had reporting solutions that had to be performed in IIS. This is no longer the case, and I can see some fantastic applications for this in future.

How to use the Office 2007 Ribbon Control


The lead designer for the ribbon has this video from mix 08.

I really cannot recommend highly enough just how much you should watch this. Especially if you are using a ribbon control in your application. Jensen takes you on a tour of the prototyping the Office team did, consequently you know when to use the ribbon and in what context it is correct to do so. I have come across a lot of developers who have just used the ribbon ‘willy-nilly’ because it was the ‘new kid on the block’, and resulted in creating a really bad application, from a usability point of view. The ribbon solves one key user interface problem, and understanding what this problem is will result in you creating a better application.

There are lessons to be learned here that mean that even if you are not using the ribbon, just the thought process itself is sufficently edifying. It is fascinating just how bad the Office 2003 user interface is, and the scalability that the ribbon creates for your application. One is left beyond doubt just why Office 2007 is far better than the previous version, with an unimpeachable presentation from Jensen.

The WPF Designer for Windows Forms Developers


As one absorbs the new WPF platform, seasoned Windows Forms developers can find it a little frustrating locating identical functionality in WPF. Typical questions may be, how do I create a menu, or how do I use my custom user control?

Thankfully, MSDN has The WPF Designer for Windows Forms Developers which is a collation of equivalent functionality.

Very useful indeed!

Finally, An example of a Multi tier architecture for Linq to Sql


Update 2/6/2008:

The original post for this is available  beneath, but the link to the original article has been removed which turns this post to a pointless rant because you cannot reference the article. Luckily Beth Massi has a very good n’tier Linq example.

Original

Anyone that is aware of my posts knows that I do whinge about the lacklustre implementability of Linq in real world scenarios. I have battled with this for some time now.

Microsoft’s response a few months back was that they were waiting to see how their customers would ‘conjure up’ a method of doing this.
I found this attitude dissatisfactory, because if you’re trying to negate the impedance mismatch between ‘objects’ and ‘data’, the ubiquitous scenario is n-tier. You cannot introduce such a feature (Linq), and not have examples of it being implemented n-tier.
I have just come across an example of implementing Linq to Sql on MSDN. The link is available here.

I have finished testing this and quite frankly, I’m very disappointed. This is not easier than datasets, but more complex, for absolutely no ROI for understanding the raised abstraction.
Validation is pain, even more painful is moving this to winforms/wpf applications, that do not have the object data source.

I keep returning to Linq because of all the noise Microsoft made. Indisputably, one is more expressive when composing queries, but that is just one small part in creating an n-tier app.

Nah, back to datasets for me, and quick. Unless a miracle happens.

Linq to SQL Compact Edition (CE)


I got asked about doing this recently, and needed somewhere to point the individual to.

Presently, unfortunately, Linq to SQL Compact Edition is unsupported. Luckily though, it is quite easy to still perform Linq queries against SQL compact using the command line utility SqlMetal. SQL Compact Edition is very handy for single user applications or demos where you want to retain a very small application imprint, but not lose functionality. All that is required is that you have the object relational mapping (ORM) file that contains the Linq to SQL classes. This in Visual Studio is the .dbml file that is generated when you elect LinqToSQLClasses in the data menu.

Open up the Visual Studio command prompt by going to

You should have the following;

C:\Program Files\Microsoft Visual Studio 9.0\VC>

Enter ‘SqlMetal’ in the command prompt and take time to explore all the options available to you.

I simply want to create a .dbml file from my database which I have in my c:\ drive. You will want to point this to wherever your .sdf file is.

Enter the following path into the Visual Studio command prompt

SqlMetal /dbml:c:\Users\MyName\Documents\Northwind.dbml "C:\Users\MyName\Documents\Visual Studio 2008\Projects\Windows Forms\Code\Northwind\Northwind Database\Northwind.sdf"

Where the above is the format; SqlMetal /dbml:northwind.dbml northwind.sdf

Note that in vista you must specify the path through the ‘Users folder’. Failure to do this will result in a file access error.

As you can see my .dbml file was copied to my documents folder. I then copied this into my project. .To access the file I reference it in the constructor of the form thus;

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        NorthwindDataContext northwindDataContext;

        public Form1()
        {
            InitializeComponent();

            this.northwindDataContext = new NorthwindDataContext(Properties.Settings.Default.NorthwindConnectionString);
        }
    }
}