422,023 Members | 1,035 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Control External Processes using Scripts - FTP

NeoPa
Expert Mod 15k+
P: 30,549
Introduction.

A number of people have asked me if there's a way of controlling external processes from within Access. By external processes I'm talking about running scripts outside of Access. That would include BAT, CMD & PowerShell scripts, and even FTP scripts using Windows' FTP.EXE command line interface.

The power of these scripting interfaces is hard to put a limit on. FTP.EXE, in particular though, gives control of sending and receiving files across the internet to various FTP sites. Most web sites are updated using this interface. It's possible to automate that in Access.

One of my favourite uses of this type of scripting is for upgrading the current version of a project. I update front-end databases automatically when started, and also give an option to upgrade later at any time in case of corruption (Something Access databases are somewhat prone to unfortunately).

For this article though, I'll concentrate on the FTP script. If I post another one later on the upgrade process I'll link it, but the attachment includes code to do both in case anyone's interested to look and see. If you particularly want the article on the Upgrade process then please PM me. The more PMs I get, the higher up my priority list it will go ;-)

That's what I'll be explaining in this article. Another, in the same subject area, is Control External Processes using Scripts - CMD.
For those who would find it easier to see this explained and shown in a video first, please visit (Video) Controlling External Processes in Access - FTP and maybe finish reading this afterwards for a fuller explanation.


Overall Concept.

This concept relies on a table which, at its simplest, is designed as :

Table=[tblCMD]
Expand|Select|Wrap|Line Numbers
  1. Field Name  Type        PK (Compound)
  2. Template    Boolean     #1
  3. Type        String(1)   #2
  4. LineNo      Long        #3
  5. Cmd         String(255)
In certain circumstances, and I come across that during my database upgrade CMD script, it's possible for the length of the command in a single line to exceed the 255 characters allowed. So, in my attached example, I use two fields [Cmd1] & [Cmd2] in place of the single [Cmd].

One very important point to remember, when dealing with the data to be entered into this table for your scripts, is that extra power comes from the ability to have parameters in the data which are replaceable. Without that, you may as well simply use saved script files. In my example I use the percent (%) followed by two alphabetic characters to mark the points in the data where I want to insert values from the code. An example for the FTP script is %Ac, which is used for the name of the account. This is used differently for the upgrade CMD script so beware of confusing the two. Here is a list of the upgrade CMD script replacements as well as the values used for the FTP script. Replacement parameters have the same name as their related variables except % replaces str. So, strBa in the code is used to replace occurrences of %Ba in the data.

The replacement parameters for the FTP script are %FS (FTP Server), %Ac (Account Name) & %PW (Password).

The next step is to create an updated copy of the template for the particular script in the same table. This new data is recognisable because the [Template] value is False. The updates are to replace the parameters mentioned earlier with their required values. This new data (only) is then exported to the script file via a query, Once exported this data is then deleted. Export specifications are necessary in order to create the script files correctly from the data.

Once all that's done and the script file is ready we need to invoke it.


Example Data.

Table=[tblCMD]
Expand|Select|Wrap|Line Numbers
  1. Template  Type  Order  Cmd                            Template  Type  Order  Cmd
  2.   TRUE      F     10   Open %FS                         FALSE     F     10   Open FTP.AccessConsultantUK.co.uk
  3.   TRUE      F     20   %Ac                              FALSE     F     20   ACUKdemo
  4.   TRUE      F     30   %PW                              FALSE     F     30   PublicPW
  5.   TRUE      F     40   binary                           FALSE     F     40   binary
  6.   TRUE      F     50   mkdir test                       FALSE     F     50   mkdir test
  7.   TRUE      F     60   cd test                          FALSE     F     60   cd test
  8.   TRUE      F     70   send ACLogo.JPG sent.file        FALSE     F     70   send ACLogo.JPG sent.file
  9.   TRUE      F     80   dir                              FALSE     F     80   dir
  10.   TRUE      F     90   rename sent.file renamed.file    FALSE     F     90   rename sent.file renamed.file
  11.   TRUE      F    100   dir                              FALSE     F     100  dir
  12.   TRUE      F    110   get renamed.file BackAgain.JPG   FALSE     F     110  get renamed.file BackAgain.JPG
  13.   TRUE      F    120   delete renamed.file              FALSE     F     120  delete renamed.file
  14.   TRUE      F    130   rmdir test                       FALSE     F     130  rmdir test
  15.   TRUE      F    140   dir                              FALSE     F     140  dir
  16.   TRUE      F    150   bye                              FALSE     F     150  bye
