From 97269fd1601f38d34d4eed9e7c029459cfd2aa23 Mon Sep 17 00:00:00 2001 From: Timerix22 Date: Fri, 14 Jan 2022 00:04:06 +0300 Subject: [PATCH] small changes --- .editorconfig | 2 +- DTLib.csproj | 4 ++++ Experimental/Tester.cs | 26 ++++++++++++-------------- Extensions/BaseConverter.cs | 1 + Extensions/StringConverter.cs | 6 ------ Filesystem/Directory.cs | 27 ++++----------------------- Hasher.cs | 2 +- Loggers/BaseLogger.cs | 7 +++++-- Loggers/DefaultLogger.cs | 19 ++++++++++++------- Network/FSP.cs | 28 ++++++++++++++-------------- Network/Package.cs | 2 +- 11 files changed, 55 insertions(+), 69 deletions(-) diff --git a/.editorconfig b/.editorconfig index a3c3072..82ff2fa 100644 --- a/.editorconfig +++ b/.editorconfig @@ -75,7 +75,7 @@ dotnet_style_allow_statement_immediately_after_block_experimental = true #### Рекомендации по написанию кода C# #### # Предпочтения var -csharp_style_var_elsewhere = false +csharp_style_var_elsewhere = true csharp_style_var_for_built_in_types = false csharp_style_var_when_type_is_apparent = true diff --git a/DTLib.csproj b/DTLib.csproj index 50648ce..399646c 100644 --- a/DTLib.csproj +++ b/DTLib.csproj @@ -7,10 +7,14 @@ DTLib True true + False + + + diff --git a/Experimental/Tester.cs b/Experimental/Tester.cs index bf20005..b806f42 100644 --- a/Experimental/Tester.cs +++ b/Experimental/Tester.cs @@ -1,18 +1,16 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; -namespace DTLib.Experimental +namespace DTLib.Experimental; + +public static class Tester { - public static class Tester + public static void LogOperationTime(string op_name, int repeats, Action operation) { - public static void LogOperationTime(string op_name, int repeats, Action operation) - { - Stopwatch clock = new(); - clock.Start(); - for (int i = 0; i < repeats; i++) - operation(); - clock.Stop(); - PublicLog.LogNoTime("c",$"operation {op_name} took {clock.ElapsedTicks / repeats} ticks\n"); - } + Stopwatch clock = new(); + clock.Start(); + for (int i = 0; i < repeats; i++) + operation(); + clock.Stop(); + LogNoTime("c",$"operation {op_name} took {clock.ElapsedTicks / repeats} ticks"); } -} +} \ No newline at end of file diff --git a/Extensions/BaseConverter.cs b/Extensions/BaseConverter.cs index e668068..fe8a7a5 100644 --- a/Extensions/BaseConverter.cs +++ b/Extensions/BaseConverter.cs @@ -1,6 +1,7 @@ global using System; global using System.Collections; global using System.Collections.Generic; +global using System.Linq; global using System.Text; global using System.Threading.Tasks; global using DTLib.Extensions; diff --git a/Extensions/StringConverter.cs b/Extensions/StringConverter.cs index dfa7028..4d12329 100644 --- a/Extensions/StringConverter.cs +++ b/Extensions/StringConverter.cs @@ -144,10 +144,4 @@ public static class StringConverter if (max * length != s.Length) parts.Add(s.Substring(max * length, s.Length - max * length)); return parts; } - - public static string AddZeroes(this T number, int length) - { - string str = number.ToString(); - return new string('0', str.Length - length) + str; - } } diff --git a/Filesystem/Directory.cs b/Filesystem/Directory.cs index 44a832b..c8e092b 100644 --- a/Filesystem/Directory.cs +++ b/Filesystem/Directory.cs @@ -10,7 +10,7 @@ public static class Directory if (!Directory.Exists(dir)) { // проверяет существование папки, в которой нужно создать dir - if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\')))) + if (dir.Contains('\\') && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\')))) Create(dir.Remove(dir.LastIndexOf('\\'))); System.IO.Directory.CreateDirectory(dir); } @@ -22,15 +22,9 @@ public static class Directory var subdirs = new List(); List files = GetAllFiles(source_dir, ref subdirs); for (int i = 0; i < subdirs.Count; i++) - { Create(subdirs[i].Replace(source_dir, new_dir)); - } for (int i = 0; i < files.Count; i++) - { - string f = files[i].Replace(source_dir, new_dir); - File.Copy(files[i], f, owerwrite); - //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" }); - } + File.Copy(files[i], files[i].Replace(source_dir, new_dir), owerwrite); } // копирует все файлы и папки и выдаёт список конфликтующих файлов @@ -41,16 +35,13 @@ public static class Directory List files = GetAllFiles(source_dir, ref subdirs); Create(new_dir); for (int i = 0; i < subdirs.Count; i++) - { Create(subdirs[i].Replace(source_dir, new_dir)); - } for (int i = 0; i < files.Count; i++) { string newfile = files[i].Replace(source_dir, new_dir); if (File.Exists(newfile)) conflicts.Add(newfile); File.Copy(files[i], newfile, owerwrite); - //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" }); } } @@ -63,11 +54,11 @@ public static class Directory File.Delete(files[i]); for (int i = subdirs.Count - 1; i >= 0; i--) { - PublicLog.Log($"deleting {subdirs[i]}\n"); + PublicLog.Log($"deleting {subdirs[i]}"); if (Directory.Exists(subdirs[i])) System.IO.Directory.Delete(subdirs[i], true); } - PublicLog.Log($"deleting {dir}\n"); + PublicLog.Log($"deleting {dir}"); if (Directory.Exists(dir)) System.IO.Directory.Delete(dir, true); } @@ -82,16 +73,10 @@ public static class Directory var all_files = new List(); string[] cur_files = Directory.GetFiles(dir); for (int i = 0; i < cur_files.Length; i++) - { all_files.Add(cur_files[i]); - //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" }); - } string[] cur_subdirs = Directory.GetDirectories(dir); for (int i = 0; i < cur_subdirs.Length; i++) - { - //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" }); all_files.AddRange(GetAllFiles(cur_subdirs[i])); - } return all_files; } @@ -101,15 +86,11 @@ public static class Directory var all_files = new List(); string[] cur_files = Directory.GetFiles(dir); for (int i = 0; i < cur_files.Length; i++) - { all_files.Add(cur_files[i]); - //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" }); - } string[] cur_subdirs = Directory.GetDirectories(dir); for (int i = 0; i < cur_subdirs.Length; i++) { all_subdirs.Add(cur_subdirs[i]); - //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" }); all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs)); } return all_files; diff --git a/Hasher.cs b/Hasher.cs index ba622aa..b3442bd 100644 --- a/Hasher.cs +++ b/Hasher.cs @@ -50,7 +50,7 @@ public class Hasher //var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second; byte[] hash = xxh32.ComputeHash(fileStream); //var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second; - //PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n"); + //PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}"); fileStream.Close(); return hash; } diff --git a/Loggers/BaseLogger.cs b/Loggers/BaseLogger.cs index 3085e45..8104629 100644 --- a/Loggers/BaseLogger.cs +++ b/Loggers/BaseLogger.cs @@ -3,11 +3,14 @@ public abstract class BaseLogger { public string Logfile { get; init; } - public BaseLogger(string logfile) => Logfile = logfile; - public BaseLogger(string dir, string programName) => Logfile = $"{dir}\\{programName}_{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_'); + public BaseLogger() { } + public BaseLogger(string logfile) => (Logfile, WriteToFile) = (logfile,true); + public BaseLogger(string dir, string programName) + : this($"{dir}\\{programName}_{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_')) { } public bool IsEnabled { get; private set; } = false; + public bool WriteToFile { get; private set; } = false; protected readonly object statelocker = new(); public void Disable() { lock (statelocker) IsEnabled = false; } public void Enable() { lock (statelocker) IsEnabled = true; } diff --git a/Loggers/DefaultLogger.cs b/Loggers/DefaultLogger.cs index 903671c..a6639d7 100644 --- a/Loggers/DefaultLogger.cs +++ b/Loggers/DefaultLogger.cs @@ -3,6 +3,7 @@ // вывод лога в консоль и файл public class DefaultLogger : BaseLogger { + public DefaultLogger() => Logfile = ""; public DefaultLogger(string logfile) : base(logfile) { } public DefaultLogger(string dir, string programName) : base(dir, programName) { } @@ -18,15 +19,19 @@ public class DefaultLogger : BaseLogger public void LogNoTime(params string[] msg) { lock (Logfile) if (!IsEnabled) return; + msg[msg.Length - 1] += '\n'; ColoredConsole.Write(msg); - if (msg.Length == 1) - lock (Logfile) File.AppendAllText(Logfile, msg[0]); - else + if (WriteToFile) { - StringBuilder strB = new(); - for (ushort i = 0; i < msg.Length; i++) - strB.Append(msg[++i]); - lock (Logfile) File.AppendAllText(Logfile, strB.ToString()); + if (msg.Length == 1) + lock (Logfile) File.AppendAllText(Logfile, msg[0]); + else + { + StringBuilder strB = new(); + for (ushort i = 0; i < msg.Length; i++) + strB.Append(msg[++i]); + lock (Logfile) File.AppendAllText(Logfile, strB.ToString()); + } } } } diff --git a/Network/FSP.cs b/Network/FSP.cs index 0f66b00..46858a6 100644 --- a/Network/FSP.cs +++ b/Network/FSP.cs @@ -21,7 +21,7 @@ public class FSP { lock (MainSocket) { - Debug("b", $"requesting file download: {filePath_server}\n"); + Debug("b", $"requesting file download: {filePath_server}"); MainSocket.SendPackage("requesting file download".ToBytes()); MainSocket.SendPackage(filePath_server.ToBytes()); } @@ -33,14 +33,14 @@ public class FSP using System.IO.Stream fileStream = File.OpenWrite(filePath_client); Download_SharedCode(fileStream, true); fileStream.Close(); - Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes\n"); + Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes"); } public byte[] DownloadFileToMemory(string filePath_server) { lock (MainSocket) { - Debug("b", $"requesting file download: {filePath_server}\n"); + Debug("b", $"requesting file download: {filePath_server}"); MainSocket.SendPackage("requesting file download".ToBytes()); MainSocket.SendPackage(filePath_server.ToBytes()); } @@ -53,7 +53,7 @@ public class FSP Download_SharedCode(fileStream, false); byte[] output = fileStream.GetBuffer(); fileStream.Close(); - Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes\n"); + Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes"); return output; } @@ -101,7 +101,7 @@ public class FSP public void UploadFile(string filePath) { BytesUploaded = 0; - Debug("b", $"uploading file {filePath}\n"); + Debug("b", $"uploading file {filePath}"); using System.IO.FileStream fileStream = File.OpenRead(filePath); Filesize = File.GetSize(filePath).ToUInt(); lock (MainSocket) @@ -129,7 +129,7 @@ public class FSP } } fileStream.Close(); - Debug("g", $" uploaded {BytesUploaded} of {Filesize} bytes\n"); + Debug("g", $" uploaded {BytesUploaded} of {Filesize} bytes"); } public void DownloadByManifest(string dirOnServer, string dirOnClient, bool overwrite = false, bool delete_excess = false) @@ -138,9 +138,9 @@ public class FSP dirOnClient += "\\"; if (!dirOnServer.EndsWith("\\")) dirOnServer += "\\"; - Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">\n"); + Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">"); var manifest = new DtsodV22(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString()); - Debug("g", $"found {manifest.Values.Count} files in manifest\n"); + Debug("g", $"found {manifest.Values.Count} files in manifest"); var hasher = new Hasher(); foreach (string fileOnServer in manifest.Keys) { @@ -148,16 +148,16 @@ public class FSP Debug("b", "file <", "c", fileOnClient, "b", ">... "); if (!File.Exists(fileOnClient)) { - DebugNoTime("y", "doesn't exist\n"); + DebugNoTime("y", "doesn't exist"); DownloadFile(dirOnServer + fileOnServer, fileOnClient); } else if (overwrite && hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer]) { - DebugNoTime("y", "outdated\n"); + DebugNoTime("y", "outdated"); DownloadFile(dirOnServer + fileOnServer, fileOnClient); } else - DebugNoTime("g", "without changes\n"); + DebugNoTime("g", "without changes"); } // удаление лишних файлов if (delete_excess) @@ -166,7 +166,7 @@ public class FSP { if (!manifest.ContainsKey(file.Remove(0, dirOnClient.Length))) { - Debug("y", $"deleting excess file: {file}\n"); + Debug("y", $"deleting excess file: {file}"); File.Delete(file); } } @@ -177,7 +177,7 @@ public class FSP { if (!dir.EndsWith("\\")) dir += "\\"; - Log($"b", $"creating manifest of {dir}\n"); + Log($"b", $"creating manifest of {dir}"); StringBuilder manifestBuilder = new(); Hasher hasher = new(); if (Directory.GetFiles(dir).Contains(dir + "manifest.dtsod")) @@ -191,7 +191,7 @@ public class FSP manifestBuilder.Append(hash.HashToString()); manifestBuilder.Append("\";\n"); } - Debug($"g", $" manifest of {dir} created\n"); + Debug($"g", $" manifest of {dir} created"); File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString()); } diff --git a/Network/Package.cs b/Network/Package.cs index 5af12e1..01ba9c1 100644 --- a/Network/Package.cs +++ b/Network/Package.cs @@ -30,7 +30,7 @@ public static class Package else Thread.Sleep(5); } - throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}\n"); + throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}"); } // отправляет пакет