Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi

I currently am running a process where files are fetch from a sever and imported into the database.
So when a user clicks the button the following code is executed
VB
Dim host As String = "ftp://*/**/**/***/****"
            Dim username As String = "*********"
            Dim password As String = "*******"
            Dim fwr As Net.FtpWebRequest = CType(Net.FtpWebRequest.Create(host), FtpWebRequest)
            fwr.Credentials = New NetworkCredential(username, password)
            fwr.KeepAlive = True
            fwr.Method = WebRequestMethods.Ftp.ListDirectory
            Dim filename As String
            Dim mydocpath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            Dim sr As StreamReader = Nothing
            Dim reqFTP As FtpWebRequest = CType(Net.FtpWebRequest.Create(host), FtpWebRequest)
            Dim ftpStream As Stream = Nothing


            Try
                sr = New StreamReader(fwr.GetResponse().GetResponseStream())
                Do Until (sr.EndOfStream())
                    filename = sr.ReadLine()
                    Dim filepath As String = (Me.Page.Server.MapPath("..\MyFolder\" + filename + ".txt"))
                    Dim outputStream As New FileStream(filepath, FileMode.Create)

                    reqFTP = DirectCast(FtpWebRequest.Create(New Uri(host + "/" + filename)), FtpWebRequest)
                    reqFTP.Credentials = New NetworkCredential(username, password)
                    reqFTP.KeepAlive = True
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
                    reqFTP.UseBinary = True

                    Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
                    ftpStream = response.GetResponseStream()
                    Dim cl As Long = response.ContentLength
                    Dim bufferSize As Integer = 2048
                    Dim readCount As Integer
                    Dim buffer As Byte() = New Byte(bufferSize - 1) {}

                    readCount = ftpStream.Read(buffer, 0, bufferSize)
                    While readCount > 0

                        outputStream.Write(buffer, 0, readCount)
                        readCount = ftpStream.Read(buffer, 0, bufferSize)

                    End While

                    ftpStream.Close()
                    outputStream.Close()
                    response.Close()

                    'Using outfile As StreamWriter = New StreamWriter(mydocpath + "\" & filename & ".txt", True)
                    'reqFTP.Method = WebRequestMethods.Ftp.DeleteFile
                    'End Using
                    'Dim sr2 As StreamReader = Nothing
                    'Try
                    '    sr2 = New StreamReader(fwr.GetResponse().GetResponseStream())
                    '    outfile = sr2.ReadToEnd()

                    'Catch ex As Exception

                    'End Try

                    'If (Not sr2 Is Nothing) Then sr2.Close() : sr2 = Nothing

                    'Delete FTP files from FTP Server
                    Dim FTPRequest As FtpWebRequest = CType(Net.WebRequest.Create(host), FtpWebRequest)
                    FTPRequest = DirectCast(FtpWebRequest.Create(New Uri(host + "/" + filename)), FtpWebRequest)
                    FTPRequest.Credentials = New System.Net.NetworkCredential(username, password)
                    FTPRequest.KeepAlive = True
                    FTPRequest.Method = WebRequestMethods.Ftp.DeleteFile
                    Dim ftpResponse As FtpWebResponse = DirectCast(FTPRequest.GetResponse(), FtpWebResponse)


                Loop

            Catch ex As Exception

            End Try

            'Try


            '    'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")

            '    reqFTP.Method = WebRequestMethods.Ftp.DeleteFile
            'Catch ex As Exception

            'End Try

            If (Not sr Is Nothing) Then sr.Close() : sr = Nothing
            If (Not fwr Is Nothing) Then fwr = Nothing
            Dim strFileSize As String = ""
            Dim di As New DirectoryInfo(Me.Page.Server.MapPath("..\MyserverFolder"))
            Dim aryFi As FileInfo() = di.GetFiles("*.txt")
            Dim fi As FileInfo


            Dim sConnStr As String = ConfigurationManager.AppSettings("myConnectionString")
            Dim cn As New System.Data.SqlClient.SqlConnection(sConnStr)
            Dim cmdInsertInto As New System.Data.SqlClient.SqlCommand("", cn)
            cmdInsertInto.CommandType = System.Data.CommandType.Text
            cmdInsertInto.CommandTimeout = 0
            Dim count As Integer = 0
            ' LblImport.Text = "Import in progress ...)"
            For Each fi In aryFi
                cn.Open()

                ' ''    strFileSize = (Math.Round(fi.Length / 1024)).ToString()
                ' ''    Console.WriteLine("File Name: {0}", fi.Name)
                ' ''    Console.WriteLine("File Full Name: {0}", fi.FullName)
                ' ''    Console.WriteLine("File Size (KB): {0}", strFileSize)
                ' ''    Console.WriteLine("File Extension: {0}", fi.Extension)
                ' ''    Console.WriteLine("Last Accessed: {0}", fi.LastAccessTime)
                ' ''    Console.WriteLine("Read Only: {0}", (fi.Attributes.ReadOnly = True).ToString)


                'Dim saveLocation As String = Page.Session.Item("saveLocation").ToString

                'If saveLocation <> "" Then




                'Opening the file

                Dim file As New FileStream(fi.FullName, FileMode.Open, FileAccess.Read)
                'Creating a strem to read the file into text
                Dim stream As New StreamReader(file)
                'Read the entire file, split it into line arrays by CRLF, and loop through it.

                '''''''''''''''''''''CANNOT TRUNCATE !!!!!!!!!!!!! <----- Else Data will be lost....
                ' ''cmdInsertInto.CommandText = "Truncate table " & ConfigurationManager.AppSettings("BankFileTempTable")
                ' ''cmdInsertInto.ExecuteNonQuery()
                Dim strReqLine As String = Replace(stream.ReadLine(), "'", "")




                Dim fileStrings() As String = fi.Name.ToString.Split(("_").ToCharArray)

                Dim FileOrderType As String = fileStrings(0) & fileStrings(1)
                Dim FileDesig As String = fileStrings(1)
                Dim FilePostingDate As String = fileStrings(2).TrimEnd((".txt").ToCharArray)
                'Dim intPos As Integer = fileStrings
                Dim sFieldsIn() As String = strReqLine.ToString.Split((",").ToCharArray)


                Try

                    While Not strReqLine Is Nothing
                        If sFieldsIn(0) = "Sales Document Type" Then

                        Else
                            '* Code to parse the line for data

                            '
                            'cmdInsertInto.CommandText = "INSERT INTO " & ConfigurationManager.AppSettings("BankFileTempTable") & " (BulkColumn) VALUES ('" & strReqLine.Replace("'", "") & "')"
                            cmdInsertInto.CommandText = "INSERT INTO " & ConfigurationManager.AppSettings("ImportTable") & " ([column1],[column2],[column3]" & _
                                                       ",[column4],[column5] ,[column6],[column7] ,[column8]" & _
                                                       ",[column9],[column10] ,[column11],[column12],[column13]" & _
                                                       ",[NameOfPersonReportingNotification],[column14],[column15]" & _
                                                       ",[column16]           ,[column17]) " & _
                                                        " VALUES ('" & fi.Name.ToString & "','" & fileStrings(3) & "','" & "','" & sFieldsIn(0) & _
                                                        "','" & sFieldsIn(1) & "','" & sFieldsIn(2) & "','" & sFieldsIn(3) & "','" & sFieldsIn(4) & "','" & sFieldsIn(5) & _
                                                        "','" & sFieldsIn(6) & "','" & sFieldsIn(7) & "','" & sFieldsIn(8) & "','" & sFieldsIn(9) & "','" & sFieldsIn(10) & _
                                                        "','" & sFieldsIn(11) & "','" & sFieldsIn(12) & "','" & sFieldsIn(13) & "','" & sFieldsIn(14) & "')"
                            cmdInsertInto.ExecuteNonQuery()
                            'If count = 10000 Then
                            '    Exit While
                            'End If
                        End If
                        strReqLine = Replace(stream.ReadLine(), "'", "")
                        If strReqLine Is Nothing Then
                        Else
                            sFieldsIn = strReqLine.ToString.Split((",").ToCharArray)
                        End If

                        count += 1
                    End While


                    stream.Close()
                    fi.MoveTo(fi.FullName.TrimEnd((".txt").ToCharArray) & ".old")
                    cn.Close()


                Catch ex As Exception
                    cmdInsertInto.CommandText = "DELETE FROM  " & ConfigurationManager.AppSettings("ImportTable") & " where [FileDescription] = '" & fi.Name.ToString & "'"
                    cmdInsertInto.ExecuteNonQuery()
                    'LblImport.Text = " Import was successful but with errors. Please review the *.error file/s in the ...\Myserverfolder and correct the exceptions. Then rename the file back to .txt and re-run the import!"
                    stream.Close()
                    fi.MoveTo(fi.FullName.TrimEnd((".txt").ToCharArray) & ".error")
                    cn.Close()
                End Try
            Next
            '  If LblImport.Text = "Import in progress ...)" Then
            'LblImport.Text = " Import was successful"
            ' End If



        End Sub



I am trying to automate this code to be executed every 24 hours

so i have added a timmer in the Global.asax page

this is my code for the timmer
VB
Dim timer As New System.Timers.Timer()
            timer.Enabled = True
            timer.Start()
            '300000 equals 5 minutes
            Dim interval As Double = 86400000
            timer.Interval = interval
            AddHandler timer.Elapsed, AddressOf OnElapsedTime





and in the sub OnElapsedTime i have the code above for the import that i use on the button

the issue i am getting is that in the global.asax i get an error on this line
Dim filepath As String = (Me.Page.Server.MapPath("..\MyFolder\" + filename + ".txt"))
i have tried Dim filepath As String = (Me.Server.MapPath("..\MyFolder\" + filename + ".txt"))
as well as Dim filepath As String = (Server.MapPath("..\MyFolder\" + filename + ".txt"))


the error is "Server operation is not available in this context."

Please could someone assist
Posted

1 solution

The larger question is: why are you trying to run a scheduled process from your web server? I would think it would be easier to run it as a separate process, with isolated code.

Anyway, the problem might be that the code is running somewhere other than a page. On my websites, I add the following module:
VB
Friend Module General

    Public Function Application() As HttpApplicationState
        Return HttpContext.Current.Application
    End Function

    Public Function Request() As HttpRequest
        Return HttpContext.Current.Request
    End Function

    Public Function Response() As HttpResponse
        Return HttpContext.Current.Response
    End Function

    Public Function Server() As HttpServerUtility
        Return HttpContext.Current.Server
    End Function

    Public Function Session() As HttpSessionState
        Return HttpContext.Current.Session
    End Function

End Module
This lets me use properties like Request or Server in situations where it is not otherwise available. Using the Friend keyword limits these function to App_Code, so they will not interfere with what is on a page. You can, of course, forget the module and just use something like HttpContext.Current.Server directly.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900