Is it possible to automate attaching a script to a folder - automation

I have new folders added daily. Is it possible to link an existing folder action script to the new folder automatically?

They have always been hidden for some reason, but but there are attach action to and remove action from commands in the System Events scripting dictionary. The syntax also changed a bit around the time of Snow Leopard, which didn't help either. A general purpose handler for attaching folder action scripts (tested in Mojave) would be something like:
on run -- example
set theFolder to (choose folder with prompt "Choose folder to attach:" default location path to desktop)
set theScript to (choose file with prompt "Choose folder action script:" default location path to Folder Action scripts)
tell application "System Events" to set theName to name of theScript
attachAction(theFolder, theName)
end run
on attachAction(folderPath, scriptName)
(*
attach a script from "~/Library/Scripts/Folder Action Scripts" to a folder
parameters - folderPath [text or alias]: the folder to attach to
scriptName [text]: the name of the script to attach
returns [boolean]: true if successfully attached, false otherwise
*)
tell application "System Events"
try -- enable existing folder action
set folderName to name of disk item (folderPath as text)
set enabled of folder action folderName to true
on error errmess -- create new
log errmess
try
make new folder action at end of folder actions with properties {enabled:true, name:folderName, path:folderPath}
on error errmess -- oops (bad path, etc)
log errmess
return false
end try
end try
try -- enable existing folder action script
tell folder action folderName to set enabled of script scriptName to true
on error errmess -- create new
log errmess
try
tell folder action folderName to make new script at end of scripts with properties {name:scriptName}
on error errmess -- oops (bad name, etc)
log errmess
return false
end try
end try
return true
end tell
end attachAction

Related

How to suppress an OS X error dialog in applescript or how to make sure a remote share is connected and sharing before using a mount volume command

Okay so I've been a few days on this, and I've only found one similar issue. Unfortunately it wasn't resolved fully.
I have a script that checks for a network connection, checks for the remote computer, and mounts the volumes.
The script works as expected and is error handled with a try blocks but in the mountVolume() handler I get the same error dialog box that Daniel from the other post gets when the share is unavailable. e.g. external drive is unplugged from remote computer or hasn't finished connecting yet.
Once I dismiss OS X's error dialog(s), my error dialog comes up. I could just get rid of my dialog but the thing is that for every share (4 now) I've tried to mount that fails, I get a separate OS X error dialog that I have to dismiss.
If I can get the script to suppress these boxes I can use one box of my own in the script for all errors.
If I can't then I would like a way to check if the share exists on the REMOTE computer before I try to use mount volume thus circumnavigating the error all together.
Thanks any ideas would be appreciated.
Here is my code:
global userName
global userPass
global ipAddress
set ipAddress to "###.###.###.###"
set userName to short user name of (system info)
set userPass to do shell script ("security find-internet-password -a " & userName & " -s " & ipAddress & " -g")
on FileExists(theFile)
tell application "System Events"
if exists file theFile then
return true
else
return false
end if
end tell
end FileExists
on FolderExists(theFolder)
tell application "System Events"
if exists folder theFolder then
return true
else
return false
end if
end tell
end FolderExists
on doCleanUp()
if FolderExists("/Volumes/SHARENAME") then
tell application "Finder" to eject disk "SHARENAME"
end if
set checkPath to ((path to home folder as text) & "SHARENAME")
if FileExists(checkPath) then
do shell script ("rm ~/SHARENAME")
end if
end doCleanUp
on checkNet()
try
do shell script ("nc -z " & ipAddress & " 445")
return true
on error
return false
end try
end checkNet
on mountVolume()
try
mount volume "smb://" & ipAddress & "/SHARENAME"
return true
on error errText number errNum
log {errText, errNum}
return false
end try
end mountVolume
on makeAlias()
if FolderExists("/Volumes/SHARENAME") then
set checkPath to ((path to home folder as text) & "SHARENAME")
tell application "Finder"
if not (exists file checkPath) then
make new alias to disk "SHARENAME" at path to home folder
end if
end tell
end if
end makeAlias
set tryAgain to 0
set ipValid to false
set doRetry to true
doCleanUp()
repeat while doRetry
repeat 3 times
if not ipValid then
set ipValid to checkNet()
end if
end repeat
if ipValid then
set volMounted to mountVolume()
if volMounted then
set aliasCreated to makeAlias()
if aliasCreated then
return
else
set notificationMessage to "Could not create alias."
display alert "An error has occurred." message notificationMessage as critical
return
end if
else
set notificationMessage to "Could not mount remote volume."
display alert "An error has occurred." message notificationMessage as critical
return
end if
else
set retryCheck to display alert "Can't connect. Do you want to retry?" buttons {"Yes", "No"} default button 1
set doRetry to button returned of retryCheck as boolean
if not doRetry then
doCleanUp()
set notificationMessage to "Could not connect to Local Area Network."
display alert "An error has occurred." message notificationMessage as critical
end if
end if
end repeat
The error dialog is being generated outside of AppleScript, so you can’t trap it with a try statement. The only way I know of to avoid the dialog is to create the mount point and mount the volume yourself with the mount shell script instead of the mount volume command, for example:
do shell script "mount -t smbfs //169.254.0.0/SHARENAME /path/to/sharepoint“
If there is an error the try statement will still catch it, just without the external dialog.

