Identity Interface


May 18, 2008

Getting started with the Google App Engine.

Category: code, maps, technology – jonshern – 4:30 am

The tutorial goes over some basic concepts surrounding Google’s App Engine Framework, demonstrates using the Google App Engine to store data, and using Django templates to create a GeoRss feed that is consumed by Google maps.

Setup your environment

I chose eclipse as my ide.
The nice thing about eclipse is if you add the lib directories of whatever you are using (including the Google App Engine) you will get some intellisense.

Download the necessary components.
Google app engine
Eclipse
Installing Pydev
The documentation helped, but the link was bad. I used http://pydev.sf.net/updates/.

The guts of the python file

 
import cgi
import os
import wsgiref.handlers
 
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
 
_DEBUG=True
 
class Business(db.Model):
    ......
 
def main():
    application = webapp.WSGIApplication([
            ('/',MainPage),
            ('/createbusiness.do',BusinessSignup),
            ('/georssfeed.xml',GeoRssFeed)
            ],debug=_DEBUG)
    wsgiref.handlers.CGIHandler().run(application)
 
if __name__ == "__main__":
    main()

The main method is where we map our urls to the classes we have defined within the python file.
Each class that handles requests should have a get or a post method.
When a get or a post occurs it will be routed automagically to the appropriate method.

Creating the table

class Business(db.Model):
    name = db.StringProperty()
    description = db.StringProperty(multiline=True)
    url = db.URLProperty()
    location = db.StringProperty()
    latitude = db.StringProperty()
    longitude = db.StringProperty()
    address = db.StringProperty()
    created = db.DateTimeProperty(auto_now_add=True)

Description can contain line breaks so we specify multiline=True
Created is of type DateTime and has the property auto_now_add set to true
created is set to the current time the first time the model instance is stored in the datastore, unless the property has already been assigned a value.

There is also an auto_now property that can be used to set the current time each time the record is created or updated. Useful for modified dates.


Handling the request

In one of googles examples(Task List) they used a base class for the request.
Here is my modified version.

class BaseRequestHandler(webapp.RequestHandler):
    """Supplies a common template generation function"""
    def generate(self,template_name,template_values={}):
        values = {
                  'request': self.request,
                  'debug': self.request.get('deb'),
                  'application_name': 'Local Business Directory'
                  }
 
        values.update(template_values)
        directory = os.path.dirname(__file__)
        path = os.path.join(directory,os.path.join('templates',template_name))
        self.response.out.write(template.render(path,values,debug=_DEBUG))

This does a few nice things.

        values = {
                  'request': self.request,
                  'debug': self.request.get('deb'),
                  'application_name': 'Local Business Directory'
                  }
        values.update(template_values)

This sets up an array of base values that will be passed into the template.
In other methods that use base request, we will add other objects to this array. So our html templates can process data.
The last line values.update is where the two arrays gets merged.

        path = os.path.join(directory,os.path.join('templates',template_name))

In this application I created a templates folder to separate the html from the code. This line just adds the template_name to the /templates path.

    self.response.out.write(template.render(path,values,debug=_DEBUG))

And finally
Write the request out.

Using the BaseRequestHandler

class MainPage(BaseRequestHandler):
    def get(self):
 
        #Get all of the businesses
        businesses = Business.all().order('-created')
 
        self.generate('index.html', {
                                     'businesses': businesses
                                     })

Here is a simple example of querying all of the businesses ordered by created date.
We then call the generate method on the BaseRequestHandler, passing in our additional objects, along with the template name.

Using Templates
The Google App Engine uses the Django templating engine. W00t

The for loop

{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}

The if statement(there are several varieties)

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% else %}
    No athletes.
{% endif %}
 
{% ifequal user.id comment.user_id %}
    ...
{% endifequal %}

