Announcement

Collapse
No announcement yet.

Please provide insight & comments...

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Please provide insight & comments...

    I hope this is posted in the correct area. The below code I wrote as my first Power Basic Application and may not fully understand how I accomplished what I did but it does what I need. The comments I would like to solicite are related to the way it appears when executed. The progarm works as designed for the backup. When run not only does the application not show up in the task bar nor give any indication that it is running, (I think that's great!) I am not sure how this was accomplished even though I did it :-). The application shows as running only in the task manager in windows. Everyday at 6pm it executes and backs up the storage drive it was designed to backup then quietly awaits the next day at 6pm to do it again. I like it and hope others may also find a use for it. It could be improved by allowing the program to figure out for itself the directory structure of the drive to be backed up then duplicate it instead of the current hard coded directory structure for backup which will cause an Error 76 bad path if the directory structure to be backed up does not match. Anyway could someone explain why it only shows up in the task manager for windows, I guess this is like a bug which is found to provide a benefit and then becomes an added feature! Here is the code:

    Code:
    '==============================================================================
    '       Created by: W.R. Suite
    ' Last Modified on: 11/15/2007
    '          Purpose: Automatic Remote Drive Backup to Local Drive
    '     Designed For: DFW Airport Board ETM
    '==============================================================================
    '   Designer Notes: Create Copy of Remote Drive/Directory and Files on Local
    '                   Once started application will monitor time past since
    '                   midnight and initiate automatic backup of remote drive at
    '                   6 pm each evening 24/7 as long as program is running in
    '                   the background and terminated by task manager.
    '
    'Operational Goals: The backup will check and create the backkup directory
    '                   structure if it does not exist on the Backup destination.
    '                   Then all files in all sub directories off the main
    '                   directory will be copied to the same on the destination
    '                   drive in the same folders mirroring the target source.
    '==============================================================================
    #COMPILE EXE
    #DIM ALL
    '====================
    ' Constants
    '====================
    %MB_ICONINFORMATION = &H00000040&
    '====================
    'Variables
    '====================================
    GLOBAL D AS STRING
    GLOBAL BD AS STRING
    GLOBAL TD AS STRING
    GLOBAL BFD() AS STRING
    GLOBAL MonthDirectory() AS STRING
    '====================================
    ' SubRoutines Area
    '==============================================================================
    SUB InitializeLocations
    '==============================================================================
    'Assigns initial values to string arrays
    'Refreshes string arrays once they are adjusted or changed
    '==============================================================================
         DIM BFD(7) AS GLOBAL STRING             :' Base Directory String Array Number of Base Directories + 1
         DIM MonthDirectory(12) AS GLOBAL STRING :' Sub Directory String Array
        '==========================================================================
        'Assign Backup Directory Strings
        '==========================================================================
        TD = "C:"          :' Target Backup Location
        BD = "E:"          :' Source Drive Location
        D = "\FY08_UTILITIES"
        '==========================
        'Base Directories
        '==========================
        BFD(0) = D & "\ELECTRIC-FY08\"
        BFD(1) = D & "\GAS-FY08\"
        BFD(2) = D & "\WATER-FY08\"
        BFD(3) = D & "\CNG-FY08\"
        BFD(4) = D & "\PROPANE-FY08\"
        BFD(5) = D & "\DFWBIO-FY08\"
        BFD(6) = D & "\REFUELING-FY08\"
        '==========================
        'Sub Directories under Base
        '==========================
        MonthDirectory(0) = "OCTOBER-FY08\"
        MonthDirectory(1) = "NOVEMBER-FY08\"
        MonthDirectory(2) = "DECEMBER-FY08\"
        MonthDirectory(3) = "JANUARY-FY08\"
        MonthDirectory(4) = "FEBRUARY-FY08\"
        MonthDirectory(5) = "MARCH-FY08\"
        MonthDirectory(6) = "APRIL-FY08\"
        MonthDirectory(7) = "MAY-FY08\"
        MonthDirectory(8) = "JUNE-FY08\"
        MonthDirectory(9) = "JULY-FY08\"
        MonthDirectory(10) = "AUGUST-FY08\"
        MonthDirectory(11) = "SEPTEMBER-FY08\"
    '==============================================================================
    END SUB
    '==============================================================================
    SUB CreateBackupStructure
    '==============================================================================
    'Creates the Exact Backup Directory Structure on the Destination Backup Drive
    '==============================================================================
        DIM DCount AS INTEGER             :' Directory String Array Identifier
        DIM SDCount AS INTEGER            :' Sub Directory String Array Identifier
        DIM AD AS STRING                  :' Active Directory
        DIM ASD AS STRING                 :' Active Sub Directory
        DIM NDir AS STRING                :' Directory Drive & Name to Create
        '==========================================================================
        'Create Main Diretory on Destination Drive
        '==========================================
        NDir = TD & D
        MKDIR(NDir)
        IF ERR>0 THEN MSGBOX("Cannot Create the Directory: " & Ndir)
        '==========================================
        'Create the Sub Directories of the Main
        '==========================================
        NDir = TD & D
        CHDIR(NDir)
        '===============================
        'True Number of Base Directories
        '===============================
        FOR DCount = 0 TO 6
        '===============================
            AD = TD & BFD(DCount)
            MKDIR(AD)
            IF ERR>0 THEN MSGBOX("Cannot Create the Directory: " & AD)
        NEXT
        '==============================================================
        'Create the Sub Directories of the Sub Directories of the Main
        '==============================================================
        'True Number of Base Directories
        '===============================
         FOR DCount = 0 TO 6
        '===============================
            AD = TD & BFD(DCount)
            CHDIR(AD)
          FOR SDCount = 0 TO 11
                ASD = MonthDirectory(SDCount)
                MKDIR(ASD)
                IF ERR>0 THEN MSGBOX("Cannot Create the Directory: " & ASD)
          NEXT
         NEXT
    '==============================================================================
    END SUB
    '==============================================================================
    SUB CheckBackupStructure                          :' OK 10/13/2007
    '==============================================================================
    'Checks the target Backup Drive to see if the Backup Directory Structure Exists
    'If the structure does not exist then Creates Exact Mirrored Backup Directory
    'Structure on the targeted Backup Destination Drive
    '==============================================================================
        DIM Checkdrive AS STRING
        '===========================================================
        'Does the main directory Exist?
        'ERR = 76 if Main Directory does not exist on target
        '===========================================================
        CheckDrive = TD & D
        CHDIR(CheckDrive)
        IF ERR>0 THEN CreateBackupStructure
    '==============================================================================
    END SUB
    '==============================================================================
    SUB Backitup
    '==============================================================================
    'This routine performs the actual backup operations at the specified time
    'TM - Minute Time extracted from System Time Clock
    'TH - Hour Time extracted from System Time Clock
    '==============================================================================
        DIM TM AS INTEGER                       :' Time in Minutes
        DIM HR AS INTEGER                       :' Time in Hours
        DIM SMSG AS STRING                      :' Successful Completion Message Holder
        DIM DCount AS INTEGER                   :' Directory String Array Identifier
        DIM SDCount AS INTEGER                  :' Sub Directory String Array Identifier
        DIM AD AS STRING                        :' Active Directory
        DIM ASD AS STRING                       :' Active Sub Directory
        '============================================
        'Variables utilized in the Backup Operations
        '============================================
        DIM FNameList(1000) AS STRING
        DIM AFCount AS INTEGER        :' Active File Count for Backup
        DIM CCount AS INTEGER         :' File Copy Counter
        DIM LDir AS STRING
        DIM LSDir AS STRING
        DIM CurrentFileName AS STRING
        DIM FSource AS STRING
        DIM FTarget AS STRING
        '==========================================================================
        'Wait for Hour to match then Minute Time to
        'Pass plus 5 Seconds then perform the backup
        '============================================
        DO UNTIL HR = 18 AND TM > 00
            HR = VAL(LEFT$(TIME$,2))
            TM = VAL(MID$(TIME$,4,2))
            SLEEP 5000
        LOOP
        '============================================================================
        'Create a list of all filenames of files in all directories below the main
        'directory of the source drive and folder. File List does NOT include Drive!
        '============================================================================
         AFCount = 0
         CCount = 0
        '===============================
        'True Number of Base Directories
        '===============================
         FOR DCount = 0 TO 6
        '===============================
             LDir = BD & BFD(DCount)
            CHDIR LDir
           FOR SDCount = 0 TO 11
            LSDir =  BD & BFD(DCount) & MonthDirectory(SDCount)
            CHDIR LSDir
            CurrentFileName = DIR$("*.pdf")
            WHILE LEN(CurrentFileName) AND AFCount < 1000
                FNameList(AFCount) = BFD(DCount) & MonthDirectory(SDCount) & CurrentFileName
                INCR AFCount
                INCR CCount
                CurrentFileName = DIR$
            WEND
          NEXT
         NEXT
        '==========================================================================
        'Utilizing the just created filepath & filenames copy all the files from
        'the source drive/directories to the Backup Destination Drive/Directories.
        'The only change being the drive designator for the copied files. BD is the
        'Base Drive or Source Drive while TD is the Target Drive or Destination.
        '==========================================================================
        FOR CCount = 0 TO (AFCount-1)
         FSource = BD & FNameList(CCount)
         FTarget = TD & FNameList(CCount)
         FILECOPY FSource, FTarget
         IF ERR>0 THEN MSGBOX("Error #: " & STR$(ERR)& " Occured!")
        NEXT
        '===============================================================================================
        'Send message indicating time of backup completion
        'then wait for user acknowledgement before exiting
        '===============================================================================================
        SMSG = "Backup was Completed at: " & TIME$ & $CRLF & " Total Files Backed Up: " & STR$(AFCount)
        MSGBOX SMSG, %MB_ICONINFORMATION, "Backup Routine"
        '===============================================================================================
    '===================================================
    END SUB
    '==============================================================================
    '   Main Code Routine
    '==============================================================================
    FUNCTION PBMAIN()
      Restart:
        InitializeLocations
        CheckBackupStructure
        Backitup
        GOTO Restart
    END FUNCTION
    '==============================================================================
    Thanks for any comments, once again if I offended anyone placing this in an inappropriate area please let me know where this kind of stuff needs to go. I see a lot of talent on this forum and would like to solicite some input from the experts. Thanks again. Wayne
    LEARNING EXPERIENCE: What you get when you didn't get what you THOUGHT you wanted!

  • #2
    Yes, this is a perfectly correct place to post your question. Welcome to the PowerBASIC community.

    Only programs with an appropriate type of main window show up in the taskbar. Yours doesn't appear to have a window until it executes the final MSGBOX.

    To get at the directory structure, you can use multiple (recursive) calls to the DIR$ function or its WIN API equivalent. There is propably some code in this forum to achieve this (try seaching for 'directory structure').

    Any more questions, feel free to ask.

    Comment


    • #3
      Code:
      'Wait for Hour to match then Minute Time to
          'Pass plus 5 Seconds then perform the backup
          '============================================
          DO UNTIL HR = 18 AND TM > 00
              HR = VAL(LEFT$(TIME$,2))
              TM = VAL(MID$(TIME$,4,2))
              SLEEP 5000
          LOOP
      Sitting in a loop like this is a terrible waste of resources; and do you really need to check every five seconds if it's 6:00 PM yet?

      TRY: Waitable Timer Object Demo June 2005

      Or, just put the program in Windows Scheduler to run once at 6:01 PM each day.

      MCM
      Michael Mattias
      Tal Systems (retired)
      Port Washington WI USA
      [email protected]
      http://www.talsystems.com

      Comment


      • #4
        Wayne
        No its not a bug, just a condition of the GUI, Windows needs a window to give a handle so it can send messages etc, as there is no window in your program it treats it like a service. This can be very useful in many ways, running a program without the user seeing it or doing preprocessing before actually creating a window ie checking if another copy already running, license rights, backing up critical data before user interaction etc though in the last case or any case that might take some time MS recommends displaying a “splash” screen.
        I agree with Michael’s comments, though even at sleep 5000 the CPU usage is miniscule for that tight bit of code, personally for timed programs I use more like SLEEP 50000 (something just less than a minute).
        The biggest problem I see with the timer is that the program now needs to be automatically started for all users and many SysOps get suspicious of unknown programs that start this way. Using the AT command or Scheduler overcomes those worries. As the program should then exit after each run then at next startup you can check that the last run it actually completed, not waiting for a user response to a message box (as the user doesn’t know the program is running) or hung for some other reason and then can take an alternative action such as emailing an administrator
        John

        Comment


        • #5
          Wayne,

          While I have no use for your program, congratulations and a hearty "well-done" just for the extensive comments in the code.

          Would that we all took the time to document (explain) posted code as well as you have.

          ===========================================
          "God, please save me from your followers!"
          Bumper Sticker
          ===========================================
          It's a pretty day. I hope you enjoy it.

          Gösta

          JWAM: (Quit Smoking): http://www.SwedesDock.com/smoking
          LDN - A Miracle Drug: http://www.SwedesDock.com/LDN/

          Comment


          • #6
            Posted Code

            This was not an instance of after documentation. The code I write I always comment in this fashion whether it be in VB, PB, Pascal or C. Many times it has saved me when I had to make a change. Thanks to all for your thoughts and comments/compliments.

            Wayne
            LEARNING EXPERIENCE: What you get when you didn't get what you THOUGHT you wanted!

            Comment


            • #7
              MCM....Give the guy a break, 1st time, and still willing to post? .... I applaud that.

              You could give new-comers a bit more of a break, than those of us that have been around longer, and have become acquainted with "What you REALLY meant to say" type of typing.

              That said....

              Wayne... I wish I was as diligent as you are, cause often I find what makes perfect sense at the time I get sloppy and not comment, and later (months, years later) find myself reacquainting myself with "What the heck was I thinking when I wrote this????"
              (I am usually good at it though when I am unsure if what I am coding is doing what I think I understand as it doing though)

              A lil' heads up....I am sure that SOMEONE is going to get on you about the use of Globals, but don't worry about that...its a topic open for debate


              Welcome, and very nice 1st try by the way....I look forward to what you may contribute in the future
              Engineer's Motto: If it aint broke take it apart and fix it

              "If at 1st you don't succeed... call it version 1.0"

              "Half of Programming is coding"....."The other 90% is DEBUGGING"

              "Document my code????" .... "WHYYY??? do you think they call it CODE? "

              Comment


              • #8
                A 'break', Cliff?

                >Sitting in a loop like this is a terrible waste of resources

                True statement; and probably not terribly obvious to a 'newbie'

                > do you really need to check every five seconds if it's 6:00 PM yet?

                I could be no further along programming than...
                Code:
                10 PRINT "HELLO"
                .. and still realize that if a job runs once per day at 6:00 PM, it's really not necessary to check every five seconds. Probably an oversight which Mr. Suite appreciates having any "second set of eyes" spot for him.

                > TRY: Waitable Timer Object Demo June 2005
                > Or, just put the program in Windows Scheduler to run once at 6:01 PM each day

                Constructive suggestions if you ask me.

                Oh, that's right, you didn't ask. But Mr. Suite DID.

                MCM
                Michael Mattias
                Tal Systems (retired)
                Port Washington WI USA
                [email protected]
                http://www.talsystems.com

                Comment


                • #9
                  Program Comments

                  Not taking away from anything anyone has said or suggested, the reason I posted was to get multiple thoughts, specifically I had hoped that after reviewing other posts by Micheal that he would have some comments and/or criticism of my code. I am sure he is one of the more advanced programmer's which frequent this forum and appreciate his or for that matter anyone's time taken to post thoughts and suggestions.

                  I followed your link you posted Micheal to the code in the forum and when I get some time I will try to purge out that code and possible keep only what I need in relation to the timer. However from first look to me it was somewhat long when I could just use the SLEEP #### command. I suppose for that matter I could have written a short assembly routine for the delay as well but my goal at the time that I wrote it was to create an application which met my goals in as short as time period as I could.

                  A larger # for the SLEEP such as 50000 which someone had suggested would have made free additional resources, but since when I looked at the application running in task manager on my system it was not indicating CPU Time usage I felt comfortable with its operation.

                  In VB of course I use the MM.dll I believe it is to obtain timing resolution which goes down to 1ms instead of the normal VB timing resolution. What my thoughts were during the creation was to pass the time of 6pm and detect it without creating havoc. I guess for that matter I could have just wrote 'If HR>18 ' but I did not want the code to execute again when I restarted it after its completion.

                  Since this code is only run on a desk computer with only a single user there was no need to account for multiple user logons/offs and the only time the application would have to restart from scratch would be when the machine was re-booted. I had addressed this by placing the application in the Startup folder for XP.

                  What I really liked was that the application only showed up as running in the Task Manager. Since no one is around the computer in the 6pm time frame when the code executes there was no chance of interference, and when the user came in the next morning I wanted him to be greeted with the message that the added .pdf documents to the storage drive along with all the current stored documents were backed up to the local hard drive of the desktop machine.

                  If I wanted to expand further I suspose I could check the flags on each .pdf document to determine which ones were added since the last backup and only add those to the local drive backup, however instead I choose to fully backup ALL the files everyday which may at some time become a problem but so far has run flawlessly since November 2007.

                  Once again thanks for all the suggestions and comments, I wanted to hear them all good, bad and ugly and it will only serve to improve my future coding in PB. Sorry I rambled on for so long.

                  Take Care,
                  Wayne.
                  LEARNING EXPERIENCE: What you get when you didn't get what you THOUGHT you wanted!

                  Comment


                  • #10
                    Wayne,

                    Just wanted to second Gosta's comments and say thanks for the comments. They are a big help to "us newbies".

                    Darrell

                    Comment

                    Working...
                    X