AppleScript: Main Script reading from random folder

How do you bundle an applescript that has a main script which is reading scripts randomly from a folder?
Check out this code: http://macosxautomation.com/applescript/linktrigger/index.html.
It's doing exactly that (besides other things) and you can use the sub-routine there for the script-handling.
Here is a full script that works when you follow these steps: save it as an application and put all your scripts into the "Resources" folder of that application (as described at the webpage, "Show Package Contents"). Good Luck.
property MyUserName : ""
if MyUserName is "" then
display dialog "User Name:" default answer "" buttons {"Cancel", "Continue…"} default button 2
copy the result as list to {returnedButton, returnedText}
if returnedButton is "Cancel" then return
-- What to do when the user did not input any text?
if returnedText is "" then return -- we stop.
set MyUserName to returnedText
say "Hello," & MyUserName & "!" using "Karen"
else
display dialog "User name: " & MyUserName buttons {"Ok"} default button 1 with icon 1 giving up after 10
end if
say "For your information, please start the Amuse App everytime you log on... and I will speak to you at random times during your visit with me." using "Karen"
delay 20
try
repeat 105 times
set rnd to (random number from 1 to 105)
set rndFileName to (rnd as text) & ".scpt"
if my run_scriptfile(rndFileName) is false then -- if the script execution fails,…
error number -128 -- … stop this app
end if
end repeat
on error the error_message number the error_number
display dialog "Error: " & the error_number & ". " & the error_message buttons {"OK"} default button 1
return
end try
on run_scriptfile(this_scriptfile)
-- This handler will execute a script file
-- located in the Resources folder of this applet
try
set the script_file to path to resource this_scriptfile
return (run script script_file)
on error
return false
end try
end run_scriptfile
This is how it looks with (only) 3 of the scripts you wanna randomly execute:
Your question is clear but here's an script that loads randomly a script from a folder, if the folder contains any.
set theFolder to choose folder as string
set theFiles to do shell script "ls " & quoted form of posix path of theFolder & " | grep '.scpt$' || true"
if theFiles = "" then return
set theFile to some item of (paragraphs of theFiles)
set randomScript to load script file (theFolder & theFile)

vb.net opening custom file extension with clickonce application