In the spirit of python, there are a lot of functions that Django gives you.
Examples:
timesince: Formats a date as the time since that date (e.g., “4 days, 6 hours”).
phone2numeric: Converts a phone number (possibly containing letters) to its numerical equivalent. For example, ‘800-COLLECT’ will be converted to ‘800-2655328′.

More Information on Django templates

In order to display a list of businesses I am just using a simple for loop and creating a row each time.

<div class="table">
	<table>
		<tr>
			<th>Business Name</th>
			<th>Address(Address, City, State)</th>
			<th>Description</th>
			<th>Url</th>
			<th>Location</th>
			<th>Latitude</th>
			<th>Longitude</th>
		</tr>
		</tr>
		{% for business in businesses %}
		<tr id="row{{ forloop.counter}}">
		<td class="main" 
		  <div class="name">{{ business.name }}</div>
		</td>
		<td class="members">
			{{ business.address }}
		</td>
		<td class="members">
			{{ business.description }}
		</td>
		<td class="members">
			{{ business.url }}
		</td>
		<td class="members">
			{{ business.location }}
		</td>
		<td class="members">
			{{ business.latitude }}
		</td>
		<td class="members">
			{{ business.longitude }}
		</td>
 
		</tr>
		{% endfor %}
	</table>
</div>

Entering Data

Two pieces of code were necessary for this
Plumbing in the python file

class BusinessSignup(webapp.RequestHandler):    
    def post(self):
        business = Business()
 
        business.name = self.request.get("txtBusinessName")
        business.address = self.request.get('txtAddress')
        business.description = self.request.get('txtDescription')
        business.url = self.request.get('txtUrl')
        business.location = self.request.get('txtLocation')
        business.latitude = self.request.get('txtLatitude')
        business.longitude = self.request.get('txtLongitude')
 
        business.put()
        self.redirect('/')

This just grabs from the data from the request and sets each property on our business object.
Then calls put.
put is an instance method that saves the data to the database.
delete, to_xml, is_saved, are a couple of other useful instance methods.

    <form action="/createbusiness.do" method="post" id="businessform">

Tells the form to post to the specified address.

Bringing it all together

application: yourapplication
version: 1
runtime: python
api_version: 1
 
handlers:
- url: /static
  static_dir: static
 
- url: /.*
  script: localbusinesslocator.py

The app.yaml is where your external url mapping occurs.
If you wanted to use several python files, this is where that would happen.
More Info can be found here

Testing the application
usr/local/google_appengine/dev_appserver.py /sourcedirectory/

Hopefully this fills in some gaps left by Googles tutorial.

The next installment of the series will go over displaying the data in the GeoRss format and displaying it on google maps.

April 12, 2008

Modeling using Enterprise Architect

Category: technology – jonshern – 12:47 pm

Recently I have been introduced to a new modeling tool called Enterprise Architect.
It is truly a great product for a great price.
It has full support for UML 2.1.

They have a robust and easy solution for distributed teams that have a need to access design artifacts.

Artifact Store

Local File or Shared Network Store
As with any modeling software you can store a file containing your models.

DBMS
You can easily configure SQL server to be your backend store, which allows a multi-user access to your modeling projects.

Source Control
Either you can use a DBMS in conjuction with a Version Control Product (Shared Model)
or you
use a local file based solution with a Version Control.
The major source control providers are supported out of the box, and you can add support for work item tracking in tfs with an optional plugin.

The price is very reasonable at $250 for an enterprise seat.
Compared with $5000 for Rational Software Architect, which is comparable to Power Designer and ErWin.

If you want to do some serious modeling without having to sacrifice your yearly budget. I would suggest getting a few copies of enterprise architect for your team.

March 17, 2008

Time Tracking and Timing

Category: technology – jonshern – 10:01 pm

Slim Timer is great web based task tracker and timer.
It also has some great reporting built in.
Check it out.

March 14, 2008

Lazy Loading Architecture

Category: code – jonshern – 7:56 am

Every place of employment has their favorite patterns and this one is no different.
Lazy Loading is a common theme amongst many of of the entities.

Basically take a property and in the get, check for null. If its null then load using a manager or something. If its not null then the list has been loaded.
It really only works for lists.

I think if you are going to do a SOA app, you should stick with the philosophy of plain old clr objects (poco) and just leave your accessors alone. Put the loading logic in a manager and load explicitly. It can become a hidden performance issue, when lists are just loading when you look at them.

The method I am talking about above is called Lazy Initialization (Fowler)
There are also several other types of Lazy Loading Fowler talks about including: Virtual Proxy, Value Holder, and Using Ghosts

The Ghost pattern looks as though it may overcome the hidden performance problem by creating a lazy loading supertype that wraps the load status. So you can tell if the list is of type “ghost”, “loading” or “loaded” A ghost would mean that the property should be lazy loaded when the oppurtunity arose. The problem I have with this, is the extra complexity of adding more layers.

In the end for me, it just seems easier to develop a robust manager architecture where explicit loads are easy and intuitive.

Fowler Martin. Patterns of Enterprise Architecture. 2003.

March 13, 2008

Resisting temptations of new language features

Category: code – jonshern – 10:27 pm

Before you go out and drop some extension methods on System.Object, read the this addendum on framework design guidelines for C# 3.0.

February 29, 2008

Quick and Dirty Data Layer — Subsonic or Enterprise Application Blocks

Category: code – jonshern – 6:01 pm

So the f1webchallenge is happening tomorrow morning.
The question is how does a .net developer who traditionally works on large projects transition to a development project that happens in just 24 hours.

One question is how do we handle our Data Layer.
Since it is Mysql, we can just use MySql.Data and get basic functionality, but for something that is going to need to be done very fast will that cut it?
There is also the Enterprise Application Blocks.
Here is how to build it into the Enterprise Application Blocks.
Adding MySQL.Data to Enterprise Application Blocks

There is also Enterprise Library Contrib
Something similar to the building it in, except you just run an installer.

Then there is the OR/M frameworks.
NHibernate
This just seems to big and bulky for a quick and dirty project.
I have used this in a larger application and things that should be simple are difficuly and things that should be hard are easy(sometimes).

Subsonic
I am going to do some more experimenting with Subsonic.
I have used it before and hooked it up as a post compile task, this had the disadvantage of invalidating code whenever the database was updated.
Early in a project this can be frequent.
This time around I have a batch file, and I am going to just generate the Table classes when something changes.
This should work pretty slick and should save a lot of time writing CRUD stuff.

I will post the results after the competition to see what solution wins.

February 20, 2008

XNA on the Zune

Category: code – jonshern – 1:04 pm

Just heard the announcement.
XNA games on the zune by the end of the year.

I am so excited.

February 11, 2008

How do you pass a pirate a message?

Category: code – jonshern – 10:24 am

Using the EventArgggggs.

January 29, 2008

ADO.NET Performance Improvements with .NET Framework 2.0 SP1

Category: code – jonshern – 10:23 pm

Recently a service pack was released for the 2.0 version of the .NET Framework.
As usual there was a laundry list of fixes, most of which were difficult to figure if they fixed or improved your production code.
ADO.NET performance was improved considerably especially when using the SqlDataReader
Original Article

December 19, 2007

Writing Readable Code

Category: code – jonshern – 10:30 pm

I think the single most important principle to writing readable code(imho)is SRP(Single Responsibility Principle)

In a nutshell
It is just making your classes and methods do one thing and that’s it.
Or at the very least name your methods accordingly if they do a couple of things.
An MS Example of breaking the SRP Rule.
bool Int32.TryParse(string s, out int result)

The benefits are numerous.
It is easy for other programmers to read your code.
Your methods get much shorter.
Refactoring becomes obvious when code starts to do more than one thing.
Unit Testing is easier and clearer.