>
Apple-AppleScript-Script-Editor-Logo

Basic AppleScript Dialog:

display dialog "Your text here" with icon stop buttons {"OK"} default button {"OK"} giving up after 5

'giving up after 5' will automatically close the script after the indicated interval of time has elapsed.

HTML Anchor Code

Here is a sample of how to write code to link one part of your blog page to another:

<a name = "By Email">[optional text]</a> --place this where you want the link to go <a href = "#By Email">By Email</a> --this is the actual link

more HTML

HTML Code to Link to Other Web Pages

Here is a sample of code to link to another page. this is similar to the anchor code, except that the destination code is the url of the destination site:

<a href= "www.webSite.
com"> Website Name</a>

--just replace "www.webSite.
com"
with the actual url destination site and replace 'Website Name' with the prompt that the user will see.

My Links

Apple-IIc-Apple-Screen

AppleScript Note:

It might be interesting to those of you who are AppleScript enthusiasts that the HyperCard (HyperTalk) project was the prototype back in the '80's of what became the system-wide Applescript language (akin to JavaScript) that is in use today.
Apple-Mac-512-Screen
3d-iMac-Large

Trapping for List Dialog Errors

With 'List Dialog' type dialogs, since errors cannot be intercepted in an 'on error' handler, there is no 'normal' way to trap for 'Cancel' which, of course, would result in some sort of undesirable error dialog such as 'User cancelled. Error number -128'. Here is an example of one simple way I have found to trap for this type of error: set x to (choose from list {"Joe","Amy",
"Bill"} with prompt "Choose a record:")
if x is false then
else
set targetItem to (x as text)
show every record whose cell "Name" contains x
end if
When the user clicks on 'Cancel', the variable x is assigned the boolean value false. So all you have to do is set up a conditional to deal with that and to perform the usual statements otherwise.

Learning AppleScript

AppleScript-123-Book

Create Multiple Folders with Terminal

If you are more of a techy kind of person and are comfortable with using Terminal, here is a script you can use to easily create multiple folders:

First, for a single folder, type in: mkdir "Folder 1" --or whatever you want to name your folder, this creates a new directory, which, in effect is a new folder. To place multiple items in the 'Documents' folder: cd/Users/Administrator/Documents mkdir "Folder 1" "Folder 2" "Folder 3" To quickly create multiple folders, create a text file with the desired folder names (as many as you want) and name it something like 'folderList.txt'. Next type this in Terminal: cat folderList.txt |xargs mkdir Or you could create folders with the same prefix by entering: mkdir "Invoices " {"Corporate", "Individual", "Pro-Bono"}

Digg! Digg This!!

Mac LC III (1994), the first Mac that I ever owned, the CD-Rom and Zip drive were added much later.

Mac LC III (1994), the first Mac that I ever owned, the CD-Rom and Zip drive were added much later.

Basic HTML

Here is an example of a very simple HTML document:

<html>
<head>
<title>Basic HTML Document</title>
</head>
<body>
Your text goes here
</body>
</html>

more HTML

Finding an Address with Google Maps

A handy script that automates Google Maps. It can be enhanced with a ‘choose from list’ dialog for frequent address searches or (as you’ll see below) you can enhance the script with a database program such as FileMaker Pro, to search for an address from a specific record

Some notes below, but first the script:

try
 set findAddress to text returned ¬
 of (display dialog "Enter address to find:" ¬
 default answer "Your address here")
 exists application "Firefox"
tell application "Firefox"
 activate
 delay 5
 open location ¬
 "http://www.google.com/maps"
 delay 10
tell application "System Events"
 keystroke findAddress
 keystroke return
end tell
end tell
on error
 display alert ¬
 "No address has been entered." message ¬
 "Enter required info and try again." as warning
end try

Remember, that for this to work correctly, GUI scripting must be enabled.

Take note of the statement ‘exists application “Firefox”‘. I use this because it will activate Firefox and helps with the timing of the delays that follow, which still may need to be adjusted for slower internet access and the speed of your processor.

Between the exists statement and activate there should be enough time for Firefox to be ready to go before the rest of the script continues.

After the Google map page opens, System Events, which requires GUI Scripting, takes over and enters the address in the address field and sends the return command to send the request for the map. It’s that simple!

This code below can be used with FileMaker Pro in place of the ‘display dialog’ text entry code at the beginning of the script.

tell application "FileMaker Pro"
  set googleSearch to (get cell "Address" of
  current record)   & " " & (get cell
  "City" of current record) & ", " &
  (get cell "State" of current record) &
  " " & (get cell "Zip Code" of
  current record)
  copy googleSearch to (cell "googleAddress" of
  current record)
end tell

Just a side note for those that are not familiar with the ‘display alert’ syntax, that I use in the error block above to see how to write this code go to Display Alert

For a script dealing with Gmail Inbox

Favorite this site:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogosphere News
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz
  • MySpace
  • YahooMyWeb
  • HackerNews
  • RSS
  • Twitter
  • E-mail this story to a friend!
  • Internetmedia
  • Webnews.de
  • Yahoo! Bookmarks

Script to Open Gmail Inbox in Firefox

Mozilla Firefox Application LogoThis is a quick and easy way to go to your Gmail Inbox. If already logged in, it goes straight to Gmail and opens your inbox. If you want instant login (even if you aren’t already logged in), you can edit this script by placing your Gmail address and password into the appropriate dialog prompts of the script below.

This script assumes that you have an email account set up through Gmail:

try
 set isLoggedIn to button returned ¬
 of (display dialog "Have you already logged in ¬
 to your email account for this session?" ¬
 buttons {"Yes", "No"} default button 2 ¬
 with icon note)
 if isLoggedIn = "No" then
  set theEmail to text returned of ¬
  (display dialog "Enter your email account ¬
  here:" default answer "yourEmail@gmail.com")
  set thePassword to text returned of ¬
  (display dialog "Enter your password here:" ¬
  default answer "" with hidden answer)
  if theEmail = "" or thePassword = "" then error
 end if
 exists application "Firefox"
 tell application "Firefox"
  activate
  delay 3
  if isLoggedIn = "No" then
   open location ¬
   "https://www.google.com/accounts/ServiceLogin?"
   delay 10
   tell application "System Events"
    keystroke theEmail
    keystroke tab
    keystroke thePassword
    keystroke return
   end tell
  end if
  open location "http://mail.google.com/mail/#inbox"
 end tell
on error
 display alert "Either your email or password ¬
 have not been entered." message "Please enter ¬
 the required info and try again." as warning
end try

Add 'http://www.scriptsforapple.com/'to Technorati Favorites

This script is pretty straightforward. The login dialog prompts gather the email address and password data and place them into the corresponding variables ‘theEmail’ and ‘thePassword’. If either the email or password is not entered, an error message is displayed and the script is aborted.

When Firefox has been launched, the ‘System Events’ application uses Apple’s GUI scripting capability to automate the entry of the text data into the text fields and sends the data to Gmail. For this to work correctly, be sure that the Enable Access for Assistive Devices check box (in your system’s Universal Access contol panel in System Preferences) is enabled (for GUI Scripting).

Contact me if you have any questions or comments at: hyperscripter@gmail.com or http://twitter.com/hyperscripter

Favorite this site:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogosphere News
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz
  • MySpace
  • YahooMyWeb
  • HackerNews
  • RSS
  • Twitter
  • E-mail this story to a friend!
  • Internetmedia
  • Webnews.de
  • Yahoo! Bookmarks

AppleScript Droplet to Convert Text to HTML

Apple AppleScript Droplet IconSometimes it’s nice to just eliminate some typing when creating html documents, especially when you write your HTML by hand (as I do). Even if it is just for the sake of setting up the initial template so you can get down to the details more efficiently.

Add to Technorati Favorites

Copy this into your Script Editor and be sure to save it as an application.

on open (dropDocument)
set dropInfo to (info for dropDocument)
set dropType to (kind of dropInfo)
if name of dropInfo contains ".html" or name of dropInfo contains ".htm" then
display alert "This is an HTML document!" message "Drop a text document on this droplet!" as warning buttons {"Abort"} default button 1 giving up after 10
else if dropType contains "document" then
tell application "AppleWorks 6"
activate
open dropDocument
set htmlData to ""
repeat with x from 1 to (count paragraphs of document 1)
set htmlData to htmlData & (paragraph x of document 1 & "")
end repeat
set docRefText to "Converted to HTML"
set htmlBody to htmlData
set htmlData to "" & return & "" & return & "--" & docRefText & return & "" & return & "" & return & htmlBody & return & "" & return & ""
make new document at front with data htmlData with properties ¬
{document kind:text document, name:"Converted to HTML.html"}
end tell
end if
end open

If you have any questions about AppleScript, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter or to subscribe, click the By Email link at the top of the page.

Favorite this site:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogosphere News
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz
  • MySpace
  • YahooMyWeb
  • HackerNews
  • RSS
  • Twitter
  • E-mail this story to a friend!
  • Internetmedia
  • Webnews.de
  • Yahoo! Bookmarks

Working with Dates and Using Math Operators

One of the more curious aspects of AppleScript that inexperienced scripters are not aware of (and even more experienced scripters often overlook) is the fact that you can use the greater than [>] operator and the less than [<] operator with dates to determine, for instance, which of two given dates occurs first in the calendar year.Apple-Mac-Motorola-Hard-Drive

This, of course, contradicts everything that we did in math class at school, but it actually is a bullt-in capability of the AppleScript language.

If you run this first script in Script Editor you can see that AppleScript can understand the use of greater than and less than. This script coerces default or entered text to date format with the time appended and returns a result reflecting which time of the entered date occurs logically before the other:

set targetDate to date string of (current date)
set targetDate to text returned of (display dialog "Enter a date:" default answer targetDate buttons {"OK"} default button 1)
set dateTime1 to date (targetDate & " 1:00:00 PM")
set dateTime2 to date (targetDate & ":" & " 7:00:00 AM")
set datetext to date string of dateTime1
set time1 to time string of dateTime1
set time2 to time string of dateTime2
set dateTimeString1 to dateTime1 as string
set dateTimeString2 to dateTime2 as string
if (dateTime1 > dateTime2) then
display dialog (datetext & return & return & time1 & " occurs after " & time2 & ".")
else if (dateTime1 < dateTime2) then
display dialog (datetext & return & return & time2 & " occurs after " & time1 & ".")
end if

120x20 thumb black

And then this example that uses just a little bit of FileMaker scripting at the beginning. It uses the ‘exists’ keyword to determine if the date can be found before proceeding and therefore is faster than if you tried this by using a repeat loop. Also, since the conditional pre-qualifies the show statement, there is no need for an error handler, although I include one here, because it is always a good practice, since there can always be some circumstance that you may have not anticipated. (FileMaker is in bold):

Freeze Window
Perform AppleScript [
tell application "FileMaker Pro"
activate
tell database 1
show every record
sort layout 0 by {field "sortDate"} in order ascending
--'sortDate' is a field defined as type date
set targetRecord to (get ID of current record)
try
set targetCalcDate to (current date)
set targetFound to true
set searchDate to date string of (targetCalcDate)
if exists (some record where searchDate is in ¬
cell "AppointmentsDate") then
--'AppointmentsDate' is a text field that
--contains the long date of each record
show (every record where searchDate is in ¬
cell "AppointmentsDate")
else
set targetFound to false
end if
if targetFound = false then display dialog ¬
"The date \"" & searchDate & ¬
"\" was not found!" with icon 0 buttons {"OK"} ¬
default button 1 giving up after 10
on error errorMsg
display dialog errorMsg
show every record
sort layout 0 by {field "sortDate"} in order ascending
set targetRecord to (get ID of current record)
end try
set targetRecord to (get ID of current record)
show every record
sort layout 0 by {field "sortDate"} in order ascending
go to record ID targetRecord
end tell
end tell
]

Designed Apple iMac teal

As always, if you have any questions or comments, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter or to subscribe, click the By Email link at the top of the page.

Favorite this site:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogosphere News
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz
  • MySpace
  • YahooMyWeb
  • HackerNews
  • RSS
  • Twitter
  • E-mail this story to a friend!
  • Internetmedia
  • Webnews.de
  • Yahoo! Bookmarks

Working with Dates in AppleScript

Apple Beveled BlueIf you have ever worked with date coercions and manipulations in AppleScript, you know how frustrating it can be, from something as simple as trying to coerce it to text so that it can be displayed in a dialog, to trying to convert it to a different date format; you have one simple thing in your syntax that keeps causing errors and you just can’t figure it out!

Here, I will try to help you through some of the most common frustrations that you will encounter. First, something that I have found very useful in my specific work, a script that verifies whether or not a date is valid in the first place. It is really pretty simple, and relies on AppleScript error messaging.

The second will deal with two aspects of coercions: 1) Converting a date in textual form to date format and then 2) Determining a future date (1 week hence, 1 month hence, etc) from the given date. This is particularly useful in databases when you want to determine a future appointment for a customer, when it is supposed to be scheduled at a regular given interval.

First, validating a given date. Keep in mind that getting the current date will also include the time of day, which may not be useful for what you want to do. Run this in the Script Editor:

set dateRecord to (current date)
set defaultDate to (date string of dateRecord)
try
set apptDate to text returned of (display dialog "Enter appointment date:" default answer defaultDate buttons {"Set"} default button {"Set"})
set datetext to apptDate as text
date apptDate --if an invalid date is entered, the next dialog is aborted and it triggers the error alert below.
display dialog datetext & " is a valid date." with icon note buttons {"OK"} default button {"OK"}
on error
set alertText to "An error has occurred!"
set messageText to quote & datetext & quote & " is an invalid date."
display alert alertText message messageText as warning buttons {"OK"} default button "OK" giving up after 15
return
end try

Now the second part, which is used here in a FileMaker database and is a bit more complex, but, once you understand how it works, can be used with other types of database formats that support AppleScript.

Like the previous script, it begins by getting the current date and coercing the result to text for further manipulations. Run this in Script Editor. The result will appear its result pane:

set AppleScript's text item delimiters to ","
set dateResult to (current date)
set comparisonDate to (date string of dateResult)
set calcBoolean to button returned of (display dialog "Determine date for next appointment?" with icon note buttons {"No", "Yes"} default button {"Yes"})
if calcBoolean = "Yes" then
set AppleScript's text item delimiters to "@"
--This next line would be used with FileMaker, otherwise something like the line of code that follows this line would compile just fine, in case you want to test this on your system:
--set prevAppointment to (get cell "History" of current record)
set prevAppointment to "Saturday, November 7, 2009 @ 8:00 am - see Joe Palmer about specs on upcoming contract"
set prevReference to (text item 1 of prevAppointment)
set dateResult to date prevReference
set scheduleInterval to (choose from list {"1 Week", "2 Weeks", "1 Month"} with prompt "Schedule interval:") as text
if scheduleInterval = "1 Week" then
set dateResult to (dateResult + 24 * 60 * 60 * 7)
else if scheduleInterval = "2 Weeks" then
set dateResult to (dateResult + 24 * 60 * 60 * 14)
else if scheduleInterval = "1 Month" then
set dateResult to (dateResult + 24 * 60 * 60 * 28)
end if
set targetDate to (date string of dateResult)
else if calcBoolean = "No" then
set targetDate to comparisonDate
end if
set defaultDate to targetDate

If you have any questions about dates and AppleScript, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter or to subscribe, click the By Email link at the top of the page.

Favorite this site:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogosphere News
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz
  • MySpace
  • YahooMyWeb
  • HackerNews
  • RSS
  • Twitter
  • E-mail this story to a friend!
  • Internetmedia
  • Webnews.de
  • Yahoo! Bookmarks

Extracting Text Using Offset and Reverse vs Text Item Delimiters

Apple Beveled BlueThere are times when you want to extract part of a text string from another for some specific purpose. There are two basic methods and each has its advantages and disadvantages. We’ll start with a combination of offset and reverse to remove the suffix from “seattleSunset.jpg”:

set jpgFile to characters of "seattleSunset.jpg"
–This gives us the characters as a list: {”s”, “e”, “a”, “t”, “t”, “l”, “e”, “S”, “u”, “n”, “s”, “e”, “t”, “.”, “j”, “p”, “g”}
set jpgFile to (reverse of jpgFile) as string
–>result: “gpj.tesnuSelttaes”

