GetAttributes() public method

Gets the SftpFileAttributes of the file on the path.
is null. Client is not connected. was not found on the remote host. The method was called after the client was disposed.
public GetAttributes ( string path ) : SftpFileAttributes
path string The path to the file.
return SftpFileAttributes
Example #1
0
        public override void SetModifiedTime(SyncQueueItem i, DateTime time)
        {
            var attr = _sftpc.GetAttributes(i.CommonPath);

            attr.LastWriteTime = time;
            _sftpc.SetAttributes(i.CommonPath, attr);
        }
        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);
            }
        }
Example #3
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
                }
            }
        }
Example #4
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
            }
        }
Example #5
0
        /// <inheritdoc />
        public Task UploadFileToServerAsync(Stream stream, string basePath, string fileName, bool overwrite = false)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            if (String.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentNullException(nameof(basePath));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(fileName);
            }
            if (stream.Length == 0)
            {
                throw new ArgumentException(LNG.SftpClient_CanNotBeEmpty, nameof(stream));
            }

            return(_retryAsyncPolicy.ExecuteAsync(() =>
            {
                EnsureConnected();

                var filePath = GetFileFullPath(basePath, fileName);

                if (_sftpClient.Exists(filePath))
                {
                    // Check file size.
                    var attributes = _sftpClient.GetAttributes(filePath);
                    if (attributes.Size == stream.Length)
                    {
                        // Size is equal. Assume that files are equal. No need to upload.
                        _logger.LogWarning(String.Format(LNG.SftpClient_SameFileAlreadyExists, fileName));
                        return Task.CompletedTask;
                    }

                    if (overwrite)
                    {
                        // can overwrite, so delete file
                        _logger.LogWarning(String.Format(
                                               LNG.SftpClient_Overwriting,
                                               fileName,
                                               attributes.Size,
                                               stream.Length));
                        _sftpClient.DeleteFile(filePath);
                    }
                    else
                    {
                        // can't overwrite, it's error
                        throw new SshException(
                            String.Format(
                                LNG.SftpClient_DifferentFileAlreadyExists,
                                fileName,
                                attributes.Size,
                                stream.Length));
                    }
                }

                var sftpDirectory = Path.GetDirectoryName(filePath)
                                    ?.Replace(@"\", "/") // windows-linux compatibility
                                    ?? throw new InvalidOperationException("File path can't be mull");

                if (!_sftpClient.Exists(sftpDirectory))
                {
                    CreateDirectoryRecursively(sftpDirectory);
                }

                //TODO #3 check it, I think we don't need it here
                // we need to set position to start because temp stream can be used in another places
                stream.Position = 0;

                return Task.Factory.FromAsync(
                    _sftpClient.BeginUploadFile(
                        stream,
                        filePath,
                        false,
                        null,
                        null),
                    _sftpClient.EndUploadFile);
            }));
        }