small changes

This commit is contained in:
Timerix22 2022-01-14 00:04:06 +03:00
parent 54d9a43e75
commit 97269fd160
11 changed files with 55 additions and 69 deletions

View File

@ -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

View File

@ -7,10 +7,14 @@
<AssemblyName>DTLib</AssemblyName>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ProduceReferenceAssembly>False</ProduceReferenceAssembly>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Experimental\**" />
<EmbeddedResource Remove="Experimental\**" />
<None Remove="Experimental\**" />
</ItemGroup>
<ItemGroup>
<Compile Include="Experimental\Tester.cs" />
</ItemGroup>
</Project>

View File

@ -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");
}
}
}

View File

@ -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;

View File

@ -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<T>(this T number, int length)
{
string str = number.ToString();
return new string('0', str.Length - length) + str;
}
}

View File

@ -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<string>();
List<string> 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<string> 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>();
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>();
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;

View File

@ -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;
}

View File

@ -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; }

View File

@ -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());
}
}
}
}

View File

@ -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());
}

View File

@ -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}");
}
// отправляет пакет