'  
'   Rebex Sample Code License
' 
'   Copyright 2026, REBEX CR s.r.o.
'   All rights reserved.
'   https://www.rebex.net/
' 
'   Permission to use, copy, modify, and/or distribute this software for any
'   purpose with or without fee is hereby granted.
' 
'   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
'   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
'   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
'   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
'   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
'   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
'   OTHER DEALINGS IN THE SOFTWARE.
' 

Imports System
Imports System.IO
Imports System.Threading
Imports Rebex.IO
Imports Rebex.Net
Imports System.Threading.Tasks

Module GetPut

    ' This sample is a simple utility to upload/download a file to/from
    ' a FTP server using asynchronous methods of the Ftp class.
    Sub Main()
            ' set the trial license key
            Rebex.Licensing.Key = Rebex.Samples.TrialKey.Key


        Dim args() As String = Environment.GetCommandLineArgs()
        Dim method As String = Nothing

        If args.Length = 6 Then
            Select Case args(1).ToLower()
                Case "get"
                    method = "get"
                Case "put"
                    method = "put"
            End Select
        End If

        If method Is Nothing Then
            ' display syntax if wrong number of parameters or unsupported operation
            Console.WriteLine("FtpGetPutAsync - uploads or downloads a file from a FTP server")
            Console.WriteLine("Syntax: FtpGetPutAsync get|put none|explicit|implicit hostname remotepath localpath")
            Console.WriteLine("Example: FtpGetPutAsync get none test.rebex.net /pub/example/readme.txt readme.txt")
            Return
        End If

        Dim security As SslMode = CType(System.Enum.Parse(GetType(SslMode), args(2), True), SslMode)
        Dim hostname As String = args(3)
        Dim remotePath As String = args(4)
        Dim localPath As String = args(5)

        ' create Ftp object and set event handlers
        Dim ftp As New Ftp
        AddHandler ftp.TransferProgressChanged, AddressOf TransferProgressChanged
        AddHandler ftp.ResponseRead, AddressOf ResponseRead
        AddHandler ftp.CommandSent, AddressOf CommandSent

        Try
            ' set SSL to accept all server certificates...
            ' do not do this in production code, server certificates should
            ' be verified - use ftp.ValidatingCertificate event instead
            ftp.Settings.SslAcceptAllCertificates = True

            ' connect to the server
            ftp.Connect(hostname, security)


            ' ask for username and password and login
            Console.Write("Username: ")
            Dim username As String = Console.ReadLine()
            Console.Write("Password: ")
            Dim password As String = Console.ReadLine()
            ftp.Login(username, password)
            Console.WriteLine()

            ' begin asynchronous transfer
            Dim operation As Task(Of Long)
            If method = "get" Then
                operation = ftp.GetFileAsync(remotePath, localPath)
            Else
                operation = ftp.PutFileAsync(localPath, remotePath)
            End If
            operation.ContinueWith(AddressOf TaskCompleted)

            operation.Wait()

            If (operation.IsFaulted) Then
                For Each ex As Exception In operation.Exception.InnerExceptions
                    If (TypeOf ex Is FtpException) Then
                        Throw ex
                    End If
                Next

                Throw operation.Exception
            End If

            ' get the result
            Dim bytes As Long = operation.Result
            ' disconnect from the server
            ftp.Disconnect()
        Catch e As FtpException
            ' output error description to the console
            Console.WriteLine("'{0}' error: {1}", e.Status, e)
        Finally
            ' release all resources
            ftp.Dispose()
        End Try
    End Sub

    Public Sub TaskCompleted(ByVal operation As Task)
        Console.WriteLine(ControlChars.Lf + "Transfer finished.")
    End Sub

    Public Sub TransferProgressChanged(ByVal sender As Object, ByVal e As FtpTransferProgressChangedEventArgs)
        If e.TransferState = TransferProgressState.DataBlockProcessed Then
            Console.WriteLine(ControlChars.Cr + "Transferred {0} bytes...", e.BytesTransferred)
        End If
    End Sub

    Public Sub ResponseRead(ByVal sender As Object, ByVal e As FtpResponseReadEventArgs)
        Console.WriteLine(e.Response)
    End Sub

    Public Sub CommandSent(ByVal sender As Object, ByVal e As FtpCommandSentEventArgs)
        Console.WriteLine("-> " + e.Command)
    End Sub

End Module
