Friday, June 17, 2016

Biking to Work is Dangerous

I think biking to work is dangerous, but not for the reasons that just popped into your head.

I was a bit lazy this morning and took a little longer to do those things I do every morning before going to work, like feeding the chickens and the raven (yes. I have a friendly raven). So, after finally getting going on the bike you would think I would choose the fastest, easiest way to get to work to make up for leaving late, but no. You see, it was a perfect morning, cool temperatures, a blue sky, and no wind. So of course I decided to take the river route to work.

Of course I started Strava before heading out, but I'm not a typical Strava user. I really don't care about KOM, PR, or other achievements, sometimes I just like to keep a record of my rides. And like I said, I was feeling lazy this morning so I was just riding and enjoying being out on the bike, and that is where the danger comes in.

I started when my son was in scouts, well that is probably not true as there is no real beginning, but it works for this story. So, it started when my son was in scouts and they were getting ready to do a White Rim biking trip, and I volunteered to go along.


The next year I went on a trip with the scouts doing the Kokopelli trail. The White Rim and the Kokopelli were great multi day trips, but somehow I jumped from that to biking across Antarctica to the South Pole, and that was followed by a couple of bike tours, one from Utah to Oregon, and a second one going down the Oregon coast.


And that is the real danger of biking to work. I start by thinking how nice it would be to just skip going to work and spend the day out on the bike. Then the idea that it would be awesome to just forget everything else and go on a bike tour with no real destination, just each day ride to somewhere new.

Now that wouldn't be so bad, but this leads to fantasies of selling everything and buying a yacht and heading out on an around the world cruise. I imagine starting in California and sailing south along the coast of South America and through the straits of Magellan, and of course stopping in Punta Arenas to visit my friends there. Then continuing up the Atlantic coast to the Caribbean, the Bahamas, maybe up to Greenland, Iceland, Scandinavia, England, through the strait of Gibraltar and into the Mediterranean. Africa scares me, but still I would have to stop somewhere in Africa just to make sure that I get all seven continents marked off the bucket list. (I'm not a bucket list kind of guy, but since I have been to Antarctica now I feel the obligation to visit Africa, Asia, and Australia).

So somewhere I'd visit Africa, and then through the Suez Canal and into the Indian Ocean, India, Indonesia and down to Australia, up along China, Japan Russia and over to Alaska, and back down to the start.

The thing is I have already proven that I am likely to do crazy trips, and so that is why biking to work is dangerous.

Hmm, I think I need to go read Call of the Wild.

Saturday, May 21, 2016

Serving Pages and Mustache with Perfect

Ryan Collins has some great videos on how to use Perfect  to serve web pages and how to use Mustache. These were great for helping me get things going, but I prefer a written format to video, so I am going to repeat a bit of what Ryan has done. Chris Manahan has a good writes up on getting a Perfect project running on how to use MySQL with Perfect so I won't repeat that.

So here we go:

My previous blog post shows how I created classes to serve my MySQL tables as JSON. Here is my
PerfectServerModuleInit Where I  add one route to return JSON from my auto_make table.

public func PerfectServerModuleInit() {
    Routing.Handler.registerGlobally() 
   
    // Create Routes
    Routing.Routes["/auto_make"] = { _ in return AutoMakeRecord() }
}


I'm creating a web service for my app, but I also want to have a web interface that allows me to administer content for the app. So I need to serve some static pages like my stylesheet to give the look and feel of my service and then of course some dynamic pages.

To get static pages I add a route and connect it to the StaticFileHandler that is part of the PerfectLib.

public func PerfectServerModuleInit() {
    Routing.Handler.registerGlobally() 
   
    // Create Routes
    Routing.Routes["/*"] = { _ in return StaticFileHandler() }
    Routing.Routes["/auto_make"] = { _ in return AutoMakeRecord() }
}

Now I need to have a file in the webroot. So in my Xcode project I create a group called webroot and add my .css file and background image:



This is great, but to get the server to find these files we need to have them copied into the webroot in the Products Directory. So I select my CarHealthServer project and the Build Phase. Then click on the "+" and add a "New Copy Files Phase"



Then I will click on the "+" in the copy files phase and add the files that are in my webroot group. Here I have added a couple of extra files, a vehicles.html and a shop messages.mustache. I'll talk about the .mustache file later.


