changed framework to dotnet6

This commit is contained in:
Timerix22 2021-12-31 00:18:05 +03:00
parent d04855bff2
commit a4d5df3fd6
26 changed files with 1194 additions and 1324 deletions

View File

@ -1,14 +1,11 @@
using System; namespace DTLib;
using System.Text;
namespace DTLib //
// вывод и ввод цветного текста в консоли
// работает медленнее чем хотелось бы
//
public static class ColoredConsole
{ {
//
// вывод и ввод цветного текста в консоли
// работает медленнее чем хотелось бы
//
public static class ColoredConsole
{
// парсит название цвета в ConsoleColor // парсит название цвета в ConsoleColor
public static ConsoleColor ParseColor(string color) => color switch public static ConsoleColor ParseColor(string color) => color switch
{ {
@ -59,8 +56,7 @@ namespace DTLib
if (strB.Length > 0) if (strB.Length > 0)
Console.Write(strB.ToString()); Console.Write(strB.ToString());
} }
else else throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
} }
// ввод цветного текста // ввод цветного текста
@ -71,5 +67,4 @@ namespace DTLib
Console.ForegroundColor = c; Console.ForegroundColor = c;
return Console.ReadLine(); return Console.ReadLine();
} }
}
} }

View File

@ -1,80 +1,16 @@
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk">
<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> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <TargetFramework>net6.0</TargetFramework>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ImplicitUsings>false</ImplicitUsings>
<ProjectGuid>{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}</ProjectGuid> <Nullable>disable</Nullable>
<OutputType>Library</OutputType> <DebugType>portable</DebugType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DTLib</RootNamespace>
<AssemblyName>DTLib</AssemblyName> <AssemblyName>DTLib</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<LangVersion>9.0</LangVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Compile Remove="Experimental\**" />
<Reference Include="System.Core" /> <EmbeddedResource Remove="Experimental\**" />
<Reference Include="System.Data.DataSetExtensions" /> <None Remove="Experimental\**" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Compile Include="DefaultLogger.cs" />
<Compile Include="Extensions\Collections.cs" />
<Compile Include="Extensions\BaseConverter.cs" />
<Compile Include="Extensions\IfMethod.cs" />
<Compile Include="Extensions\StringConverter.cs" />
<Compile Include="Extensions\FrameworkFix.cs" />
<Compile Include="Filesystem\Symlink.cs" />
<Compile Include="Dtsod\DtsodV21.cs" />
<Compile Include="Dtsod\DtsodV22.cs" />
<Compile Include="Dtsod\V30\DtsodSerializableAttribute.cs" />
<Compile Include="Dtsod\V30\DtsodV30.cs" />
<Compile Include="Dtsod\V30\DtsodVersion.cs" />
<Compile Include="EventHandlerAsync.cs" />
<Compile Include="Filesystem\Directory.cs" />
<Compile Include="Filesystem\File.cs" />
<Compile Include="Filesystem\OldFilework.cs" />
<Compile Include="ColoredConsole.cs" />
<Compile Include="Network\FSP.cs" />
<Compile Include="Network\Package.cs" />
<Compile Include="PublicLog.cs" />
<Compile Include="Network\OldNetwork.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Hasher.cs" />
<Compile Include="TImer.cs" />
<Compile Include="XXHash.cs" />
<Compile Include="Experimental\CompressedArray.cs" />
<Compile Include="Experimental\MyDict.cs" />
<Compile Include="Experimental\SecureRandom.cs" />
<Compile Include="Experimental\Reactive\ReactiveListener.cs" />
<Compile Include="Experimental\Reactive\ReactiveProvider.cs" />
<Compile Include="Experimental\Reactive\ReactiveSender.cs" />
<Compile Include="Experimental\Reactive\ReactiveStream.cs" />
<Compile Include="Experimental\Reactive\TimeSignedObject.cs" />
</ItemGroup>
<ItemGroup>
<Content Include=".gitignore" />
</ItemGroup>
<ItemGroup>
<None Include="README.md" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project> </Project>

