Automating the Mac OS X Keychain App with Ruby

Recently, I needed a way to automate the generation of 100+ Apple Push notification certificates for my iOS development. So, I created a Ruby Gem [keychain_manager] to automate the Mac OS X Keychain application.

Here is how you can use it:

gem install keychain_manager

require 'keychain_manager'

USER = 'jprichardson@gmail.com'
KEYCHAIN = 'apple_push_keychain' #this can be anything, we just don't want to pollute the 'login' keychain
YOUR_DOWNLOADS_DIR = '' # you must set this, this is where the file aps_production_identity.cer exists

RSA_FILE = '/tmp/myrsa.key'
KeychainManager.generate_rsa_key(RSA_FILE)

CERT_FILE = '/tmp/CertificateSigningRequest.certSigningRequest'
KeychainManager.generate_cert_request(USER, 'US', CERT_FILE) #'US' is the country abbreviation.

kcm = KeychainManager.new(KEYCHAIN)
kcm.delete if kcm.exists?
kcm.create

kcm.import_rsa_key(RSA_FILE)

#now from your browser, you'll have downloaded a file from Apple typically named: aps_production_identity.cer
kcm.import_apple_cert(File.join(YOUR_DOWNLOADS_DIR, '/aps_production_identity.cer'))

P12_FILE = '/tmp/push_prod.p12'
kcm.export_identites(P12_FILE)

PEM_FILE = '/tmp/push_prod.pem'
KeychainManager.convert_p12_to_pem(P12_FILE, PEM_FILE)

kcm.delete

#Now upload the PEM_FILE to your server.

This gem could easily be modified to support other Keychain functions. Browse the sourcecode here: Keychain Manager source code.

I’ll post soon on how I automated the web portion of communicating with the iOS Provisioning Portal.

Do you use Git? If so, checkout Gitpilot to make using Git thoughtless.

Follow me on Twitter: @jprichardson and read my blog on entrepreneurship: Techneur.

-JP Richardson

Using Mongoid with Rspec

I’m a fan of testing. I’m still trying to discipline myself to test before I write code, that’s been a tough habit to develop, however testing after I develop a feature is a good habit that has paid dividends. Lately I’ve started learning how to use Rspec for Rails.

Out of the box, Rspec is configured to use ActiveRecord. I’ve pretty much stopped using relational databases in favor of NoSql solutions. My favorite NoSql DB is MongoDB. The Ruby MongoDB ORM that I’ve been using is Mongoid.

To prep for Rspec, make your gemfile look like this (Assuming Rails 3.x):

gem 'rspec-rails', :group => [:test, :development]
group :test do
  gem 'database_cleaner'
end

Then run:

bundle install
rails g rspec:install

When I started learning how to use Rspec, I started having problems. The first was the following error message:

undefined method `fixture_path=' for # (NoMethodError)

Oops, just needed to comment out the line spec_helper.rb:

config.fixture_path = "#{::Rails.root}/spec/fixtures"

Was I safe yet? Nope. Another error:
undefined method `use_transactional_fixtures=' for # (NoMethodError)

Oops, just needed to comment out the line spec_helper.rb:

config.use_transactional_fixtures = true

I should have known as the there are comments in the file.

Now, when I run my specs, the changes to the database persist from one test to the next. Ideally, you want a clean database when you start each test. This is where the gem database_cleaner comes in handy.

Then add this to your spec_helper.rb file:

  config.before(:suite) do
    DatabaseCleaner[:mongoid].strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner[:mongoid].start
  end

  config.after(:each) do
    DatabaseCleaner[:mongoid].clean
  end

That’s it!

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

If you made it this far, read my blog on software entrepreneurship and follow me on Twitter: @jprichardson.

FridayThe13th the Best JSON Parser for Silverlight and C#/.NET

Up until a couple of months ago I was writing most of my code using WPF. Recently, a project came up where Silverlight made more sense to use. I’d thought that wouldn’t be a problem since I’d just use JavaScriptSerializer [wrote about it here] like I did for my WPF project.

Uh oh. It turns out that Silverlight doesn’t have JavaScriptSerializer. Never fear! DataContractJsonSerializer is here! Or so I thought.

