Exists() public method

Checks whether file or directory exists;
is null or contains only whitespace characters. Client is not connected. Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server. A SSH error where is the message from the remote host. The method was called after the client was disposed.
public Exists ( string path ) : bool
path string The path.
return bool
 public bool UploadFile(string filePath)
 {
     ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password);
     try
     {
         using (var sftp = new SftpClient(connectionInfo))
         {
             sftp.Connect();
             using (var file = File.OpenRead(filePath))
             {
                 if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY))
                 {
                     sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 }
                 sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 string filename = Path.GetFileName(filePath);
                 sftp.UploadFile(file, filename);
             }
             sftp.Disconnect();
         }
     }
     catch (Renci.SshNet.Common.SshConnectionException)
     {
         Console.WriteLine("Cannot connect to the server.");
         return false;
     }
     catch (System.Net.Sockets.SocketException)
     {
         Console.WriteLine("Unable to establish the socket.");
         return false;
     }
     catch (Renci.SshNet.Common.SshAuthenticationException)
     {
         Console.WriteLine("Authentication of SSH session failed.");
         return false;
     }
     return true;
 }
Beispiel #2
2
        private static void CreateDirectoriesRecursively(string directory, SftpClient sftp)
        {
            if (sftp.Exists(directory) == false)
            {
                // try creating one above, in case we need it:
                var directoryAbove = FlatRedBall.IO.FileManager.GetDirectory(directory, FlatRedBall.IO.RelativeType.Relative);

                CreateDirectoriesRecursively(directoryAbove, sftp);

                sftp.CreateDirectory(directory);
            }
        }
        /// <summary>
        /// Lists the files.
        /// </summary>
        /// <param name="remotePath">The remote path.</param>
        /// <param name="failRemoteNotExists">if set to <c>true</c> [fail remote not exists].</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public List<IRemoteFileInfo> ListFiles(string remotePath)
        {
            List<IRemoteFileInfo> fileList = new List<IRemoteFileInfo>();
            try
            {
                this.Log(String.Format("Connecting to Host: [{0}].", this.hostName), LogLevel.Minimal);
                using (SftpClient sftp = new SftpClient(this.hostName, this.portNumber, this.userName, this.passWord))
                {
                    sftp.Connect();
                    this.Log(String.Format("Connected to Host: [{0}].", this.hostName), LogLevel.Verbose);

                    if (!sftp.Exists(remotePath))
                    {
                        this.Log(String.Format("Remote Path Does Not Exist: [{0}].", this.hostName), LogLevel.Verbose);
                        if (this.stopOnFailure)
                            throw new Exception(String.Format("Invalid Path: [{0}]", remotePath));
                    }
                    else
                    {
                        this.Log(String.Format("Listing Files: [{0}].", remotePath), LogLevel.Minimal);
                        this.Log(String.Format("Getting Attributes: [{0}].", remotePath), LogLevel.Verbose);

                        SftpFile sftpFileInfo = sftp.Get(remotePath);
                        if (sftpFileInfo.IsDirectory)
                        {
                            this.Log(String.Format("Path is a Directory: [{0}].", remotePath), LogLevel.Verbose);
                            IEnumerable<SftpFile> dirList = sftp.ListDirectory(remotePath);
                            foreach (SftpFile sftpFile in dirList)
                                fileList.Add(this.CreateFileInfo(sftpFile));
                        }
                        else
                        {
                            this.Log(String.Format("Path is a File: [{0}].", remotePath), LogLevel.Verbose);
                            fileList.Add(this.CreateFileInfo(sftpFileInfo));
                        }
                    }
                }
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
            }
            catch (Exception ex)
            {
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
                this.ThrowException("Unable to List: ", ex);
            }
            return fileList;
        }
