AppleScript: Make conditions for different error number - macos

So I'm mounting different smb shares, and want to display a relevant text according to the error number, and do nothing for the numbers I have not defined.
Sort of what i'm looking for:
on error
if error_number - 5014 then
display dialog "Can't connect to" & chosen as text
else if error_number - 5016 then
display dialog "Can't connect to" & chosen as text
else if error_number then --do nothing
end if
Right now I get this popup from MacOSX :
"There was a problem connecting to the server ....."
and then then my defined error message. How do I get rid of the double popup? I prefer just getting my notification, not the one from the OS.

This is pretty easy because error provides an optional parameter number
on error errorMessage number errorNumber
if errorNumber = -36 then
display dialog "Can't connect to" & chosen as text
else if errorNumber = 5016 then
display dialog "Catch error 5016"
end if -- ignore all other errors
end try
Edit:
To mount volumes without error dialog boxes use the shell commands mount_afp or mount_smbfs.
This is an example for AFP.
It checks if the volume is already mounted. If not it creates the mount point "manually" and mounts the volume. On failure the mount point will be deleted. The SMB version works accordingly.
property server : "myServer.local"
property serverVolume : "Server"
property user : "user"
property pass : "pass"
set isMounted to serverVolume is in (do shell script "/bin/ls /Volumes") or mountAFP(user, pass, server, serverVolume)
if isMounted then
-- do something
end if
on mountAFP(user_name, pass_word, thehost, theVolume)
set theAddress to quoted form of ("afp://" & user_name & ":" & pass_word & "#" & thehost & "/" & theVolume)
set mountpoint to quoted form of ("/Volumes/" & theVolume)
try
do shell script "/bin/mkdir " & mountpoint & "; /sbin/mount_afp " & theAddress & space & mountpoint
return true
on error e
log e
do shell script "/bin/rm -r " & mountpoint
return false
end try
end mountAFP

Related

"tell application 'Mail'" won't accept string from IBOutlet in AppleScript-ObjC app

I'm working on an AppleScript-ObjC application that generates an email message in Mail. My UI has three IBOutlets (two text fields and a pop-up menu) where users can enter text that will be filled into the email. I can save the values from those outlets into variables, but when I try to use those variables inside my tell application "Mail" statement, I get this error:
AppleEvents: received mach msg which wasn't complex type as expected
in getMemoryReference.
And here's what prints in the log:
(
"<NSAppleEventDescriptor: 'ctxt'>",
": ",
"Status: MyProjectName, Part No.: 12345"
)
It seems like there's a difference between ctxt (which I think is an NSString) and an AppleScript string, but I can't figure out how to convert to an AppleScript string. Please let me know how if you do.
Here's the code for the whole function:
-- IBOutlets
property theWindow : missing value
property statusMenu : missing value
property partNumberField : missing value
property projectNameField : missing value
on generateButtonClicked:sender
set projectName to projectNameField's stringValue() as text
set partNumber to partNumberField's stringValue() as text
set status to statusMenu's objectValueOfSelectedItem as text
set theSubject to (status & ": " & projectName & ", Part No.: " & partNumber) as string
log (class of theSubject) & ": " & theSubject
tell application "Mail"
try
set newMessage to make new outgoing message with properties {subject: theSubject, theContent: "", visible: true}
on error e
log e
end try
activate
end tell
end generateButtonClicked:
set newMessage to make new outgoing message ¬
with properties {subject: theSubject, theContent: "", visible: true}
theContent isn't a property of outgoing message. Change it to content.

VBScript get SNMP OID values

I'm trying to use access SNMP via VBScript to access a few OID values as it's a climate monitor which has figures for temperature, humidity and airflow. I know which OID's I need to use but cannot find any script or piece of code which effectively connects and pulls out out this information.
Has anyone got anything that fits the bill?
I tried using this code but keep getting an error: ActiveX component can't create object: 'Scripting.SNMPManager'
Set oSNMPManager = CreateObject("Scripting.SNMPManager")
oSNMPManager.Agent = "unitip"
oSNMPManager.Community = "public"
'Add Variable objects to Variables collection
Call oSNMPManager.Variables.Add( "1.3.6.1.4.1.17373.2.2.1.6.1" )
Result = oSNMPManager.Get( ErrorIndex )
WScript.Echo "Get result: " & Result
If Result = 10 Then
WScript.Echo "ErrorIndex: " & ErrorIndex
End If
'Display properties of all Variable objects
WScript.Echo "OID, Type, Value"
For Each SNMPVariable in oSNMPManager.Variables
WScript.Echo SNMPVariable.OID & ", " & SNMPVariable.Type & ", " & SNMPVariable.Value
next
'Remove all Variable objects from the Variables collection
oSNMPManager.Variables.RemoveAll
Set objSnmpManager = CreateObject( "AxNetwork.SnmpManager" )
Set objConstants = CreateObject( "AxNetwork.NwConstants" )
' A license key is required to unlock this component after the trial period has expired.
' Call 'Activate' with a valid license key as its first parameter. Second parameter determines whether to save the license key permanently
' to the registry (True, so you need to call Activate only once), or not to store the key permanently (False, so you need to call Activate
' every time the component is created). For details, see manual, chapter "Product Activation".
'
' objSnmpManager.Activate "XXXXX-XXXXX-XXXXX", False

Capturing An AppleEvent in Applescript

Ok Unity3d allows you to set your external script editor in the application preferences. So I want to use applescript to launch my own editor. This applescript has worked pretty well for me so far but I have been unable to jump to the line number.
According to Unity the "line number should be sent through a parameter in an AppleEvent. It should be of typeChar and of keyAEPosition ('kpos') The structure sent through this parameter has the following layout:"
struct TheSelectionRange
{
short unused1; // 0 (not used)
short lineNum; // line to select (<0 to specify range)
long startRange; // start of selection range (if line < 0)
long endRange; // end of selection range (if line < 0)
long unused2; // 0 (not used)
long theDate; // modification date/time
};
"lineNum should be populated with the correct line. The other fields will not be populated with anything than 0 and -1."
So how come I don't see any of this coming through my input? how do I capture this apple event?
My Script:
on run input
set element to item 1 of input
if (element is in {{}, {""}, ""}) then
return
else
tell application "System Events"
set ProcessList to name of every process
if "iTerm" is in ProcessList then
set iterm_running to true
else
set iterm_running to false
end if
log iterm_running
end tell
tell application "iTerm"
activate
if (count terminal) < 1 then
set term to (make new terminal)
else
set term to current terminal
end if
tell term
set create_session to false
try
do shell script ("/usr/local/bin/vim --servername UNITY --remote-send ''")
set create_session to false
on error errorMessage number errorNumber
set create_session to true
end try
if iterm_running then
if create_session then
launch session "Default Session"
activate current session
tell current session
set name to "Unity"
write text "/usr/local/bin/vim --servername UNITY --remote-silent \"$(echo \"/Volumes/" & input & "\" | tr : /)\""
end tell
else
do shell script ("/usr/local/bin/vim --servername UNITY --remote-silent \"$(echo \"/Volumes/" & input & "\" | tr : /)\"")
end if
else
activate current session
tell current session
set name to "Unity"
write text "/usr/local/bin/vim --servername UNITY --remote-silent \"$(echo \"/Volumes/" & input & "\" | tr : /)\""
end tell
end if
end tell
end tell
end if
return input
end run
If you handle the open event, you should see some parameters, including the line number:
on open (x,y)
display dialog x
display dialog y
-- use x and y in your own script
end open

Why doesn't this simple applescript work any more in ML mail.app (as a rule)