It turns out that if you want to use DataContractJsonSerializer you must actually create POCOs to backup this “data contract.” I didn’t want to do that.

I wanted to turn this…

{
	"some_number": 108.541,
	"date_time": "2011-04-13T15:34:09Z",
	"serial_number": "SN1234"
	"more_data": {
		"field1": 1.0
		"field2": "hello"
	}
}

into..

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541
Console.WriteLine(dict["more_data"]["field2"]); //outputs hello

So I set out to write my own JSON parser. I call it FridayThe13th… how fitting huh? Now, using either Silverlight or .NET 4.0, you can parse the previous JSON into the following:

using FridayThe13th;

var jsonText = File.ReadAllText("mydata.json");

var jsp = new JsonParser(){CamelizeProperties = true};
dynamic json = jsp.Parse(jsonText);

Console.WriteLine(json.SomeNumber); //outputs 108.541
Console.WriteLine(json.MoreData.Field2); //outputs hello

Since I work with a lot of Ruby on Rails backends, I want to add a property “CamelizeProperties” to turn “some_number” into “SomeNumber”… it’s more .NET like.

Try it! You can find it on Github. Oh yeah… it’s also faster than that other .NET JSON library that everyone uses.

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

If you made it this far, read my blog on software entrepreneurship and follow me on Twitter: @jprichardson.

-JP

Printing to a Postscript File from Delphi/C++ Builder

Unfortunately for me, I had to patch some legacy C++ Builder code to output the reports that were sent to a printer to a PDF file. Fortunately, many printers support standard Postscript and converting to a PDF from a Postscript is trivial.

Here are the instructions, assuming Windows XP:
1)Go to Printers/Faxes and Add New Printer
2)When the wizard pops up click “Next”
3)You should be on the screen “Add Printer Wizard”… select “Local Printer Attached”, uncheck “Automatically detect…”
4)Use port “LPT1”
5)Select “Apple” for manufacturer and printers select “Apple LaserWriter 12/640 PS”
6)In printer name I put “Apple PS”
7)For default, you can select “No”
8)No on sharing/or printing test page.

Now we have a Postscript printer installed.

Here is some sample code:

void __fastcall TForm2::Button1Click(TObject *Sender)
{
    TDocInfo di;
 
    int i = Printer()->Printers->IndexOf("Apple PS");
    Printer()->PrinterIndex = i;
 
    Printer()->BeginDoc();
    EndPage(Printer()->Canvas->Handle);
    AbortDoc(Printer()->Canvas->Handle);
 
    memset(&di, sizeof(di), 0);
    di.cbSize = sizeof(di);
    di.lpszDocName = "TEST";
    di.lpszOutput = "C:\\somefile.ps";
    StartDoc(Printer()->Canvas->Handle, &di);
    StartPage(Printer()->Canvas->Handle);
 
    Printer()->Canvas->TextOutA(0,0, "Testing Printer");
    Printer()->EndDoc();
}

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson and read my blog on software entrepreneurship: Techneur

-JP

Disable Sprockets for Rails in Development Mode

Sprockets (is/are)? the technology in Rails 3.1 and up that combines your CSS and Javascript files into one CSS and Javascript file. It remains to be seen if this was a positive change or not. The argument is that the client only has to make one HTTP request instead of many for each file; this is a good thing. However, if you change one line in one of your Javascript files, the client then has to redownload the entire combined file instead of just the one Javascript file that you modified.

Regardless, you may want to disable Sprockets while you’re developing your Rails application. This will aid in debugging.

Change…

<%= stylesheet_include_tag "application" %>
<%= javascript_include_tag "application" %>

to…

<%= stylesheet_include_tag "application", debug: Rails.env.development? %>
<%= javascript_include_tag "application", debug: Rails.env.development? %>

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson and read my blog on software entrepreneurship: Techneur

-JP

Missing DockPanel? Add DockPanel for Silverlight 4 or Silverlight 5

When I first created a demo project for Silverlight 5, I opened the XAML code to start editing. I started typing “DockPanel” but then I noticed that intellisense didn’t show anything. It turns out that DockPanel and some other controls aren’t included in the default installation of Silverlight 4 or Silverlight 5 beta.