View File

@ -1,22 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31410.357
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Build|Any CPU = Build|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.ActiveCfg = Build|Any CPU
{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {64E0B2C4-C103-43B8-AF8C-03C1C2302008}
EndGlobalSection
EndGlobal

View File

@ -1,42 +0,0 @@
using DTLib.Filesystem;
using System;
using System.Text;
namespace DTLib
{
// вывод лога в консоль и файл
public class DefaultLogger
{
public DefaultLogger(string logfile) => Logfile = logfile;
public DefaultLogger(string dir, string programName) => Logfile = $"{dir}\\{programName}_{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
public string Logfile { get; set; }
private bool isEnabled=false;
public void Enable() { lock (Logfile) isEnabled = true; }
public void Disable() { lock (Logfile) isEnabled = false; }
public void Log(params string[] msg)
{
lock (Logfile) if (!isEnabled) return;
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
LogNoTime(msg);
}
public void LogNoTime(params string[] msg)
{
lock (Logfile) if (!isEnabled) return;
ColoredConsole.Write(msg);
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

@ -1,11 +1,8 @@
using System.Threading.Tasks; namespace DTLib;
namespace DTLib // по идее это нужно, чтоб делать так: SomeEvent?.Invoke().Wait()
{ public delegate Task EventHandlerAsyncDelegate();
// по идее это нужно, чтоб делать так: SomeEvent?.Invoke().Wait() public delegate Task EventHandlerAsyncDelegate<T>(T e);
public delegate Task EventHandlerAsyncDelegate(); public delegate Task EventHandlerAsyncDelegate<T0, T1>(T0 e0, T1 e1);
public delegate Task EventHandlerAsyncDelegate<T>(T e); public delegate Task EventHandlerAsyncDelegate<T0, T1, T2>(T0 e0, T1 e1, T2 e2);
public delegate Task EventHandlerAsyncDelegate<T0, T1>(T0 e0, T1 e1); public delegate Task EventHandlerAsyncDelegate<T0, T1, T2, T3>(T0 e0, T1 e1, T2 e2, T3 e3);
public delegate Task EventHandlerAsyncDelegate<T0, T1, T2>(T0 e0, T1 e1, T2 e2);
public delegate Task EventHandlerAsyncDelegate<T0, T1, T2, T3>(T0 e0, T1 e1, T2 e2, T3 e3);
}

18
Experimental/Tester.cs Normal file
View File

@ -0,0 +1,18 @@
using System;
using System.Diagnostics;
namespace DTLib.Experimental
{
public static class Tester
{
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");
}
}
}

View File

@ -1,21 +1,30 @@
using System; global using DTLib.Extensions;
using System.Collections.Generic; global using DTLib.Filesystem;
global using System;
global using System.Collections;
global using System.Collections.Generic;
global using System.Text;
global using System.Threading.Tasks;
global using static DTLib.PublicLog;
namespace DTLib.Extensions namespace DTLib.Extensions;
public static class BaseConverter
{ {
public static class BaseConverter
{
// сокращение конвертации // сокращение конвертации
public static bool ToBool<T>(this T input) => Convert.ToBoolean(input);
public static char ToChar<T>(this T input) => Convert.ToChar(input);
public static byte ToByte<T>(this T input) => Convert.ToByte(input);
public static sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
public static short ToShort<T>(this T input) => Convert.ToInt16(input);
public static ushort ToUShort<T>(this T input) => Convert.ToUInt16(input);
public static int ToInt<T>(this T input) => Convert.ToInt32(input); public static int ToInt<T>(this T input) => Convert.ToInt32(input);
public static uint ToUInt<T>(this T input) => Convert.ToUInt32(input); public static uint ToUInt<T>(this T input) => Convert.ToUInt32(input);
public static long ToLong<T>(this T input) => Convert.ToInt64(input); public static long ToLong<T>(this T input) => Convert.ToInt64(input);
public static ulong ToULong<T>(this T input) => Convert.ToUInt64(input); public static ulong ToULong<T>(this T input) => Convert.ToUInt64(input);
public static short ToShort<T>(this T input) => Convert.ToInt16(input); public static float ToFloat(this string input) => float.Parse(input, System.Globalization.CultureInfo.InvariantCulture);
public static ushort ToUShort<T>(this T input) => Convert.ToUInt16(input);
public static double ToDouble<T>(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture); public static double ToDouble<T>(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture);
public static byte ToByte<T>(this T input) => Convert.ToByte(input); public static decimal ToDecimal<T>(this T input) => Convert.ToDecimal(input, System.Globalization.CultureInfo.InvariantCulture);
public static sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
public static bool ToBool<T>(this T input) => Convert.ToBoolean(input);
public static int ToInt(this byte[] bytes) public static int ToInt(this byte[] bytes)
{ {
@ -40,5 +49,4 @@ namespace DTLib.Extensions
// Math.Truncate принимает как decimal, так и doublе, // Math.Truncate принимает как decimal, так и doublе,
// из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов" // из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
public static int Truncate<T>(this T number) => Math.Truncate(number.ToDouble()).ToInt(); public static int Truncate<T>(this T number) => Math.Truncate(number.ToDouble()).ToInt();
}
} }

View File

@ -1,13 +1,7 @@
using System; namespace DTLib.Extensions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTLib.Extensions public static class Collections
{ {
public static class Collections
{
public static void ForEach<T>(this IEnumerable<T> en, Action<T> act) public static void ForEach<T>(this IEnumerable<T> en, Action<T> act)
{ {
@ -41,5 +35,4 @@ namespace DTLib.Extensions
return true; return true;
return false; return false;
} }
}
} }

View File

@ -1,8 +1,7 @@
using System.ComponentModel; using System.ComponentModel;
// включает init и record из c# 9.0 // включает init и record из c# 9.0
namespace System.Runtime.CompilerServices namespace System.Runtime.CompilerServices;
{
[EditorBrowsable(EditorBrowsableState.Never)] [EditorBrowsable(EditorBrowsableState.Never)]
public class IsExternalInit { } public class IsExternalInit { }
}

View File

@ -1,9 +1,7 @@
using System; namespace DTLib.Extensions;
namespace DTLib.Extensions public static class IfMethod
{ {
public static class IfMethod
{
public static T If<T>(this T input, bool condition, Func<T, T> if_true, Func<T, T> if_false) => public static T If<T>(this T input, bool condition, Func<T, T> if_true, Func<T, T> if_false) =>
condition ? if_true(input) : if_false(input); condition ? if_true(input) : if_false(input);
@ -20,5 +18,4 @@ namespace DTLib.Extensions
{ {
if (condition) if_true(input); if (condition) if_true(input);
} }
}
} }

View File

@ -1,10 +1,7 @@
using System.Collections.Generic; namespace DTLib.Extensions;
using System.Text;
namespace DTLib.Extensions public static class StringConverter
{ {
public static class StringConverter
{
public static Encoding UTF8 = new UTF8Encoding(false); public static Encoding UTF8 = new UTF8Encoding(false);
public static byte[] ToBytes(this string str) => UTF8.GetBytes(str); public static byte[] ToBytes(this string str) => UTF8.GetBytes(str);
public static string BytesToString(this byte[] bytes) => UTF8.GetString(bytes); public static string BytesToString(this byte[] bytes) => UTF8.GetString(bytes);
@ -151,7 +148,6 @@ namespace DTLib.Extensions
public static string AddZeroes<T>(this T number, int length) public static string AddZeroes<T>(this T number, int length)
{ {
var str = number.ToString(); var str = number.ToString();
return Multiply('0', str.Length - length) + str; return new string('0', str.Length - length) + str;
}
} }
} }

View File

@ -1,11 +1,7 @@
using DTLib.Extensions; namespace DTLib.Filesystem;
using System;
using System.Collections.Generic;
namespace DTLib.Filesystem public static class Directory
{ {
public static class Directory
{
public static bool Exists(string dir) => System.IO.Directory.Exists(dir); public static bool Exists(string dir) => System.IO.Directory.Exists(dir);
// создает папку, если её не существует // создает папку, если её не существует
@ -121,21 +117,6 @@ namespace DTLib.Filesystem
public static string GetCurrent() => System.IO.Directory.GetCurrentDirectory(); public static string GetCurrent() => System.IO.Directory.GetCurrentDirectory();
public static void GrantAccess(string fullPath)
{
var dirInfo = new System.IO.DirectoryInfo(fullPath);
System.Security.AccessControl.DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
new System.Security.Principal.SecurityIdentifier(
System.Security.Principal.WellKnownSidType.WorldSid, null),
System.Security.AccessControl.FileSystemRights.FullControl,
System.Security.AccessControl.InheritanceFlags.ObjectInherit |
System.Security.AccessControl.InheritanceFlags.ContainerInherit,
System.Security.AccessControl.PropagationFlags.NoPropagateInherit,
System.Security.AccessControl.AccessControlType.Allow));
dirInfo.SetAccessControl(dirSecurity);
}
public static void CreateSymlink(string sourceName, string symlinkName) public static void CreateSymlink(string sourceName, string symlinkName)
{ {
if (symlinkName.Contains("\\")) if (symlinkName.Contains("\\"))
@ -155,5 +136,4 @@ namespace DTLib.Filesystem
File.CreateSymlink(files[i], files[i].Replace(srcdir, newdir)); File.CreateSymlink(files[i], files[i].Replace(srcdir, newdir));
return i; return i;
} }
}
} }

View File

@ -1,10 +1,7 @@
using DTLib.Extensions; namespace DTLib.Filesystem;
using System;
namespace DTLib.Filesystem public static class File
{ {
public static class File
{
public static int GetSize(string file) => new System.IO.FileInfo(file).Length.ToInt(); public static int GetSize(string file) => new System.IO.FileInfo(file).Length.ToInt();
public static bool Exists(string file) => System.IO.File.Exists(file); public static bool Exists(string file) => System.IO.File.Exists(file);
@ -83,5 +80,4 @@ namespace DTLib.Filesystem
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.File)) if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.File))
throw new InvalidOperationException($"some error occured while creating symlink\nFile.CreateSymlink({symlinkName}, {sourceName})"); throw new InvalidOperationException($"some error occured while creating symlink\nFile.CreateSymlink({symlinkName}, {sourceName})");
} }
}
} }