My program has two different major functions.
By Default - opening the program itself with the .appref-ms (desktop shortcut) opens the program in the normal mode.
I have also created a .TRA extension. When a .TRA file is opened with my program it should open the program in a secondary mode.
I can see that my program has been registered with the .tra extension and the icons have all been changed.
If I drag a file with the .TRA extension onto the .exe file in the debugging bin it opens as-expected in this second mode. However, by simply double-clicking the .TRA file it is still opening in the default mode.
The code is set to look at all of the command lines passed for the .TRA extension:
For i = 0 To System.Environment.GetCommandLineArgs.Length
Dim _file = System.Environment.GetCommandLineArgs(i)
Dim format As String = IO.Path.GetExtension(_file)
If format = ".TRA" Then
file = System.Environment.GetCommandLineArgs(i)
openedwithext = True
Exit For
End If
Next i
What am I missing?
Is double-clicking my .TRA file not sending a command-line argument to my app as I'm thinking it does?
How else could this be performed?
Thanks in advance.
Because the .appref-ms works like a shortcut it takes the commandline arguments differently.
I solved the issued by adding the System.Deployment namespace and using the following code on the .loaded event.
'Are we launching as a click-once?
If (IsNetworkDeployed) Then
Try
Dim urifile As New Uri(AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData(0))
Dim uristring As String = urifile.ToString
If uristring.Contains(".TRA") Then
file = uristring.Substring(8) 'Substring removes the - file:///
openedwithext = True
End If
Catch ex As Exception
End Try
End If

how to open selected files through the default application of the file in VB 2010?

I have Windows application written in VB 2010.Here, user may select any file from open dialog.So, I want to open the file in corresponding application.for example, suppose user selecting docx file then i have to open the file using msword,suppose,if it is a pdf file, then i have to open with adobe reader or available pdf reader(default application).
Is this possible to do?
Shell and the Windows API CreateProcess() are for starting executable files.
If you're loading a document/file then these are handled by ShellExecute() and can be initiated in .NET using the Process.UseShellExecute property:
Private Function ShellExecute(ByVal File As String) As Boolean
Dim myProcess As New Process
myProcess.StartInfo.FileName = File
myProcess.StartInfo.UseShellExecute = True
myProcess.StartInfo.RedirectStandardOutput = False
myProcess.Start()
myProcess.Dispose()
End Function
Taken from the #VB wiki.
Try this:
now with openfiledialog
Dim OpenFileDlg as new OpenFileDialog.
OpenFileDlg.FileName = "" ' Default file name
OpenFileDlg.DefaultExt = ".xlsx" ' Default file extension
OpenFileDlg.Filter = "Excel Documents (*.XLSX)|*.XLSX"
OpenFileDlg.Multiselect = True
OpenFileDlg.RestoreDirectory = True
' Show open file dialog box
Dim result? As Boolean = OpenFileDlg.ShowDialog()
' Process open file dialog box results
for each path in OpenFileDlg.Filenames
Try
System.Diagnostics.Process.Start(Path)
Catch ex As Exception
MsgBox("Unable to load the file. Maybe it was deleted?")
End Try
If result = True Then
' Open document
Else
Exit Sub
End If
next
This will work if the file is registered with the OS. Use Try catch because it can throw errors if the file is in use.
Edit: It uses always the default application.

VB.net Save File Dialogue error - Could not find special directory 'Desktop'

I have a fairly straight forward peice of code that just tries to set the default saved directory for a standard .net save dialogue to a specific folder. If that folder doesn't exist, it sets it to the desktop.
This works fine for everyone but one user who is getting the following error:
Could not find special directory 'Desktop'
How is that even possible?
'Check if folder exists
If Not IO.Directory.Exists(strDirectory) Then
strDirectory = FileIO.SpecialDirectories.Desktop
If Not IO.Directory.Exists(strDirectory) Then
strDirectory = IO.Directory.GetCurrentDirectory
End If
End If
'Show save file dialogue.
Dim folderDlg As New Windows.Forms.FolderBrowserDialog
folderDlg.RootFolder = Environment.SpecialFolder.Desktop
folderDlg.SelectedPath = strDirectory
folderDlg.ShowNewFolderButton = True
How about:
strDirectory = _
Environment.GetFolderPath(Environment.SpecialFolder.Desktop).ToString()
I use GetFolderPath() to get "My Documents" and it works fine (I don't ever have to think about it).