Building a Netduino Rover – Part 2

See other posts in this series

Adding a Bumper

From the moment the wheels started turning it was clear I needed a bumper. With both motors on full power the rover can move rather fast. Thoughtfully the guys over at DFRobot included a bumper-shaped mounting bracket as part of the chassis kit.

I bought some foam profile channels (used for furniture packing) at a stationary shop, and a foam sheet from a crafts shop just to give it a nice black finish.

netduino007

Using a scalpel, carefully cut the foam channel in half leaving you with a V shape. Wrap the foam sheet around the foam channel and cut to size so the foam channel is completely covered. Slide the bracket inside the V and secure everything together with some cable ties.

netduino003

The bracket can then be mounted to the chassis using spare screws from the chassis kit. The bracket can be recovered and reused at any time by cutting the cable ties. Hopefully I won’t need the bumper once the range sensors are working.

netduino004

Advertisements
Posted in Projects | Tagged , | Leave a comment

Building a Netduino Rover – Part 1

See other posts in this series

Parts List

As a software developer with no electronics training, this project was daunting from the start. My aim was to create a mobile robotics platform, programmable using .NET and Visual Studio. The Netduino was a perfect choice since it’s the .NET cousin of the very popular Arduino, and is compatible with many of the Arduino shields.

netduino006

Since my metal working skills don’t extend far beyond a keyring, I decided to invest in an off-the-shelf chassis from DFRobot for around £25 (or $40). They can supply chassis’ and kits for any budget and any size of robot. I would strongly suggest you decide on a budget before visiting.

Here’s my parts list:
1 x Netduino
1 x Turtle 2WD Mobile Platform
2 x IR Distance Sensor (10-80cm)
1 x Sensor Shield
1 x 1A Motor Shield
1 x 9V Power Adapter (optional)

netduino001

netduino002

You can mount the Netduino to the chassis using the bronze mounting screws that came with the kit. The battery compartment is optional – I decided to use a 9V power adapter instead. The shields should be stackable, I have the Netduino at the bottom with the motor shield in the middle and the sensor shield on top. This arrangement made it easier to debug the sensors (especially since the connections were a little intermittent).

Posted in Projects | Tagged , | Leave a comment

Calculating the Previous Month’s Date Range in SQL

Here’s a handy snippet that calculates the start and end dates for the previous month based on the current date. I find this very handy when I have an automated script that reports on the figures for only the last month.

DECLARE @LastMonth AS smalldatetime
DECLARE @LastMonthStart AS smalldatetime
DECLARE @LastMonthEnd AS smalldatetime

-- Move back one month from today's date
SET @LastMonth = DATEADD(month, -1, GETDATE())

-- Use the year and month components but set the day to be the 1st
SET @LastMonthStart = CAST(YEAR(@LastMonth) AS varchar) + '-' + CAST(MONTH(@LastMonth) AS varchar) + '-01'

-- The end date should be exactly one month from the start date
SET @LastMonthEnd = DATEADD(month, 1, @LastMonthStart)

-- Typical usage
...WHERE [DateColumn] >= @LastMonthStart AND [DateColumn] < @LastMonthEnd
Posted in Tips and Tricks | Tagged | Leave a comment

Wiki Markup Hyperlinks for WPF or HTML

This article shows an example of a Wiki-inspired markup for embedding hyperlinks in text – and how to render it as WPF and HTML.

When building any kind of content management system, it’s a good idea to give users the ability to add hyperlinks. Many web-based systems either require that the user knows HTML, or provides some kind of toolbar and preview area that lets the user work with the rendered HTML. The bottom line is that the user is still exposed to an HTML editor, and this is where so many problems can occur.

HTML isn’t very useful if the content needs to be displayed away from the web, such as a WPF application. My preferred way of handling this is to use a simplified markup that can be converted to WPF or HTML at render time. The http://en.wikipedia.org/wiki/Help:Wiki_markup is a great example of this.

The following code demonstrates how I’ve allowed my users to add hyperlinks inside a content management system using a simple syntax, and how those hyperlinks can be rendered either on a webpage or inside a WPF application.

Here’s an example of the syntax:
[[ web address | friendly description ]]

