Wednesday, October 12, 2011

Selectively Close Open files in Server

A question is raised recently in Foxite Forum on how to avoid an error during backup creation if a table is left open by users.  My suggestion is to use Computer Management Console in the server itself either by logging directly onto the server unit or remote controlling it via MSTSC command:

However, that is the manual way of doing it.  A fellow foxiter named Yahia Aboudalal said he is using this command to close those files, i.e., OpenFiles.  That is great because I am not even aware that such command exists, LOL!

Anyway, this will need to know the ID of the open files so we can selectively close those.  Like in our office here, some engineers stays well beyond 5PM so I would not want to execute something that will suddenly close their files as well, won't we?  So here is a simple snippet I prepared today to test on our server.  The purpose is to selectively close only the files my app is using:

Create Cursor junkopen (xID I, xuser c(10), xsystem c(10), xfiles c(100))

Local oShell As wscript.Shell, lcTempFile
lcTempFile = Addbs(Getenv("TMP"))+Sys(3)+".txt"
oShell = Createobject("WScript.Shell")

* create a CSV list of open files in server
oShell.Run("cmd /c openfiles /query /S < your server name >"+;
      "/U administrator /FO CSV /NH > "+m.lcTempFile,2,.T.)

* Clean it up, remove those warnings above the list

* add records to our cursor
Append From (m.lcTempFile) Type Csv

* Clean it up
Select xfiles, xID From junkopen Where ;
      INLIST(Upper(Justext(xfiles)),"DBF","CDX","APP","FPT") ;
      AND !Empty(Justext(xfiles)) Into Cursor junkopen

* Start closing remaining files on the list
      Wait Window "Attempting to close "+;
            ALLTRIM(junkopen.xfiles) Nowait
      oShell.Run("CMD /C OPENFILES /DISCONNECT /S "+;
            "< your server name > /ID "+Transform(junkopen.xID),2,.T.)

Messagebox("Target Open Files has been closed!")

* Perform your backup routine

And as usual if I believe this will benefit others, then I post it here in my blog than inside the forum so it won't be lost easily.

No comments:

Post a Comment