Here’s what you need to do:

  1. Download the Silverlight 4 Toolkit. Install it. (Yes, this will work with Silverlight 5 beta)
  2. Add a reference to “System.Windows.Controls.Toolkit”. In Silverlight 5, you will need to navigate to the file:
    %ProgramFiles%\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Bin\System.Windows.Controls.Toolkit.dll
  3. Add the following attribute to your UserControl: xmlns:tk=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit”
  4. So your code might look like:

    <UserControl x:Class="Project1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    	xmlns:tk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
    
        <Grid x:Name="LayoutRoot" Background="White">
    		<tk:DockPanel>
    			
    		</tk:DockPanel>
        </Grid>
    	
    </UserControl>
    

    Enjoy.

    Advertisement:
    Make Git simple. Let Gitpilot show you the right way to Git things done. Gitpilot will help you write software faster.

    Follow me on Twitter: @jprichardson and read my blog on software entrepreneurship: Techneur

    -JP

Open a New Tab in Terminal.app in the Same Directory on Mac OS X

When working with Rails on my Mac OS X machine, I often find myself opening a lot of terminal tabs. Unfortunately I then need to navigate to the same directory as the other tabs. It’s a big pain. Fortunately superuser.com has a solution.

Create a new file in “/usr/local/bin” named “nt”

#!/bin/bash
osascript -e 'tell application "Terminal"' \
-e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' \
-e "do script with command \"cd `pwd`;clear\" in selected tab of the front window" \
-e 'end tell' &> /dev/null

Then set its executable bit. “chmod +x /usr/local/bin/nt”

That’s it!

Advertisement:
Make Git simple. Let Gitpilot show you the right way to Git things done. Gitpilot will help you write software faster.

Installing MongoDB 1.8.1 on Ubuntu 10.04 LTS

A lot of this information will seem obvious to a lot of you. But it did require me to perform a few Google searches, so hopefully I can save you the trouble.

I provide a script to automate this process:

This script is deprecated now. Fortunately 10Gen (the company who makes MongoDB) provides an Apt repository. Do not use the current MongoDB version in the Ubuntu apt sources. It’s version 1.6.*

All you need to do:

vim /etc/apt/sources.list

Add the following line:
deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen


apt-get update
apt-get install mongodb-10gen

By default MongoDB runs in trusted mode. This means that it’s listening on port 27017 for any connection. We want it to only listen on localhost.

Edit the file: /etc/mongodb.conf

Add the following lines:
bind_ip 127.0.0.1
noauth = true ##### YOU MUST add this line if you use bind_ip

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

That’s it. Follow me on Twitter: @jprichardson and read my blog on software entrepreneurship.

-JP

Linear Regression in C#/.NET Using Least Squares

I had a class that handled the regression of my data sets, but it had too many business rules. It was necessary for me to refactor the code.

Here’s how you can use it:

double[] X = { 75.0, 83, 85, 85, 92, 97, 99 };
double[] Y = { 16.0, 20, 25, 27, 32, 48, 48 };
var ds = new XYDataSet(X, Y);

Console.WriteLine(Math.Round(ds.Slope,2)); //1.45
Console.WriteLine(Math.Round(ds.YIntercept,2)); //-96.85
ConsoleWriteLine(Math.Round(ds.ComputeRSquared(), 3)); //0.927

The source is in my .NET CommonLib library.
XYDataSet.cs: https://github.com/jprichardson/CommonLib/blob/master/CommonLib/Numerical/XYDataSet.cs
XYDataSetTest.cs: https://github.com/jprichardson/CommonLib/blob/master/TestCommonLib/Numerical/XYDataSetTest.cs

Here is the source for XYDataSet.cs:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using CommonLib.Geometry;

namespace CommonLib.Numerical
{
	public class XYDataSet : IList<PointD>
	{
		
		private List<PointD> _internalList = new List<PointD>();

		public XYDataSet() : this(null, null) { }

		public XYDataSet(IEnumerable<PointD> points) {
			ResetValues();

			foreach (var point in points)
				Add(point);
		}

		public XYDataSet(IEnumerable<double> Xs, IEnumerable<double> Ys) {
			ResetValues();
			
			if (Xs != null || Ys != null) {
				if (Xs.Count() != Ys.Count())
					throw new Exception("X count must be the same as the Y count.");

				for (int i = 0; i < Xs.Count(); ++i)
					Add(Xs.ElementAt(i), Ys.ElementAt(i));
			}
		}

