Results 1 to 8 of 8

Thread: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

  1. #1
    Lively Member
    Join Date
    Dec 11
    Posts
    75

    Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    My code posted below. The routine gets a list of files from a set of directories, loops though and connect to an ftp server moving the documents after each transfer. However, if the connection drops (for example) the code still moves all the files as though the code had completed successfully. Any advise greatfully received. Theworrying part is if I set my after process decision to delete then potentially on an exception documents might be deleted even if not processed correctly.

    Code:
    Me.Timer1.Enabled = False
    
            Try
    
                'Set the ftp variables from the application configuration file
                Dim strftpSourceDirectory As String
                strftpSourceDirectory = System.Configuration.ConfigurationManager.AppSettings("ftpSourceDirectory")
    
                Dim strftpUserName As String
                strftpUserName = System.Configuration.ConfigurationManager.AppSettings("ftpUserName")
    
                Dim strftpPassword As String
                strftpPassword = System.Configuration.ConfigurationManager.AppSettings("ftpPassword")
    
                Dim strftpTargetDirectory As String
                strftpTargetDirectory = System.Configuration.ConfigurationManager.AppSettings("ftpTargetDirectory")
    
                Dim strAfterProcessDecision As String
                strAfterProcessDecision = System.Configuration.ConfigurationManager.AppSettings("AfterUploadDecision")
    
                Dim strProcessedDirectory As String
                strProcessedDirectory = System.Configuration.ConfigurationManager.AppSettings("ProcessedDirectory")
    
                Dim intProcessingStartTime As Integer
                intProcessingStartTime = System.Configuration.ConfigurationManager.AppSettings("ProcessingStartTime")
    
                Dim intProcessingEndTime As Integer
                intProcessingEndTime = System.Configuration.ConfigurationManager.AppSettings("ProcessingEndTime")
    
                Dim intTime As Integer
                intTime = TimeOfDay.Hour
    
                'Check if processing time is valid
                If intTime >= intProcessingStartTime And intTime <= intProcessingEndTime Then
    
                    ' Inumerate list of documents contained within and below the source location
                    Dim dir As New IO.DirectoryInfo(strftpSourceDirectory)
                    Dim files() As IO.FileInfo = dir.GetFiles("*.*", IO.SearchOption.AllDirectories)
    
                    Dim searchResults As String() = Directory.GetFiles(strftpSourceDirectory, "*.*", SearchOption.AllDirectories)
                    Dim dt As New DataTable
                    dt.Columns.Add("RootDrive", GetType(String))
                    dt.Columns.Add("SourceFolder", GetType(String))
                    dt.Columns.Add("UserFolder", GetType(String))
                    dt.Columns.Add("DocumentName", GetType(String))
                    dt.Columns.Add("2", GetType(String))
                    dt.Columns.Add("3", GetType(String))
    
                    For Each filename As String In searchResults
                        Dim parts As String() = filename.Split(New Char() {"\"c})
                        dt.Rows.Add(parts)
                    Next
    
                    Dim row As DataRow
                    For Each row In dt.Rows
    
                        Dim strUploadString As String
                        strUploadString = (strftpTargetDirectory) & (row(1)) & "/" & (row(2)) & "/" & (row(3))
    
                        Dim strLocalFilePath As String
                        strLocalFilePath = (strftpTargetDirectory) & (row(1)) & "\" & (row(2)) & "\" & (row(3))
    
                        Dim strUploadFileName As String
                        strUploadFileName = (row(0) & "\" & row(1) & "\" & row(2) & "\" & row(3))
    
                        Dim credential As New NetworkCredential(strftpUserName, strftpPassword)
                        Upload(strUploadFileName, strUploadString, credential)
    
                        'Delete or move the fileafter processing
                        Dim AfterProcessDecision As String
                        AfterProcessDecision = strAfterProcessDecision
                        'MsgBox(AfterProcessDecision)
                        Select Case AfterProcessDecision
    
                            Case "move"
                                Dim FileToMove As String
                                FileToMove = (strftpSourceDirectory) & row(2) & "\" & row(3)
                                'MsgBox(FileToMove, MsgBoxStyle.Information, "FileToMove")
                                Dim FileMovePath As String
                                FileMovePath = (strProcessedDirectory) & row(3)
                                'MsgBox(FileMovePath, MsgBoxStyle.Information, "FileMovePath")
                                File.Move(FileToMove, FileMovePath)
    
                                Dim tt As StreamWriter
                                tt = New StreamWriter(Application.StartupPath & "\FtpUploaderLog.txt", True)
                                tt.WriteLine("Document Moved " & "- " & Date.Now & " - " & FileToMove)
                                tt.Flush()
                                tt.Close()
                                'Rename the document to reflect uploaded status
                                Dim MyFileName As String
                                MyFileName = row(3)
                                Dim FileName = Path.GetFileName(FileToMove)
                                Dim FileExt As String = Path.GetExtension(FileToMove)
                                Dim strFileRenamed As String
                                strFileRenamed = "Uploaded" & " " & FileName & " " & row(2) & " " & Format(Date.Now, "ddmmyy HHmmss") & FileExt
                                My.Computer.FileSystem.RenameFile(FileMovePath, strFileRenamed)
    
                            Case "delete"
                                Dim FileDeletePath As String
                                FileDeletePath = (strftpSourceDirectory) & row(2) & "\" & row(3)
                                File.Delete(FileDeletePath)
    
                                Dim tt As StreamWriter
                                tt = New StreamWriter(Application.StartupPath & "\FtpUploaderLog.txt", True)
                                tt.WriteLine("Document Deleted " & "- " & Date.Now & " - " & FileDeletePath)
                                tt.Flush()
                                tt.Close()
                            Case Else
    
                        End Select
    
                    Next
                    EventLog1.WriteEntry("Process Completed.")
                    dt.Clear()
                    dt.Dispose()
                End If
    
            Catch ex As Exception
                Dim t As StreamWriter
                t = New StreamWriter(Application.StartupPath & "\FtpUploaderLog.txt", True)
                t.WriteLine("Exception Message From Private Sub Timer1_Tick " & "- " & Date.Now & " - " & ex.Message)
                t.Flush()
                t.Close()
                EventLog1.WriteEntry("Process Not Completed. Review The Log File")
    
            End Try
    
            'Finally check the size of the log file and replace it if it is 1mb or greater in size
            Dim strPath As String = (Application.StartupPath)
            Dim strFileName As String = "FtpUploaderLog.txt"
            Dim info As New FileInfo(strPath & "\" & strFileName)
            Dim length As Long = info.Length
            Dim Count As Integer
    
            If Len(Dir$(Application.StartupPath & "\" & "*.txt")) Then Count = Count + 1
            Do While Len(Dir$) <> 0
                Count = Count + 1
            Loop
    
            Dim strNewCount As String
            strNewCount = Count + 1
    
            If length >= 1048576 Then
                My.Computer.FileSystem.RenameFile(Application.StartupPath & "\" & strFileName, "[" & Count & "]" & strFileName)
                Dim sw As StreamWriter = File.CreateText(Application.StartupPath & "\" & strFileName)
                sw.Close()
            End If
    
            Me.Timer1.Enabled = True

  2. #2
    PowerPoster
    Join Date
    Feb 12
    Location
    West Virginia
    Posts
    4,954

    Re: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    I haven't read through all of that code but if your intent is to exit the sub should an exception occur then you may be able to simply add an Exit Sub in the Catch portion of your code which would stop it from executing the code that follows

  3. #3
    Lively Member
    Join Date
    Dec 11
    Posts
    75

    Re: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    Thanks for the reply. I addedas suggested but it makes no difference. Running the code with no internet connection stillresults in all the files in the dataset getting moved and marked as processed.

  4. #4
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 12
    Posts
    5,501

    Re: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    I'm assuming Upload() is a custom sub? It would be better as a boolean function which returns information as to the success or otherwise of the transaction. Surely you have some way to monitor the ftp service sufficiently to establish that the connection exists?

  5. #5
    Lively Member
    Join Date
    Dec 11
    Posts
    75

    Re: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    This is the Upload sub routine. Yes I pickup response messages and try to exit the routine on exception.

    Code:
    Private Sub Upload(ByVal source As String, ByVal target As String, ByVal credential As NetworkCredential)
    
            Try
                Dim request As FtpWebRequest = _
                DirectCast(WebRequest.Create(target), FtpWebRequest)
                request.Proxy = Nothing
                request.Method = WebRequestMethods.Ftp.UploadFile
                request.Credentials = credential
                'request.EnableSsl = True
                Dim reader As New FileStream(source, FileMode.Open)
                Dim buffer(Convert.ToInt32(reader.Length - 1)) As Byte
                reader.Read(buffer, 0, buffer.Length)
                reader.Close()
                reader.Dispose()
                request.ContentLength = buffer.Length
                Dim stream As Stream = request.GetRequestStream
                stream.Write(buffer, 0, buffer.Length)
                stream.Flush()
                stream.Close()
                stream.Dispose()
                Dim response As FtpWebResponse = DirectCast(request.GetResponse, FtpWebResponse)
                'MessageBox.Show(response.StatusDescription, "File Uploaded")
                Dim t As StreamWriter
                t = New StreamWriter(Application.StartupPath & "\FtpUploaderLog.txt", True)
                t.WriteLine("Response Begin," & response.StatusDescription & "," & Date.Now & "," & "," & "response End")
                t.Flush()
                t.Close()
                response.Close()
    
            Catch ex As Exception
    
                Dim t As StreamWriter
                t = New StreamWriter(Application.StartupPath & "\FtpUploaderLog.txt", True)
                t.WriteLine("Exception Message From Private Sub Upload " & "- " & Date.Now & " - " & ex.Message)
                t.Flush()
                t.Close()
                Exit Sub
            End Try
    
        End Sub

  6. #6
    Lively Member
    Join Date
    Dec 11
    Posts
    75

    Re: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    Would "Exit Try" performdifferently? Rather than Exit Sub

  7. #7
    Lively Member
    Join Date
    May 10
    Posts
    103

    Re: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    As dunfiddlin suggested... Turn your "Private Sub Upload()" to a "Private Function Upload() as Boolean" and "Return True" in the Try, and "Return Flase" on the Catch. That way it will return True on success, and False on Failure.

    Code:
    Private Function Upload(ByVal source As String, ByVal target As String, ByVal credential As NetworkCredential) as Boolean
    
            Try
                Dim request As FtpWebRequest = _
                DirectCast(WebRequest.Create(target), FtpWebRequest)
                request.Proxy = Nothing
                request.Method = WebRequestMethods.Ftp.UploadFile
                request.Credentials = credential
                'request.EnableSsl = True
                Dim reader As New FileStream(source, FileMode.Open)
                Dim buffer(Convert.ToInt32(reader.Length - 1)) As Byte
                reader.Read(buffer, 0, buffer.Length)
                reader.Close()
                reader.Dispose()
                request.ContentLength = buffer.Length
                Dim stream As Stream = request.GetRequestStream
                stream.Write(buffer, 0, buffer.Length)
                stream.Flush()
                stream.Close()
                stream.Dispose()
                Dim response As FtpWebResponse = DirectCast(request.GetResponse, FtpWebResponse)
                'MessageBox.Show(response.StatusDescription, "File Uploaded")
                Dim t As StreamWriter
                t = New StreamWriter(Application.StartupPath & "\FtpUploaderLog.txt", True)
                t.WriteLine("Response Begin," & response.StatusDescription & "," & Date.Now & "," & "," & "response End")
                t.Flush()
                t.Close()
                response.Close()
    
                Return True
    
            Catch ex As Exception
    
                Dim t As StreamWriter
                t = New StreamWriter(Application.StartupPath & "\FtpUploaderLog.txt", True)
                t.WriteLine("Exception Message From Private Sub Upload " & "- " & Date.Now & " - " & ex.Message)
                t.Flush()
                t.Close()
                ''Exit Sub  ''You don't need Exit Sub here, because it will exit here anyway.
    
                Return False
          
            End Try
    
        End Function
    Then, when you call the Upload, if it returns False you can Exit Sub. That way it wont run your "AfterProcessDecision" Case Select if it is False. Or, you can do something else...

    Code:
    If Upload(strUploadFileName, strUploadString, credential) = False Then
       Exit Sub
    End If
    Last edited by MotoX646; Sep 2nd, 2012 at 06:13 AM.

  8. #8
    Lively Member
    Join Date
    Dec 11
    Posts
    75

    Re: Refining Code. Where Can I be Going Wrong? Exit Routine On Exception

    Thanks for the advice and examples. I will make those changes. As it happens I added Exit Try and it worked properly however i can see how the above construction is better set out.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •