Writing Blogs and Syntax Highlighting

I’ve posted a couple of articles now to Blogger which both have code snippets in them with the syntax highlighted and I thought I’d share what I have learnt and some of the issues I ran into.

When I started my first blog I was surprised that there didn’t seem to be any obvious de facto standard tool to use, but a lot of people seemed to be using Markdown. I’m using Windows so installed probably the best known Markdown editor Markdown Pad. It supports Github Flavoured Markup (GFM) by making use of a service provided by GitHub to convert the markdown to HTML. This enabled in Markdown Pad’s Tools | Options pages:

image

To see it’s effects in the LivePreview Pane you will also need to select the GitHub CSS:

image

With this configuration I was able to add code snippets into Markdown Pad using the GFM code blocks, for example:

````C#
public class MainViewModel
{
    public string MainText { get; private set; }
    public MainViewModel()
    {
        MainText = "Hello SmartTiles!";
    }
}
````

This was shown very nicely in the LivePreview Pane:

image

But how do I get this into my Blog? Well I started of exporting to HTML and taking a look at what Markdown Pad gave me: https://gist.github.com/JasonBSteele/4c99d9525022941644ca#file-post-2-html-export

As you can see from the gist, there is a lot of CSS included in the file to make it self contained. I certainly wouldn’t want to repeat all that for each of my posts so I extracted what I thought was relevant to the syntax highlighting: https://gist.github.com/JasonBSteele/4c99d9525022941644ca#file-github-css.

To get this into the blog I selected Template from the left vertical menu then clicked the Customise button. This navigated me to the Blogger Template Designer page where I selected Advanced | Add CSS which showed the text area for adding the CSS:

image

I then pasted the CSS into the text area and checked the results.

I found that any CSS I added here actually gets added to the page, it isn’t put into a separate CSS files then linked to. I also had some reservations about the way I had extracted the CSS in the first place – how did I know I had the correct CSS, what if other code snippets require CSS that the original snippet didn’t?

Nevertheless I went with it for my first two posts. To post from Markdown Pad I would select the whole text, then right click and select Copy as HTML. I would then go to the Blogger site, start a new post a paste the HTML into the HTML tab of the edit post text area. I found that switching between the HTML tab and the Compose tab would wreck the content so I had to stay on the HTML tab.

I also found that the resulting post didn’t look much like content of Markdown Pad’s LivePreview Pane. This isn’t surprising as the site’s CSS wasn’t being applied. I think there is a way to make this work by extracting all the CSS from the site and applying it to Markdown Pad but I didn’t investigate this further.

None of this made me feel that I was taking the best approach so I did some Googling.

I came across a couple of Scott Hanselman’s posts where he recommends using Windows Live Writer for writing posts: http://www.hanselman.com/blog/DownloadWindowsLiveWriter2012.aspx
and using Alex Gorbatchev’s SyntaxHighlighter for Syntax Highlighting: http://www.hanselman.com/blog/BestCodeSyntaxHighlighterForSnippetsInYourBlog.aspx.

I tried Windows Live Writer and loved the way I could just point it at my Blog and it would download all the relevant files it needs to enable WYSIWYG editing for a post. It then allows you to click a single button to push the post to the blog.

This was a lot easier, however it doesn’t support GFM and Github’s Syntax Highlighting so I decided to try Alex Gorbatchev’s SyntaxHighlighter; which was actually a little trickier than I thought it was going to be.

Scott’s post indicated that I would need to link to a few scripts, but I had already found that there is no way to upload script and CSS files to Blogger. However I did find that they are already hosted by Cloudflare CDN at https://cdnjs.com/libraries/syntaxhighlighter (bizarrely this link is now currently saying “Library not found” but the scripts in https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/ are still being returned).

I added the following script and CSS links into the blogger template just before the tag:

<link href="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shCore.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shThemeDefault.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shCore.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushCSharp.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushCpp.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushCss.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushGroovy.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushJScript.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushJava.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushRuby.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushPython.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushXml.min.js" type="text/javascript"></script>

and the following javascript:

SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();

just before the last tag. Notice that bloggerMode must be set to true to indicate to SyntaxHighlighter that we are using Blogger and to allow for the way Blogger handles
tags.

Conclusion

Whilst SyntaxHighlighter has some nice features I don’t think the highlighting looks as nice as GitHub’s. Also my digging found the Crayon Syntax Highlighter which looks really great and also has some nice features, but this appears to only be supported by WordPress, not Blogger.

However, to me, using Windows Live Writer for editing and posting outweighs this.

Update

And then this happened: https://productforums.google.com/forum/#!msg/blogger/-49FC2_0l-g/gA1zmGmvzjYJ and https://twitter.com/shanselman/status/603632170855440384.

So, at the time of writing, Windows Live Writer is unable to connect to Blogger because Blogger now requires OAuth authentication which WLW does not support.

This has forced me to look into going over to http://wordpress.com. They will host your blog for free (although they may show ads). However even though the blog engine is WordPress they only support a limited number of WordPress plugins (unless you go premium) and unfortunately this does not include Crayon Syntax Highlighter.

However WordPress.com do support a built in Syntax Highlighter described here: https://en.support.wordpress.com/code/posting-source-code/ and I found a plugin for it here: http://richhewlett.com/wlwsourcecodeplugin/.

So I’ve exported my blog from Blogger, imported it into WordPress.com and am now using Richard Hewlett’s plugin (thanks Richard!).

Advertisements
Writing Blogs and Syntax Highlighting

Xamarin.Forms Tiled UI – Part 2