		public int Count { get { return _internalList.Count; } }

		public bool IsReadOnly { get { return false; } }

		private double _maxX = Double.NegativeInfinity;
		public double XMax { get { return _internalList[XMaxIndex].X; } }
		private double _minX = Double.PositiveInfinity;
		public double XMin { get { return _internalList[XMinIndex].X; } }
		public int XMaxIndex { get; protected set; }
		public int XMinIndex { get; protected set; }

		private double _maxY = Double.NegativeInfinity;
		public double YMax { get { return _internalList[YMaxIndex].Y; } }
		private double _minY = Double.PositiveInfinity;
		public double YMin { get { return _internalList[YMinIndex].Y; } }
		public int YMaxIndex { get; protected set; }
		public int YMinIndex { get; protected set; }

		public double XMean { get { return XSum / Count; } }
		public double YMean { get { return YSum / Count; } }

		public double RSquare { get; protected set; }

		public PointD RegressionPoint0 { get; protected set; }
		public PointD RegressionPointN { get; protected set; }

		public double Slope { get; protected set; }

		public double XSum { get; set; }
		public double YSum { get; set; }
		public double XSquaredSum { get; set; }
		public double XYProductSum { get; set; }

		public double XIntercept { get { return -YIntercept / Slope; } }
		public double YIntercept { get; protected set; }


		public PointD this[int index] {
			get { return _internalList[index]; }
			set {
				var p = value;
				var old = _internalList[index];
				_internalList[index] = p;

				ComputeSums(old, SumMode.Subtract);
				ComputeSums(p, SumMode.Add);
				ComputeMinAndMax();
				ComputeSlopeAndYIntercept();
			}
		}

		public void Add(double x, double y) {
			Add(new PointD(x, y));
		}

		public void Add(PointD p) {
			_internalList.Add(p);
			RSquare = double.NaN;

			ComputeSums(p, SumMode.Add);
			ComputeMinAndMax(Count - 1, p);
			ComputeSlopeAndYIntercept();
		}

		public void Clear() {
			_internalList.Clear();
			ResetValues();
		}

		public void ComputeSlopeAndYIntercept() {
			double delta = Count * XSquaredSum - Math.Pow(XSum, 2.0);
			YIntercept = (1.0 / delta) * (XSquaredSum * YSum - XSum * XYProductSum);
			Slope = (1.0 / delta) * (Count * XYProductSum - XSum * YSum);

			RegressionPoint0.X = XMin;
			RegressionPoint0.Y = Slope * XMin + YIntercept;
			RegressionPointN.X = XMax;
			RegressionPointN.Y = Slope * XMax + YIntercept;
		}

		public double ComputeRSquared() {
			var SStot = _internalList.Sum(p => Math.Pow(p.Y - YMean, 2.0));
			var SSerr = _internalList.Sum(p => Math.Pow(p.Y - (Slope * p.X + YIntercept), 2.0));
			RSquare = 1.0 - SSerr / SStot;
			return RSquare;
		}

		public bool Contains(PointD p) {
			return _internalList.Contains(p);
		}

		public void CopyTo(PointD[] points, int index) {
			_internalList.CopyTo(points, index);
		}