View File

@ -1,12 +1,10 @@
using System; namespace DTLib.Filesystem;
namespace DTLib.Filesystem //
// некоторые старые методы, которые хорошо бы вырезать
//
public static class OldFilework
{ {
//
// некоторые старые методы, которые хорошо бы вырезать
//
public static class OldFilework
{
// записывает текст в файл и закрывает файл // записывает текст в файл и закрывает файл
/*public static void LogToFile(string logfile, string msg) /*public static void LogToFile(string logfile, string msg)
{ {
@ -64,5 +62,4 @@ namespace DTLib.Filesystem
throw new Exception($"ReadFromConfig({configfile}, {key}) error: key not found"); throw new Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
} }
} }
}
} }

View File

@ -1,14 +1,9 @@
using System; using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace DTLib.Filesystem namespace DTLib.Filesystem;
internal class Symlink
{ {
internal class Symlink
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static internal extern bool CreateSymbolicLink(string symlinkName, string sourceName, SymlinkTarget type); static internal extern bool CreateSymbolicLink(string symlinkName, string sourceName, SymlinkTarget type);
@ -17,5 +12,4 @@ namespace DTLib.Filesystem
File, File,
Directory Directory
} }
}
} }

View File

@ -1,14 +1,12 @@
using System.Collections.Generic; using System.Security.Cryptography;
using System.Security.Cryptography;
using DTLib.Filesystem;
namespace DTLib namespace DTLib;
//
// хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
//
public class Hasher
{ {
//
// хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
//
public class Hasher
{
readonly HashAlgorithm sha256 = SHA256.Create(); readonly HashAlgorithm sha256 = SHA256.Create();
readonly HashAlgorithm xxh32 = XXHash32.Create(); readonly HashAlgorithm xxh32 = XXHash32.Create();
@ -56,5 +54,4 @@ namespace DTLib
fileStream.Close(); fileStream.Close();
return hash; return hash;
} }
}
} }

34
Loggers/AsyncLogger.cs Normal file
View File

@ -0,0 +1,34 @@
namespace DTLib.Loggers;
// вывод лога в консоль и файл
public class AsyncLogger : BaseLogger
{
public AsyncLogger(string logfile) : base(logfile) { }
public AsyncLogger(string dir, string programName) : base(dir, programName) { }
readonly object consolelocker = new();
public override void Log(params string[] msg)
{
lock (statelocker) if (!IsEnabled) return;
// добавление даты
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
// перенос строки
msg[msg.Length - 1] += '\n';
// вывод в консоль
lock (consolelocker)
ColoredConsole.Write(msg);
// вывод в файл
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());
}
}
public void LogAsync(params string[] msg) => Task.Run(() => Log(msg));
}

16
Loggers/BaseLogger.cs Normal file
View File

@ -0,0 +1,16 @@
namespace DTLib.Loggers;
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 bool IsEnabled { get; private set; } = false;
readonly protected object statelocker = new();
public void Disable() { lock (statelocker) IsEnabled = false; }
public void Enable() { lock (statelocker) IsEnabled = true; }
public abstract void Log(params string[] msg);
}

32
Loggers/DefaultLogger.cs Normal file
View File

@ -0,0 +1,32 @@
namespace DTLib.Loggers;
// вывод лога в консоль и файл
public class DefaultLogger : BaseLogger
{
public DefaultLogger(string logfile) : base(logfile) { }
public DefaultLogger(string dir, string programName) : base(dir, programName) { }
public override void Log(params string[] msg)
{
lock (Logfile) if (!IsEnabled) return;
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
LogNoTime(msg);
}
public void LogNoTime(params string[] msg)
{
lock (Logfile) if (!IsEnabled) return;
ColoredConsole.Write(msg);
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

@ -1,17 +1,13 @@
using DTLib.Dtsod; using DTLib.Dtsod;
using DTLib.Extensions;
using DTLib.Filesystem;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text;
using static DTLib.PublicLog;
namespace DTLib.Network namespace DTLib.Network;
//
// передача файлов по сети
//
public class FSP
{ {
//
// передача файлов по сети
//
public class FSP
{
Socket MainSocket { get; init; } Socket MainSocket { get; init; }
public static bool debug = false; public static bool debug = false;
public FSP(Socket _mainSocket) => MainSocket = _mainSocket; public FSP(Socket _mainSocket) => MainSocket = _mainSocket;
@ -207,5 +203,4 @@ namespace DTLib.Network
{ {
if (debug) LogNoTime(msg); if (debug) LogNoTime(msg);
} }
}
} }

View File

@ -1,17 +1,17 @@
using System.Diagnostics; using System.Diagnostics;
using System.Net; using System.Net.Http;
namespace DTLib.Network namespace DTLib.Network;
//
// пара почти никогда не используемых методов
//
public static class OldNetwork
{ {
//
// пара почти никогда не используемых методов
//
public static class OldNetwork
{
// получает с сайта публичный ip // получает с сайта публичный ip
public static string GetPublicIP() => new WebClient().DownloadString("https://ifconfig.me/ip"); public static string GetPublicIP() => new HttpClient().GetStringAsync("https://ifconfig.me/ip").GetAwaiter().GetResult();
// пингует айпи с помощью встроенной в винду проги, возвращает задержку // пингует айпи с помощью встроенной в винду проги, возвращает задержку
public static string PingIP(string address) public static string PingIP(string address)
@ -29,5 +29,4 @@ namespace DTLib.Network
return rezult.Remove(rezult.Length - 4); return rezult.Remove(rezult.Length - 4);
} }
}
} }

View File

@ -1,16 +1,13 @@
using DTLib.Extensions; using System.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading; using System.Threading;
namespace DTLib.Network namespace DTLib.Network;
//
// отправка/получение пакетов
//
public static class Package
{ {
//
// отправка/получение пакетов
//
public static class Package
{
// принимает пакет // принимает пакет
public static byte[] GetPackage(this Socket socket) public static byte[] GetPackage(this Socket socket)
{ {
@ -67,5 +64,4 @@ namespace DTLib.Network
return socket.GetPackage(); return socket.GetPackage();
} }
public static byte[] RequestPackage(this Socket socket, string request) => socket.RequestPackage(request.ToBytes()); public static byte[] RequestPackage(this Socket socket, string request) => socket.RequestPackage(request.ToBytes());
}
} }

View File

@ -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")]

View File

@ -1,10 +1,10 @@
namespace DTLib namespace DTLib;
//
// вывод логов со всех классов в библиотеке
//
public static class PublicLog
{ {
//
// вывод логов со всех классов в библиотеке
//
public static class PublicLog
{
public delegate void LogDelegate(params string[] msg); public delegate void LogDelegate(params string[] msg);
// вот к этому объекту подключайте методы для вывода логов // вот к этому объекту подключайте методы для вывода логов
public static event LogDelegate LogEvent; public static event LogDelegate LogEvent;
@ -12,5 +12,4 @@
public static event LogDelegate LogNoTimeEvent; public static event LogDelegate LogNoTimeEvent;
public static void LogNoTime(params string[] msg) => LogNoTimeEvent?.Invoke(msg); public static void LogNoTime(params string[] msg) => LogNoTimeEvent?.Invoke(msg);
}
} }

View File

@ -1,14 +1,12 @@
using System; using System.Threading;
using System.Threading;
using System.Threading.Tasks;
namespace DTLib namespace DTLib;
//
// простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
//
public class Timer
{ {
//
// простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
//
public class Timer
{
Task TimerTask; Task TimerTask;
bool Repeat; bool Repeat;
CancellationTokenSource кансель = new(); CancellationTokenSource кансель = new();
@ -38,5 +36,4 @@ namespace DTLib
Repeat = false; Repeat = false;
кансель.Cancel(); кансель.Cancel();
} }
}
} }

View File

@ -1,11 +1,10 @@
using System; using System.Security.Cryptography;
using System.Security.Cryptography; namespace DTLib;
namespace DTLib
// честно взятый с гитхаба алгоритм хеширования
// выдаёт хеш в виде массива четырёх байтов
sealed class XXHash32 : HashAlgorithm
{ {
// честно взятый с гитхаба алгоритм хеширования
// выдаёт хеш в виде массива четырёх байтов
sealed class XXHash32 : HashAlgorithm
{
private const uint PRIME32_1 = 2654435761U; private const uint PRIME32_1 = 2654435761U;
private const uint PRIME32_2 = 2246822519U; private const uint PRIME32_2 = 2246822519U;
private const uint PRIME32_3 = 3266489917U; private const uint PRIME32_3 = 3266489917U;
@ -171,5 +170,4 @@ namespace DTLib
_Seed32 = seed; _Seed32 = seed;
Initialize(); Initialize();
} }
}
} }