Here’s an example in context:
The markup [[http://www.bing.com|Click here for Bing]] would appear as Click here for Bing.

I’ve resisted the temptation of solving this using a Regular Expression, and instead I’m using the much underused string.Split(string[]) method which breaks the source text into chunks whenever an opening or closing bracket are found. I’m then checking for the presence of the bar (|) character to decide if the chunk should be converted to a hyperlink or displayed as-is. The resulting TextBlock is then returned to the caller from where it can be added dynamically to the page.

Here’s the code for WPF. Note that in order for the hyperlink to open when clicked, the RequestNavigate event must be wired up.

private TextBlock ParseHyperlinks(string line)
{
    if (line.Contains("[["))
    {
        var textBlock = new TextBlock { TextWrapping = System.Windows.TextWrapping.Wrap };
        var chunks = line.Split(new string[] { "[[", "]]" }, StringSplitOptions.RemoveEmptyEntries);
        
        foreach(var chunk in chunks)
        {
            if (chunk.Contains("|"))
            {
                var blocks = chunk.Split('|');
                if (blocks.Length == 2)
                {
                    var hyperlink = new Hyperlink();
                    hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
                    hyperlink.NavigateUri = new Uri(blocks[0]);
                    hyperlink.Inlines.Add(blocks[1]);
                    textBlock.Inlines.Add(hyperlink);
                }
                else
                    textBlock.Inlines.Add(chunk);
            }
            else
                textBlock.Inlines.Add(chunk);
        }
        return textBlock;
    }
    else
        return new TextBlock { Text = line, TextWrapping = System.Windows.TextWrapping.Wrap };
}

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    System.Diagnostics.Process.Start(e.Uri.ToString());
}

The code to convert the same markup into HTML is very similar:

public string ParseHyperlinks(string line)
{
    if (line.Contains("[["))
    {
        var sb = new StringBuilder();
        var chunks = line.Split(new string[] { "[[", "]]" }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var chunk in chunks)
        {
            if (chunk.Contains("|"))
            {
                var blocks = chunk.Split('|');
                if (blocks.Length == 2)
                    sb.Append(string.Format("<a href='{0}'>{1}</a>", blocks[0], blocks[1]));
                else
                    sb.Append(chunk);
            }
            else
                sb.Append(chunk);
        }
        return sb.ToString();
    }
    else
        return line;
}
Posted in Tips and Tricks | Tagged , , | Leave a comment

Posting to Twitter with C#

In this post I’ll walk through the steps required to post to your own Twitter feed using C#.

Step 1:
Before you start you must register an application name with Twitter:
dev.twitter.com/apps/new

Step 2:
Open Visual Studio 2010 and, using NuGet, download and install the Twitterizer package:

Step 3:
Grant your application access to your own Twitter account. Ensure that both read and write and enabled:

Step 4:
Here’s an example of two call the library from C#:

public static void Tweet(string message)
{
    OAuthTokens tokens = new OAuthTokens();
    tokens.ConsumerKey = "***";
    tokens.ConsumerSecret = "***";
    tokens.AccessToken = "***";
    tokens.AccessTokenSecret = "***";

    IAsyncResult asyncResult = TwitterStatusAsync.Update(
        tokens,                     // The OAuth tokens
        message,                    // The text of the tweet
        null,                       // Optional parameters (none given here)
        new TimeSpan(0, 3, 0),      // The maximum time to let the process run
        updateResponse =>           // The callback method
        {
            // Handle any errors here with: updateResponse.ErrorMessage
        });
}

Resources:
Twitterizer
Twitter Developer Site

Posted in Reference | Tagged , , | 2 Comments

WPF Expander HeaderTemplates – Don’t Forget The Binding!

Every time I customize an Expander in WPF using a HeaderTemplate, I make a critical mistake. I forget to set the binding for the header. Here’s a contrived example to demonstrate the problem – and the solution.

Here’s what we’re aiming for. A simple Expander with a title and a few lines of text contained within. Of course, a HeaderTemplate is overkill here, but it’s necessary in order to demonstrate the problem.

Let’s start by creating a simple view model for our Expander to bind to:

public class DemoViewModel
{
    public string Title { get; set; }
    public string ContentLine1 { get; set; }
    public string ContentLine2 { get; set; }
    public string ContentLine3 { get; set; }
}

Now create an instance of the view model and set it as the data context for the window:

public partial class MainWindow : Window
{
    public DemoViewModel ViewModel { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        InitializeViewModel();
    }

    private void InitializeViewModel()
    {
        ViewModel = new DemoViewModel
        {
            Title = "Expander Title",
            ContentLine1 = "This is line 1",
            ContentLine2 = "This is line 2",
            ContentLine3 = "This is line 3"
        };
        this.DataContext = ViewModel;
    }
}

Switch to XAML mode and create an Expander with a HeaderTemplate:

<Expander Width="200">
    <Expander.HeaderTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Title}" />
            </StackPanel>
        </DataTemplate>
    </Expander.HeaderTemplate>
    <StackPanel>
        <TextBlock Text="{Binding ContentLine1}" />
        <TextBlock Text="{Binding ContentLine2}" />
        <TextBlock Text="{Binding ContentLine3}" />
    </StackPanel>