		public IEnumerator<PointD> GetEnumerator() {
			return _internalList.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator() {
			return _internalList.GetEnumerator();
		}

		public int IndexOf(PointD p) {
			return _internalList.IndexOf(p);
		}

		public void Insert(int index, PointD p) {
			_internalList.Insert(index, p);
			RSquare = double.NaN;

			ComputeSums(p, SumMode.Add);
			ComputeMinAndMax();
			ComputeSlopeAndYIntercept();
		}

		public bool Remove(PointD p) {
			var success = _internalList.Remove(p);
			if (success) {
				RSquare = double.NaN;
				ComputeSums(p, SumMode.Subtract);
				ComputeMinAndMax();
				ComputeSlopeAndYIntercept();
			}
			return success;
		}

		public void RemoveAt(int index) {
			var old = _internalList[index];
			_internalList.RemoveAt(index);
			RSquare = double.NaN;

			ComputeSums(old, SumMode.Subtract);
			ComputeMinAndMax();
			ComputeSlopeAndYIntercept();
		}

		protected void ComputeMinAndMax() { //methods that call this, Insert, 
			ResetMinAndMax();

			for (int i = 0; i < _internalList.Count; ++i)
				ComputeMinAndMax(i, _internalList[i]);
		}

		protected void ComputeMinAndMax(int index, PointD newPoint) {
			if (newPoint.X <= _minX) {
				_minX = newPoint.X;
				XMinIndex = index;
			}

			if (newPoint.X >= _maxX) {
				_maxX = newPoint.X;
				XMaxIndex = index;
			}

			if (newPoint.Y <= _minY) {
				_minY = newPoint.Y;
				YMinIndex = index;
			}

			if (newPoint.Y >= _maxY) {
				_maxY = newPoint.Y;
				YMaxIndex = index;
			}
		}

		protected enum SumMode { Add, Subtract };
		protected void ComputeSums(PointD p, SumMode mode) {
			if (mode == SumMode.Add) {
				XSum += p.X;
				YSum += p.Y;
				XSquaredSum += Math.Pow(p.X, 2.0);
				XYProductSum += (p.X * p.Y);
			}
			else if (mode == SumMode.Subtract) {
				XSum -= p.X;
				YSum -= p.Y;
				XSquaredSum -= Math.Pow(p.X, 2.0);
				XYProductSum -= (p.X * p.Y);
			}
		}

		protected void ResetMinAndMax() {
			_maxX = double.NegativeInfinity;
			_maxY = double.NegativeInfinity;
			_minX = double.PositiveInfinity;
			_minY = double.PositiveInfinity;
		}

		protected void ResetValues() {
			ResetMinAndMax();

			RegressionPoint0 = new PointD();
			RegressionPointN = new PointD();

			RSquare = double.NaN;

			Slope = double.NaN;
			YIntercept = double.NaN;

			XSum = 0.0;
			YSum = 0.0;
			XSquaredSum = 0.0;
			XYProductSum = 0.0;

			XMaxIndex = -1;
			YMaxIndex = -1;
			XMinIndex = -1;
			YMinIndex = -1;
		}
		
	}
}

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson and read my blog on software entrepreneurship: Techneur

-JP

Quick JSON Serialization/Deserialization in C#

*This outdated*. You should use FridayThe13th the best JSON parser for Silverlight and .NET 4.0.

You don’t need to download an additional libraryto serialize/deserialize your objects to/from JSON. Since .NET 3.5, .NET can do it natively.

Add a reference to your project to “System.Web.Extensions.dll”

Let’s look at this example JSON string:

{
	"some_number": 108.541, 
	"date_time": "2011-04-13T15:34:09Z", 
	"serial_number": "SN1234"
}

You can deserialize the previous JSON into a dictionary like so:

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,string>>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541

So what if your JSON is a bit more complex?

{
	"some_number": 108.541, 
	"date_time": "2011-04-13T15:34:09Z", 
	"serial_number": "SN1234"
	"more_data": {
		"field1": 1.0
		"field2": "hello"	
	}
}

Deserialize like so…

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,dynamic>>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541
Console.WriteLine(dict["more_data"]["field2"]); //outputs hello

The field “more_data” gets deserialized into a Dictionary<string, object>.

You can actually just just deserialize like so:

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);

Console.WriteLine(dict["some_number"]); //outputs 108.541
Console.WriteLine(dict["more_data"]["field2"]); //outputs hello

And everything still works the same. The only caveat is that you lose intellisense by using the “dynamic” data type.

Serialization is just as easy:

using System.Web.Script.Serialization;

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);

var json = jss.Serialize(dict);
Console.WriteLine(json);

Outputs…

{
	"some_number": 108.541, 
	"date_time": "2011-04-13T15:34:09Z", 
	"serial_number": "SN1234"
	"more_data": {
		"field1": 1.0
		"field2": "hello"	
	}
}

Do you use Git? If so, checkout Gitpilot to make project management and collaborating on projects seamless.

If you made it this far, read my blog on software entrepreneurship and follow me on Twitter: @jprichardson.

-JP

Follow

Get every new post delivered to your Inbox.