Logo
programming4us
programming4us
programming4us
programming4us
Home
programming4us
XP
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Windows Phone
 
Windows XP

Visual Basic 2008 : Using FTP in the Service (part 1)

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
11/10/2011 11:30:47 AM

Creating FTP Directories

I have created an upload and download directory beneath the FTP Home Directory, which in my case is c:\inetpub\ftproot. I have assigned write privileges to the upload directory and read privileges to the download directory, and set the anonymous logons to true. Microsoft FTP Publishing Service does not support authentication over secured sockets, so we will use anonymous logons.

Adding an FTP Class

Our FTP class is very simple. It allows for uploading and downloading files, but it lacks more in-depth features, such as listing directories locally or remotely. For our purposes, though, it will be sufficient. In this section, we’ll simulate downloading and processing files from one FTP folder that can exist anywhere in the world. This could mean moving the file from its current location to another intranet or extranet location where a predefined process such as a SQL Task, Web Service, or other mechanism is in place to process the file further. This procedure works well for moving data from one data store to another, where a process specific to that data store has been created to export data to a flat file. In many cases the systems that create these files have no access to other intranet or extranet sites and thus have no ability themselves to directly or indirectly move or process this data on behalf of the remote data store. Imagine that you have a small Web store application that uses SQL Server as its back-end data store. Your shipping and receiving, purchase order information, and customer database is stored in your back-end mainframe or other secondary centralized SQL Server. If the two databases can’t communicate—whether because of security issues or network limitations—you can use an intermediate process, such as a service that sits on both subnets and has the proper authority to move the data between network segments or data stores.

We’ll use the FTP class to read data files from our download directory and store it in our locally defined folder. In this section, we will do no other processing because the service will only simulate moving data between network subnets, allowing a predefined process running on the upload directory’s subnet, or with access to that subnet, to capture that file and process it. Let’s review the FTP class, shown in Listing 1.

Listing 1. FTP class implementation.
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Threading

Public Class FTP
Public m_Error As String = Nothing
Private m_Uri As String
Private m_User As String
Private m_Pwd As String
Private m_Port As Integer
Private m_LocalFolder As String
Private m_File As String
Private m_Files() As String
Public m_Incoming As Thread
Private m_ThreadAction As Thread_Action_State

Public Sub New(ByRef threadaction As Thread_Action_State)
m_ThreadAction = threadaction
End Sub

Public Sub Start()
m_Incoming = New Thread(AddressOf DownloadFiles)
m_Incoming.Priority = ThreadPriority.Normal
m_Incoming.IsBackground = True
m_Incoming.Start()
End Sub

Public Function GetError() As String
Try
Return m_Error
Catch ex As Exception
Return ex.ToString
End Try
End Function

Private Sub DownloadFiles()
While Not m_ThreadAction.StopThread
If Not m_ThreadAction.Pause Then
Try
Dim bDownload As Boolean
bDownload = GetFile(Me.URI, Me.File, Me.User, Me.Pwd,
Me.Port, Me.LocalFolder)

If Not (bDownload) Then
Throw New Exception("Failed to Download File: " +
Me.File)
End If
Catch tab As ThreadAbortException
WriteLogEvent(My.Resources.ThreadAbortMessage + "_" +
tab.ToString + "_" + Now.ToString, THREAD_ABORT_ERROR,
EventLogEntryType.Error, My.Resources.Source)
Catch ex As Exception
WriteLogEvent(My.Resources.ThreadErrorMessage + "_" +
ex.ToString + "_" + Now.ToString, THREAD_ERROR,
EventLogEntryType.Error, My.Resources.Source)
End Try
End If

If Not m_ThreadAction.StopThread Then
Thread.Sleep(THREAD_WAIT)
End If
End While

End Sub

Private Shared Sub WriteLogEvent(ByVal pszMessage As String,
ByVal dwID As Long, ByVal iType As EventLogEntryType,
ByVal pszSource As String)
Try
Dim eLog As EventLog = New EventLog("Application")
eLog.Source = pszSource

Dim eInstance As EventInstance = New EventInstance(dwID, 0, iType)
Dim strArray() As String

ReDim strArray(1)
strArray(0) = pszMessage
eLog.WriteEvent(eInstance, strArray)

eLog.Dispose()
Catch ex As Exception
'Do not Catch here as it doesn't do any good for now
End Try
End Sub

Public Property URI() As String
Get
Return m_Uri
End Get
Set(ByVal value As String)
m_Uri = value
End Set
End Property