NB. The data on the left is the original template data. The data on the right is the updated data and that's what's exported to create the actual script file.

This script is mainly to illustrate some of the commands available within FTP.EXE. The same file is moved around and renamed to demo some possibilities. To see more of what it can do for you type FTP on a CMD command line, to start FTP, then type ? for a list of available commands. Type HELP {command} to see more detail for any particular command. When done type bye to terminate the FTP session.


Code.

While some of the lines of code I show will refer to some of my own routines, this is a very small part of the code and should be very obvious what it's doing even if the code isn't shown. So, I'll show and explain the main code and include the whole database in the attachment so any other routines may be explored if desired. My code can always be reused if required. The only thing I claim is copyright. Others can use and change the code freely.

I'll start by explaining that MultiReplace() is one of my functions and that it simply extends the VBA.Replace() function by allowing multiple pairs of from and to replacements. I don't use this in the SQL though, as you'll see from the clumsy multi-use of the Replace() function calls in lines #16 through #19. This is where the parameters are replaced. To see the effect of this put a breakpoint on line #41 and print the value of strSQL at that point in the code.

I've included the code for SetStrings() below, but it's basically used (here) for getting the folder that we're running the project from.
  • Lines #10 & #11 set the names of the files to use.
  • Lines #42 & #43 clear up any data leftover previously then add the new data using the SQL just prepared.
  • Lines #44 through #49 delete the file first if it exists then exports our newly prepared data to the file.
    DoCmd.TransferText() fails if the file extension isn't TXT, or at least something it recognises as text. So, we have to create the file with that name and then rename it.
  • Lines #50 & #51 rename the file safely.
  • Line #52 clears the new data from [tblCMD].
  • Lines #53 through #58 handle prompting the user.
  • Lines #59 through #64 execute the FTP script file using the START command of CMD.EXE. It also uses the procedure ShellWait(), which can be found at ShellWait() Function. This is obviously included in the attachment too.
    For help on CMD.EXE type HELP CMD on a CMD command line. For help using START type START /? on a CMD command line (Please ignore where it says that the "title" is an optional parameter. It isn't. Getting past that one wasted a number of hours for me).
    The use of &&PAUSE at the end of the line is purely for demo purposes. It allows the operator to see the log of what's happened before hitting any key on the keyboard when the window will close and return to the Access project.
  • NB. Line #60 uses single-quotes (') to represent double-quotes (") within a VBA string. These are amended to the (correct) double-quotes in line #62 though. Part of the same code.

Expand|Select|Wrap|Line Numbers
  1. 'TestFTP() creates and runs the script file to test FTP.
  2. Public Function TestFTP() As Boolean
  3.     Dim strAccount As String, strFTPServer As String, strFile As String
  4.     Dim strTemp As String, strSQL As String, strMsg As String, strCmd As String
  5.     Dim dbVar As DAO.Database
  6.  
  7.     On Error GoTo ErrorHandler
  8.     strMode = SwitchMode(strType:="Process")
  9.     Call SetStrings
  10.     strFile = strFo & "\SCRIPT.FTP"
  11.     strTemp = strFo & "\SCRIPTFTP.Txt"
  12.     'Before we go any further, and regardless of whether or not we run the
  13.     '  script, let's clear away any existing copy of SCRIPTFTP.Txt.
  14.     '  It's checked again immediately prior to being created.
  15.     If Exist(strTemp) Then Call KillFile(strTemp)
  16.     strCmd = "Replace(Nz([~C],''),'%FS','%sFS')"
  17.     strCmd = Replace("Replace(%C,'%Ac','%sAc')", "%C", strCmd)
  18.     strCmd = Replace("Replace(%C,'%PW','%sPW')", "%C", strCmd)
  19.     strCmd = MultiReplace(strCmd, "%sFS", conFTPServer _
  20.                                 , "%sAc", conFTPAccount _
  21.                                 , "%sPW", Scramble(conFTPPW))
  22.     strSQL = "INSERT INTO [tblCMD]%L" _
  23.            & "      ( [Template]%L" _
  24.            & "      , [Type]%L" _
  25.            & "      , [Order]%L" _
  26.            & "      , [Cmd1]%L" _
  27.            & "      , [Cmd2])%L" _
  28.            & "SELECT  False AS [Template]%L" _
  29.            & "      , [Type]%L" _
  30.            & "      , [Order]%L" _
  31.            & "      , [C1] AS [Cmd1]%L" _
  32.            & "      , Null AS [Cmd2]%L" _
  33.            & "FROM    (SELECT [Type]%L" _
  34.            & "              , [Order]%L" _
  35.            & "              , %C1 AS [C1]%L" _
  36.            & "         FROM   [tblCMD]%L" _
  37.            & "         WHERE  ([Template])%L" _
  38.            & "           AND  ([Type]='F')) AS [qC]"
  39.     strSQL = MultiReplace(strSQL, "%C1", Replace(strCmd, "~C", "Cmd1") _
  40.                                 , "%L", vbNewLine)
  41.     Set dbVar = CurrentDb()
  42.     Call ClearTable(strTable:="tblCMD", strWhere:=conClearCMD)
  43.     Call dbVar.Execute(Query:=strSQL, Options:=dbFailOnError)
  44.     If Exist(strTemp) Then Call KillFile(strTemp)
  45.     Call DoCmd.TransferText(TransferType:=acExportDelim, _
  46.                             SpecificationName:="FTP Spec", _
  47.                             TableName:="qryFTP", _
  48.                             FileName:=strTemp, _
  49.                             HasFieldNames:=False)
  50.     If Exist(strFile) Then Call KillFile(strFile)
  51.     Name strTemp As strFile
  52.     Call ClearTable(strTable:="tblCMD", strWhere:=conClearCMD)
  53.     strMsg = Replace("Testing FTP script.%L%L" _
  54.                    & "This process should be very quick (<10 seconds).%L" _
  55.                    , "%L", vbNewLine)
  56.     Call MsgBox(Prompt:=strMsg, _
  57.                 Buttons:=vbInformation Or vbOKOnly, _
  58.                 TITLE:=CurrentProject.NAME)
  59.     strTemp = MultiReplace("CMD.EXE /T:1E /C " _
  60.                          & "Start 'FTP Test' /D '%F' /MAX /WAIT /B " _
  61.                          & "FTP.EXE -s:SCRIPT.FTP&&PAUSE" _
  62.                          , "'", """" _
  63.                          , "%F", strFo)
  64.     Call ShellWait(strCommand:=strTemp, intWinStyle:=vbMaximizedFocus)
  65.     If Exist(strFile) Then Call KillFile(strFile)
  66.     Call SwitchMode(strType:=strMode)
  67.     TestFTP = True
  68.     Exit Function
  69.  
  70. ErrorHandler:
  71.     If Exist(strFile) Then Call KillFile(strFile)
  72.     If Exist(strTemp) Then Call KillFile(strTemp)
  73.     Call ClearTable(strTable:="tblCMD", strWhere:=conClearCMD)
  74.     strMsg = MultiReplace("Error (%N) :%L%D%L%L" & _
  75.                           "Unable to complete FTP Test", _
  76.                           "%N", Err, _
  77.                           "%D", Err.DESCRIPTION, _
  78.                           "%L", vbNewLine)
  79.     Call MsgBox(Prompt:=strMsg, Buttons:=vbCritical Or vbOKOnly, TITLE:=strOr)
  80.     Call SwitchMode(strType:=strMode)
  81. End Function
Expand|Select|Wrap|Line Numbers
  1. 'SetStrings() prepares the global string variables strA, strB, strF & strO.
  2. Public Sub SetStrings()
  3.     If strAc = "" Then
  4.         With CurrentProject
  5.             strAc = BareFolder(SysCmd(acSysCmdAccessDir)) & "\MSAccess.Exe"
  6.             strOr = .NAME
  7.             strFo = Left(.Path, 1)
  8.             If strFo >= "A" And strFo <= "Z" And strFo <> Left(CurDir, 1) Then _
  9.                 Call ChDrive(Drive:=strFo)
  10.             strFo = BareFolder(.Path)
  11.             If BareFolder(CurDir) <> strFo Then Call ChDir(Path:=strFo)
  12.         End With
  13.     End If
  14. End Sub

Conclusion.

There are few limits to what you can control from within Access. I include an attachment with this that can be extracted to any folder and run. The attachment uses an Add-Ins toolbar to give access to the items to test. It may immediately upgrade you the first time you run. Don't worry. The upgraded version is exactly the same except with a higher version number stored internally. Use the Add-In toolbar to test the FTP process. This should work for you exactly as it is until the end of June 2016. If you want to use it after that point simply provide an FTP server and credentials in the modRelease module. See the picture in the Overall Concept section above for the lines of code to change.

Attached Images
File Type: jpg CEPReplacements.jpg (72.7 KB, 4178 views)
File Type: jpg CEPToolbar.JPG (12.9 KB, 4094 views)
Attached Files
File Type: zip ControlExternalProcesses.ZIP (1.60 MB, 200 views)
Mar 28 '16 #1
Share this Article
Share on Google+