In my previous post I wrote about the SmartThings SmartApp I will be connecting my app to. In this post I will start with creating the app solution and then creating the page to host the UI.

Using Visual Studio 2013 I created a Xamarin.Forms solution by creating a new project and selecting the Blank App (Xamarin.Forms Portable) project template. I named the solution SmartTiles.

The template creates an iOS, Android and Windows Phone 8.0 project. It’s always worth compiling the solution and even running it as soon as it’s been created, to ensure that it has been set up correctly with all it’s dependencies.

I’ll be using the MVVM pattern so I created a Views and ViewModels folder in the root of the SmartTiles (Portable) PCL project

The app will initially consist of a single page for showing the tiles so I added a new item to Views folder and selected the Forms Xaml Page template naming the page MainPage. I then added the view-model by adding a Class called MainViewModel to the ViewModels folder.

The XAML created by the template for MainPage looks like this:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="SmartTiles.Views.MainPage">
    <Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

As you can see it contain a Label which binds it’s Text property to a property called MainText. So to prove everything is working I’ll add a property called MainText to MainViewModel:

public class MainViewModel
{
    public string MainText { get; private set; }
    public MainViewModel()
    {
        MainText = "Hello SmartTiles!";
    }
 }

To bind my view-model to my view I need to set the BindingContext of the view which I will do in the view`s constructor:

public MainPage()
{
    InitializeComponent();
    this.BindingContext = new MainViewModel();
}

Now I just need to change the App class to load and show MainView by commenting out the code added by the template and setting the MainPage property to a new instance of the MainPage view:

public App()
{
    // The root page of your application
    MainPage = new MainPage();
    //MainPage = new ContentPage
    //{
    //    Content = new StackLayout
    //    {
    //        VerticalOptions = LayoutOptions.Center,
    //        Children = {
    //            new Label {
    //                XAlign = TextAlignment.Center,
    //                Text = "Welcome to Xamarin Forms!"
    //            }
    //        }
    //    }
    //};
}

The app is now ready to be run! Here it is running on the Windows Phone emulator:

Conclusion

Displaying a single Label in the middle of a page doesn’t seem like a very big achievement! But we do now have three apps for iOS, Android and Windows Phone all running the same code and using the MVVM pattern.

In the next post we will actually start looking at the SmartTiles layout – promise!

Xamarin.Forms Tiled UI – Part 2

Xamarin.Forms Tiled UI – Part 1

Hello! Welcome to my blog on using Xamarin’s tools to develop mobile apps.

I’m going to start with a project that provides a UI to my SmartThings devices. SmartThings sells a local hub device that is connected to your router providing connectivity between your Z-Wave or Zigbee devices and the SmartThings cloud. The devices are things like sensors for doors being opened, temperature, moisture, and also actuators which do things like switches and alarms.

The SmartThings cloud provides an online IDE in which you can write your own SmartApps. They are written in a language called Groovy which provides a Domain Specific Language for handling your devices events and invoking their actions.

So my first Xamarin post doesn’t have any C#, it’s Groovy!

But please don’t be put off by this! This series of posts will show how to create a tiled interface (like the Windows 8 Start Menu) with each tile data bound to a device. I will be using the SmartApp as a source for the data to show in the tiles, and operations to call when interacting with the tiles. However you can easily use other web services to provide a UI to interact with them.

SmartApp

So let’s start with the Groovy SmartApp. I have followed the tutorial here to create a SmartApp called REST Endpoints which responds to REST requests for sensor data and to perform actions.

The SmartApp script can be found in my SmartThings repository https://github.com/JasonBSteele/SmartThings where the README explains how to install it, get authorisation, and to call its endpoints.

I won’t go through the SmartApp in detail but hopefully just enough for you to see how it wires up my devices to a REST interface. The snippet below handles the REST requests for switch devices. The path specifies the pattern to match against the URL and the action maps the HTTP verb to the function to call.

path("/switches") {
action: [
GET: "listSwitches"
]
}
path("/switches/:id") {
action: [
GET: "showSwitch"
]
}
path("/switches/:id/:command") {
action: [
GET: "updateSwitch"
]
}

Both listSwitches and showSwitch call deviceToJson with the attribute name of the value of a switch, which is switch. A JSON response is built in deviceMap which is of type Map (similar to a C# Dictionary). You will notice below that the return keyword is optional.

private deviceToJson(device, attributeName) {
if (!device)
null

def s = device.currentState(attributeName)
def deviceMap = [id: device.id, name: device.displayName, unitTime: s?.date?.time]
deviceMap[attributeName] = s?.value
deviceMap
}

The JSON response for a single switch looks like this:

{
"id":"be7c0195-ef58-4b16-969b-91299c1e0c82",
"name":"My Switch",
"unitTime":1425247415223,
"switch":"on"
}

The remaining function updateSwitch calls updateToggle which finds the specific device in the switches collection and executes it’s on or off command.

private void updateToggle(devices) {
log.debug "updateToggle request: params: ${params}, devices: $devices.id"

def command = params.command
if (command)
{
def device = devices.find { it.id == params.id }
if (!device) {
httpError(404, "Device not found")
}
else {
if(command == "toggle") {
if(device.currentValue('switch') == "on")
device.off();
else
device.on();
}
else {
//else 'on' or 'off'
device."$command"()
}
}
}
}

You may have noticed that the HTTP verb GET invokes updateSwitch. For proper REST I should really use a PUT to change state but I have client applicatons for which it was easier to use a GET so decided, for now, to relax this convention.

Conclusion

We now have a web service for our Xamarin client to connect to. The next post will start with creating the app and it’s main page.

Xamarin.Forms Tiled UI – Part 1