</Expander>

When you run this code you’ll notice that the header is blank. The bindings inside the HeaderTemplate don’t bind. I’m no expert, but this seems to be because the data context for the header is not inherited from the data context of the Expander… which seems a little odd to me, but I’m sure there’s a good reason.

The fix is simple enough, just add the attribute Header={Binding} to the Expander:

<Expander Header="{Binding}" Width="200">
...

The bindings inside the HeaderTemplate should now work:

Posted in Reference | Tagged , , | 8 Comments

Posting to Facebook with C#

In this post I’ll walk through the steps required to register a Facebook app, and post to your own Facebook wall using C# and Visual Studio 2010.

Step 1:
Before starting, you’ll need to log on to the Facebook developer site and confirm your Facebook profile if you haven’t already done so:
www.facebook.com/help/verify

Step 2:
Next, select Apps from the toolbar, then select +Create New App:

Step 3:
Enter the display name and namespace for the application:

Step 4:
Add the contact email address and category, or add any additional administrator accounts:

Step 5:
Open Visual Studio 2010 and, using NuGet, download and install the Facebook package:

Step 6:
Since the application is only posting to our own account, the access keys can be generated up-front. This can be done using the Graph API Explorer. Open the Graph API Explorer and change the application dropdown from “Graph API Explorer” to the name of your app.

Select “Get Access Token”. For this to work, three additional permissions are required:

  • publish_stream – Enables your app to post content, comments, and likes to a user’s stream and to the streams of the user’s friends
  • manage_pages – Enables your application to retrieve access_tokens for pages the user administrate
  • offline_access – Enables your app to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.

Copy the access token for later. For more information on Facebook permissions check out their permissions page.

Step 7 – Posting to Your Wall:
Using the Facebook package, and the access token from Step 6, we can now post a comment to your Facebook wall:

private static void PostToWall(string message, long userId, string wallAccessToken)
{
    var fb = new FacebookClient(wallAccessToken);
    string url = string.Format("{0}/{1}", userId, "feed");
    var argList = new Dictionary<string, object>();
    argList["message"] = message;
    fb.Post(url, argList);
}

Under the hood the Facebook Client is sending a HTTP POST request to Facebook’s graph API. The actual URL is:
https://graph.facebook.com/USER_ID/feed?message=MESSAGE&access_token=TOKEN

Step 8 – Posting to a Page:
Posting to a Facebook page that you own is just as simple, but you’ll need to create an access token using the Graph API Explorer. Each page has it’s own access token, and Facebook uses this to determine which page you are posting to.

private static void PostToPage(string message, string pageAccessToken)
{
    var fb = new FacebookClient(pageAccessToken);
    var argList = new Dictionary<string, object>();
    argList["message"] = message;
    fb.Post("feed", argList);
}

This post doesn’t go into much detail, that’s intentional as this is as far as my knowledge goes on the subject. For more information I’d recommend you visit the Facebook Docs or the brilliant StackOverflow.

Resources:
NuGet
Facebook Developer Site
Facebook Permissions
Facebook Graph API Explorer
StackOverlow – Post on a Facebook business page from another user app

Posted in Reference | Tagged , , | 6 Comments