2010-10-06

Add a Version Number to Your Classes

When creating classes to be shared with others, add a property to represent the version.

Programmatic access to the version number is good for at least 2 reasons:

  • Review what version is currently installed in an app.
  • Calling code can work around bugs or changes in behavior if it knows the version number.*
At the very least, add a simple string to store something like "2.4".

Make the property a "static" or "class" field with one value shared among all instances. The number will not vary across instances, so there is no need to make it a regular member. In REALbasic, make it a Shared Property.

2010-10-03

Tracking a field's value in REALbasic

Oddly enough, REAL Studio 2010 through Release 3 does not offer an event meaning the user (or code) changed the value in a TextField. On every keystroke, both "KeyUp" and "TextChange" fire. But that is too often. In boring database-backed business apps, we usually don't care about the user's edit as it happens. We only care after the edit, when the change is complete.

Hopefully the REAL Software team will add such an event in the future. In the meantime, I am giving away a single file, a subclass of TextField named "TextField_ValueTracking". I have an example project to demonstrate how it works. See here.

Moving files securely between Macs

How do you move files across a network or Internet to a secure Mac server?


iDisk

As a faithful Apple customer with a MobileMe account, my first thought was to use my iDisk to transfer files. I put files into my "Public" folder, then on the server in the Finder I choose Go > iDisk > Other User's Public Folder. The Finder mounts the public folder as a drive. Works well. Until it doesn't.


Problem

Twice now I've been burned in Mac OS X 10.6.4 and .5 where the Finder gets confused about the mounted iDisk folder. One symptom of this Finder bug is refusing to dismount. The Finder complains that a file is in use, but that's not true. The list of files in the mounted iDisk no longer updates its display to show current contents. "Force ejecting" the mounted iDisk fails. Your only option left is to force-quit the Finder. But that hoses your Mac, requiring a restart of your secure server. That's a drag.

I don't expect a fix soon. The Finder has always been lousy with bugs related to iDisk and its WebDAV protocol. With Snow Leopard, the Finder got a re-write in Cocoa from Carbon, which means new hiding places for bugs.


Workaround

One dead-simple workaround:
Rather than mount the iDisk in the Finder, use a web browser. 

Apple has been greatly improving the web access to MobileMe features. That includes iDisk file access. A nice multi-columned view of the file system appears in your web browser when you access the iDisk icon.

To log in to your MobileMe account with full access:
http://www.me.com/

To access somebody's iDisk public folder, point your web browser to:
http://public.me.com/TheirUserNameGoesHere

By the way, there are some other handy such URLs for accessing a MobileMe account's picture gallery, calendars, and web site.

You may be able to use Safari or other web browsers such as Camino, Firefox, Chrome, or Opera. I've some of those successfully, but don't recall which. You may get a warning message, but I've ignored it with no penalty.

2010-09-29

How to type an end-of-line

Recently a fellow programmer asked me a couple questions about how to type a linefeed on the keyboard, and how to handle newline delimiters from one program to another.

1. "What keyboard key can I press to create a linefeed character on a Mac?"

Depends on the app. End-of-line delimiters (also known as Newline) are not really input by the keyboard. The app interprets a press of the Return or Enter key, inserting into the data what it believes to be appropriate.

In most text editors such as TextMate, JEdit, BBEdit, TextWrangler, etc. you specify in prefs what the end of character should be. Some setting like "Lines end in: " with a popup menu offering LineFeed, Carriage Return, both. An app might even offer some special Unicode characters meant explicitly for such use (that nobody uses unfortunately). 

So, the upshot is: The user presses Return (or whatever) and the app inserts the particular octet(s) for a LineFeed, Carriage Return, both, etc.


2. "I was having some issues with 4D text fields that were getting pasted in HTML code from TextMate which was supposed to be putting in linefeeds."


Yes, sharing data between apps is almost always tricky. The programmer or user must set/manipulate the desired end-of-line delimiters either in the data source (TextMate here) or the sink (4D here).

Remember that computers are illiterate. Ultimately they know nothing about characters and text. They truly only understand numbers. What you think of as a file full of text is actually a file full of numbers. If an app reads that file and encounters a "10" (Linefeed), the app may choose to treat that octet as an end-of-line. Or that app may ignore each occurrence of 10, blissfully cruising along looking for an expected '13' (Carriage Return) on which to break lines. To really see what an app sees when it opens a file, to see octet-by-octet, open the file yourself using a hex editor such as HexFiend.

Believe it or not, the geek in me finds this kind of topic fascinating: human language vs computerized data, character sets, Unicode, etc. I have actually had a friend call me to discuss such topics as a cure for his insomnia. Don't even get me started on the lack of foresight of the early computer information folks in the `60s and `70s.
http://en.wikipedia.org/wiki/Newline

Tips:
  • Many text editors do not convert existing documents when you change the end-of-line prefs setting. Your setting might apply only to future new files. 
  • You can verify what is being used with a hex editor such as HexFiend.
  • Some older Mac programs still default to Carriage Return for end-of-line rather than the Unix convention of linefeed.
  • Some cross-platform development tools try to help by defaulting to the convention used on the computer at runtime. But this can cause confusion as it changes the behavior of your app depending on which computer a user uses. Usually you should hard-code a specific consistent end-of-line. Java and REALbasic switch defaults, and as I recall 4D does too at least in some circumstances.
Here's how to hard-code generating a linefeed in REALbasic:
Encodings.UTF8.Chr(10)


2010-09-28

Nil versus Null

The 4D language has two words that may be confused: Nil & Null.

Nil tests whether the pointer points to a valid container of a value, a field, variable or array. Nil has nothing to do with the content of what is being pointed to. Nil tells you nothing about what may or may not be inside that field, variable, or array.

  • To test if a pointer is nil:
    If ( Nil( $myPointer) )
      …
    End If

NULL means the container (a database field) has no contents. No value = NULL. Do not confuse no value with an empty value. For an Alpha field or Text variable, we represent an empty value in our code as a pair of double-quotes: $companyName := ""
  • To test for NULL, call the command Is field value Null
  • To set a NULL, removing the value entirely, call the command SET FIELD VALUE NULL


Here's code to test for nil pointer…

C_pointer( $pointerToText )
if Nil( $pointerToText )
  `ERROR condition.
else ` else not nil, we have a valid pointer. So use it.
  C_TEXT( $myText )
  $myText := $pointerToText-> `Copy the value of the text.
end if


You should always test a pointer for nil when passed as a parameter, as seen in this code…

C_pointer($1)
if Not(Nil($1))
  …
end if


4D versions 11 & 12 introduce the feature/problem of NULL values in a record's field, as do most other SQL databases. You can have a valid pointer to a record's field, but have no value (NULL) stored in that field. On the other hand, the record's field may have a value (be non-NULL) but that value may be empty such as empty text for Alpha Field, !00/00/00! for date, etc.

So generally you should be testing for 2 or 3 issues:

  • Is pointer valid? (not Nil)
  • Is what's being pointed to a record field with a value? (not NULL)
  • Is the value valid in the record field being pointed to? (not empty, within expected range, etc.)


--- 4D code --------
C_pointer( $pointerToField )
C_TEXT( $myText )
$myText := "ERROR - This text never got set"

if Nil($ pointerToField )
  `ERROR condition.
else ` else not nil, we have a valid pointer. So use it.
  IF ( Type($pointerToField->) = Is Alpha Field )
    If ( Is field value Null( $pointerToField )
        `ERROR condition. No value (NULL).
    Else // Else we have an actual value

      If ( $pointerToField-> = "" )
        $myText := "Got text? Nope." `Flag error condition if having an empty string was unexpected.
      Else
        $myText := $pointerToField-> `Copy the value of the field.   <-------- GOAL
      End If

    End IF

  Else
    `ERROR - Expected an Alpha field, but got a pointer pointing to something else.
  End if
end if
… Do something with $myText


If you're working with Date, Blob, or other types of variabless or fields rather than Alpha/String, same concepts apply. Just change the data types in code above, but logic is the same.

Caveat: These code examples were written freehand, not written or tested in 4D.

Tip: In general you should avoid dealing with NULL by defining your database fields as "NOT NULL" in SQL, meaning a record with a NULL in that field will be rejected by the database engine. Chris Date explains why.

2010-09-27

REALbasic code to connect to Postgres

I have another blog post with example code in REAL Studio for connecting with REAL Server.

Here's the same example adjusted for connecting to a Postgres server.


  dim db as PostgreSQLDatabase = new PostgreSQLDatabase

  // ---------------- Prepare connection.
  db.Host = "127.0.0.1"
  db.port = 5432 // 5432 is default port for PostgreSQL.
  //db.Encryption = 128 // Always encrypt your connection when on an untrusted network.
  db.UserName = "postgres" // "postgres" is the default admin user name.
  db.Password = "YourPostgresPasswordGoesHere"
  db.DatabaseName = "YourDatabaseNameGoesHere" // Postgres supports multiple databases. Which one do you want? Default is name the same name as user, such as 'postgres'.

  // ---------------- Try connecting.
  dim status as String
  if( db.Connect ) then
    status = "Success connecting to db server"
  else // Error connecting
    status = "Error occurred when connecting to database server. Code: " + str(db.ErrorCode) + " " + db.ErrorMessage
  end if

  // ---------------- Execute a "SELECT *"
  dim sql as String = "SELECT * FROM YourTableNameGoesHere"
  dim rs as RecordSet = db.SQLSelect( sql)
  if(db.Error) then
    status = "Error when running a SELECT. Code: " + str(db.ErrorCode) + " " + db.ErrorMessage
  else // Else normal.
    if( rs = nil ) then
      status = "ERROR - RecordSet is nil"
    else
      status = "Record count = " + str( rs.RecordCount ) // Replace with more useful code.
    end if
  end if

  db.Close

  // ---------------- Catch any exception thrown by code above.
Exception
  if( db <> nil) then
    db.Close
  end if

2010-09-26

Hiding extraneous stuff in pgAdmin3

When starting out in Postgres 9 using the bundled pgAdmin3 app, I was confused by all the various pieces of the installation. Postgres has many internal support files, tables, and such, none of which is useful to a newbie like me.

Thanks to SeaPug, I got a tip to hide all that extra stuff, instead showing just my own tables, etc.


  1. In Preferences, choose the Browser tab, and uncheck "Show System Objects". 
  2. Restart pgAdmin3.