Friday, June 29, 2012

Ruby error "invalid multibyte character (US-ASCII)"

If you try to include non-ASCII characters in the source code of a Ruby program, you may get the error "invalid multibyte character (US-ASCII)". This one-line program illustrates the problem, using the right angle quote character: foo = "»" If you Google the error message, you'll find a lot of advice about placing "# encoding: UTF-8" or "# coding UTF-8" or "$KCODE = 'u'" at the top of the file. None of these worked for me. However, I found a simple fix. My environment is Ruby 1.9.3p194 on Windows. I opened my .rb file in Notepad, selected Save As, chose "UTF-8" from the "Encoding" dropdown, and clicked "Save". This -- with no other changes made -- solved the problem.

Monday, June 25, 2012

Enumerating the rows and columns for an arbitrary SQL query using Dapper ORM

The Dapper object-relational mapper makes it easy to execute SQL queries and manipulate the results in a .NET program. I thought it would be nice to be able to execute an arbitrary query, without knowing in advance the number, names and data types of the resulting columns, and output the results. The C# program below does exactly that.

Before using this in the real world, consider:

  • Error handling. What happens if the connection string is wrong? If the query times out? If the query returns no results? Etc.
  • Security. Do you want everyone to be able to execute any query against your database?!
  • Performance: What if someone constructs a query that takes an hour to execute?
Here's the code, which assumes you're building a C# Console Application and have added Dapper's SqlMapper.cs to the project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections;

static void Main(string[] args)
{
    string connectionString = "YOUR CONNECTION STRING GOES HERE";
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        var rows = (IEnumerable<IDictionary<string, object>>)conn.Query("ANY SQL QUERY YOU LIKE"); // e.g. select top 10 * from FooBar
        foreach (var row in rows)
        {
            foreach (var column in row)
            {
                Console.WriteLine(column.Key + " = " + column.Value);
            }
        }
    }
}