Optimal Setup for SyntaxHighlighter & TinyMCE

My favorite Javascript-based WYSIWYG editor is TinyMCE. I find it the most visually appealing, and the most well constructed from all of the offerings available on the Internet.

When posting code for others to see, I prefer using SyntaxHighlighter. This javascript-based formatting tool by Alex Gorbatchev allows you to put the code to be displayed into a Pre or TextArea tag, formats based on the code language, and allows for good degradation in case of NoScript.

I have previously posted on how to get SyntaxHighlighter to play nicely with the built-in text editor inside WordPress (TinyMCE). Now for the first time I needed to set it up on another platform (Telligent Community Server). Here are my recommendations on what to use to achieve optimal setup (this can work on any platform):

Problem 1: Need Friendlier Way to Input Code – The default method for adding code to be formatted woudl be to open up HTML mode in TinyMCE, type in the Pre or TextArea tag with specially formatted attributes, and put in the code. This is ok for myself (this is what I use in WordPress), but when designing a site for others, a friendlier interface is preferable. I found a plugin for TinyMCE: SyntaxHL by Richard Grundy. After installing this (download and copy files to tinymce/plugins directory, and add plugin and button to TinyMCE.Init), a new button is added to TinyMCE that loads a popup which allows easy entry of the code to be formatted and customization of language and display options, without the need to enter html mode. (I would prefer something that could load up highlighted text when the button is pressed, but I will settle on this one for now)

Problem 2: TinyMCE adds BR Tags within PRE – When opening up TinyMCE it performs some cleanup of the Html that is input. Part of this cleanup involves (by default) substituting <BR /> tags instead of New Lines in the source text. For code that has already been saved, this presents a problem. When editing a post with code formatted in a <PRE> tag, instead of preserving the new lines, <BR />’s are inserted, completely messing up the formatting. This has been noted by others, and has even been reported in the TinyMCE forums, but so far the bug is still in there. To the rescue, another plugin for TinyMCE: PreElementFix by T Andersen. After installing the files and adding the plugin to TinyMCE.Init, PRE acts as it should: no more insertion of <BR /> tags, and the tab key adds a Tab to the text, rather than advancing to the next field.

Casting vs. Converting in .Net

I recently saw a piece of code in a project that was throwing an exception that I did not understand:

string boolString = (string)DataBinder.Eval(DataItem, "IsNew");

One would expect that boolString would be assigned the value “True” or “False” depending on the value of the IsNew property of the DataItem object. However, this through an Exception with the message: “Cannot explicitly convert bool to string”. What is going on here?

The syntax of (type)variable attempts to explicitly cast the variable into the given type. Casting does not attempt to interpret the data in the variable – it just tries to fit the object referred to by the variable into the new data type. This will work whenever the two types are somehow compatible (for example, an int can be cast into a float with no exceptions) though sometimes it may result in data loss (a float cast into an int). However, in cases where there is no connection between the two classes, casting will result in an Exception (like the one that I received above).

(There is another way to cast an object – using the as keyword. This will return a null if the cast fails, and is much faster than the explicit casting referred to above).

However, when converting an object, the conversion function has “knowledge” of the data contained in both the source and final object types, and will create the equivalent of the variable in the new data type. In the case above, using the System.Convert.ToString() method in place of the attempted cast to (string) would have worked fine. This is because the ToString method “knows” that a bool cannot be case into a string – but it also knows what the equivalent string to each value of a bool will be, and is able to process the operation accordingly. In this case, reflector uncovers the following code (in the Boolean class):

