Добавьте файлы проекта.

This commit is contained in:
User
2021-07-19 21:25:07 +03:00
parent 93934555f6
commit 99ba577733
272 changed files with 19884 additions and 0 deletions

122
.old 2/DTLib/ColoredText.cs Normal file
View File

@@ -0,0 +1,122 @@
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;
}
}
}

257
.old 2/DTLib/ConsoleGUI.cs Normal file
View File

@@ -0,0 +1,257 @@
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<string>();
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;
}
}
}

49
.old 2/DTLib/DTLib.csproj Normal file
View File

@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DTLib</RootNamespace>
<AssemblyName>DTLib</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="FileWork.cs" />
<Compile Include="ColoredText.cs" />
<Compile Include="NetWork.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SecureHasher.cs" />
<Compile Include="SecureRandom.cs" />
<Compile Include="SimpleConverter.cs" />
<Compile Include="TImer.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>

43
.old 2/DTLib/FileWork.cs Normal file
View File

@@ -0,0 +1,43 @@
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;
}
}
}

370
.old 2/DTLib/NetWork.cs Normal file
View File

@@ -0,0 +1,370 @@
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<byte> output = new List<byte>();
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<byte> text = new List<byte>();
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<ServerObject> servers = new List<ServerObject>();
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(), "<filename>", "<filename>");
file.Size = Convert.ToUInt32(mainSocket.GetPackageClear(64, "<filesize>", "<filesize>").ToStr());
file.Hash = mainSocket.GetPackageClear(64, "<filehash>", "<filehash>");
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, "<remain>", "<remain>");
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, "<filename>", "<filename>").ToStr();
file.Size = new FileInfo(file.ServerFilePath).Length;
file.Hash = new SecureHasher(256).HashFile(file.ServerFilePath);
mainSocket.SendPackage(64, file.Size.ToString().ToBytes(), "<filesize>", "<filesize>");
mainSocket.SendPackage(64, file.Hash, "<filehash>", "<filehash>");
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, "<remain>", "<remain>");
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<byte>();
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<byte> text = new List<byte>();
for (short i = 28; i < 2028; i++)
{
text.Add(recieved[i]);
}
Text = text.ToStr();
//Log($"message <{Number}> is had recieved");
}
}
}

View File

@@ -0,0 +1,35 @@
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")]

View File

@@ -0,0 +1,97 @@
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<byte> rez = new List<byte>();
rez.AddRange(input);
rez.AddRange(salt);
return hasher.ComputeHash(rez.ToArray());
}
// читает стрим и вычисляет хеш всей инфы в нём
public byte[] HashStream(Stream st)
{
byte[] data = new byte[1024];
List<byte> rez = new List<byte>();
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;
}
}
}

View File

@@ -0,0 +1,37 @@
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;
}
}
}*/
}
}

View File

@@ -0,0 +1,82 @@
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<byte> bytes)
{
return UTF8.GetString(bytes.ToArray());
}
static public List<byte> ToList(this byte[] input)
{
var list = new List<byte>();
list.AddRange(input);
return list;
}
static public byte[] Remove(this byte[] input, int startIndex, int count)
{
List<byte> 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));
}
}

31
.old 2/DTLib/TImer.cs Normal file
View File

@@ -0,0 +1,31 @@
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();
}
}
}