Or we can combine the statements into one:

set jpgFile to (reverse of characters of "seattleSunset.jpg") as string

–>result: “gpj.tesnuSelttaes”

Next we extract the file name without the prefix:

set periodDelimiter to offset of "." in jpgFile
set jpgFile to text (periodDelimiter + 1) thru -1 of jpgFile

–>result: “tesnuSelttaes”

set AppleScript's text item delimiters to {""} –we must reset the item delimiters to empty for this to work correctly
set jpgFile to (reverse of characters of jpgFile) as string
–After resetting the item delimiters, we use the same syntax as above.

First, remembering that what is in parentheses is performed first, jpgFile is coerced to list form and converted to the reverse order.

Then it is coerced back to a string: “seattleSunset”

If we start with set jpgFile to characters of “seattleSunset.jpeg” we still get the result: “seattleSunset”

Note that we could set the text item delimiters to “.” to get the same result:

set AppleScript's text item delimiters to "."
set jpgFile to text item 1 of "seattleSunset.jpg"

–>result: “seattleSunset”

120x20 thumb black

The problem with this method is that if we have something such as “http://www.scriptsforapple.com/” (my website), the result is: “http://www”, which is probably not the result that we want. The original version, however gives us “http://www.scriptsforapple” which is useful if we want to change “.com/” to “.org/”:

set AppleScript's text item delimiters to "."
set theURL to "http://www.scriptsforapple.com/"
set AppleScript's text item delimiters to {""}
set trimURL to (reverse of characters of theURL) as string
set periodDelimiter to offset of "." in trimURL
set trimURL to text (periodDelimiter + 1) thru -1 of trimURL
set trimURL to (reverse of characters of trimURL) as string
set theURL to trimURL & ".org/"

–>”http://www.scriptsforapple.org/”

The point here being that if you use this method, you can get the correct result for many, if not most, cases that you will encounter. That is not to say that there are not times when using text item delimiters alone will not be the right way to go depending upon the situation.


Give me your opinion on this post:
hyperscripter@gmail.com or http://twitter.com/hyperscripter.

Favorite this site:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogosphere News
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz
  • MySpace
  • YahooMyWeb
  • HackerNews
  • RSS
  • Twitter
  • E-mail this story to a friend!
  • Internetmedia
  • Webnews.de
  • Yahoo! Bookmarks
Apple-ID-Badge

Apple-Computer-Sticker-Old
Create Multiple Folders with Terminal

If you are more of a techy kind of person and are comfortable with using Terminal, here is a script you can use to easily create multiple folders:

First, for a single folder, type in: mkdir "Folder 1" --or whatever you want to name your folder, this creates a new directory, which, in effect is a new folder. To place multiple items in the 'Documents' folder: cd/Users/Administrator/Documents mkdir "Folder 1" "Folder 2" "Folder 3" To quickly create multiple folders, create a text file with the desired folder names (as many as you want) and name it something like 'folderList.txt'. Next type this in Terminal: cat folderList.txt |xargs mkdir Or you could create folders with the same prefix by entering: mkdir "Invoices " {"Corporate", "Individual", "Pro-Bono"}

Add http://www.scriptsforapple.com to Technorati Favorites

Apple-iMac-Rainbow

Digg! Digg This!!

An AppleScript to Verify a Date

Run this in the Script Editor:

set dateRecord to (current date)
set defaultDate to (date string of dateRecord)
try
set apptDate to text returned of (display dialog "Enter appointment date:" default answer defaultDate buttons {"Set"} default button {"Set"})
set datetext to apptDate as text
date apptDate --if an invalid date is entered, the next dialog is aborted and it triggers the error alert below.
display dialog datetext & " is a valid date." with icon note buttons {"OK"} default button {"OK"}
on error
set alertText to "An error has occurred!"
set messageText to quote & datetext & quote & " is an invalid date."
display alert alertText message messageText as warning buttons {"OK"} default button "OK" giving up after 15
return
end try

Airport-Extreme-Hardware