It works only when you right click on the mail message and choose "run rules", but not on incoming messages (without interaction).
The first dialog is shown both when incoming or running manually, but the second dialog (with the id) is only shown when running manually. Nothing is shown in console.log
Any ideas?
using terms from application "Mail"
on perform mail action with messages theMessages for rule theRule
tell application "Mail"
repeat with theMessage in theMessages
display dialog "inside"
set theId to id of theMessage
display dialog "the id is " & theId
end repeat
end tell
end perform mail action with messages
end using terms from
update: i added a try catch block around
set theId to id of theMessage
and this is the error I get:
Can't get class mssg 1 of class mbxp "Incoming POP messages" of class mact "Telenet". Invalid index. -1719
Any idea what this means? I don't get the error when applying rules manually.
Update 2: OK i found out that incoming messages don't have an ID yet. That's a problem since I want to save the email to disk:
set theEmail to (do shell script "mdfind -onlyin ~/Library/Mail \"kMDItemFSName = '" & theId & ".emlx'\"")
set archiveName to theId & "-" & (extract address from theMessage's sender) & ".emlx"
set saveLocation to "Users:wesley:Documents:Incoming:"
do shell script "cp '" & theEmail & "' '" & POSIX path of saveLocation & "';"
Is there any way around this?
As promised in my comment, here's an AppleScript that logs Mail messages' subject, id, and message id to ~/Desktop/log.txt.
using terms from application "Mail"
on perform mail action with messages theMessages for rule theRule
try
repeat with theMessage in theMessages
LogText("subject: " & (theMessage's subject as string))
LogText("id: " & (theMessage's id as string))
LogText("message id: " & (theMessage's message id as string))
LogText("")
end repeat
on error errorText number errorNumber
tell application "Mail" to display alert ("Error: " & errorNumber) message errorText
return
end try
end perform mail action with messages
end using terms from
on LogText(theText)
tell application "Finder"
set logPath to (path to the desktop as text) & "log.txt"
try
set writeText to open for access file logPath with write permission
set currentDateAsString to do shell script "date +\"%Y-%m-%d %T\""
write (currentDateAsString & " " & (theText as text) & return) to writeText starting at ((get eof writeText) + 1)
close access writeText
on error errorText number errorNumber
close access writeText
error errorText number errorNumber
end try
end tell
end LogText
I'm also running OS X 10.8.2 and Mail 6.2. As I said, I'm surprised to say this, but triggering the above AppleScript via mail rule works just as well for incoming messages as it does when selecting the menu "Apply Rules".

MessageBox if Recordset Update is Successful

In Access 2007, I have a form to add a new contact to a table:
RecSet.AddNew
RecSet![Code_Personal] = Me.txtCodePersonal.Value
RecSet![FName] = Me.TxtFName.Value
RecSet![LName] = Me.txtLName.Value
RecSet![Tel Natel] = Me.txtNatTel.Value
RecSet![Tel Home] = Me.txtHomeTel.Value
RecSet![Email] = Me.txtEmail.Value
RecSet.Update
This has worked so far, and the contact has successfully been aded. But I'm having two problems:
I want to display a messagebox to tell the user the contact was successfully added
If the contact was not successfully added because
A contact with this name already exists
A different issue
Then display a message box "Contact already exists" or "error occured" respectively.
My idea of doing this is:
If recSet.Update = true Then
MsgBox "Paolo Bernasconi was successfully added"
Else if RecSet![FName] & RecSet![LName] 'already exist in table
MsgBox "Contact already exists"
Else
MsgBox "An unknown error occured"
I know this code is wrong, and obviously doesn't work, but it's just to give you an idea of what I'm trying to achieve. Thanks for all your help in advance.
Add an error handler to your procedure.
On Error GoTo ErrorHandler
Then display the "success" notice to user immediately after updating the recordset.
RecSet.Update
MsgBox RecSet![FName] & " " & RecSet![FName] & _
" was successfully added"
If the update attempt fails, flow control passes to the ErrorHandler section.
ErrorHandler:
MsgBox "Oops!"
Undoubtedly you want something more refined than an "Oops!" message. A slick approach is to use a Select Case block to customize the response based on error number.
Determine whether the contact exists already before attempting to add it.
strCriteria = "Fname = '" & RecSet![FName] & "' AND LName = '" & _
RecSet![LName] & "'"
Debug.Print strCriteria
If DCount("*", "YourTable", strCriteria) > 0 Then
' do not attempt to add it again
MsgBox "Contact already exists"
Else
RecSet.AddNew
' and so forth
End If
Check the Debug.Print output in case I made a mistake when building strCriteria.
The intention here is to avoid the duplication error condition ... by only attempting to add a contact which doesn't exist. So that error should not happen, and any other errors will be dealt with by the error handler.

Resources