473,289 Members | 1,840 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,289 developers and data experts.

Control External Processes using Scripts - FTP

NeoPa
32,554 Expert Mod 16PB
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, 7649 views)
File Type: jpg CEPToolbar.JPG (12.9 KB, 6522 views)
Attached Files
File Type: zip ControlExternalProcesses.ZIP (1.60 MB, 536 views)
Mar 28 '16 #1
0 7346

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Filipe Bonjour | last post by:
Hi, I'm used to Unix, and shell scripting for doing a variety of admin tasks. Recently, my company started using Windows as well, and I'm looking into the possibility of rewriting some of our...
2
by: AKR | last post by:
I have to create control panel applet using C# . I have read in the net that it is not possible using C# . How can i create control panel applet using C# .
1
by: Henke | last post by:
I get a unresolved external error when linking this code. Does anybody know why? ..h-file namespace TestDll { __gc class Class1 { public: Class1();
4
by: Jimmy V | last post by:
Hi all, I am a VB programmer who is moving out of the shadows and starting to code in C#. I would like to know how to determine a control's type using a swtich statement. In VB i would do...
4
by: arunasunil | last post by:
Hi, Is there a way to track external processes launched by python on the Mac? I am using subprocess module to launch the process. Thanks Sunil
1
by: nekha | last post by:
how to send alert message to another member now iam in online using scripts
2
by: shashikantbokaro1976 | last post by:
Hi all, How to create a control panel applets using c#.
3
by: vingomail | last post by:
How can I clear the history of a browser page by using scripts or programming
1
by: kamakshi k | last post by:
is it possible to repeat one control many times using for loop? like, for(i=0;i<5;i++) { textbox1.text; } anybody know plz help me
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.