Wednesday, April 22, 2015

How to create a SFTP server on the fly for unit test?\



Usage:
NuaneSFTPServer server = new NuaneSFTPServer("username", "Passw0rd!", SftpRootFolder, 990);
server.Start();

server.Stop();



    public class NuaneSFTPServer
    {
        volatile SftpServer sFTPserver = null;
        public string UserName;
        public string Password;
        public string FtpPath;
        public int PortNumber;
        private static Thread workerThread;

        public NuaneSFTPServer(string userName, string password, string ftpPath, int portNumber)
        {
            UserName = userName;
            Password = password;
            FtpPath = ftpPath;
            PortNumber = portNumber;
            SshKey rsaKey = SshKey.Generate(SshKeyAlgorithm.RSA, 1024);
            SshKey dssKey = SshKey.Generate(SshKeyAlgorithm.DSS, 1024);

            // add keys, bindings and users
            sFTPserver = new SftpServer();
            sFTPserver.Log = Console.Out;
            sFTPserver.Keys.Add(rsaKey);
            sFTPserver.Keys.Add(dssKey);
            sFTPserver.Bindings.Add(IPAddress.Any, portNumber);
            sFTPserver.Users.Add(new SshUser(userName, password, ftpPath));
        }
        public void Start()
        {
            workerThread = new Thread(sFTPserver.Start);
            workerThread.Start();
            while (!workerThread.IsAlive) ;
        }
        public void Stop()
        {
            sFTPserver.Stop();
            workerThread.Join();
        }
    }


How to fix The thread xxx has exited with code 259 (0x103)?

When try to wait for a thread to be alive, but not call thread Start method, will get a lot of errors like this::The thread xxx has exited with code 259 (0x103)

            workerThread = new Thread(StartMethod);
//            workerThread.Start();
            while (!workerThread.IsAlive) ;

:)