Posted by Chad Hendry on 10 Dec 2009
One of the requirements in my current pet Ruby project is to, given the address of a bar, determine its latitude and longitude coordinates.
This is easy with the GeoKit gem:
class Bar < ActiveRecord::Base
validates_presence_of :name, :address1, :city, :state, :zip, :phone
acts_as_mappable :auto_geocode => { :field => :street_address }
private
def street_address
parts = [ address1, address2, city, "#{state} #{zip}" ]
parts.compact.join(', ')
end
end
Whenever a new bar is saved, GeoKit automatically calls the model object’s street_address method to get a string to pass to a provider. (Providers include Google, Yahoo, Geocoder.us, etc.) GeoKit uses the provider’s response to populate the model’s latitude and longitude attributes:

With this in place, you can query to find all bars within a certain distance from an origin location:
Bar.find(:all, :origin => '68506', :within => 5)
This generates the following SQL:
SELECT
*,
(
ACOS(
least(
1,
COS(0.71180079486811) * COS(-1.68663538782878) *
COS(RADIANS(bars.lat)) * COS(RADIANS(bars.lng)) +
COS(0.71180079486811) * SIN(-1.68663538782878) *
COS(RADIANS(bars.lat)) * SIN(RADIANS(bars.lng)) +
SIN(0.71180079486811) * SIN(RADIANS(bars.lat))
)
) * 3963.19
) AS distance
FROM
`bars`
WHERE
(
(
(
bars.lat > 40.7108964735732
AND bars.lat < 40.8554663264268
AND bars.lng > -96.7325543757321
AND bars.lng < -96.5416242242679
)
)
AND
(
(
ACOS(
least(
1,
COS(0.71180079486811) * COS(-1.68663538782878) *
COS(RADIANS(bars.lat)) * COS(RADIANS(bars.lng)) +
COS(0.71180079486811) * SIN(-1.68663538782878) *
COS(RADIANS(bars.lat)) * SIN(RADIANS(bars.lng)) +
SIN(0.71180079486811) * SIN(RADIANS(bars.lat))
)
) * 3963.19
) <= 5
)
)
Posted by Chad Hendry on 15 Sep 2009
I created my first Flex application today and it was remarkably painless. Here’s how:
First download and install the Flex 3 SDK. Unzip it anywhere and add the bin subdirectory to your path.
Next create a file called hello.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
]]>
</mx:Script>
<mx:Button id="button" label="Hello, World!"
click="Alert.show('hi!')" />
</mx:Application>
Then compile it using mxmlc:

Next, embed the compiled .swf file in a webpage using the following HTML:
<html>
<head>
<title>Chad's First Flash Application</title>
</head>
<body>
<object type="application/x-shockwave/flash" data="hello.swf"
width="200" height="200" />
</body>
</html>
Here’s the result:

Posted by Chad Hendry on 09 Aug 2009
This tutorial describes how to create an iPhone application using Xcode and Interface Builder. I’m assuming that you have installed Xcode and the iPhone SDK. The application prompts the user for a name and displays a message when the user touches a button.
To begin, start Xcode, and create a new view-based application:

Next, double-click on HelloViewController.xib. This will launch Interface Builder. Open the Library (Tools → Library) if it’s not already visible, and drag a Text Field, Round Rect Button, and Label onto the view window. Arrange them as they appear in the following screenshot. Double-click on the button to edit it’s text.

Next we need to add two instance variables and one method to the HelloViewController class. The two instance variables (outlets) will hold pointers to the UITextField and UILabel controls we added using Interface Builder. The method (action) will be wired up to execute in response to the user touching the Hello button. Go back to Xcode and edit your HelloViewController.h file to look like this:

Next, save everything (important!) and go back to Interface Builder. We need to tell Interface Builder to “wire up” our variables (outlets) and methods (actions) to the controls we placed on the view. To do this, control+click “File’s Owner,” drag to the text field, release, and select the outlet you want to attach. In this case, select “name.”

Do the same thing to attach the UILabel to the message outlet: Control+Click “File’s Owner,” drag to the label, release, and select message.
Now we need to attach the button to the hello: action. This is done similiarly to how we connected our outlets, except in the reverse direction. Control+click the button, drag to “File’s Owner,” release, and select the “hello:” action:

Now that we have our user interface wired up to our view controller, the only thing left to do is implement the hello: action. Open up the HelloViewController.m file in Xcode. You’ll notice a bunch of commented-out code and empty methods. These are all safe to delete. Edit the file so that it looks like this:

At this point, everything is ready to run. To recap, we have:
- Created an iPhone View-Based application.
- Used Interface Builder to add three controls to our view: a text field, a label, and a button.
- Added two outlets to our view controller: one called
name for the text field, and another called message for the label.
- Added an action called
hello: to our view controller.
- Used Interface Builder to “wire up” our outlets and actions.
- Implemented the
hello: action in our view controller.
Click Run → Go. This will compile the application and run it using the iPhone Simulator:

Posted by Chad Hendry on 27 Jun 2009
UPDATE: 2009-09-25: Roughly two months after introducing this console application to our team, the vast majority of the team voted to enable multiple checkouts. Next stop, Git!
Well, not really. But at least now I have a compromise to help wean the company off exclusive checkouts. Here’s the trick: when somebody has a file checked out that you need to modify, do this:
- Enable multiple checkouts on the team project.
- Remove the lock (but not the checkout) from the workspace that has the file checked out.
- Check out the file in your workspace.
- Turn multiple checkouts back off.
If the other person beats you to the checkin, he will notice nothing. However, if you check in first, TFS will prompt him to merge before checking in. (Obviously, if your team is accustomed to pessimistic locking, you should let the the other person know what you’re up to.)
I’ve created a program to do this quickly so that others don’t catch on to your mischief. It has a few quirks (no error checking and some assumptions about the working directory) but it works rather nicely:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
class Program
{
static VersionControlServer _sourceControl;
static Workspace _workspace;
static TeamProject _project;
static void Main(string[] args)
{
ConnectToTfs();
try
{
_project.ExclusiveCheckout = false;
UnlockFiles(args);
CheckoutFiles(args);
}
finally
{
_project.ExclusiveCheckout = true;
}
}
private static void ConnectToTfs()
{
var wsInfo = Workstation.Current.GetLocalWorkspaceInfo(".");
var tfs = TeamFoundationServerFactory.GetServer(wsInfo.ServerUri.ToString());
_sourceControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
_workspace = _sourceControl.GetWorkspace(wsInfo);
_project = _workspace.GetTeamProjectForLocalPath(".");
}
static void UnlockFiles(string[] localPaths)
{
var serverPaths = GetServerPaths(localPaths);
var pendingSets = _sourceControl.QueryPendingSets(serverPaths, RecursionType.Full, null, null);
foreach (var pendingSet in pendingSets)
UnlockItemsFromPendingSet(serverPaths, pendingSet);
}
static string[] GetServerPaths(string[] localPaths)
{
return new List<String>(localPaths)
.Select(arg => _workspace.GetServerItemForLocalItem(arg))
.Select(arg => arg.ToLower())
.ToArray();
}
static void UnlockItemsFromPendingSet(string[] serverPaths, PendingSet pendingSet)
{
foreach (var change in pendingSet.PendingChanges)
{
if (serverPaths.Contains(change.ServerItem.ToLower()))
{
var ws = _sourceControl.GetWorkspace(pendingSet.Computer, pendingSet.OwnerName);
if (ws.SetLock(change.ServerItem, LockLevel.None) > 0)
Console.WriteLine("Lock unset on {0}", change.ServerItem);
}
}
}
private static void CheckoutFiles(string[] args)
{
_workspace.PendEdit(args);
}
}
Posted by Chad Hendry on 19 May 2009
After playing around with NHibernate for a couple weeks, I’ve come up with this “whirlwind tour” of sorts. Suppose that you have three classes: Individual, Address and Account. The Individual class contains the individual’s name, DOB, address, and a collection of Account objects. The Account class simply contains a Type property that can be, for example, “Checking” or “Savings”:
public class Individual
{
public Individual()
{
Accounts = new List<Account>();
}
public virtual int Id { get; set; }
public virtual IList<Account> Accounts { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual DateTime DOB { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public virtual string Line1 { get; set; }
public virtual string Line2 { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual string Zip { get; set; }
}
public class Account
{
public virtual int Id { get; set; }
public virtual string Type { get; set; }
}
In the database there is a table called IndividualAccount which allows for a many-to-many relationship between individuals and accounts. This means that an individual can have both a checking and a savings account, and that two individuals can share the same account. Think joint checking. Here’s the DDL:
CREATE TABLE Account (
Id INT IDENTITY NOT NULL,
Type NVARCHAR(255) null,
primary key (Id)
)
CREATE TABLE IndividualAccount (
Account_id INT not null,
Individual_id INT not null
)
CREATE TABLE Individual (
Id INT IDENTITY NOT NULL,
FirstName NVARCHAR(255) null,
LastName NVARCHAR(255) null,
DOB DATETIME null,
Addr1 NVARCHAR(255) null,
Addr2 NVARCHAR(255) null,
City NVARCHAR(255) null,
State NVARCHAR(255) null,
Zip NVARCHAR(255) null,
primary key (Id)
)
Mapping
Now we need to tell NHibernate how to map between the object model and the database. We can do this by creating .hbm (Hibernate Mapping) XML files, or we can use Fluent NHibernate to write the mappings in code. I’ve opted for the fluent approach. These two classes (behind the scenes) generate HBM:
public class IndividualMap : ClassMap<Individual>
{
public IndividualMap()
{
Id(x => x.Id);
HasManyToMany<Account>(x => x.Accounts)
.WithTableName("IndividualAccount")
.Cascade.All();
Map(x => x.FirstName);
Map(x => x.LastName);
Map(x => x.DOB);
Component<Address>(x => x.Address, m =>
{
m.Map(x => x.Line1, "Addr1");
m.Map(x => x.Line2, "Addr2");
m.Map(x => x.City);
m.Map(x => x.State);
m.Map(x => x.Zip);
});
}
}
public class AccountMap : ClassMap<Account>
{
public AccountMap()
{
Id(x => x.Id);
HasManyToMany<Individual>(x => x.Individuals)
.WithTableName("IndividualAccount")
.Inverse();
Map(x => x.Type);
}
}
Next we have to build an ISessionFactory object. Again, Fluent NHibernate helps us out:
private ISessionFactory BuildSessionFactory()
{
return Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2005
.ConnectionString(c => c.FromConnectionStringWithKey("NHTest"))
)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Individual>())
.BuildSessionFactory();
}
Once we have a session factory, we use it to build an ISession object. All persistent objects are registered with this session object. When a session gets “flushed,” NHibernate determines which objects in the session have been added, updated, and deleted and generates the appropriate SQL to “make it so” in the database.
Inserting Data
We can use the following method populate our database with a couple individuals and accounts:
private void PopulateTestData(ISession session)
{
var chad = new Individual
{
FirstName = "Chad",
LastName = "Hendry",
DOB = new DateTime(1980, 7, 30),
Address = new Address
{
Line1 = "12 Main Street",
Line2 = "#1A",
City = "Chicago",
State = "IL",
Zip = "60622"
}
};
chad.Accounts.Add(new Account { Type = "Checking" });
chad.Accounts.Add(new Account { Type = "Savings" });
session.Save(chad);
var bob = new Individual
{
FirstName = "Bob",
LastName = "Jones",
DOB = new DateTime(1970, 10, 24),
Address = new Address
{
Line1 = "13 Main Street",
Line2 = "",
City = "Chicago",
State = "IL",
Zip = "60622"
}
};
bob.Accounts.Add(new Account { Type = "Checking" });
session.Save(bob);
session.Flush();
}
The generated SQL from the NHibernate logging is as follows:
INSERT INTO [Individual] (FirstName, LastName, DOB, Addr1, Addr2, City, State, Zip)
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7);
select SCOPE_IDENTITY();
@p0 = 'Chad', @p1 = 'Hendry', @p2 = '7/30/1980 12:00:00 AM', @p3 = '12 Main Street', @p4 = '#1A',
@p5 = 'Chicago', @p6 = 'IL', @p7 = '60622'
INSERT INTO [Account] (Type) VALUES (@p0); select SCOPE_IDENTITY(); @p0 = 'Checking'
INSERT INTO [Account] (Type) VALUES (@p0); select SCOPE_IDENTITY(); @p0 = 'Savings'
INSERT INTO [Individual] (FirstName, LastName, DOB, Addr1, Addr2, City, State, Zip)
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7);
select SCOPE_IDENTITY();
@p0 = 'Bob', @p1 = 'Jones', @p2 = '10/24/1970 12:00:00 AM', @p3 = '13 Main Street', @p4 = '',
@p5 = 'Chicago', @p6 = 'IL', @p7 = '60622'
INSERT INTO [Account] (Type) VALUES (@p0); select SCOPE_IDENTITY(); @p0 = 'Checking'
INSERT INTO IndividualAccount (Individual_id, Account_id) VALUES (@p0, @p1); @p0 = '1', @p1 = '1'
INSERT INTO IndividualAccount (Individual_id, Account_id) VALUES (@p0, @p1); @p0 = '1', @p1 = '2'
INSERT INTO IndividualAccount (Individual_id, Account_id) VALUES (@p0, @p1); @p0 = '2', @p1 = '3'
Let’s query to retrieve an individual, update it, and persist it:
[Test]
public void MoveChadToHawaii()
{
var i = _session
.CreateQuery("from Individual i where i.FirstName = :name")
.SetString("name", "Chad")
.List<Individual>()
.First();
i.Address.Line1 = "10 Beach St";
i.Address.Line2 = null;
i.Address.City = "Maui";
i.Address.State = "HI";
i.Address.Zip = "96767";
_session.Flush();
}
The generated code is:
select
individual0_.Id as Id3_,
individual0_.Addr1 as Addr2_3_,
individual0_.Addr2 as Addr3_3_,
individual0_.City as City3_,
individual0_.State as State3_,
individual0_.Zip as Zip3_,
individual0_.FirstName as FirstName3_,
individual0_.LastName as LastName3_,
individual0_.DOB as DOB3_
from
[Individual] individual0_
where
(individual0_.FirstName=@p0 ); @p0 = 'Chad'
UPDATE
[Individual]
SET
Addr1 = @p0,
Addr2 = @p1,
City = @p2,
State = @p3,
Zip = @p4,
FirstName = @p5,
LastName = @p6,
DOB = @p7
WHERE
Id = @p8;
@p0 = '10 Beach St', @p1 = '', @p2 = 'Maui', @p3 = 'HI', @p4 = '96767', @p5 = 'Chad',
@p6 = 'Hendry', @p7 = '7/30/1980 12:00:00 AM', @p8 = '1'
Lazy Loading
Let’s say we want to load an individual and iterate through the associated accounts:
[Test]
public void LoadIndividualAndIterateAccounts()
{
Console.WriteLine("-- getting individual");
var individual = _session.Get<Individual>(1);
Console.WriteLine("iterating accounts");
foreach (var account in individual.Accounts)
Console.WriteLine("-- {0}", account.Type);
}
The output is as follows:
-- getting individual
SELECT
individual0_.Id as Id3_0_,
individual0_.Addr1 as Addr2_3_0_,
individual0_.Addr2 as Addr3_3_0_,
individual0_.City as City3_0_,
individual0_.State as State3_0_,
individual0_.Zip as Zip3_0_,
individual0_.FirstName as FirstName3_0_,
individual0_.LastName as LastName3_0_,
individual0_.DOB as DOB3_0_
FROM
[Individual] individual0_
WHERE
individual0_.Id=@p0; @p0 = '1'
-- iterating accounts
SELECT
accounts0_.Individual_id as Individual2_1_,
accounts0_.Account_id as Account1_1_,
account1_.Id as Id1_0_,
account1_.Type as Type1_0_
FROM
IndividualAccount accounts0_
left outer join [Account] account1_ on accounts0_.Account_id=account1_.Id
WHERE
accounts0_.Individual_id=@p0; @p0 = '1'
-- Checking
-- Savings
Notice how the accounts are not queried for until the first time we access the Accounts property. Also notice that we didn’t do anything fancy in our Individual class. The Accounts property is a simple IList<Account>; it knows nothing about the database or even persistence in general. What’s happening is that NHibernate is assigning to the Accounts property a proxy object that implements IList<Account>, and that object queries for the associated accounts when (and if) it’s used. You can also configure NHibernate to perform eager loading if, for example, you want to bring back the individual and accounts all in one query.
Querying
NHibernate provides a query language called HQL. Taken from the NHibernate refererence documentation: “NHibernate is equiped with an extremely powerful query language that (quite intentionally) looks very much like SQL. But don’t be fooled by the syntax; HQL is fully object-oriented, understanding notions like inheritence, polymorphism and association.”
Our simple schema doesn’t give us room to execute too interesting of a query, but consider trying to find all individuals that have a checking account:
SELECT DISTINCT
i
FROM
Individual i
JOIN i.Accounts a
WHERE
a.Type = 'Checking'
This produces the following, reasonably decent SQL:
select distinct
individual0_.Id as Id7_,
individual0_.Addr1 as Addr2_7_,
individual0_.Addr2 as Addr3_7_,
individual0_.City as City7_,
individual0_.State as State7_,
individual0_.Zip as Zip7_,
individual0_.FirstName as FirstName7_,
individual0_.LastName as LastName7_,
individual0_.DOB as DOB7_
from
[Individual] individual0_
inner join IndividualAccount accounts1_ on individual0_.Id=accounts1_.Individual_id
inner join [Account] account2_ on accounts1_.Account_id=account2_.Id
where
(account2_.Type='Checking' )
Many more interesting examples can be found in the HQL Examples section of the reference documentation.
Posted by Chad Hendry on 25 Apr 2009
Today I installed mono and nant on my MacBook and finally got around to test-driving StructureMap, a dependency injection / inversion of control framework for .Net. Here’s what happened:
using System;
using StructureMap;
class Program {
static void Main() {
ObjectFactory.Initialize(x => {
x.ForRequestedType<IMood>().TheDefaultIsConcreteType<Sleepy>();
});
Person p = ObjectFactory.GetInstance<Person>();
p.SaySomething();
}
}
class Person {
private IMood _mood;
public Person(IMood mood) {
_mood = mood;
}
public void SaySomething() {
Console.WriteLine(_mood.Say("I think I need a coffee"));
}
}
interface IMood {
string Say(string message);
}
class Sleepy : IMood {
public string Say(string message) {
return "Zzzz... " + message;
}
}
As you can see, to create a new Person we must pass it an IMood object. So, we tell StructureMap that the default concrete type for IMood is Sleepy and let it assemble the Person object accordingly.
In addition to the (recommended) fluent API above, StructureMap supports configuration through an XML configuration file. One way to do this is to tell StructureMap to use it’s default configuration file:
ObjectFactory.Initialize(x => {
x.UseDefaultStructureMapConfigFile = true;
});
Then create a file named StructureMap.config in the same directory as your executable with the following XML:
<StructureMap MementoStyle="Attribute">
<DefaultInstance
PluginType="IMood,MyAssembly"
PluggedType="Sleepy,MyAssembly"
/>
</StructureMap>
Another feature that seems like it could be useful is the ability to use conditional logic for determining which concrete types are used. For instance, given the following Wired mood:
public class Wired : IMood {
public string Say(string message) {
return message.Replace(" ", "") + "!!";
}
}
We can have StructureMap use the Sleepy mood when it’s early and the Wired mood when it’s not:
ObjectFactory.Initialize(x => {
x.InstanceOf<IMood>().Is.Conditional(o => {
o.If(c => IsEarly()).ThenIt.Is.OfConcreteType<Sleepy>();
o.TheDefault.Is.OfConcreteType<Wired>();
});
});
That’s just a short overview of some of the features I tried out during my initial sitting with StructureMap. There are several more very interesting features described in the documentation. A couple of the features I’m most interested in and hope to learn (and blog about) soon are:
- The ability to define conventions that specify which concrete types are loaded, i.e., convention over configuration.
- Ways to scope the lifecycle of objects that StructureMap creates, for instance, “create one object per
HttpContext.”
- StructureMap’s built-in integration with mocking frameworks such as RhinoMocks and Moq.