Public Property LocalFolder() As String
Get
Return m_LocalFolder
End Get
Set(ByVal value As String)
m_LocalFolder = value
End Set
End Property

Public Property User() As String
Get
Return m_User
End Get
Set(ByVal value As String)
m_User = value
End Set
End Property

Public Property Pwd() As String
Get
Return m_Pwd
End Get
Set(ByVal value As String)
m_Pwd = value
End Set
End Property

Public Property Port() As Integer
Get
Return m_Port
End Get
Set(ByVal value As Integer)
m_Port = value
End Set
End Property

Public Property File() As String
Get
Return m_File
End Get
Set(ByVal value As String)
m_File = value
End Set
End Property

Public Property Files() As String()
Get
Return m_Files
End Get
Set(ByVal value As String())
Array.Copy(value, m_Files, value.Length)
End Set
End Property

Public Function GetFile( _
ByVal pszUri As String, _
ByVal pszFile As String, _
ByVal pszUser As String, _
ByVal pszPWD As String, _
ByVal dwPort As Integer, _
ByVal pszLocalDir As String) _
As Boolean
Try
' Set up the request
Dim ftpURI As New Uri(pszUri + "/" + pszFile)

Dim ftpRequest As FtpWebRequest = _
CType(FtpWebRequest.Create(ftpURI),
FtpWebRequest)
'Setup the Credentials
If pszUser.ToUpper <> "ANONYMOUS" Then
ftpRequest.Credentials = New NetworkCredential(pszUser, pszPWD)
End If

'Download a file.
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile

' get the response object
Dim ftpResponse As FtpWebResponse = _
CType(ftpRequest.GetResponse, FtpWebResponse)

Dim tmpStream As Stream = Nothing
Dim tmpReader As StreamReader = Nothing
Dim tmpWriter As StreamWriter = Nothing

'Read the Stream from the Response and Save the File Locally
Try
tmpStream = ftpResponse.GetResponseStream
tmpReader = New StreamReader(tmpStream, Encoding.UTF8)
tmpWriter = New StreamWriter(pszLocalDir + "\" + pszFile,
False)
tmpWriter.Write(tmpReader.ReadToEnd)
Finally
tmpStream.Close()
tmpReader.Close()
tmpWriter.Close()
End Try

Return True
Catch ex As Exception
m_Error = ex.ToString
Return False
End Try

End Function

Public Function GetFiles( _
ByVal pszUri As String, _
ByVal pszFiles() As String, _
ByVal pszUser As String, _
ByVal pszPWD As String, _
ByVal dwPort As Integer, _
ByVal pszLocalDir As String) _
As Boolean()
Try
'Setup our Return Object
Dim bRet(pszFiles.Length - 1) As Boolean

Dim iLoop As Short

For iLoop = 0 To pszFiles.Length - 1
Try
bRet(iLoop) = GetFile( _
pszUri, _
pszFiles(iLoop), _
pszUser, _
pszPWD, _
dwPort, _
pszLocalDir _
)
Catch ex As Exception
bRet(iLoop) = False
End Try
Next

Return bRet
Catch ex As Exception
m_Error = ex.ToString
Return Nothing
End Try

End Function

Public Function SendFile( _
ByVal pszServer As String, _
ByVal pszRemoteDir As String, _
ByVal pszFile As String, _
ByVal pszUser As String, _
ByVal pszPWD As String, _
ByVal dwPort As Integer, _
ByVal pszLocalDir As String) _
As Boolean
Try
' Set up the request
Dim ftpURI As New Uri("FTP://" + pszServer + "/" + pszRemoteDir +
"/" + pszFile)

Dim ftpRequest As FtpWebRequest = _
CType(FtpWebRequest.Create(ftpURI),
FtpWebRequest)

'Setup the Credentials
ftpRequest.Credentials = New NetworkCredential(pszUser, pszPWD)

'Upload a file.
'setup options
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
ftpRequest.UseBinary = False
' ftpRequest.UsePassive = True

'Now we have to read the local file into a stream
Dim pFile As New FileInfo(pszLocalDir + pszFile)
Dim bData(pFile.Length) As Byte
Dim fStream As FileStream = pFile.OpenRead

fStream.Read(bData, 0, pFile.Length)
fStream.Close()

ftpRequest.ContentLength = bData.Length
Dim tmpStream As Stream = Nothing

'Read the Stream from the Response and Save the File Locally
Try
tmpStream = ftpRequest.GetRequestStream
tmpStream.Write(bData, 0, bData.Length)
Finally
tmpStream.Close()
End Try

'Whats the Response
Dim ftpResponse As FtpWebResponse = _
CType(ftpRequest.GetResponse,
FtpWebResponse)
Return True
Catch ex As Exception
m_Error = ex.ToString
Return False
End Try
End Function

Public Function SendFiles( _
ByVal pszServer As String, _
ByVal pszRemoteDir As String, _
ByVal pszFiles() As String, _
ByVal pszUser As String, _
ByVal pszPWD As String, _
ByVal dwPort As Integer, _
ByVal pszLocalDir As String) _
As Boolean()
Try
Dim iLoop As Short
Dim bRet(pszFiles.Length - 1) As Boolean

For iLoop = 0 To pszFiles.Length - 1
Try

bRet(iLoop) = SendFile( _
pszServer, _
pszRemoteDir, _
pszFiles(iLoop), _
pszUser, _
pszPWD, _
dwPort, _
pszLocalDir _
)
Catch ex As Exception
bRet(iLoop) = False
End Try
Next

Return bRet
Catch ex As Exception
m_Error = ex.ToString
Return Nothing
End Try
End Function

Public Sub Dispose()
Try
Return
Catch ex As Exception
m_Error = ex.ToString
Return
End Try
End Sub

Public ReadOnly Property Incoming() As Thread
Get
Return m_Incoming
End Get
End Property
End Class


The <DownloadFiles> Method

<DownloadFiles> is our thread method, started by the <Start> method. It will use the <GetFile> method to download the files that have been specified in our modService.vb file. If the file doesn’t download successfully, we will throw a new exception of System.Exception type. Our Try/Catch will catch the exception and then write an event into the Application log. If the file downloads successfully, it will be saved locally in the local folder, which is specified in the LocalFolder property.

FTP Class Properties

The FTP class has several properties that are required to make our FTP class work. These properties are outlined in Listing 2.

Listing 2. FTP class properties.
Public Property URI() As String
Get
Return m_Uri
End Get
Set(ByVal value As String)
m_Uri = value
End Set
End Property

Public Property LocalFolder() As String
Get
Return m_LocalFolder
End Get
Set(ByVal value As String)
m_LocalFolder = value
End Set
End Property
Public Property User() As String
Get
Return m_User
End Get
Set(ByVal value As String)
m_User = value
End Set
End Property

Public Property Pwd() As String
Get
Return m_Pwd
End Get
Set(ByVal value As String)
m_Pwd = value
End Set
End Property

Public Property Port() As Integer
Get
Return m_Port
End Get
Set(ByVal value As Integer)
m_Port = value
End Set
End Property

Public Property File() As String
Get
Return m_File
End Get
Set(ByVal value As String)
m_File = value
End Set
End Property


  • The Uri property represents the physical path and virtual location of the server and FTP directory where the file that we want to download resides.

  • The User property represents the user that we want to log in as. Since we are using anonymous logins, I’ll use anonymous as my user entry.

  • The LocalFolder property represents where we will store the files after downloading them. This can represent a physical local or remote location.

  • The Pwd property represents the password used to log on. Since I am using anonymous, any e-mail address will be valid here.

  • The Port property represents the port being used by the FTP service. By default this will be 21 on an FTP server, so I’ll use 21. The File property represents the name of the file that we want to look for. This is not a very flexible FTP example. We could extend it to use a wild card or use the Files property to allow you to pass in an array of file names to download.

Adding New FTP Constants

Listing 3. FTP constant declaration.
Public Const FTP_ERROR As Integer = 6000
Public Const FTP_INFO As Integer = 6001

Other -----------------
- Windows Presentation Foundation in .NET 4 : Introducing WPF - The Architecture of WPF
- Windows Presentation Foundation in .NET 4 : Introducing WPF - Resolution Independence
- Windows Presentation Foundation in .NET 4 : Introducing WPF - The Evolution of Windows Graphics & A Higher-Level API
- Silverlight and ASP.NET : WCF Services and Silverlight
- Silverlight and ASP.NET : Integrating with HTML & Animations
- Silverlight and ASP.NET : Silverlight and Layout
- Silverlight and ASP.NET : Adding Silverlight Content to a Web Page
- Silverlight and ASP.NET : XAML
- Silverlight and ASP.NET : Creating a Silverlight Application
- Microsoft ASP.NET 4 : Developing a Web Part
 
 
Top 10
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
 
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server