So now when we run our server and go to http://localhost:8181/BackView.css in my browser I get the contents of my .css file.

I want a page that will let me create an html document that will get saved in a MySQL table. So I create a file call shopmessage.mustache:

(Sorry blogger is having problems with this, and I am feeling lazy so you get a picture or this file)
   

The important things here are "{{% handler:ShopMessageHandler}}" which specifies the class that will handle the dynamic content for the mustache file, and "{{doc}}" which is supplied by the handler. Here is my ShopMessageHandler.swift class:

import PerfectLib

class ShopMessageHandler: PageHandler {

    func valuesForResponse(context: MustacheEvaluationContext, collector: MustacheEvaluationOutputCollector) throws -> MustacheEvaluationContext.MapType {
    
        var values = MustacheEvaluationContext.MapType()
        
        values["doc"] = "my shop message" 
        return values
    }
    
}

Now I need to modify the  PerfectServerModuleInit to register the ShopMessageHandler.

public func PerfectServerModuleInit() {
    
    PageHandlerRegistry.addPageHandler("ShopMessageHandler") { (r: WebResponse) -> PageHandler in return ShopMessageHandler() }
    
    Routing.Handler.registerGlobally()
    
    // Create Routes
    Routing.Routes["/*"] = { _ in return StaticFileHandler() }
    Routing.Routes["auto_make"] = { _ in return AutoMakeRecord() }
}

In the valuesForRespose I create a dictionary of the values to be used in the .mustache file. In this case there is just one value and it is hard coded to a static string. But this now gives me the framework to develop my service.

Now when I go to http://localhost:8181/shopmessage.mustache I get this:

Friday, May 20, 2016

Working with Swift subclasses

I decided to build the web service for my iOS and Android app using Perfect which is a Swift server implementation. I am using MySQL to host a database and wanted to a nice way to get the database tables written out as JSON. I had some problems but here is what I came up with:

My first attempt was to create a base class that I could subclass for each table type and do the read/write database operations and the JSON operations in the base class. But I ran into a lot of problems getting the base class to access the overridden properties and methods of the subclasses. Then I discovered this. Fist I create a simple protocol that all the record classes will use:

protocol DatabaseRecord : RequestHandler {
    var sqlTableName: String {get}
    var loaded: Bool {get set}
    func loadRow(row: [String])
    func getDictionary() -> [String : String]
    func load(forName:String)
    func load(forID:Int)
    func getAll() -> [AnyObject]
    init()
}

Then I create an extension to the protocol so all of this will get added to all of the classes that implement the DatabaseRecord protocol.

extension DatabaseRecord {

The methods here to load from the database don't seem like a big deal, but this just didn't work as a super class because despite all my google searching and efforts I couldn't get the base class to call the subclass methods or get the sqlTableName from the sub classes. But as an extension this jus works without any strange code.

    func loadFromDatabase(query:String) {
        var mysql = MySQLConnection.mysql;
        MySQLConnection.connectToMySQL()
        defer {
            mysql.close()
        }
        if mysql.query(query) {
            if let results = mysql.storeResults() {
                if results.numRows() >= 1 {
                    if let row = results.next() {
                        loadRow(row)
                        return
                    }
                }
            }
        }
    }
    func load(forName:String) {
        self.loadFromDatabase("SELECT * FROM \(sqlTableName) WHERE name = \"\(forName)\"")
    }
    func load(forID:Int) {
        self.loadFromDatabase("SELECT * FROM \(sqlTableName) WHERE id = \"\(forID)\"")
    }

This next method was where I had the most problems. I tried using Self, dynamicType, and everything else I could think of to get the sqlTableName from the subclasses and got it going but the creating objects of my subclasses and adding them to an array that I would return seemed impossible. Now as an extension the sqlTableName just works, and I can create a new object of the correct class using self.dynamicType.init() and add it to the array. 

    func getAll() -> [AnyObject] {
        var records = [AnyObject]()
        var mysql = MySQLConnection.mysql;
        
        MySQLConnection.connectToMySQL()
        defer {
            mysql.close()
        }
        if mysql.query("SELECT * FROM \(sqlTableName)") {
            if let results = mysql.storeResults() {
                results.forEachRow { row in
                    let obj = self.dynamicType.init()
                    obj.loadRow(row)
                    if let o = obj as? AnyObject {
                        records.append(o)
                  }
                }
            }
        }
        return records
    }

PerfectLib has a JSON encoder but when I tried to use it, it would crash. It was late and the JSON that I need to generate was simple so I just quickly wrote this to create the JSON for my table:

    func encodeAsJSON(dicts:Array<[String:String]>) -> String {
        var str: String = "["
        for dict in dicts {
            var first = true
            for (key, value) in dict {
                if !first {
                    str.appendContentsOf(",")
                } else {
                    first = false
                }
                str.appendContentsOf("{\"\(key)\":\"\(value)\"}")
            }
        }
        str.appendContentsOf("]")
        return str
    }

Now I can add a request handler to the extension and now all my database record classes have a easy way to take a http get request and turn it into JSON array.

    func handleRequest(request: WebRequest, response: WebResponse) {
        let records = getAll()
        var dicts = Array<[String:String]>()
    
        for rec in records {
            if let r = rec as? DatabaseRecord {
                let dict = r.getDictionary()
                dicts.append(dict)
            }
        }
        response.appendBodyString(encodeAsJSON(dicts))
        response.requestCompletedCallback()
    }
}

So then I have a simple Swift class representing a SQL database record. For example:

/*
auto_make SQL table
 +-------------+------------------+------+-----+---------+----------------+
 | Field       | Type             | Null | Key | Default | Extra          |
 +-------------+------------------+------+-----+---------+----------------+
 | id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
 | name        | varchar(255)     | YES  |     | NULL    |                |
 +-------------+------------------+------+-----+---------+----------------+
 */
class AutoMakeRecord: DatabaseRecord {
    var id: Int?
    var name: String = ""
    var loaded: Bool
    var sqlTableName: String {
        return "auto_make"
    }
    
    func loadRow(row: [String])
    {
        id = Int(row[0]) ?? -1
        name = row[1]
        loaded = true
    }
  
    func getDictionary() -> [String : String] {
        var dict = [String: String]()
        dict["id"] = String(id!)
        dict["name"] = name
        return dict
    }
    
    required init() {
        loaded = false
    }
}

Now a public method that registers the routes.  

public func PerfectServerModuleInit() {
    Routing.Handler.registerGlobally() 
   
    // Create Routes
    Routing.Routes["/auto_make"] = { _ in return AutoMakeRecord() }
}

And it is easy to create additional classes for database tables and add them to the routes.  Of course I will want to create http handlers that will allow to more than just dump out tables to JSON, but this now gives me the base I need to create the rest of my web service.

Friday, January 29, 2016

Land of Opportunity

I used to work with a woman from India. One day we were talking and she referred to the USA as "loo". I had no idea what she ment. Yeah, I have heard the phrase Land of Opportunity, but hadn't given it much thought.

Wikipedia entry for Land of Opportunity says, "The land of opportunity is a phrase used to suggest that a place presents many possibilities for people to earn a prosperous living, and succeed in their economic or social objectives.
It is often used with reference to the United States of America, and is similar to the concept of the "American dream". It became popular among immigrant populations who left the "old world" in search of a better life in the "new world".

Politicians talk about making America great again. I think we sometimes loose sight of the fact that America is great. I don't mean that in a prideful way. I have no desire to argue if America is greater than somewhere else. There are a lot of great places in this world, and America is a great place. 

This is definitely a land of opportunity. We will see how this goes but I am thinking of writing a few political posts talking about the blessings we enjoy. Next post will be more on LOO. 

Thursday, December 03, 2015

Antarctica Weather: extremely difficult

One hundred years ago Ernest Shackleton and his team attempted to cross Antarctica. They didn't make it to the South Pole but their expedition became one of the greatest adventure stories ever written.

Two expeditions are commemorating Shackleton's expedition.Shackleton Solo has been going for 20 days. Henry is battling fierce winds and demoralizing whiteous. Meanwhile Shackleton 2015 is waiting at Union glacier for a freak in the weather so they can fly to their starting point.

A lot of things have changed over the last 100 years, but the unrepentant weather in Antarctica remains just as challenging as ever.

I wish the best for the two expeditions trying to make a trans Antarctic crossing. 

My Bicycle Store