diff --git a/.old 2/DTLib/ColoredText.cs b/.old 2/DTLib/ColoredText.cs deleted file mode 100644 index a8147cd..0000000 --- a/.old 2/DTLib/ColoredText.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; - -namespace DTLib -{ - // - // изменение цвета текста в консоли - // - static public class ColoredText - { - // присвоение цвета тексту - static public ConsoleColor ParseColor(string color) - { - switch (color) - { - //case "magneta": - case "m": - return ConsoleColor.Magenta; - //case "green": - case "g": - return ConsoleColor.Green; - //case "red": - case "r": - return ConsoleColor.Red; - //case "yellow": - case "y": - return ConsoleColor.Yellow; - //case "white": - case "w": - return ConsoleColor.White; - //case "blue": - case "b": - return ConsoleColor.Blue; - //case "cyan": - case "c": - return ConsoleColor.Cyan; - //case "gray": - case "a": - return ConsoleColor.Gray; - //case "black": - case "t": - return ConsoleColor.Black; - default: - throw new Exception("incorrect color: " + color); - } - } - - // вывод цветного текста - static public void WriteColored(string[] input) - { - if (input.Length % 2 == 0) - { - string str = ""; - for (ushort i = 0; i < input.Length; i++) - { - var c = ParseColor(input[i]); - if (Console.ForegroundColor != c) - { - Console.Write(str); - Console.ForegroundColor = c; - str = ""; - } - str += input[++i]; - } - if (str != "") - Console.Write(str); - } - else - { - throw new Exception("error in WriteColored(): every text string must have color string before"); - } - } - - /*static public void WriteColoredB(string[] input) - { - if (input.Length % 3 == 0) - { - string str = ""; - for (ushort i = 0; i < input.Length; i++) - { - var f = ParseColor(input[i]); - var b = ParseColor(input[++i]); - if (Console.ForegroundColor != f || Console.BackgroundColor != b) - { - Console.Write(str); - Console.ForegroundColor = f; - Console.BackgroundColor = b; - str = ""; - } - str += input[++i]; - } - if (str != "") - Console.Write(str); - } - else - { - throw new Exception("error in WriteColored(): every text string must have color string before"); - } - }*/ - - static public void WriteColored(string color, string text) - { - var c = ParseColor(color); - if (Console.ForegroundColor != c) - { - Console.ForegroundColor = c; - } - Console.Write(text); - } - - // ввод цветного текста - static public string ReadColored(string color) - { - var c = ParseColor(color); - if (Console.ForegroundColor != c) - { - Console.ForegroundColor = c; - } - string text = Console.ReadLine(); - return text; - } - } -} \ No newline at end of file diff --git a/.old 2/DTLib/ConsoleGUI.cs b/.old 2/DTLib/ConsoleGUI.cs deleted file mode 100644 index 7e4351d..0000000 --- a/.old 2/DTLib/ConsoleGUI.cs +++ /dev/null @@ -1,257 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - -namespace DTLib.ConsoleGUI -{ - // - // создание gui из текста в консоли - // - public class Window - { - public int WindowWidth { get; private set; } - public int WindowHeight { get; private set; } - public char[,] Text; - public char[,] nowText; - public char[,] TextColors; - public char[,] nowTextColors; - - public Window(int windowWidth, int windowHeight) - { - WindowWidth = windowWidth; - WindowHeight = windowHeight; - Text = new char[windowWidth, windowHeight]; - TextColors = new char[windowWidth, windowHeight]; - nowText = new char[windowWidth, windowHeight]; - nowTextColors = new char[windowWidth, windowHeight]; - Console.WindowWidth = WindowWidth + 1; - Console.WindowHeight = WindowHeight + 1; - Console.BufferWidth = WindowWidth + 1; - Console.BufferHeight = WindowHeight + 1; - Console.OutputEncoding = SimpleConverter.UTF8; - Console.InputEncoding = SimpleConverter.UTF8; - Console.CursorVisible = false; - // заполнение массивов - for (sbyte y = 0; y < WindowHeight; y++) - { - for (sbyte x = 0; x < WindowWidth; x++) - { - Text[x, y] = ' '; - nowText[x, y] = ' '; - TextColors[x, y] = 'w'; - nowTextColors[x, y] = 'w'; - } - } - } - - // считывает массив символов из файла - // ширина и высота текста должны быть как указанные при инициализации объекта этого класса - public void ReadFromFile(string path) - { - var r = new StreamReader(path, SimpleConverter.UTF8); - char[] s = new char[1]; - // считывание текста - sbyte y = 0, x = 0; - r.Read(s, 0, 1); - while (!r.EndOfStream && y < WindowHeight) - { - if (x == WindowWidth) - { - r.Read(s, 0, 1); - x = 0; - y++; - } - else - { - Text[x, y] = s[0]; - x++; - } - r.Read(s, 0, 1); - } - r.Read(s, 0, 1); - // считывание цвета - // если не находит цвет в файле, оставляет старый - if (s[0] == '\n') - { - r.Read(s, 0, 1); - y = 0; - x = 0; - while (!r.EndOfStream && y < WindowHeight) - { - if (x == WindowWidth) - { - r.Read(s, 0, 1); - x = 0; - y++; - } - else - { - TextColors[x, y] = s[0]; - x++; - } - r.Read(s, 0, 1); - } - } - r.Close(); - } - - public void ResetCursor() - { - Console.SetCursorPosition(0, WindowHeight); - } - - // заменяет символ выведенный, использовать после ShowAll() - public void ChangeChar(sbyte x, sbyte y, char ch) - { - Text[x, y] = ch; - nowText[x, y] = ch; - Console.SetCursorPosition(x, y); - ColoredText.WriteColored(TextColors[x, y].ToString(), ch.ToString()); - } - - public void ChangeColor(sbyte x, sbyte y, char color) - { - TextColors[x, y] = color; - nowTextColors[x, y] = color; - Console.SetCursorPosition(x, y); - ColoredText.WriteColored(color.ToString(), Text[x, y].ToString()); - } - - public void ChangeCharAndColor(sbyte x, sbyte y, char color, char ch) - { - Text[x, y] = ch; - nowText[x, y] = ch; - TextColors[x, y] = color; - nowTextColors[x, y] = color; - Console.SetCursorPosition(x, y); - ColoredText.WriteColored(color.ToString(), ch.ToString()); - } - - public void ChangeLine(sbyte x, sbyte y, char color, string line) - { - Console.SetCursorPosition(x, y); - for (sbyte i = 0; i < line.Length; i++) - { - Text[x + i, y] = line[i]; - nowText[x + i, y] = line[i]; - TextColors[x + i, y] = color; - nowTextColors[x + i, y] = color; - } - ColoredText.WriteColored(color.ToString(), line); - } - - // выводит все символы - public void ShowAll() - { - var l = new List(); - for (sbyte y = 0; y < WindowHeight; y++) - { - for (sbyte x = 0; x < WindowWidth; x++) - { - l.Add(TextColors[x, y].ToString()); - l.Add(Text[x, y].ToString()); - nowText[x, y] = Text[x, y]; - nowTextColors[x, y] = TextColors[x, y]; - } - l.Add("w"); - l.Add("\n"); - } - ColoredText.WriteColored(l.ToArray()); - //Console.WriteLine(); - } - - public void UpdateAll() - { - for (sbyte y = 0; y < WindowHeight; y++) - { - for (sbyte x = 0; x < WindowWidth; x++) - { - Console.SetCursorPosition(x, y); - if (TextColors[x, y] != nowTextColors[x, y] || Text[x, y] != nowText[x, y]) - { - ColoredText.WriteColored(TextColors[x, y].ToString(), Text[x, y].ToString()); - nowText[x, y] = Text[x, y]; - nowTextColors[x, y] = TextColors[x, y]; - } - } - Console.Write('\n'); - } - } - - - - public async void ChangeCharAsync(sbyte x, sbyte y, char ch) - { - await Task.Run(() => - { - ChangeChar(x, y, ch); - }); - } - - public async void ChangeColorAsync(sbyte x, sbyte y, char color) - { - await Task.Run(() => - { - ChangeColor(x, y, color); - }); - } - - public async void ChangeCharAndColorAsync(sbyte x, sbyte y, char color, char ch) - { - await Task.Run(() => - { - ChangeCharAndColor(x, y, color, ch); - }); - } - - public async void ChangeLineAsync(sbyte x, sbyte y, char color, string line) - { - await Task.Run(() => - { - ChangeLine(x, y, color, line); - }); - } - - public async void ShowAllAsync() - { - await Task.Run(() => - { - ShowAll(); - }); - } - - public async void UpdateAllAsync() - { - await Task.Run(() => - { - UpdateAll(); - }); - } - } - - public class Tab - { - public Window Window; - public string Name; - - public Tab(Window window) - { - Window = window; - } - } - - public class Box - { - public Tab Tab; - public int LeftTopCorner, Width, Heigth; - - public Box(Tab tab, int leftTopCorner, int width, int heigth) - { - Tab = tab; - LeftTopCorner = leftTopCorner; - Width = width; - Heigth = heigth; - } - } -} diff --git a/.old 2/DTLib/DTLib.csproj b/.old 2/DTLib/DTLib.csproj deleted file mode 100644 index 99fb4aa..0000000 --- a/.old 2/DTLib/DTLib.csproj +++ /dev/null @@ -1,49 +0,0 @@ - - - - - Debug - AnyCPU - {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} - Library - Properties - DTLib - DTLib - v4.8 - 512 - true - - - none - true - bin\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.old 2/DTLib/FileWork.cs b/.old 2/DTLib/FileWork.cs deleted file mode 100644 index 8758afd..0000000 --- a/.old 2/DTLib/FileWork.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.IO; - -namespace DTLib -{ - public static class FileWork - { - public static void Log(string logfile, string msg) - { - lock (new object()) - { - var st = File.Open(logfile, FileMode.Append); - var writer = new StreamWriter(st, SimpleConverter.UTF8); - string logMsg = $"[{DateTime.Now}]: {msg}"; - writer.Write(logMsg); - writer.Close(); - st.Close(); - } - } - - public static void DirExistenceCheck(string dir) - { - if (!Directory.Exists(dir)) - Directory.CreateDirectory(dir); - } - - static public string ReadFromConfig(string configfile, string key) - { - var reader = new StreamReader(configfile); - while (!reader.EndOfStream) - { - string st = reader.ReadLine(); - if (!st.StartsWith("#") && st.Contains(key + ": ")) - { - reader.Close(); - return st.Remove(0, st.IndexOf(key + ": ") + key.Length + 2); - } - } - reader.Close(); - return null; - } - } -} diff --git a/.old 2/DTLib/NetWork.cs b/.old 2/DTLib/NetWork.cs deleted file mode 100644 index de6fd21..0000000 --- a/.old 2/DTLib/NetWork.cs +++ /dev/null @@ -1,370 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Threading; - -namespace DTLib -{ - // - // некоторые полезные методы для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - // - static public class NetWork - { - public delegate void LogDelegate(string[] msg); - // можно присвоить методы этому делегату чтоб выводить логи - static public LogDelegate Log; - static void LogSimple(string color, string msg) - { - Log(new string[] { color, msg }); - } - - // правильно закрывает сокет - static public void CloseSocket(this Socket socket) - { - socket.Shutdown(SocketShutdown.Both); - socket.Close(); - } - // получение информации (сокет должен быть в режиме Listen) - static public byte[] GetData(this Socket socket) - { - List output = new List(); - byte[] data = new byte[256]; - do - { - int amount = socket.Receive(data, data.Length, 0); - for (int i = 0; i < amount; i++) - output.Add(data[i]); - } - while (socket.Available > 0); - return output.ToArray(); - } - - // отправка запроса и получение ответа на него (сокет должен быть в режиме Listen) - static public byte[] Request(this Socket socket, string request) - { - socket.Send(request.ToBytes()); - return GetData(socket); - } - - static public byte[] Request(this Socket socket, byte[] request) - { - socket.Send(request); - return GetData(socket); - } - - /*static public MessageObject SplitMessage(byte[] recieved) - { - if (recieved.Length != 2284) throw new Exception("incorrect message length: " + recieved.Length); - var msg = new MessageObject(); - msg.Number = recieved[2]; - for (byte i = 3; i < 9; i++) - { - msg.Number = msg.Number * 10 + recieved[i]; - } - msg.Datetime = new DateTime(recieved[9] * 100 + recieved[10], recieved[11], recieved[12], - recieved[13], recieved[14], recieved[15]); - for (byte i = 16; i < 22; i++) - { - msg.Sender = msg.Sender * 10 + recieved[i]; - } - for (byte i = 22; i < 28; i++) - { - msg.Channel = msg.Channel * 10 + recieved[i]; - } - List text = new List(); - for (short i = 28; i < 2028; i++) - { - text.Add(recieved[i]); - } - msg.Text = text.ToStr(); - Log($"message <{msg.Number}> is had recieved"); - return msg; - }*/ - - static public void FtpDownload(string address, string login, string password, string outfile) - { - try - { - // debug - Log(new string[] { - "y", "file on server: <", "c",address, "y",">\nfile on client: <", - "c",outfile,"y", ">\n"}); - // создание запроса - // "ftp://m1net.keenetic.pro:20000/" + @infile - FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address); - request.Credentials = new NetworkCredential(login, password); - request.Method = WebRequestMethods.Ftp.DownloadFile; - // получение ответа на запрос - FtpWebResponse response = (FtpWebResponse)request.GetResponse(); - Stream responseStream = response.GetResponseStream(); - FileStream fs = new FileStream(@Directory.GetCurrentDirectory() + '\\' + @outfile, FileMode.Create); - byte[] buffer = new byte[64]; - int size = 0; - - while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0) - { - fs.Write(buffer, 0, size); - } - fs.Close(); - response.Close(); - } - catch (WebException e) - { - throw new Exception("ftp error:\n" + ((FtpWebResponse)e.Response).StatusDescription + '\n'); - } - } - - static public ServerObject[] RequestServersList(Socket centralServer) - { - List servers = new List(); - string[] lines = Request(centralServer, "a356a4257dbf9d87c77cf87c3c694b30160b6ddfd3db82e7f62320207109e352").ToStr().Split('\n'); - for (int i = 0; i < lines.Length; i++) - { - string[] properties = lines[i].Split(','); - servers.Add(new ServerObject(properties[0], properties[1], properties[2])); - } - return servers.ToArray(); - } - - static public string PingIP(string address) - { - Process proc = new Process(); - proc.StartInfo.FileName = "cmd.exe"; - proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address; - proc.StartInfo.CreateNoWindow = true; - proc.StartInfo.UseShellExecute = false; - proc.StartInfo.RedirectStandardOutput = true; - proc.Start(); - var outStream = proc.StandardOutput; - var rezult = outStream.ReadToEnd(); - rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2); - return rezult.Remove(rezult.Length - 4); - } - - static public bool Ping(this Socket socket) - { - var rec = Request(socket, "ab53bf045004875fb17086f7f992b0514fb96c038f336e0bfc21609b20303f07"); - if (rec.ToStr() == "91b5c0383b75fb1708f00486f7f9b96c038ab3bfc21059b20176f603692b05e0") - { - return true; - } - else return false; - } - - static public void FSP_Download(this Socket mainSocket, FSP_FileObject file) - { - Log(new string[] { "c", $"remote socket accepted download request: {file.ClientFilePath}\n" }); - mainSocket.Send("requesting file download".ToBytes()); - string answ = mainSocket.GetPackageClear(64, "<", ">").ToStr(); - if (answ != "download request accepted") - throw new Exception($"FSP_Download() error: a download socket recieved an incorrect message: {answ}\n"); - mainSocket.SendPackage(276, file.ServerFilePath.ToBytes(), "", ""); - file.Size = Convert.ToUInt32(mainSocket.GetPackageClear(64, "", "").ToStr()); - file.Hash = mainSocket.GetPackageClear(64, "", ""); - mainSocket.SendPackage(64, "ready".ToBytes(), "<", ">"); - file.Stream = File.Open(file.ClientFilePath, FileMode.Create, FileAccess.Write); - int packagesCount = 0; - byte[] buffer = new byte[5120]; - var hashstr = file.Hash.HashToString(); - int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length); - // рассчёт скорости - int seconds = 0; - var speedCounter = new Timer(true, 1000, () => - { - seconds++; - LogSimple("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n"); - }); - // получение файла - for (; packagesCount < fullPackagesCount; packagesCount++) - { - string header = $"<{packagesCount}>"; - buffer = mainSocket.GetPackageRaw(buffer.Length + 2 + header.Length, header, "<>"); - file.Stream.Write(buffer, 0, buffer.Length); - file.Stream.Flush(); - } - Log(new string[] { "y", " full packages recieved\n" }); - speedCounter.Stop(); - // получение остатка - mainSocket.SendPackage(64, "remain request".ToBytes(), "<", ">"); - buffer = mainSocket.GetPackageRaw(Convert.ToInt32(file.Size - fullPackagesCount * 5120) + 16, "", ""); - file.Stream.Write(buffer, 0, buffer.Length); - file.Stream.Flush(); - file.Stream.Close(); - Log(new string[] { "g", $" file {file.ClientFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) downloaded.\n" }); - } - - static public void FSP_Upload(this Socket mainSocket) - { - mainSocket.SendPackage(64, "download request accepted".ToBytes(), "<", ">"); - var file = new FSP_FileObject(); - file.ServerFilePath = mainSocket.GetPackageClear(276, "", "").ToStr(); - file.Size = new FileInfo(file.ServerFilePath).Length; - file.Hash = new SecureHasher(256).HashFile(file.ServerFilePath); - mainSocket.SendPackage(64, file.Size.ToString().ToBytes(), "", ""); - mainSocket.SendPackage(64, file.Hash, "", ""); - if (mainSocket.GetPackageClear(64, "<", ">").ToStr() != "ready") - throw new Exception("user socket isn't ready"); - Log(new string[] { "c", $"local socket accepted file download request: {file.ServerFilePath}\n" }); - file.Stream = new FileStream(file.ServerFilePath, FileMode.Open, FileAccess.Read); - byte[] buffer = new byte[5120]; - var hashstr = file.Hash.HashToString(); - int packagesCount = 0; - int seconds = 0; - // рассчёт скорости - var speedCounter = new Timer(true, 1000, () => - { - seconds++; - LogSimple("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n"); - }); - // отправка файла - int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length); - for (; packagesCount < fullPackagesCount; packagesCount++) - { - string header = $"<{packagesCount}>"; - file.Stream.Read(buffer, 0, buffer.Length); - try { mainSocket.SendPackage(buffer.Length + 2 + header.Length, buffer, header, "<>"); } - catch (Exception ex) { Log(new string[] { "r", "FSP_Upload() error: " + ex.Message + "\n" + ex.StackTrace + '\n' }); } - } - Log(new string[] { "y", " full packages send\n" }); - speedCounter.Stop(); - // досылка остатка - var req = mainSocket.GetPackageClear(64, "<", ">"); - if (req.ToStr() != "remain request") - { - throw new Exception("FSP_Upload() error: didn't get remain request"); - } - buffer = new byte[Convert.ToInt32(file.Size - file.Stream.Position)]; - file.Stream.Read(buffer, 0, buffer.Length); - mainSocket.SendPackage(buffer.Length + 16, buffer, "", ""); - file.Stream.Close(); - Log(new string[] { "g", $" file {file.ServerFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) uploaded.\n" }); - } - - // убирает пустые байты в конце пакета - static public byte[] GetPackageClear(this Socket socket, int packageSize, string startsWith, string endsWith) - { - byte[] data = socket.GetPackageRaw(packageSize, startsWith, endsWith); - bool clean = false; - for (int i = 0; !clean; i++) - { - if (data[i] != 00) - { - if (i != 0) data = data.Remove(0, i); - clean = true; - } - else clean = i == data.Length - 1; - } - return data; - } - //не убирает пустые байты в конце пакета - static public byte[] GetPackageRaw(this Socket socket, int packageSize, string startsWith, string endsWith) - { - byte[] data = new byte[packageSize]; - //Log(new string[] { "y", $"GetPackage() packegesize=<","c",packageSize.ToString(), - // "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" }); - for (short s = 0; s < 2000; s += 10) - { - if (socket.Available >= packageSize) - { - socket.Receive(data, packageSize, 0); - if (data.StartsWith(startsWith) & data.EndsWith(endsWith)) - { - data = data.Remove(0, startsWith.ToBytes().Length); - data = data.Remove(data.Length - endsWith.ToBytes().Length, endsWith.ToBytes().Length); - return data; - } - else throw new Exception($"GetPackage() error: has got incorrect package\n"); - } - else Thread.Sleep(10); - } - throw new Exception($"GetPackage() error: timeout\n"); - } - - static public void SendPackage(this Socket socket, int length, byte[] data, string startsWith, string endsWith) - { - var list = new List(); - list.AddRange(startsWith.ToBytes()); - int i = startsWith.ToBytes().Length + endsWith.ToBytes().Length + data.Length; - //Log(new string[] { "y", $"SendPackage() length=<","c",length.ToString(),"y", "> packegesize=<","c",i.ToString(), - // "y", "> data.Length=<","c",data.Length.ToString(), "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" }); - if (i > length) throw new Exception("SendPackage() error: int length is too small\n"); - for (; i < length; i++) - list.Add(0); - list.AddRange(data); - list.AddRange(endsWith.ToBytes()); - socket.Send(list.ToArray()); - } - } - - public class FSP_FileObject - { - public string ServerFilePath; - public string ClientFilePath; - public long Size; - public byte[] Hash; - public Stream Stream; - - public FSP_FileObject(string serverFile, string clientFile) - { - ServerFilePath = serverFile; - ClientFilePath = clientFile; - } - - public FSP_FileObject() { } - } - - public class ServerObject - { - public string Address; - public string Name; - public string Speed; - - public ServerObject(string address, string name, string speed) - { - Address = address; - Name = name; - Speed = speed; - } - } - - public class MessageObject - { - public uint Number; - public DateTime Datetime; - public int Sender; - public int Channel; - public string Text; - - public MessageObject() { } - - public MessageObject(byte[] recieved) - { - if (recieved.Length != 2284) throw new Exception("incorrect message length: " + recieved.Length); - Number = recieved[2]; - for (byte i = 3; i < 9; i++) - { - Number = Number * 10 + recieved[i]; - } - Datetime = new DateTime(recieved[9] * 100 + recieved[10], recieved[11], recieved[12], - recieved[13], recieved[14], recieved[15]); - for (byte i = 16; i < 22; i++) - { - Sender = Sender * 10 + recieved[i]; - } - for (byte i = 22; i < 28; i++) - { - Channel = Channel * 10 + recieved[i]; - } - List text = new List(); - for (short i = 28; i < 2028; i++) - { - text.Add(recieved[i]); - } - Text = text.ToStr(); - //Log($"message <{Number}> is had recieved"); - } - } -} diff --git a/.old 2/DTLib/Properties/AssemblyInfo.cs b/.old 2/DTLib/Properties/AssemblyInfo.cs deleted file mode 100644 index c0201c5..0000000 --- a/.old 2/DTLib/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// Общие сведения об этой сборке предоставляются следующим набором -// набора атрибутов. Измените значения этих атрибутов для изменения сведений, -// связанные со сборкой. -[assembly: AssemblyTitle("DTLib")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("DTLib")] -[assembly: AssemblyCopyright("Copyright © 2021")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми -// для компонентов COM. Если необходимо обратиться к типу в этой сборке через -// COM, задайте атрибуту ComVisible значение TRUE для этого типа. -[assembly: ComVisible(false)] - -// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM -[assembly: Guid("ce793497-2d5c-42d8-b311-e9b32af9cdfb")] - -// Сведения о версии сборки состоят из указанных ниже четырех значений: -// -// Основной номер версии -// Дополнительный номер версии -// Номер сборки -// Редакция -// -// Можно задать все значения или принять номера сборки и редакции по умолчанию -// используя "*", как показано ниже: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/.old 2/DTLib/SecureHasher.cs b/.old 2/DTLib/SecureHasher.cs deleted file mode 100644 index 691664d..0000000 --- a/.old 2/DTLib/SecureHasher.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Security.Cryptography; - -namespace DTLib -{ - // - // создаёт хеши из массива байт, двух массивов байт, стрима - // - public class SecureHasher - { - private dynamic hasher; - - // можно указать размер хеша (по умолчанию 256 байт) - public SecureHasher(short type) - { - switch (type) - { - case 256: - hasher = SHA256.Create(); - break; - case 384: - hasher = SHA384.Create(); - break; - case 512: - hasher = SHA512.Create(); - break; - default: - throw new Exception("unknown hash algorithm type: " + type + "\nin shouid be 256, 384 or 512\n"); - } - } - public SecureHasher() - { - hasher = SHA256.Create(); - } - - // просто хеш - public byte[] Hash(byte[] input) - { - return hasher.ComputeHash(input); - } - - // хеш из двух массивов - public byte[] HashSalt(byte[] input, byte[] salt) - { - List rez = new List(); - rez.AddRange(input); - rez.AddRange(salt); - return hasher.ComputeHash(rez.ToArray()); - } - - // читает стрим и вычисляет хеш всей инфы в нём - public byte[] HashStream(Stream st) - { - byte[] data = new byte[1024]; - List rez = new List(); - int offset = 0; - while (offset < st.Length) - { - offset += st.Read(data, offset, 1024); - rez.AddRange(hasher.ComputeHash(data)); - } - return hasher.ComputeHash(rez.ToArray()); - } - - // Хеш двух массивов в цикле. - // Работает быстро, так что вполне можно использовать количество циклов до 8к - - public byte[] HashSaltCycled(byte[] input, byte[] salt, ushort cycles) - { - for (uint i = 0; i < cycles; i++) - { - input = HashSalt(input, salt); - } - return input; - } - - public byte[] HashCycled(byte[] input, ushort cycles) - { - for (uint i = 0; i < cycles; i++) - { - input = Hash(input); - } - return input; - } - - public byte[] HashFile(string filename) - { - var md5 = MD5.Create(); - var stream = File.OpenRead(filename); - var hash = HashSaltCycled(md5.ComputeHash(stream), filename.ToBytes(), 512); - stream.Close(); - return hash; - } - } -} diff --git a/.old 2/DTLib/SecureRandom.cs b/.old 2/DTLib/SecureRandom.cs deleted file mode 100644 index 98217cf..0000000 --- a/.old 2/DTLib/SecureRandom.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Security.Cryptography; - -namespace DTLib -{ - // - // Вычисление псевдослучайного числа из множества параметров. - // Работает медленнее чем класс System.Random, но производит более случайные значения - // - public class SecureRandom - { - private RNGCryptoServiceProvider crypt = new RNGCryptoServiceProvider(); - - // получение массива случайных байтов - public byte[] NextBytes(uint length) - { - byte[] output = new byte[length]; - crypt.GetNonZeroBytes(output); - return output; - } - - // получение случайного числа от 0 до 2147483647 - /*public int NextInt(uint from, int to) - { - int output = 0; - int rez = 0; - while (true) - { - rez = output * 10 + NextBytes(1)[0]; - if (rez < to && rez > from) - { - output = rez; - return output; - } - } - }*/ - } -} diff --git a/.old 2/DTLib/SimpleConverter.cs b/.old 2/DTLib/SimpleConverter.cs deleted file mode 100644 index 9f6c1a3..0000000 --- a/.old 2/DTLib/SimpleConverter.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace DTLib -{ - // - // содержит методы расширения для конвертации байт в строку и наоборот - // - public static class SimpleConverter - { - static public Encoding UTF8 = new UTF8Encoding(false); - // байты в кодировке UTF8 в строку - static public string ToStr(this byte[] bytes) - { - return UTF8.GetString(bytes); - } - static public string ToStr(this List bytes) - { - return UTF8.GetString(bytes.ToArray()); - } - - static public List ToList(this byte[] input) - { - var list = new List(); - list.AddRange(input); - return list; - } - - static public byte[] Remove(this byte[] input, int startIndex, int count) - { - List list = input.ToList(); - list.RemoveRange(startIndex, count); - return list.ToArray(); - } - - // строку в байты - static public byte[] ToBytes(this string str) - { - return UTF8.GetBytes(str); - } - - // хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним) - static public string HashToString(this byte[] hash) - { - var builder = new StringBuilder(); - for (int i = 0; i < hash.Length; i++) - { - builder.Append(hash[i].ToString("x2")); - } - return builder.ToString(); - } - - static public bool StartsWith(this byte[] source, byte[] startsWith) - { - for (int i = 0; i < startsWith.Length; i++) - { - if (source[i] != startsWith[i]) - return false; - } - return true; - } - - static public bool StartsWith(this byte[] source, string startsWith) - => StartsWith(source, startsWith.ToBytes()); - - static public bool EndsWith(this byte[] source, byte[] endsWith) - { - for (int i = 0; i < endsWith.Length; i++) - { - if (source[source.Length - endsWith.Length + i] != endsWith[i]) - return false; - } - return true; - } - static public bool EndsWith(this byte[] source, string endsWith) - => EndsWith(source, endsWith.ToBytes()); - - static public int Truncate(decimal number) - => Convert.ToInt32(Math.Truncate(number)); - } -} diff --git a/.old 2/DTLib/TImer.cs b/.old 2/DTLib/TImer.cs deleted file mode 100644 index 2383078..0000000 --- a/.old 2/DTLib/TImer.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Threading; - -namespace DTLib -{ - public class Timer - { - public Thread TimerThread; - bool Repeat; - public Timer(bool repeat, int delay, Action method) - { - Repeat = repeat; - TimerThread = new Thread(() => - { - do - { - Thread.Sleep(delay); - method(); - } while (Repeat); - }); - TimerThread.Start(); - } - - public void Stop() - { - Repeat = false; - //throw new Exception("thread stop\n"); - TimerThread.Abort(); - } - } -} diff --git a/.old 2/dtlauncher-client-win/App.config b/.old 2/dtlauncher-client-win/App.config deleted file mode 100644 index 193aecc..0000000 --- a/.old 2/dtlauncher-client-win/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.old 2/dtlauncher-client-win/App.xaml b/.old 2/dtlauncher-client-win/App.xaml deleted file mode 100644 index 87bbcc3..0000000 --- a/.old 2/dtlauncher-client-win/App.xaml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/.old 2/dtlauncher-client-win/App.xaml.cs b/.old 2/dtlauncher-client-win/App.xaml.cs deleted file mode 100644 index 4aa3d80..0000000 --- a/.old 2/dtlauncher-client-win/App.xaml.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Windows; - -namespace dtlauncher_client_win -{ - /// - /// Логика взаимодействия для App.xaml - /// - public partial class App : Application - { - } -} diff --git a/.old 2/dtlauncher-client-win/LauncherWindow.xaml b/.old 2/dtlauncher-client-win/LauncherWindow.xaml deleted file mode 100644 index 7b406c3..0000000 --- a/.old 2/dtlauncher-client-win/LauncherWindow.xaml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - diff --git a/.old 2/dtlauncher-client-win/LauncherWindow.xaml.cs b/.old 2/dtlauncher-client-win/LauncherWindow.xaml.cs deleted file mode 100644 index f920ce1..0000000 --- a/.old 2/dtlauncher-client-win/LauncherWindow.xaml.cs +++ /dev/null @@ -1,46 +0,0 @@ -using DTLib; -using System; -using System.Net; -using System.Net.Sockets; -using System.Windows; -using static DTLib.NetWork; - -namespace dtlauncher_client_win -{ - /// - /// Логика взаимодействия для LauncherWindow.xaml - /// - public partial class LauncherWindow : Window - { - Socket socket; - string logfile; - - public LauncherWindow(Socket _socket, string _logfile) - { - InitializeComponent(); - socket = _socket; - logfile = _logfile; - NetWork.Log += Log; - //mainSocket.FSP_Download(new FSP_FileObject("share\\file.arc", "downloads\\file.arc")); - } - - void Log(string msg) - { - msg = "[" + DateTime.Now.ToString() + "]: " + msg; - FileWork.Log(logfile, msg); - //LogBox.Text += msg; - } - - void Log(string[] input) - { - if (input.Length % 2 == 0) - { - string str = ""; - for (ushort i = 0; i < input.Length; i++) - str += input[++i]; - Log(str); - } - else throw new Exception("error in Log(): every text string must have color string before"); - } - } -} diff --git a/.old 2/dtlauncher-client-win/LoginWindow.xaml b/.old 2/dtlauncher-client-win/LoginWindow.xaml deleted file mode 100644 index c5b0e39..0000000 --- a/.old 2/dtlauncher-client-win/LoginWindow.xaml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - -