Skip to main content
Dave Mason - Mastodon Dave Mason - LinkedIn Dave Mason - GitHub Dave Mason - Counter Social

Code Beautifier

One of the challenges I've faced as a blogger is quickly reproducing code that looks good in HTML. I've tried a few different online code conversion sites, and even a C# library. But I never quite got the results I wanted. I found myself revising the HTML to fix up key words, comments, and operators that sometimes got missed, were the wrong color, or the wrong font. All that HTML editing was tedious and time consuming.

What I really wanted to do was copy my code from SSMS, Visual Studio, or the PowerShell ISE and paste it into my blog so I could spend less time as a web dev and more time writing. Since none of the other tools I found gave me the results I wanted, I wrote my own. The code for my little app is available on GitHub. (It's my first project, so if something is missing or wrong, let me know.) It was created with Visual Studio 2015--there's a compiled exe if you prefer that.

Using The App

Copy code from your development environment and paste it into the text field on the "Rich Text" tab. Here's a CREATE TABLE example from SSMS:

Now click the "Beautify" button. The app generates HTML and automatically copies it to the clipboard. If desired, you can view the HTML in the "Formatted HTML" tab. Now paste the code into your blogging platform or HTML editor to see the results.


USE [msdb]
GO

/****** Object: Table [dbo].[syssessions] Script Date: 4/26/2017 11:11:26 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF
NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[syssessions]') AND type in (N'U'))
BEGIN
CREATE TABLE
[dbo].[syssessions](
[session_id] [int] IDENTITY(1,1) NOT NULL,
[agent_start_date] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
[session_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO


Here's another example, this time from the PowerShell ISE:

Again, I click the "Beautify" button. The app generates this HTML:


# Open SQL connection
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=.\SQLExpress;Database=master;Integrated Security=True"
$conn.Open()


# Get data via SqlDataReader
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.CommandText = "SELECT * FROM sys.objects"
$cmd.Connection = $conn

$dr
= New-Object System.Data.SqlClient.SqlDataReader
$dr = $cmd.ExecuteReader()

while ($dr.Read())
{
write-host $dr.GetString(0)
}
$cn.Close()


Notes and Observations

  • You may have noticed the line numbers from the PowerShell ISE were lost. I didn't bother addressing that--I didn't care. I suspect that's an easy enhancement. Maybe someday...
  • The generated HTML doesn't use any CSS. Real web devs would probably scoff, but that's ok.
  • Speaking of HTML, I usually wrap all my code samples in a <pre> tag, which is decorated with CSS.
  • The options tab is (hopefully) self-explanatory. The more options you check, the "larger" the generated HTML gets. I suspect I'll only ever use the "Color" option.
  • Font names could be problematic: the list of fonts available within your glorious OS is probably much larger than what your browser supports. Admittedly, I didn't do a lot of testing with this.
  • I tried coding a "Font size" option, but it was tricky. Font.Size in the .NET Framework doesn't translate too well to a browser. I didn't like the results, so I scrapped the idea.
  • I discovered background colors in the Visual Studio shell aren't included in the copy buffer when I paste into my app (or a Word document or an HTML-formatted email, etc.). I was able to paste from Visual Studio into a Word document, decorate text with a background color, and then copy/paste text from the Word document into the app.

  • Let me know if you find this tool useful. Or crappy. Or whatever. Comments welcome.


    UPDATE: September 21, 2017

    I've added three enhancements: a menu strip, root node options, and app configurations settings that allow you to save default values for the Options tab.

    Menu Strip

    This is a simple menu with File|Exit and Help|About. (The about window is new.)

    Root Node Options

    This allows you to wrap all of the encoded HTML into a "root" node. For instance, I enclose mine in a <pre> node. You can further specify node attributes. For instance class, style, or both, etc.

    App Configuration

    The "Code Beautifier.exe.config" file is a plain-text file consisting of XML data, as seen below. You can set default values (highlighted in yellow) for the Options tab by editing this file. Then, when you open the app, your desired settings will already be selected.


    <?xml version="1.0" encoding="utf-8" ?>
    <
    configuration>
    <
    startup>
    <
    supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </
    startup>

    <
    appSettings>
    <!--
    Set these values as desired and the app will default to them when it is started.
    -->

    <!--
    HTML format options: Valid values are "true" or "false". -->
    <
    add key="Color" value="true" />
    <
    add key="BackColor" value="false" />
    <
    add key="FontName " value="false" />
    <
    add key="FontBold" value="false" />

    <!--
    Root Node Options:-->
    <!--
    Valid values are "true" or "false". -->
    <
    add key="EncloseHtmlInRootNode" value="true" />

    <!--
    String values.
    Note the encoding of quotes in XML via &quot;
    https://stackoverflow.com/questions/3979297/how-to-use-double-quotes-in-app-config
    -->
    <
    add key="RootNodeName" value="pre" />
    <!--
    add key="NodeAttributes" value="class=&quot;myCode&quot;" /-->
    <
    add key="NodeAttributes" value="class=&quot;myCode&quot; style=&quot;font-size: small; color: black; font-family: Consolas, &quot;Courier New&quot;, Courier, Monospace;&quot;" />
    </
    appSettings>
    </
    configuration>

    UPDATE:
    Version 1.2 has been released.

    I've enhanced the app to include an option for line numbers. The settings for this feature are on the Options tab.

    Dave Mason Visual Studio Code Beautifier

    Here's a sample of what the line numbers look like:



    USE [msdb]
    GO

    /****** Object: Table [dbo].[syssessions] Script Date: 11/2/2017 4:12:05 PM ******/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE
    [dbo].[syssessions](
    [session_id] [int] IDENTITY(1,1) NOT NULL,
    [agent_start_date] [datetime] NOT NULL,
    PRIMARY KEY CLUSTERED
    (
    [session_id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO


    Highlight-able

    When your readers view your code in a browser, they will want to copy and paste it somewhere, right? Do you want the line numbers to be included in the copy/paste buffer? Check or un-check "Highlight-able" to control that behavior. The code example above *is not* highlight-able. If you copy/paste it somewhere else, the line numbers are excluded. The code example below *is* highlight-able. If you copy/paste it somewhere else, the line numbers are included. Give it a try and see the difference.



    1USE [msdb]
    2
    GO
    3
    4
    /****** Object: Table [dbo].[syssessions] Script Date: 11/2/2017 4:12:05 PM ******/
    5
    SET ANSI_NULLS ON
    6GO
    7
    8SET QUOTED_IDENTIFIER ON
    9GO
    10
    11CREATE TABLE
    [dbo].[syssessions](
    12
    [session_id] [int] IDENTITY(1,1) NOT NULL,
    13
    [agent_start_date] [datetime] NOT NULL,
    14
    PRIMARY KEY CLUSTERED
    15
    (
    16
    [session_id] ASC
    17
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    18
    ) ON [PRIMARY]
    19
    GO


    HTML Color

    This controls the color of the line numbers. You can specify either a named HTML color, or a hex color code.


    App Configuration

    Default values for Line Number options can be set in the "Code Beautifier.exe.config" file. Look for this section in the <appSettings> node:


    <!--Line Numbers:-->
    <!--
    Valid values are "true" or "false". -->
    <
    add key="AddLineNumbers" value="false" />
    <
    add key="LineNumbersHighlightable" value="false" />

    <!--
    String values. -->
    <
    add key="HtmlColor" value="#2B91AF" />

    Comments

    Post comment