public string ToString() {
    if (!this) {
        return "False";
    return "True";

This is obviously a very simple type conversion. However, there are many more complex conversion utilities built into the .Net framework (accessible through the System.Convert class – see the DateTime.ToString conversion for an example of this. Also see the IConvertible interface). While conversions can be more expensive to run, since they are strongly typed, they are checked at compile time, and when used properly are more reliable to use when producing stable code. (See the MSDN article on Casting and Type Conversions for more info).

Signing Code Using PVK and SPC Files

I have a Windows Forms application that is ready for distribution. One of the last steps is getting code-signing working. We purchased a Code Signing certificate from Thawte. This resulted in a PVK (private key) and an SPC (certificate) file being delivered. Then the question arose of how to go about using them.

Referring to the documentation for SignTool.exe, there did not seem to be a way to sign the code using the PVK and SPC files via the command line. Though this was possible using the GUI program (accessible using the -signwizard command line option), in order to get this integrated with my build process, I needed a way to initiate the code signing fully from the command line.

The solution turned out to be the following:

1) Convert the PVK and SPC files to a PFX file (Personal Information Exchange file – this encapsulates the info found in the PVK and SPC files). This is done using the pvk2pfx.exe executable (which had been included as part of the .Net SDK, and was found in C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin on my computer). I used the following syntax to do this (Pass1 is the original password for the PVK file, Pass2 is the new password for the pfx file. Ref):

pvk2pfx.exe -pvk mykey.pvk -pi Pass1 -spc mycert.spc -pfx newpfxfile.pfx -po Pass2 -f

After this ran, I now had a PFX file called newpfxfile.pfx ready to be used.

2) Use SignTool and the PFX file to sign my code. Now that I had a PFX file, I was able to sign my code (and timestamp it) using the following command line syntax:

signtool.exe sign /f newpfxfile.pfx /p Pass2 /d "AppDescription" /du "AppURL" /t http://timestamp.verisign.com/scripts/timstamp.dll LocationOfCode

Seems simple, but it took quite a lot of research to get this process right. Hopefully the info can help save someone else some time.

Memory Profiler Eating Up My Memory

I have a Windows Forms app that has a very long and complicated initialization process. As the release is approaching, today was my day to try and shoft things around in the init, get it loading faster. So on recommendation from a few sources, I downloaded a profiler – Jet Brains dotTrace. Install and first profile went well. However, as I started to make more changes and run more profiles, I noticed that there were no improvements in initialization time. If anything, things were getting worse. Task Manager helped pinpoint the culprit:

If the numbers are too small, that is 1,241,596 KB. Yikes. Compare that with the second and third-place contestants, FireFox 3 at 174,584 KB, Visual Studio 2005 at 144,940 KB.

This is what happened after I closed the profiler (see if you can guess when that happened):

And I thought that Firefox 2 was using a lot of memory. I know that these programs are complicated, but I find it hard to comprehend how a program is supposed to help you track the memory usage of the applications that you are debugging when it ends up gobbling down over 1.2GB of RAM all by itself and making the computer basically unusable.

Ajax Progress Image Generator

I was in need of an Ajax-style animated gif that could be used to indicate that something is going on in the background or loading. I have seen them on hundreds of sites, but I don’t feel comfortable just copying someone else’s image to use for myself.

After a bit of searching, I found this site: AjaxLoad.Info. This is a nice, simple site that generates 37 different “loading” animated gifs, allowing you to customize the style, foreground and background colors, and transparency. Definitely a good site to know about.

Using SyntaxHighlighter to Format Code in WordPress

Based on a question in the StackOverflow beta site, I did some quick research into what are the best ways to perform syntax highlighting on code that is posted on blogs. Among the methods that were suggested (by myself or others):

  1. Hack together your own display logic to format it as you see fit
  2. Use the SyntaxHighlighter JavaScript library
  3. Use Windows Live Writer with the Insert Code plugin (I discuss that here)
  4. For WordPress, use the WP-Syntax plugin

Coincidentally, I had heard Scott Hanselman talking about how he does code formatting just a couple of days ago, in Hanselminutes #125, where he described how he posted code on his blog by putting it inside <pre></pre> tags, adding specific name and class attributes, and letting some JavaScript library do the formatting work. So I went to his blog, opened up a post with some code, and found my way to the SyntaxHighlighter JavaScript library. This is a very nifty library that handles formatting very nicely for a number of popular programming and scripting languages, and seemed to have a very easy implementation. So I decided to implement it for formatting code on my site.
Continue reading