Logo
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
EPL Standings
 
 
Windows XP

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

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
- Microsoft ASP.NET 4 : The Web Parts Architecture
- Microsoft ASP.NET 4 : Handlers and Session State & Generic Handlers (ASHX Files)
- Microsoft ASP.NET 4 : HTTP Handlers - Handlers and IHttpHandler
- Microsoft ASP.NET 4 : HTTP Handlers - The Built-in Handlers
- Microsoft ASP.NET 4 : ASP.NET Request Handlers
- Microsoft ASP.NET 4 : HttpModules (part 2) - Seeing Active Modules & Storing State in Modules
- Microsoft ASP.NET 4 : HttpModules (part 1) - Existing Modules & Implementing a Module
- Microsoft ASP.NET 4 : The HttpApplication Class and HTTP Modules - Overriding HttpApplication
- Microsoft ASP.NET 4 : Diagnostics and Debugging - Error Pages
- Microsoft ASP.NET 4 : Diagnostics and Debugging - Debugging with Visual Studio
 
 
Most view of day
- Microsoft Exchange Server 2007 : Managing a Windows Server 2003 Cluster
- Windows Server 2012 : Installing and Managing Hyper-V in Full or Server Core Mode - Verifying Hyper-V requirements
- Designing and Configuring Unified Messaging in Exchange Server 2007 : Monitoring and Troubleshooting Unified Messaging (part 1) - Active Calls , Connectivity
- Sharepoint 2013 : Managing Security - Grant Permissions to a File or List Item
- Microsoft Visio 2010 : Linking External Data to Shapes (part 5) - Using Link Data - Preparing a Master for Link Data , Importing Data for Link Data
- SharePoint 2010 : Configuring Search Settings and the User Interface - Web Parts (part 3)
- System Center Configuration Manager 2007 : Customizing Configuration Manager Reports (part 3) - Reporting on Custom Data
- How to Troubleshoot Driver Problems (part 2) - How to Use the Driver Verifier
- Windows Small Business Server 2011 : Adding a Terminal Server - Adding a RemoteApp to Remote Web Workplace
- Microsoft SharePoint 2013 : Working with Visio Services - Customizing Visio Services solutions
Top 10
- Windows Server 2012 : DHCP,IPv6 and IPAM - Exploring DHCP (part 3) - Creating IPv4 DHCP Scopes
- Windows Server 2012 : DHCP,IPv6 and IPAM - Exploring DHCP (part 2) - Installing DHCP Server and Server Tools
- Windows Server 2012 : DHCP,IPv6 and IPAM - Exploring DHCP (part 1)
- Windows Server 2012 : DHCP,IPv6 and IPAM - Understanding the Components of an Enterprise Network
- Microsoft OneNote 2010 : Using the Research and Translate Tools (part 3) - Translating Text with the Mini Translator
- Microsoft OneNote 2010 : Using the Research and Translate Tools (part 2) - Translating a Word or Phrase with the Research Pane
- Microsoft OneNote 2010 : Using the Research and Translate Tools (part 1) - Setting Options for the Research Task Pane, Searching with the Research Task Pane
- Microsoft OneNote 2010 : Doing Research with Linked Notes (part 2) - Ending a Linked Notes Session, Viewing Linked Notes
- Microsoft OneNote 2010 : Doing Research with Linked Notes (part 1) - Beginning a Linked Notes Session
- Microsoft OneNote 2010 : Doing Research with Side Notes (part 3) - Moving Side Notes to Your Existing Notes
 
 
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
2015 Camaro