Beispiel #4
2
        private void Execute()
        {
            var keyPath = textBoxFile.Text;
            var host = textBoxHost.Text;
            var user = textBoxUser.Text;
            var pass = textBoxPass.Text;

            Action _execute = () =>
            {
                try
                {
                    //Read Key
                    Status("opening key");
                    FileStream file = File.OpenRead(keyPath);

                    //Connect to SFTP
                    Status("sftp connecting");
                    SftpClient sftp = new SftpClient(host, user, pass);
                    sftp.Connect();

                    //users home directory
                    string homepath = "/home/" + user + "/";
                    if (user == "root")
                    {
                        homepath = "/root/";
                    }

                    //Find authorized keys
                    string authKeys = homepath + ".ssh/authorized_keys";
                    if (!sftp.Exists(authKeys))
                    {
                        Status("creating");
                        if (!sftp.Exists(homepath + ".ssh"))
                            sftp.CreateDirectory(homepath + ".ssh");
                        sftp.Create(authKeys);
                    }

                    //Download
                    Status("downloading");
                    Stream stream = new MemoryStream();
                    sftp.DownloadFile(authKeys, stream);
                    Status("downloaded");

                    //Read
                    byte[] buffer = new byte[10240]; //No key should be this large
                    int length = file.Read(buffer, 0, buffer.Length);

                    //Validate
                    String strKey;
                    if (length < 20)
                    {
                        Status("Invalid Key (Length)");
                        return;
                    }
                    if (buffer[0] == (byte) 's' && buffer[1] == (byte) 's' && buffer[2] == (byte) 'h' &&
                        buffer[3] == (byte) '-' && buffer[4] == (byte) 'r' && buffer[5] == (byte) 's' &&
                        buffer[6] == (byte) 'a')
                    {
                        strKey = Encoding.ASCII.GetString(buffer, 0, length).Trim();
                    }
                    else
                    {
                        Status("Invalid Key (Format)");
                        return;
                    }

                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader reader = new StreamReader(stream);

                    //Check for key that might already exist
                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine().Trim();
                        if (line == strKey)
                        {
                            Status("key already exists");
                            return;
                        }
                    }

                    //Check new line
                    if (stream.Length != 0)
                    {
                        stream.Seek(0, SeekOrigin.End);
                        stream.WriteByte((byte) '\n');
                    }
                    else
                    {
                        stream.Seek(0, SeekOrigin.End);
                    }

                    //Append
                    Status("appending");
                    stream.Write(buffer, 0, length);

                    //Upload
                    Status("uploading");
                    stream.Seek(0, SeekOrigin.Begin);
                    sftp.UploadFile(stream, authKeys);
                    Status("done");

                    //Save key path
                    Settings.Default.KeyPath = textBoxFile.Text;
                    Settings.Default.Save();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            };

            Thread thread = new Thread(new ThreadStart(_execute));
            thread.Start();
        }
        private void UploadSingleFile(ISftpFileUploader fileUploaderImplementation, string fileToUpload, string destinationPath, bool overWriteExistingFiles)
        {
            System.Diagnostics.Debug.WriteLine($"Will upload {fileToUpload}");

            // check if file can be read
            var fileAvailability = _fileAvailabilityChecker.CheckFileAvailability(fileToUpload);

            if (fileAvailability.FileAvailabilityResult != FileAvailabilityResult.IsReadable)
            {
                _logger.LogError($"File '{fileAvailability.FileName}' could not be read - {fileAvailability.Description}/{fileAvailability.FileAvailabilityResult}");
                return;
            }

            // Remove any trailing forward-slashes.
            if (destinationPath.EndsWith("/"))
            {
                destinationPath = destinationPath.Substring(0, destinationPath.Length - 1);
            }

            string sftpServerDestinationFilePath = destinationPath + @"/" + Path.GetFileName(fileToUpload);

            if (_sftpClient.Exists(sftpServerDestinationFilePath) && overWriteExistingFiles == false)
            {
                string fileNotUploadedMessage = ($"'{fileToUpload}' not uploaded - already exists in destination-dir '{destinationPath}'");
                _logger.LogInformation(fileNotUploadedMessage);
            }
            else if (_sftpClient.Exists(sftpServerDestinationFilePath) && overWriteExistingFiles == true)
            {
                // Exists, overwrite if size changed or newer.
                long existingFileSize = _sftpClient.GetAttributes(sftpServerDestinationFilePath).Size;
                long localFileSize    = new FileInfo(fileToUpload).Length;
                bool isDifferentSize  = existingFileSize != localFileSize;

                DateTime existingFileTimeStamp = _sftpClient.GetLastWriteTimeUtc(sftpServerDestinationFilePath);
                DateTime localFileTimeStamp    = File.GetLastWriteTimeUtc(fileToUpload);
                bool     localFileIsNewer      = localFileTimeStamp > existingFileTimeStamp;

                if (isDifferentSize || localFileIsNewer)
                {
                    fileUploaderImplementation.PerformFileUpload(fileToUpload, sftpServerDestinationFilePath, _sftpClient, _logger);
                    string fileUploadMessage = ($"Uploaded '{fileToUpload}' into destination-dir '{destinationPath}'");
                    _logger.LogInformation(fileUploadMessage);
                }
                else
                {
                    string fileNotUploadedMessage = ($"'{fileToUpload}' not uploaded - already exists in destination-dir '{destinationPath}'");
                    _logger.LogInformation(fileNotUploadedMessage);
                }
            }
            else
            {
                // All-new file, just upload it.
                fileUploaderImplementation.PerformFileUpload(fileToUpload, sftpServerDestinationFilePath, _sftpClient, _logger);
                string fileUploadMessage = ($"Uploaded '{fileToUpload}' into destination-dir '{destinationPath}'");
                _logger.LogInformation(fileUploadMessage);
            }
        }
Beispiel #6
0
        /// <inheritdoc />
        public byte[]? DownloadFileFromServer(string basePath, string fileName)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            if (String.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentNullException(nameof(basePath));
            }

            return(_retryPolicy.Execute(() =>
            {
                EnsureConnected();

                var filePath = GetFileFullPath(basePath, fileName);

                if (!_sftpClient.Exists(filePath))
                {
                    _logger.LogWarning($"File \"{filePath}\" not found on SFTP server");
                    return null;
                }

                using (var file = _sftpClient.Open(filePath, FileMode.Open))
                {
                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        return ms.ToArray();
                    }
                }
            }));
        }
        /// <summary>
        /// Downloads the files.
        /// </summary>
        /// <param name="fileList">The file list.</param>
        /// <param name="failRemoteNotExists">if set to <c>true</c> [fail remote not exists].</param>
        /// <exception cref="System.Exception">
        /// Local File Already Exists.
        /// </exception>
        public void DownloadFiles(List<ISFTPFileInfo> fileList)
        {
            try
            {
                this.Log(String.Format("Connecting to Host: [{0}].", this.hostName), LogLevel.Minimal);

                using (SftpClient sftp = new SftpClient(this.hostName, this.portNumber, this.userName, this.passWord))
                {
                    sftp.Connect();

                    this.Log(String.Format("Connected to Host: [{0}].", this.hostName), LogLevel.Verbose);

                    // Download each file
                    foreach (SFTPFileInfo filePath in fileList)
                    {
                        if (!sftp.Exists(filePath.RemotePath))
                        {
                            this.Log(String.Format("Remote Path Does Not Exist: [{0}].", this.hostName), LogLevel.Verbose);
                            if (this.stopOnFailure)
                                throw new Exception(String.Format("Remote Path Does Not Exist: [{0}]", filePath.RemotePath));
                            else
                                continue;
                        }

                        if (Directory.Exists(filePath.LocalPath))
                            filePath.LocalPath = Path.Combine(filePath.LocalPath, filePath.RemotePath.Substring(filePath.RemotePath.LastIndexOf("/") + 1));

                        // Can we overwrite the local file
                        if (!filePath.OverwriteDestination && File.Exists(filePath.LocalPath))
                            throw new Exception("Local File Already Exists.");

                        this.Log(String.Format("Downloading File: [{0}] -> [{1}].", filePath.RemotePath, filePath.LocalPath), LogLevel.Minimal);
                        using (FileStream fileStream = File.OpenWrite(filePath.LocalPath))
                        {
                            sftp.DownloadFile(filePath.RemotePath, fileStream);
                        }
                        this.Log(String.Format("File Downloaded: [{0}]", filePath.LocalPath), LogLevel.Verbose);
                    }
                }
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
            }
            catch (Exception ex)
            {
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
                this.ThrowException("Unable to Download: ", ex);
            }
        }
        /// <summary>
        /// Uploads the files.
        /// </summary>
        /// <param name="fileList">The file list.</param>
        /// <exception cref="System.Exception">Remote File Already Exists.</exception>
        public void UploadFiles(List<ISFTPFileInfo> fileList)
        {
            try
            {
                this.Log(String.Format("Connecting to Host: [{0}].", this.hostName), LogLevel.Minimal);

                using (SftpClient sftp = new SftpClient(this.hostName, this.portNumber, this.userName, this.passWord))
                {
                    sftp.Connect();

                    this.Log(String.Format("Connected to Host: [{0}].", this.hostName), LogLevel.Verbose);

                    // Upload each file
                    foreach (SFTPFileInfo sftpFile in fileList)
                    {
                        FileInfo fileInfo = new FileInfo(sftpFile.LocalPath);
                        if (sftpFile.RemotePath.EndsWith("/"))
                            sftpFile.RemotePath = Path.Combine(sftpFile.RemotePath, fileInfo.Name).Replace(@"\", "/");

                        // if file exists can we overwrite it.
                        if (sftp.Exists(sftpFile.RemotePath))
                        {
                            if (sftpFile.OverwriteDestination)
                            {
                                this.Log(String.Format("Removing File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose);
                                sftp.Delete(sftpFile.RemotePath);
                                this.Log(String.Format("Removed File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose);
                            }
                            else
                            {
                                if (this.stopOnFailure)
                                    throw new Exception("Remote File Already Exists.");
                            }
                        }

                        using (FileStream file = File.OpenRead(sftpFile.LocalPath))
                        {
                            this.Log(String.Format("Uploading File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Minimal);
                            sftp.UploadFile(file, sftpFile.RemotePath);
                            this.Log(String.Format("Uploaded File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Verbose);
                        }
                    }
                }
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
            }
            catch (Exception ex)
            {
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
                this.ThrowException("Unable to Upload: ", ex);
            }
        }
Beispiel #9
0
 private void CreateDirectory(SftpClient client, string sourceFolderName, string destination)
 {
     var arr = sourceFolderName.Split(DeployUtil.TransferFolder.ToCharArray());
     var relativeFolder = arr.Last();
     var destinationPath = Path.Combine(destination, relativeFolder);
     if (!client.Exists(destinationPath))
     {
         client.CreateDirectory(destination);
         client.ChangeDirectory(destination);
     }
 }
Beispiel #10
0
 public override bool Exists(string cpath)
 {
     return(_sftpc.Exists(cpath));
 }
Beispiel #11
0
        private static void Main(string[] args)
        {
            string shufSharp = "ShufflySharp";

            var projs = new[] {
                                      shufSharp + @"\Libraries\CommonLibraries\",
                                      shufSharp + @"\Libraries\CommonShuffleLibrary\",
                                      shufSharp + @"\Libraries\ShuffleGameLibrary\",
                                      shufSharp + @"\Libraries\NodeLibraries\",
                                      shufSharp + @"\Servers\ServerManager\", 
                                      shufSharp + @"\Models\",
                                      shufSharp + @"\Client\",
                                      shufSharp + @"\ClientLibs\",
                                      shufSharp + @"\ServerSlammer\",
                              };
            var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\";

            foreach (var proj in projs) {
#if DEBUG
                var from = pre + proj + @"\bin\debug\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#else
                var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#endif
                var to = pre + shufSharp + @"\output\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";

                if (File.Exists(to)) tryDelete(to);
                tryCopy(from, to);
            }

            //client happens in buildsite.cs
            var depends = new Dictionary<string, Application>(); 
            depends.Add(shufSharp + @"\Servers\ServerManager\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./CommonLibraries.js",
                                                                 @"./CommonShuffleLibrary.js",
                                                                 @"./ShuffleGameLibrary.js",
                                                                 @"./Models.js",
                                                                 @"./RawDeflate.js",
                                                         })); 


            depends.Add(shufSharp + @"\Libraries\CommonShuffleLibrary\",
                        new Application(false,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                         }));
            depends.Add(shufSharp + @"\Libraries\NodeLibraries\", new Application(true, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\CommonLibraries\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ClientLibs\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ServerSlammer\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./Models.js",
                                                                 @"./ClientLibs.js",
                                                         }));
            depends.Add(shufSharp + @"\Models\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\ShuffleGameLibrary\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Client\",
                        new Application(false,
                                        new List<string> {}));

#if FTP
            string loc = ConfigurationSettings.AppSettings["web-ftpdir"];
            Console.WriteLine("connecting ftp");
            /*   Ftp webftp = new Ftp();
            webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]);
            webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]);

            Console.WriteLine("connected");

            webftp.Progress += (e, c) =>
            {
                var left = Console.CursorLeft;
                var top = Console.CursorTop;

                Console.SetCursorPosition(65, 5);
                Console.Write("|");

                for (int i = 0; i < c.Percentage / 10; i++)
                {
                    Console.Write("=");
                }
                for (int i = (int)(c.Percentage / 10); i < 10; i++)
                {
                    Console.Write("-");
                }
                Console.Write("|");

                Console.Write(c.Percentage + "  %  ");
                Console.WriteLine();
                Console.SetCursorPosition(left, top);
            };
*/
            string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"];
            string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"];
            Console.WriteLine("connecting server ftp");
            SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]);
            client.Connect();

            Console.WriteLine("server connected");

#endif

            foreach (var depend in depends) {
                var to = pre + shufSharp + @"\output\" + depend.Key.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
                var output = "";

                Application application = depend.Value;

                if (application.Node) {
                    output += "require('./mscorlib.js');";
                    output += "EventEmitter= require('events.js').EventEmitter;";
                } else {
                    //output += "require('./mscorlib.debug.js');";
                }

                foreach (var depe in application.IncludesAfter) {
                    output += string.Format("require('{0}');", depe);
                }

                var lines = new List<string>();
                lines.Add(output);
                lines.AddRange(File.ReadAllLines(to));

                //      lines.Add(application.After);

                File.WriteAllLines(to, lines);
                var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last();

#if FTP

                long length = new FileInfo(to).Length;
                /*       if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length)
                {
                    Console.WriteLine("ftp start " + length.ToString("N0"));
                    webftp.Upload(loc + name, to);
                    Console.WriteLine("ftp complete " + to);
                }
*/
                if (true || !client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
                if (true || !client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc2 + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
#endif
                if (File.Exists(@"C:\code\node\" + name) && /*new FileInfo(@"C:\code\node\" + name).Length != new FileInfo(to).Length*/ true) {
                    tryDelete(@"C:\code\node\" + name);
                    tryCopy(to, @"C:\code\node\" + name);
                }
            }

            foreach (var d in Directory.GetDirectories(pre + shufSharp + @"\ShuffleGames\")) {
                string game = d.Split('\\').Last();
                var to = pre + shufSharp + @"\output\Games\" + game;
                if (!Directory.Exists(to))

                    Directory.CreateDirectory(to);
                if (d.EndsWith("bin") || d.EndsWith("obj"))
                    continue;
                File.WriteAllText(to + @"\app.js", File.ReadAllText(d + @"\app.js"));

#if FTP

                Console.WriteLine("server ftp start ");

                var fileStream = new FileInfo(to + @"\app.js").OpenRead();
                if (!client.Exists(serverloc + string.Format("Games/{0}", game)))
                    client.CreateDirectory(serverloc + string.Format("Games/{0}", game));
                client.UploadFile(fileStream, serverloc + string.Format("Games/{0}/app.js", game), true);
                fileStream.Close();

                Console.WriteLine("server ftp complete " + to);
#endif
            }
        }
Beispiel #12
0
 public static bool DoexRemoteFolderExist(string host, string user, string password, string remotePath)
 {
     using (SftpClient client = new SftpClient(host, user, password))
     {
         client.KeepAliveInterval = TimeSpan.FromSeconds(60);
         client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
         client.OperationTimeout = TimeSpan.FromMinutes(180);
         client.Connect();
         bool r = client.Exists(remotePath);
         client.Disconnect();
         return r;
     }
 }
Beispiel #13
0
        private static void Main(string[] args)
        {
            string llo = "LampLightOnlineSharp";
            var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\..\";

            /*


            var projs = new[]
                { 
                    llo+@"\LampLightOnlineClient\",
                    llo+@"\LampLightOnlineServer\",
                };

            foreach (var proj in projs)
            {
#if DEBUG
                var from = pre + proj + @"\bin\debug\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#else
                var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#endif
                var to = pre + llo + @"\output\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
                if (File.Exists(to)) File.Delete(to);
                File.Copy(from, to);
            }
*/

            //client happens in buildsite.cs
            var depends = new Dictionary<string, Application> {
                                                                      /*{
                        llo+@"\Servers\AdminServer\", new Application(true, "new AdminServer.AdminServer();", new List<string>
                            {
                                @"./CommonLibraries.js",
                                @"./CommonServerLibraries.js",
                                @"./Models.js",
                            })
                    }*/
                                                                      {
                                                                              "MM.ChatServer", new Application(true,
                                                                                                               new List<string> {
                                                                                                                                        @"./CommonAPI.js",
                                                                                                                                        @"./ServerAPI.js",
                                                                                                                                        @"./CommonLibraries.js",
                                                                                                                                        @"./CommonServerLibraries.js",
                                                                                                                                        @"./Models.js",
                                                                                                                                })
                                                                      }, {
                                                                                 "MM.GameServer", new Application(true,
                                                                                                                  new List<string> {
                                                                                                                                           @"./CommonAPI.js",
                                                                                                                                           @"./MMServerAPI.js",
                                                                                                                                           @"./CommonLibraries.js",
                                                                                                                                           @"./CommonServerLibraries.js",
                                                                                                                                           @"./CommonClientLibraries.js",
                                                                                                                                           @"./MMServer.js",
                                                                                                                                           @"./Games/ZombieGame/ZombieGame.Common.js",
                                                                                                                                           @"./Games/ZombieGame/ZombieGame.Server.js",
                                                                                                                                           @"./Models.js",
                                                                                                                                           @"./RawDeflate.js",
                                                                                                                                   }) {}
                                                                         }, {
                                                                                    "MM.GatewayServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonAPI.js",
                                                                                                                                                 @"./ServerAPI.js",
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./MMServerAPI.js",
                                                                                                                                                 @"./MMServer.js",
                                                                                                                                                 @"./Games/ZombieGame/ZombieGame.Common.js",
                                                                                                                                                 @"./Games/ZombieGame/ZombieGame.Server.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                            }, {
                                                                                       "MM.HeadServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonAPI.js",
                                                                                                                                                 @"./ServerAPI.js",
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                               }, {
                                                                                          "SiteServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                                  },
                                                                      {"Client", new Application(false, new List<string> {})},
                                                                      {"CommonWebLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonClientLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonServerLibraries", new Application(false, new List<string> {})},
                                                                      {"MMServer", new Application(false, new List<string> {})},
                                                                      {"MMServerAPI", new Application(false, new List<string> {})},
                                                                      {"ClientAPI", new Application(false, new List<string> {})},
                                                                      {"ServerAPI", new Application(false, new List<string> {})},
                                                                      {"CommonAPI", new Application(false, new List<string> {})},
                                                              };

#if FTP
            string loc = ConfigurationSettings.AppSettings["web-ftpdir"];
            Console.WriteLine("connecting ftp");
            Ftp webftp = new Ftp();
            webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]);
            webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]);

            Console.WriteLine("connected");

            webftp.Progress += (e, c) => {
                                   var left = Console.CursorLeft;
                                   var top = Console.CursorTop;

                                   Console.SetCursorPosition(65, 5);
                                   Console.Write("|");

                                   for (int i = 0; i < c.Percentage / 10; i++) {
                                       Console.Write("=");
                                   }
                                   for (int i = (int) ( c.Percentage / 10 ); i < 10; i++) {
                                       Console.Write("-");
                                   }
                                   Console.Write("|");

                                   Console.Write(c.Percentage + "  %  ");
                                   Console.WriteLine();
                                   Console.SetCursorPosition(left, top);
                               };

            string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"];
            string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"];
            Console.WriteLine("connecting server ftp");
            SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]);
            client.Connect();

            Console.WriteLine("server connected");

#endif

            foreach (var depend in depends) {
                var to = pre + "\\" + llo + @"\output\" + depend.Key + ".js";
                var output = "";

                if (depend.Value.Node)
                    output += "require('./mscorlib.debug.js');\r\n";
                else {
                    //output += "require('./mscorlib.debug.js');";
                }

                foreach (var depe in depend.Value.IncludesAfter) {
                    output += string.Format("require('{0}');\r\n", depe);
                }

                if (depend.Value.Postpend != null) output += depend.Value.Postpend + "\r\n";
                var lines = new List<string>();
                lines.Add(output);
                lines.AddRange(File.ReadAllLines(to).After(1)); //mscorlib

                string text = lines.Aggregate("", (a, b) => a + b + "\n");
                File.WriteAllText(to, text);

                //     lines.Add(depend.Value.After); 

                var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last();
                //   File.WriteAllText(to, text);

#if FTP

                long length = new FileInfo(to).Length;
                if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length) {
                    Console.WriteLine("ftp start " + length.ToString("N0"));
                    webftp.Upload(loc + name, to);
                    Console.WriteLine("ftp complete " + to);
                }

                if (!client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
                if (!client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc2 + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
#endif
            }

            string[] games = {"ZombieGame" /*, "TowerD", "ZakGame" */};

            foreach (var depend in games) {
                var to = pre + llo + @"\output\Games\" + depend + @"\";

                string[] exts = {"Client", "Common", "Server"};

                foreach (var ext in exts) {
                    //     lines.Add(depend.Value.After); 
                    string fm = to + depend + "." + ext + ".js";

                    string text = File.ReadAllText(fm);
                    File.WriteAllText(fm, text);

#if FTP
                    Console.WriteLine("ftp start " + text.Length.ToString("N0"));
                    webftp.Upload(loc + "Games/" + depend + "/" + depend + "." + ext + ".js", fm);
                    Console.WriteLine("ftp complete " + fm);

                    Console.WriteLine("server ftp start " + text.Length.ToString("N0"));

                    var fileStream = new FileInfo(fm).OpenRead();
                    client.UploadFile(fileStream, serverloc + "Games/" + depend + "/" + depend + "." + ext + ".js", true);
                    fileStream.Close();
                    fileStream = new FileInfo(fm).OpenRead();
                    client.UploadFile(fileStream, serverloc2 + "Games/" + depend + "/" + depend + "." + ext + ".js", true);
                    fileStream.Close();

                    Console.WriteLine("server ftp complete " + fm);
#endif
                }
            }
        }
 private static void CreatSSHDir(SftpClient ssh, string file)
 {
     var newDir = Tools.Misc.GetUnixDirecoryOfFile(file);
     if (ssh.Exists(newDir)) return;
     string[] dirs = new string[newDir.ToCharArray().Count(x => x == '/')];
     dirs[0] = newDir;
     for (int i = 1; i < dirs.Count(); i++)
     {
         dirs[i] = Tools.Misc.GetUnixDirecoryOfFile(dirs[i - 1]);
     }
     for (int i = dirs.Count()-1; i >= 0; i--)
     {
         if (ssh.Exists(dirs[i])) continue;
         ssh.CreateDirectory(dirs[i]);
     }
 }