Bassem Mohsen's Programming Blog

"High thoughts must have high language." —Aristophanes

  • The Author

    Bassem Mohsen - Freelance Windows and
    Web application developer. Technical writer. 24 yo. Based in Cairo, Egypt.

  • MCTS certification logo

ConvertSourceToHtml

Posted by Bassem Mohsen on May 23, 2011


Download ConvertSourceToHtml from CodePlex.
This project is based on CopySourceAsHtml 3.0.
This project uses the NumericUpDown control form the MSDN samples.

Motivation

I spent some time searching for a way to display code with nice formatting and syntax highlighting in my website. I found many server-side and client-side scripts that performed the formatting and highlighting dynamically, but did not like them. I thought this is too much unnecessary complexity. Styling should be done by static HTML and CSS. Plus the tools could not recognize type names to apply a special formatting to them. I also found ‘online syntax highlighters’ where you paste your source code and the tool generates HTML that you can place in your website or blog. These tools were still unable to recognize class names.

Finally I found CopySourceAsHtml. A Visual Studio plugin that takes formatted and highlighted code from Visual Studio in RTF format and converts this RTF to HTML then places the HTML in the clipboard. This plugin gives perfect results. Only one problem, I am using the Express editions of Visual Studio which do not support plugins. Fortunately CopySourceAsHtml is an open source project, so I was able to modify the source code to make it work as a standalone program. I called the standalone version ConvertSourceToHtml.

Using the Program

The program replaces RTF code in your clipboard by HTML code when you click on the ‘Convert’ button. So you will keep ConvertSourceToHtml open, copy from Visual Studio, click ‘Convert’, then paste in your HTML editor.

convert-source-to-html-main-window

The program has settings that enable you to control some aspects of the HTML output. Some settings can be changed from the program GUI, for example the settings that determine whether line numbers should be included, the number of the first line, the background color and whether to alternate the background color.

ConvertSourceToHtml settings window

Other more advanced settings like the CSS rules for the container HTML element can only be changed by editing the Settings.settings file in Visual Studio and recompiling the program. I know this is not very convenient and I am sorry about that.

The Program Architecture

The Most important namespaces in the ConvertSourceToHtml project are ClipboardUtilities, Conversion, and Conversion.HtmlCodeElements.
The ClipboardUtilities namespace contains the classes responsible for reading RTF data from the clipboard and writing HTML data to the clipboard.
The Conversion namespace contains the classes responsible for parsing RTF code and generating HTML code.
The Conversion.HtmlCodeElements namespace contains the classes that represent HTML code elements like HtmlStyle and HtmlLine.
ConvertSourceToHtmlCustomControls is a separate assembly for the custom controls used in the program. The assembly contains only the NumericUpDown control.

Binding WPF Controls to Application Settings

The technique I used to bind the controls in the SettingsWindow to the application settings deserves a section to document it because there is a very good chance I will use this technique again.

The Settings class is contained in the namespace ConvertSourceToHtml.Properties, so to use this class in XAML, an XML namespace prefix must be created for the CLR namespace.

<Window

        xmlns:props="clr-namespace:ConvertSourceToHtml.Properties"

        … >

Next we bind the appropriate property of the control to the property representing the setting.

<TextBox Name="fontSizeTextBox" Width="30"

         Text="{Binding Source={x:Static props:Settings.Default}, Path=FontSize,

                        Mode=TwoWay, UpdateSourceTrigger=Explicit}" />

The control will display the value of the setting and update the value of the setting, this is why the Binding Mode was set to TwoWay. But we want to update the data source only after the ‘Save Settings’ button is clicked and after the form data is validated, so we set the Binding.UpdateSourceTrigger property to Explicit (it is LostFocus by default for the TextBox control).

To update the binding source we must extract the binding from the control property and call BindingExpression.UpdateSource(). The following method does exactly that.

private void UpdateBindingSource(FrameworkElement element, DependencyProperty property)

{

    BindingExpression bindingExpression = element.GetBindingExpression(property);

    bindingExpression.UpdateSource();

}

Now updating the binding source (after performing the necessary validation) is as simple as making the following method call.

UpdateBindingSource(fontSizeTextBox, TextBox.TextProperty);

Thanks to ValueConverters, it is possible to present the setting value to the user in a way that is different from how it is stored. All you need is to implement an IValueConverter.

[ValueConversion(typeof(double), typeof(double))]

public class FractionToPercentageConverter : IValueConverter

{

    #region IValueConverter Members

 

    public object Convert(object value, Type targetType, object parameter,

        System.Globalization.CultureInfo culture)

    {

        return ((double)value) * 100;

    }

 

    public object ConvertBack(object value, Type targetType, object parameter,

        System.Globalization.CultureInfo culture)

    {

        return (double.Parse(value.ToString())) / 100;

    }

 

    #endregion

}

And specify that IValueConverter in the binding expression.

<Window.Resources>

    …

    <local:FractionToPercentageConverter x:Key="fractionToPercentageConverter" />

</Window.Resources>

<uc:NumericUpDown

                  Value="{Binding Source={x:Static props:Settings.Default},

                                  Path=AlternateBackgroundColorAdjustment,

                                  Mode=TwoWay, UpdateSourceTrigger=Explicit,

                                  Converter={StaticResource fractionToPercentageConverter}}"

                  … />

This allows the user to see and edit the setting value as a percentage while it is stored as a fraction between 0 and 1.

Update: CopySourceAsHtml was not updated for Visual Studio 2010. The solution for making it work with VS 2010 increases the Visual Studio startup time considerably. I think ConvertSourceToHtml is a good alternative to CopySourceAsHtml for VS 2010 users.

Download ConvertSourceToHtml from CodePlex.
This project is based on CopySourceAsHtml 3.0.
This project uses the NumericUpDown control form the MSDN samples.

2 Responses to “ConvertSourceToHtml”

  1. Thanks, just what I was looking for

  2. […] Convert Source To HTML […]

Leave a comment