Delete .old 6 directory
This commit is contained in:
parent
9afa03d9ee
commit
bc925cca61
@ -1,23 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class Color
|
||||
{
|
||||
public record RGBA(byte R, byte G, byte B, byte A)
|
||||
{
|
||||
public RGBA(byte[] arrayRGBA) : this(arrayRGBA[0], arrayRGBA[1], arrayRGBA[2], arrayRGBA[3])
|
||||
{
|
||||
if (arrayRGBA.Length != 4) throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
|
||||
}
|
||||
}
|
||||
|
||||
public record RGB(byte R, byte G, byte B)
|
||||
{
|
||||
public RGB(byte[] arrayRGB) : this(arrayRGB[0], arrayRGB[1], arrayRGB[2])
|
||||
{
|
||||
if (arrayRGB.Length != 3) throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 3\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// вывод и ввод цветного текста в консоли
|
||||
// работает медленнее чем хотелось бы
|
||||
//
|
||||
public static class ColoredConsole
|
||||
{
|
||||
// парсит название цвета в ConsoleColor
|
||||
public static ConsoleColor ParseColor(string color)
|
||||
{
|
||||
return color switch
|
||||
{
|
||||
//case "magneta":
|
||||
"m" => ConsoleColor.Magenta,
|
||||
//case "green":
|
||||
"g" => ConsoleColor.Green,
|
||||
//case "red":
|
||||
"r" => ConsoleColor.Red,
|
||||
//case "yellow":
|
||||
"y" => ConsoleColor.Yellow,
|
||||
//case "white":
|
||||
"w" => ConsoleColor.White,
|
||||
//case "blue":
|
||||
"b" => ConsoleColor.Blue,
|
||||
//case "cyan":
|
||||
"c" => ConsoleColor.Cyan,
|
||||
//case "gray":
|
||||
"gray" => ConsoleColor.Gray,
|
||||
//case "black":
|
||||
"black" => ConsoleColor.Black,
|
||||
_ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"),
|
||||
};
|
||||
}
|
||||
|
||||
// вывод цветного текста
|
||||
public static void Write(params string[] input)
|
||||
{
|
||||
if (input.Length == 1)
|
||||
{
|
||||
if (Console.ForegroundColor != ConsoleColor.Gray) Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.Write(input[0]);
|
||||
}
|
||||
else 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("ColoredConsole.Write() error: every text string must have color string before");
|
||||
}
|
||||
|
||||
// ввод цветного текста
|
||||
public static string Read(string color)
|
||||
{
|
||||
var c = ParseColor(color);
|
||||
if (Console.ForegroundColor != c) Console.ForegroundColor = c;
|
||||
return Console.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,72 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
public class CompressedArray
|
||||
{
|
||||
public class Array1D<T> where T : IComparable<T>
|
||||
{
|
||||
byte[] Description;
|
||||
T[] Memory;
|
||||
|
||||
public Array1D() { }
|
||||
public Array1D(T[] sourceArray)
|
||||
{
|
||||
CompressArray(sourceArray);
|
||||
}
|
||||
|
||||
public void CompressArray(T[] sourceArray)
|
||||
{
|
||||
var listMem = new List<T>();
|
||||
var listDesc = new List<byte>();
|
||||
T prevElement = sourceArray[0];
|
||||
listMem.Add(sourceArray[0]);
|
||||
listDesc.Add(1);
|
||||
byte repeats = 1;
|
||||
for (int i = 1; i < sourceArray.Length; i++)
|
||||
{
|
||||
if (prevElement.CompareTo(sourceArray[i]) == 0) repeats++;
|
||||
else
|
||||
{
|
||||
listMem.Add(sourceArray[i]);
|
||||
listDesc.Add(1);
|
||||
if (repeats > 1)
|
||||
{
|
||||
listDesc[listDesc.Count - 2] = repeats;
|
||||
repeats = 1;
|
||||
}
|
||||
}
|
||||
prevElement = sourceArray[i];
|
||||
}
|
||||
Memory = listMem.ToArray();
|
||||
Description = listDesc.ToArray();
|
||||
ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count + "\n");
|
||||
for (short i = 0; i < listDesc.Count; i++)
|
||||
{
|
||||
ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
|
||||
}
|
||||
}
|
||||
|
||||
// блокирует обращение к памяти из нескольких потоков
|
||||
Mutex storageUsing = new();
|
||||
|
||||
// возвращает элемент по индексу так, как если бы шло обращение к обычном массиву
|
||||
public T GetElement(int index)
|
||||
{
|
||||
storageUsing.WaitOne();
|
||||
T output = default;
|
||||
int sum = 0;
|
||||
for (int i = 0; i < Description.Length; i++)
|
||||
{
|
||||
if (sum < index) sum += Description[i];
|
||||
else if (sum == index) output = Memory[i];
|
||||
else output = Memory[i - 1];
|
||||
}
|
||||
storageUsing.ReleaseMutex();
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,55 +0,0 @@
|
||||
<?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>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<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>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Color.cs" />
|
||||
<Compile Include="CompressedArray.cs" />
|
||||
<Compile Include="Dtsod.cs" />
|
||||
<Compile Include="cs9somefix.cs" />
|
||||
<Compile Include="FileWork.cs" />
|
||||
<Compile Include="ColoredConsole.cs" />
|
||||
<Compile Include="PublicLog.cs" />
|
||||
<Compile Include="NetWork.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Hasher.cs" />
|
||||
<Compile Include="SecureRandom.cs" />
|
||||
<Compile Include="SimpleConverter.cs" />
|
||||
<Compile Include="TImer.cs" />
|
||||
<Compile Include="XXHash.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@ -1,174 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// это как json но не совсем
|
||||
//
|
||||
public class Dtsod
|
||||
{
|
||||
string Text;
|
||||
public Dictionary<string, dynamic> Values { get; }
|
||||
public Dtsod(string text)
|
||||
{
|
||||
Text = text;
|
||||
Values = Parse(text);
|
||||
}
|
||||
|
||||
// выдаёт Exception
|
||||
public dynamic this[string key]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (TryGet(key, out dynamic value)) return value;
|
||||
else throw new Exception($"Dtsod[{key}] key not found");
|
||||
}
|
||||
}
|
||||
|
||||
// не выдаёт KeyNotFoundException
|
||||
public bool TryGet(string key, out dynamic value)
|
||||
{
|
||||
try
|
||||
{
|
||||
value = Values[key];
|
||||
return true;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
//PublicLog.Log("y", $"key {key} not found\n");
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString() => Text;
|
||||
|
||||
|
||||
Dictionary<string, dynamic> Parse(string text)
|
||||
{
|
||||
Dictionary<string, dynamic> output = new();
|
||||
StringBuilder nameStrB = new();
|
||||
StringBuilder valStrB = new();
|
||||
dynamic value = null;
|
||||
bool readValue = false;
|
||||
bool readString = false;
|
||||
bool readListElem = false;
|
||||
bool isList = false;
|
||||
|
||||
dynamic StringToElse(string str)
|
||||
{
|
||||
if (readString) return str;
|
||||
//PublicLog.Log("m", $"value: <{value}>\n");
|
||||
// bool
|
||||
if (str == "true") return true;
|
||||
else if (str == "false") return false;
|
||||
// double
|
||||
else if (str.Contains(".")) return SimpleConverter.ToDouble(str);
|
||||
// ushort, uint, ulong
|
||||
else if (str.Length > 2 && str[str.Length - 2] == 'u')
|
||||
return str[str.Length - 1] switch
|
||||
{
|
||||
's' => SimpleConverter.ToUShort(str.Remove(str.Length - 2)),
|
||||
'i' => SimpleConverter.ToUInt(str.Remove(str.Length - 2)),
|
||||
'l' => SimpleConverter.ToULong(str.Remove(str.Length - 2)),
|
||||
_ => throw new Exception($"ParseConfig() error: unknown data type <u{str[str.Length - 1]}>"),
|
||||
};
|
||||
// short, int, long
|
||||
else return str[str.Length - 1] switch
|
||||
{
|
||||
's' => SimpleConverter.ToShort(str.Remove(str.Length - 1)),
|
||||
'l' => SimpleConverter.ToLong(str.Remove(str.Length - 1)),
|
||||
_ => SimpleConverter.ToInt(str),
|
||||
};
|
||||
}
|
||||
|
||||
for (int i = 0; i < text.Length; i++)
|
||||
{
|
||||
switch (text[i])
|
||||
{
|
||||
case '{':
|
||||
i++;
|
||||
for (; text[i] != '}'; i++) valStrB.Append(text[i]);
|
||||
value = Parse(valStrB.ToString());
|
||||
valStrB.Clear();
|
||||
break;
|
||||
case '}':
|
||||
throw new Exception("ParseConfig() error: unexpected '}' at " + i + "char");
|
||||
case '<':
|
||||
readString = true;
|
||||
short balance = 1;
|
||||
while (balance != 0)
|
||||
{
|
||||
i++;
|
||||
if (text[i] == '>') balance--;
|
||||
else if (text[i] == '<') balance++;
|
||||
valStrB.Append(text[i]);
|
||||
}
|
||||
valStrB.Remove(valStrB.Length - 1, 1);
|
||||
break;
|
||||
case '"':
|
||||
readString = true;
|
||||
while (text[i] != '"' && text[i--] != '\\')
|
||||
{
|
||||
i++;
|
||||
valStrB.Append(text[i]);
|
||||
}
|
||||
break;
|
||||
case ':':
|
||||
readValue = true;
|
||||
break;
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case '[':
|
||||
isList = true;
|
||||
value = new List<dynamic>();
|
||||
break;
|
||||
case ',':
|
||||
case ']':
|
||||
if (isList) value.Add(StringToElse(valStrB.ToString()));
|
||||
else throw new Exception($"unexpected {text[i]}");
|
||||
valStrB.Clear();
|
||||
break;
|
||||
case ';':
|
||||
// конвертация value в нужный тип данных
|
||||
if (!isList) value = StringToElse(valStrB.ToString());
|
||||
if (readListElem)
|
||||
{
|
||||
if (!output.ContainsKey(nameStrB.ToString())) output.Add(nameStrB.ToString(), new List<dynamic>());
|
||||
output[nameStrB.ToString()].Add(value);
|
||||
}
|
||||
else output.Add(nameStrB.ToString(), value);
|
||||
nameStrB.Clear();
|
||||
valStrB.Clear();
|
||||
value = null;
|
||||
readValue = false;
|
||||
readString = false;
|
||||
readListElem = false;
|
||||
isList = false;
|
||||
break;
|
||||
// коммент
|
||||
case '#':
|
||||
for (; i < text.Length && text[i] != '\n'; i++) ;
|
||||
break;
|
||||
// если $ перед названием параметра поставить, значение (value) добавится в лист с таким названием (nameStrB.ToString())
|
||||
case '$':
|
||||
if (nameStrB.ToString().Length != 0) throw new Exception("unexpected usage of '$' at char " + i.ToString());
|
||||
readListElem = true;
|
||||
break;
|
||||
default:
|
||||
if (readValue) valStrB.Append(text[i]);
|
||||
else nameStrB.Append(text[i]);
|
||||
break;
|
||||
};
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@ -1,202 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// методы для работы с файловой системой
|
||||
//
|
||||
public static class FileWork
|
||||
{
|
||||
// записывает текст в файл и закрывает файл
|
||||
public static void Log(string logfile, string msg)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
if (logfile.Contains("\\")) DirCreate(logfile.Remove(logfile.LastIndexOf('\\')));
|
||||
var st = File.Open(logfile, FileMode.Append);
|
||||
var writer = new StreamWriter(st, SimpleConverter.UTF8);
|
||||
writer.Write(msg);
|
||||
writer.Close();
|
||||
st.Close();
|
||||
}
|
||||
}
|
||||
|
||||
// создает папку если её не существует
|
||||
public static void DirCreate(string dir)
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
// проверяет существование папки, в которой нужно создать dir
|
||||
if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
|
||||
DirCreate(dir.Remove(dir.LastIndexOf('\\')));
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
}
|
||||
|
||||
// создаёт файл, сохдаёт папки из его пути
|
||||
public static void FileCreate(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
if (path.Contains("\\")) DirCreate(path.Remove(path.LastIndexOf('\\')));
|
||||
using var s = File.Create(path);
|
||||
s.Close();
|
||||
}
|
||||
}
|
||||
|
||||
// чтение параметров из конфига
|
||||
public static string ReadFromConfig(string configfile, string key)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
key += ": ";
|
||||
using var reader = new StreamReader(configfile);
|
||||
while (!reader.EndOfStream)
|
||||
{
|
||||
string st = reader.ReadLine();
|
||||
if (st.StartsWith(key))
|
||||
{
|
||||
string value = "";
|
||||
for (int i = key.Length; i < st.Length; i++)
|
||||
{
|
||||
if (st[i] == '#') return value;
|
||||
if (st[i] == '%')
|
||||
{
|
||||
bool stop = false;
|
||||
string placeholder = "";
|
||||
i++;
|
||||
while (!stop)
|
||||
{
|
||||
if (st[i] == '%')
|
||||
{
|
||||
stop = true;
|
||||
value += ReadFromConfig(configfile, placeholder);
|
||||
}
|
||||
else
|
||||
{
|
||||
placeholder += st[i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else value += st[i];
|
||||
}
|
||||
reader.Close();
|
||||
//if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
reader.Close();
|
||||
throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
|
||||
}
|
||||
}
|
||||
|
||||
// копирует все файли и папки
|
||||
public static void DirCopy(string source_dir, string new_dir, bool Override)
|
||||
{
|
||||
DirCreate(new_dir);
|
||||
List<string> subdirs = new List<string>();
|
||||
List<string> files = GetAllFiles(source_dir, ref subdirs);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
{
|
||||
DirCreate(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, Override);
|
||||
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
|
||||
}
|
||||
}
|
||||
|
||||
// копирует все файли и папки и выдаёт список конфликтующих файлов
|
||||
public static void DirCopy(string source_dir, string new_dir, bool owerwrite, out List<string> conflicts)
|
||||
{
|
||||
conflicts = new List<string>();
|
||||
var subdirs = new List<string>();
|
||||
var files = GetAllFiles(source_dir, ref subdirs);
|
||||
DirCreate(new_dir);
|
||||
for (int i = 0; i < subdirs.Count; i++)
|
||||
{
|
||||
DirCreate(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'" });
|
||||
}
|
||||
}
|
||||
|
||||
// выдает список всех файлов
|
||||
public static List<string> GetAllFiles(string dir)
|
||||
{
|
||||
List<string> 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;
|
||||
}
|
||||
|
||||
// выдает список всех файлов и подпапок в папке
|
||||
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
|
||||
{
|
||||
List<string> 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;
|
||||
}
|
||||
|
||||
// удаляет папку со всеми подпапками и файлами
|
||||
public static void DirDelete(string dir)
|
||||
{
|
||||
var subdirs = new List<string>();
|
||||
var files = GetAllFiles(dir, ref subdirs);
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
File.Delete(files[i]);
|
||||
for (int i = subdirs.Count - 1; i >= 0; i--)
|
||||
Directory.Delete(subdirs[i]);
|
||||
Directory.Delete(dir);
|
||||
}
|
||||
|
||||
// вычисляет и записывает в manifest.dtsod хеши файлов из files_list.dtsod
|
||||
public static void CreateManifest(string dir)
|
||||
{
|
||||
if (!dir.EndsWith("\\")) dir += "\\";
|
||||
var dtsod = new Dtsod(File.ReadAllText(dir + "files_list.dtsod"));
|
||||
System.Text.StringBuilder manifestBuilder = new();
|
||||
Hasher hasher = new();
|
||||
for (int i = 0; i < dtsod["files"].Count; i++)
|
||||
{
|
||||
manifestBuilder.Append(dtsod["files"][i]);
|
||||
manifestBuilder.Append(": \"");
|
||||
byte[] hash = hasher.HashFile(dir + dtsod["files"][i]);
|
||||
manifestBuilder.Append(hash.HashToString());
|
||||
manifestBuilder.Append("\";\n");
|
||||
}
|
||||
File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,61 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
|
||||
//
|
||||
public class Hasher
|
||||
{
|
||||
readonly HashAlgorithm sha256 = SHA256.Create();
|
||||
readonly HashAlgorithm xxh32 = XXHash32.Create();
|
||||
|
||||
public Hasher() { }
|
||||
|
||||
// хеш массива
|
||||
public byte[] Hash(byte[] input)
|
||||
=> sha256.ComputeHash(input);
|
||||
|
||||
// хеш из двух массивов
|
||||
public byte[] Hash(byte[] input, byte[] salt)
|
||||
{
|
||||
List<byte> rez = new List<byte>();
|
||||
rez.AddRange(input);
|
||||
rez.AddRange(salt);
|
||||
return sha256.ComputeHash(rez.ToArray());
|
||||
}
|
||||
|
||||
// хеш двух массивов зацикленный
|
||||
public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
|
||||
{
|
||||
for (uint i = 0; i < cycles; i++)
|
||||
{
|
||||
input = Hash(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)
|
||||
{
|
||||
using var fileStream = File.OpenRead(filename);
|
||||
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
|
||||
var 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");
|
||||
fileStream.Close();
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,180 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static DTLib.PublicLog;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// весь униврсальный неткод тут
|
||||
// большинство методов предназначены для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
|
||||
//
|
||||
public static class NetWork
|
||||
{
|
||||
// скачивание файла с фтп сервера
|
||||
public static 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'); }
|
||||
}
|
||||
|
||||
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
|
||||
public static 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);
|
||||
}
|
||||
|
||||
// скачивает файл с помощью FSP протокола
|
||||
public static void FSP_Download(this Socket mainSocket, string filePath_server, string filePath_client)
|
||||
{
|
||||
FileWork.FileCreate(filePath_client);
|
||||
using var fileStream = File.OpenWrite(filePath_client);
|
||||
mainSocket.SendPackage("requesting file download".ToBytes());
|
||||
Log("c", $"requesting file download: {filePath_server}\n");
|
||||
mainSocket.SendPackage(filePath_server.ToBytes());
|
||||
var fileSize = Convert.ToUInt32(mainSocket.GetPackage().ToStr());
|
||||
var hashstr = mainSocket.GetPackage().HashToString();
|
||||
mainSocket.SendPackage("ready".ToBytes());
|
||||
int packagesCount = 0;
|
||||
byte[] buffer = new byte[5120];
|
||||
int fullPackagesCount = SimpleConverter.Truncate(fileSize / buffer.Length);
|
||||
// рассчёт скорости
|
||||
int seconds = 0;
|
||||
var speedCounter = new Timer(true, 1000, () =>
|
||||
{
|
||||
seconds++;
|
||||
Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
|
||||
});
|
||||
// получение файла
|
||||
for (; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
buffer = mainSocket.GetPackage();
|
||||
fileStream.Write(buffer, 0, buffer.Length);
|
||||
fileStream.Flush();
|
||||
}
|
||||
speedCounter.Stop();
|
||||
// получение остатка
|
||||
mainSocket.SendPackage("remain request".ToBytes());
|
||||
buffer = mainSocket.GetPackage();
|
||||
fileStream.Write(buffer, 0, buffer.Length);
|
||||
fileStream.Flush();
|
||||
fileStream.Close();
|
||||
Log(new string[] { "g", $" downloaded {packagesCount * 5120 + buffer.Length} of {fileSize} bytes\n" });
|
||||
|
||||
}
|
||||
|
||||
// отдаёт файл с помощью FSP протокола
|
||||
public static void FSP_Upload(this Socket mainSocket, string filePath)
|
||||
{
|
||||
using var fileStream = File.OpenRead(filePath);
|
||||
Log("b", $"uploading file {filePath}\n");
|
||||
var fileSize = new FileInfo(filePath).Length;
|
||||
var fileHash = new Hasher().HashFile(filePath);
|
||||
mainSocket.SendPackage(fileSize.ToString().ToBytes());
|
||||
mainSocket.SendPackage(fileHash);
|
||||
if (mainSocket.GetPackage().ToStr() != "ready") throw new Exception("user socket isn't ready");
|
||||
byte[] buffer = new byte[5120];
|
||||
var hashstr = fileHash.HashToString();
|
||||
int packagesCount = 0;
|
||||
int seconds = 0;
|
||||
// рассчёт скорости
|
||||
var speedCounter = new Timer(true, 1000, () =>
|
||||
{
|
||||
seconds++;
|
||||
Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
|
||||
});
|
||||
// отправка файла
|
||||
int fullPackagesCount = SimpleConverter.Truncate(fileSize / buffer.Length);
|
||||
for (; packagesCount < fullPackagesCount; packagesCount++)
|
||||
{
|
||||
fileStream.Read(buffer, 0, buffer.Length);
|
||||
mainSocket.SendPackage(buffer);
|
||||
}
|
||||
speedCounter.Stop();
|
||||
// досылка остатка
|
||||
if (mainSocket.GetPackage().ToStr() != "remain request")
|
||||
throw new Exception("FSP_Upload() error: didn't get remain request");
|
||||
buffer = new byte[Convert.ToInt32(fileSize - fileStream.Position)];
|
||||
fileStream.Read(buffer, 0, buffer.Length);
|
||||
mainSocket.SendPackage(buffer);
|
||||
fileStream.Close();
|
||||
Log(new string[] { "g", $" uploaded {packagesCount * 5120 + buffer.Length} of {fileSize} bytes\n" });
|
||||
|
||||
}
|
||||
|
||||
// ждёт пакет заданного размера с заданным началом и концом
|
||||
public static byte[] GetPackage(this Socket socket)
|
||||
{
|
||||
int packageSize = 0;
|
||||
byte[] data = new byte[2];
|
||||
// цикл выполняется пока не пройдёт 1000 мс
|
||||
for (ushort s = 0; s < 200; s += 1)
|
||||
{
|
||||
if (packageSize == 0 && socket.Available >= 2)
|
||||
{
|
||||
socket.Receive(data, data.Length, 0);
|
||||
packageSize = data.BytesToInt();
|
||||
|
||||
}
|
||||
if (packageSize != 0 && socket.Available >= packageSize)
|
||||
{
|
||||
data = new byte[packageSize];
|
||||
socket.Receive(data, data.Length, 0);
|
||||
return data;
|
||||
}
|
||||
else Thread.Sleep(5);
|
||||
}
|
||||
throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}\n");
|
||||
}
|
||||
|
||||
// отправляет пакет заданного размера, добавля в конец нули если длина data меньше чем packageSize
|
||||
public static void SendPackage(this Socket socket, byte[] data)
|
||||
{
|
||||
if (data.Length > 65536) throw new Exception($"SendPackage() error: package is too big ({data.Length} bytes)");
|
||||
if (data.Length == 0) throw new Exception($"SendPackage() error: package has zero size");
|
||||
var list = new List<byte>();
|
||||
byte[] packageSize = data.Length.IntToBytes();
|
||||
if (packageSize.Length == 1) list.Add(0);
|
||||
list.AddRange(packageSize);
|
||||
list.AddRange(data);
|
||||
socket.Send(list.ToArray());
|
||||
}
|
||||
|
||||
// получает с сайта публичный ip
|
||||
public static string GetPublicIP() => new WebClient().DownloadString("https://ipv4bot.whatismyipaddress.com/");
|
||||
}
|
||||
}
|
||||
@ -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")]
|
||||
@ -1,16 +0,0 @@
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// вывод логов со всех классов в библиотеке
|
||||
//
|
||||
public static class PublicLog
|
||||
{
|
||||
public delegate void LogDelegate(string[] msg);
|
||||
// вот к этому объекту подключайте методы для вывода логов
|
||||
public static LogDelegate LogDel;
|
||||
|
||||
// этот метод вызывается в библиотеке
|
||||
public static void Log(params string[] msg)
|
||||
=> LogDel(msg);
|
||||
}
|
||||
}
|
||||
@ -1,37 +0,0 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// Вычисление псевдослучайного числа из множества параметров.
|
||||
// Работает медленнее чем класс System.Random, но выдаёт более случайные значения
|
||||
//
|
||||
public class SecureRandom
|
||||
{
|
||||
private RNGCryptoServiceProvider crypt = new();
|
||||
|
||||
// получение массива случайных байтов
|
||||
public byte[] GenBytes(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;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
@ -1,161 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// содержит методы расширения для различных операций и преобразований
|
||||
//
|
||||
public static class SimpleConverter
|
||||
{
|
||||
public static Encoding UTF8 = new UTF8Encoding(false);
|
||||
// байты в кодировке UTF8 в строку
|
||||
public static string ToStr(this byte[] bytes) => UTF8.GetString(bytes);
|
||||
public static string ToStr(this List<byte> bytes) => UTF8.GetString(bytes.ToArray());
|
||||
|
||||
// хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
|
||||
public static 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();
|
||||
}
|
||||
|
||||
// строку в байты
|
||||
public static byte[] ToBytes(this string str) => UTF8.GetBytes(str);
|
||||
|
||||
// эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
|
||||
public static bool StartsWith(this byte[] source, byte[] startsWith)
|
||||
{
|
||||
for (int i = 0; i < startsWith.Length; i++)
|
||||
{
|
||||
if (source[i] != startsWith[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static 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;
|
||||
}
|
||||
|
||||
// Math.Truncate принимает как decimal, так и doublе,
|
||||
// из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
|
||||
public static int Truncate(this double number) => Convert.ToInt32(Math.Truncate(number));
|
||||
|
||||
// сортирует в порядке возрастания элементы если это возможно, используя стандартный метод list.Sort();
|
||||
public static T[] Sort<T>(this T[] array)
|
||||
{
|
||||
var list = array.ToList();
|
||||
list.Sort();
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
// массив в лист
|
||||
public static List<T> ToList<T>(this T[] input)
|
||||
{
|
||||
var list = new List<T>();
|
||||
list.AddRange(input);
|
||||
return list;
|
||||
}
|
||||
|
||||
// удаление нескольких элементов массива
|
||||
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
|
||||
{
|
||||
List<T> list = input.ToList();
|
||||
list.RemoveRange(startIndex, count);
|
||||
return list.ToArray();
|
||||
}
|
||||
public static T[] RemoveRange<T>(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length - startIndex);
|
||||
|
||||
// метод как у листов
|
||||
public static bool Contains<T>(this T[] array, T value)
|
||||
{
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
if (array[i].Equals(value)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// конвертирует массив в строку
|
||||
public static string MergeToString<T>(this T[] array, string separator)
|
||||
{
|
||||
var b = new StringBuilder();
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
b.Append(array[i].ToString());
|
||||
b.Append(separator);
|
||||
}
|
||||
return b.ToString();
|
||||
}
|
||||
public static string MergeToString<T>(this List<T> list, string separator)
|
||||
{
|
||||
var b = new StringBuilder();
|
||||
b.Append(list[0].ToString());
|
||||
for (int i = 1; i < list.Count; i++)
|
||||
{
|
||||
b.Append(separator);
|
||||
b.Append(list[i].ToString());
|
||||
}
|
||||
return b.ToString();
|
||||
}
|
||||
|
||||
// сокращение конвертации
|
||||
public static int ToInt<T>(this T input) => Convert.ToInt32(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 ulong ToULong<T>(this T input) => Convert.ToUInt64(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 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 sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
|
||||
public static bool ToBool<T>(this T input) => Convert.ToBoolean(input);
|
||||
|
||||
public static string AutoBuild(params object[] parts)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
for (int i = 0; i < parts.Length; i++)
|
||||
builder.Append(parts[i]);
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
public static int BytesToInt(this byte[] bytes)
|
||||
{
|
||||
int output = 0;
|
||||
for (ushort i = 0; i < bytes.Length; i++) output = output * 256 + bytes[i];
|
||||
return output;
|
||||
}
|
||||
|
||||
public static byte[] IntToBytes(this int num)
|
||||
{
|
||||
List<byte> output = new();
|
||||
while (num != 0)
|
||||
{
|
||||
output.Add(ToByte(num % 256));
|
||||
num = Truncate(num / 256);
|
||||
}
|
||||
output.Reverse();
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
public static string ToString<T>(this IEnumerable<T> collection, string separator)
|
||||
{
|
||||
StringBuilder builder = new();
|
||||
foreach (T elem in collection)
|
||||
{
|
||||
builder.Append(elem.ToString());
|
||||
builder.Append(separator);
|
||||
}
|
||||
builder.Remove(builder.Length - separator.Length, separator.Length);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
|
||||
//
|
||||
public class Timer
|
||||
{
|
||||
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;
|
||||
TimerThread.Abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,180 +0,0 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
namespace DTLib
|
||||
{
|
||||
//
|
||||
// честно взятый с гитхаба алгоритм хеширования
|
||||
// выдаёт хеш в виде массива четырёх байтов
|
||||
//
|
||||
sealed class XXHash32 : HashAlgorithm
|
||||
{
|
||||
private const uint PRIME32_1 = 2654435761U;
|
||||
private const uint PRIME32_2 = 2246822519U;
|
||||
private const uint PRIME32_3 = 3266489917U;
|
||||
private const uint PRIME32_4 = 668265263U;
|
||||
private const uint PRIME32_5 = 374761393U;
|
||||
private static readonly Func<byte[], int, uint> FuncGetLittleEndianUInt32;
|
||||
private static readonly Func<uint, uint> FuncGetFinalHashUInt32;
|
||||
private uint _Seed32;
|
||||
private uint _ACC32_1;
|
||||
private uint _ACC32_2;
|
||||
private uint _ACC32_3;
|
||||
private uint _ACC32_4;
|
||||
private uint _Hash32;
|
||||
private int _RemainingLength;
|
||||
private long _TotalLength = 0;
|
||||
private int _CurrentIndex;
|
||||
private byte[] _CurrentArray;
|
||||
|
||||
static XXHash32()
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return *(uint*)(array + i);
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
|
||||
}
|
||||
else
|
||||
{
|
||||
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* array = x)
|
||||
{
|
||||
return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
|
||||
}
|
||||
}
|
||||
});
|
||||
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => i);
|
||||
}
|
||||
}
|
||||
|
||||
// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
|
||||
// <returns></returns>
|
||||
public static new XXHash32 Create() => new XXHash32();
|
||||
|
||||
// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
|
||||
public XXHash32() => Initialize(0);
|
||||
|
||||
// Initializes a new instance of the <see cref="XXHash32"/> class, and sets the <see cref="Seed"/> to the specified value.
|
||||
// <param name="seed">Represent the seed to be used for xxHash32 computing.</param>
|
||||
public XXHash32(uint seed) => Initialize(seed);
|
||||
|
||||
// Gets the <see cref="uint"/> value of the computed hash code.
|
||||
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint HashUInt32 => State == 0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
|
||||
// Gets or sets the value of seed used by xxHash32 algorithm.
|
||||
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
|
||||
public uint Seed
|
||||
{
|
||||
get => _Seed32;
|
||||
set
|
||||
{
|
||||
if (value != _Seed32)
|
||||
{
|
||||
if (State != 0) throw new InvalidOperationException("Hash computation has not yet completed.");
|
||||
_Seed32 = value;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initializes this instance for new hash computing.
|
||||
public override void Initialize()
|
||||
{
|
||||
_ACC32_1 = _Seed32 + PRIME32_1 + PRIME32_2;
|
||||
_ACC32_2 = _Seed32 + PRIME32_2;
|
||||
_ACC32_3 = _Seed32 + 0;
|
||||
_ACC32_4 = _Seed32 - PRIME32_1;
|
||||
}
|
||||
|
||||
// Routes data written to the object into the hash algorithm for computing the hash.
|
||||
// <param name="array">The input to compute the hash code for.</param>
|
||||
// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
|
||||
// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
|
||||
protected override void HashCore(byte[] array, int ibStart, int cbSize)
|
||||
{
|
||||
if (State != 1) State = 1;
|
||||
var size = cbSize - ibStart;
|
||||
_RemainingLength = size & 15;
|
||||
if (cbSize >= 16)
|
||||
{
|
||||
var limit = size - _RemainingLength;
|
||||
do
|
||||
{
|
||||
_ACC32_1 = Round32(_ACC32_1, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
_ACC32_2 = Round32(_ACC32_2, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
_ACC32_3 = Round32(_ACC32_3, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
_ACC32_4 = Round32(_ACC32_4, FuncGetLittleEndianUInt32(array, ibStart));
|
||||
ibStart += 4;
|
||||
} while (ibStart < limit);
|
||||
}
|
||||
_TotalLength += cbSize;
|
||||
if (_RemainingLength != 0)
|
||||
{
|
||||
_CurrentArray = array;
|
||||
_CurrentIndex = ibStart;
|
||||
}
|
||||
}
|
||||
|
||||
// Finalizes the hash computation after the last data is processed by the cryptographic stream object.
|
||||
// <returns>The computed hash code.</returns>
|
||||
protected override byte[] HashFinal()
|
||||
{
|
||||
if (_TotalLength >= 16)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_ACC32_1, 1) + RotateLeft32(_ACC32_2, 7) + RotateLeft32(_ACC32_3, 12) + RotateLeft32(_ACC32_4, 18);
|
||||
}
|
||||
else
|
||||
{
|
||||
_Hash32 = _Seed32 + PRIME32_5;
|
||||
}
|
||||
_Hash32 += (uint)_TotalLength;
|
||||
while (_RemainingLength >= 4)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
|
||||
_CurrentIndex += 4;
|
||||
_RemainingLength -= 4;
|
||||
}
|
||||
unsafe
|
||||
{
|
||||
fixed (byte* arrayPtr = _CurrentArray)
|
||||
{
|
||||
while (_RemainingLength-- >= 1)
|
||||
{
|
||||
_Hash32 = RotateLeft32(_Hash32 + arrayPtr[_CurrentIndex++] * PRIME32_5, 11) * PRIME32_1;
|
||||
}
|
||||
}
|
||||
}
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 15)) * PRIME32_2;
|
||||
_Hash32 = (_Hash32 ^ (_Hash32 >> 13)) * PRIME32_3;
|
||||
_Hash32 ^= _Hash32 >> 16;
|
||||
_TotalLength = State = 0;
|
||||
return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
|
||||
}
|
||||
|
||||
private static uint Round32(uint input, uint value) => RotateLeft32(input + (value * PRIME32_2), 13) * PRIME32_1;
|
||||
|
||||
private static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
|
||||
|
||||
private void Initialize(uint seed)
|
||||
{
|
||||
HashSizeValue = 32;
|
||||
_Seed32 = seed;
|
||||
Initialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
// включает init и record из c# 9.0
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace System.Runtime.CompilerServices
|
||||
{
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
internal class IsExternalInit { }
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
|
||||
</startup>
|
||||
</configuration>
|
||||
@ -1,165 +0,0 @@
|
||||
<Application x:Class="dtlauncher_client_win.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:dtlauncher_client_win">
|
||||
<Application.Resources>
|
||||
<ControlTemplate x:Key="myScrollBar" TargetType="{x:Type ScrollBar}">
|
||||
<Grid x:Name="Bg" SnapsToDevicePixels="True">
|
||||
<Border BorderBrush="Transparent" BorderThickness="0"
|
||||
Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" Grid.Row="1"/>
|
||||
<Track x:Name="PART_Track" IsDirectionReversed="True" IsEnabled="{TemplateBinding IsMouseOver}" Grid.Row="1">
|
||||
<Track.Thumb>
|
||||
<Thumb>
|
||||
<Thumb.Style>
|
||||
<Style TargetType="{x:Type Thumb}">
|
||||
<Setter Property="OverridesDefaultStyle" Value="True"/>
|
||||
<Setter Property="IsTabStop" Value="False"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="{x:Type Thumb}">
|
||||
<Border x:Name="rectangle" CornerRadius="2" Background="#FF9A9FC5" Height="{TemplateBinding Height}" SnapsToDevicePixels="True" Width="{TemplateBinding Width}"/>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Background" TargetName="rectangle" Value="#FF9A9FC5"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsDragging" Value="True">
|
||||
<Setter Property="Background" TargetName="rectangle" Value="#FF515ED1"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</Thumb.Style>
|
||||
</Thumb>
|
||||
</Track.Thumb>
|
||||
</Track>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
|
||||
<ControlTemplate x:Key="myScrollViewer" TargetType="{x:Type ScrollViewer}">
|
||||
<Grid x:Name="Grid">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Rectangle x:Name="Corner" Grid.Column="1" Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Grid.Row="1"/>
|
||||
<ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" CanHorizontallyScroll="False" CanVerticallyScroll="False" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Grid.Column="0" Margin="{TemplateBinding Padding}" Grid.Row="0"/>
|
||||
<ScrollBar Template="{DynamicResource myScrollBar}" Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" x:Name="PART_VerticalScrollBar" AutomationProperties.AutomationId="VerticalScrollBar" Cursor="Arrow" Grid.Column="1" Maximum="{TemplateBinding ScrollableHeight}" Minimum="0" Grid.Row="0" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}"/>
|
||||
<ScrollBar Template="{DynamicResource myScrollBar}" Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" x:Name="PART_HorizontalScrollBar" AutomationProperties.AutomationId="HorizontalScrollBar" Cursor="Arrow" Grid.Column="0" Maximum="{TemplateBinding ScrollableWidth}" Minimum="0" Orientation="Horizontal" Grid.Row="1" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}"/>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
|
||||
<ControlTemplate x:Key="myTabControl" TargetType="{x:Type TabControl}">
|
||||
<Grid KeyboardNavigation.TabNavigation="Local">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
<TabPanel
|
||||
Name="HeaderPanel"
|
||||
Grid.Row="0"
|
||||
Panel.ZIndex="1"
|
||||
Margin="0,0,4,0"
|
||||
IsItemsHost="True"
|
||||
KeyboardNavigation.TabIndex="1"
|
||||
Background="Transparent" />
|
||||
<Border
|
||||
Name="Border"
|
||||
Grid.Row="1"
|
||||
Background="Transparent"
|
||||
BorderBrush="Transparent"
|
||||
BorderThickness="0"
|
||||
CornerRadius="2"
|
||||
KeyboardNavigation.TabNavigation="Local"
|
||||
KeyboardNavigation.DirectionalNavigation="Contained"
|
||||
KeyboardNavigation.TabIndex="2" >
|
||||
<ContentPresenter
|
||||
Name="PART_SelectedContentHost"
|
||||
Margin="4"
|
||||
ContentSource="SelectedContent"/>
|
||||
</Border>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Foreground" Value="#FFF0F0F0" />
|
||||
<Setter TargetName="Border" Property="BorderBrush" Value="Transparent" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
|
||||
<ControlTemplate x:Key="myTabItem" TargetType="{x:Type TabItem}">
|
||||
<Grid>
|
||||
<Border
|
||||
x:Name="Border"
|
||||
Margin="0,0,-4,0"
|
||||
Background="#FF4D4D4D"
|
||||
BorderBrush="#FF73C300"
|
||||
BorderThickness="2,2,2,2"
|
||||
CornerRadius="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}" >
|
||||
<ContentPresenter x:Name="ContentSite"
|
||||
VerticalAlignment="Center"
|
||||
HorizontalAlignment="Center"
|
||||
ContentSource="Header"
|
||||
Margin="12,2,12,2"
|
||||
RecognizesAccessKey="True"/>
|
||||
</Border>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter Property="Panel.ZIndex" Value="100" />
|
||||
<Setter TargetName="Border" Property="Background" Value="#FF0A11A2" />
|
||||
<Setter TargetName="Border" Property="BorderThickness" Value="3,3,3,3" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="Border" Property="Background" Value="Transparent" />
|
||||
<Setter TargetName="Border" Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="white" />
|
||||
</Trigger>
|
||||
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
|
||||
<ControlTemplate x:Key="myTextBox" TargetType="{x:Type TextBoxBase}">
|
||||
<Border
|
||||
Name="Border"
|
||||
Padding="2"
|
||||
Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
BorderBrush="Transparent"
|
||||
BorderThickness="1" >
|
||||
<ScrollViewer Margin="0" x:Name="PART_ContentHost" Template="{DynamicResource myScrollViewer}"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="Border" Property="Background" Value="Black"/>
|
||||
<Setter TargetName="Border" Property="BorderBrush" Value="White"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
|
||||
<ControlTemplate x:Key="roundedButton" TargetType="Button">
|
||||
<Border x:Name="Border"
|
||||
Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
BorderBrush="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
BorderThickness="{Binding BorderThickness, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
CornerRadius="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}">
|
||||
<ContentPresenter Margin="2" HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center" RecognizesAccessKey="True"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="true">
|
||||
<Setter TargetName="Border" Property="Background" Value="#FF4E4E59"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="true">
|
||||
<Setter TargetName="Border" Property="Background" Value="#FF38384F"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@ -1,35 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Windows;
|
||||
|
||||
namespace dtlauncher_client_win
|
||||
{
|
||||
/// <summary>
|
||||
/// Логика взаимодействия для App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
base.OnStartup(e);
|
||||
string[] args = e.Args;
|
||||
try
|
||||
{
|
||||
if (args.Length > 0 || args[0] == "updated")
|
||||
{
|
||||
LoginWindow window = new();
|
||||
window.ShowDialog();
|
||||
}
|
||||
else
|
||||
{
|
||||
Process.Start("cmd", "/c timeout 1 && start dtlauncher.exe");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"STARTUP ERROR:\n{ex.Message}\n{ex.Source}");
|
||||
}
|
||||
Current.Shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,98 +0,0 @@
|
||||
<Window x:Class="dtlauncher_client_win.LauncherWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:dtlauncher_client_win"
|
||||
mc:Ignorable="d"
|
||||
Title="LauncherWindow" Icon="dtscript.ico" Width="800" Height="500" MinWidth="800" MinHeight="500" Background="#FF232328">
|
||||
<Grid x:Name="MainGrid">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="10"/>
|
||||
<ColumnDefinition/>
|
||||
<ColumnDefinition Width="10"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="10"/>
|
||||
<RowDefinition Height="40"/>
|
||||
<RowDefinition Height="8"/>
|
||||
<RowDefinition/>
|
||||
<RowDefinition Height="10"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Rectangle Fill="#FF474747" Grid.Row="2" Grid.ColumnSpan="3" Margin="0,5,0,0"/>
|
||||
<Grid Grid.Column="1" Grid.Row="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition/>
|
||||
<ColumnDefinition Width="8"/>
|
||||
<ColumnDefinition/>
|
||||
<ColumnDefinition Width="8"/>
|
||||
<ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button x:Name="HomeButton" Content="Home" FontWeight="Bold" FontFamily="Unispace" FontSize="20"
|
||||
Grid.Column="0" Background="Transparent" Foreground="#FF2CDA11"
|
||||
BorderThickness="3" Template="{DynamicResource roundedButton}" Tag="14"/>
|
||||
<Button x:Name="LogButton" Content="Log" FontWeight="Bold" FontFamily="Unispace" FontSize="20"
|
||||
Grid.Column="2" Background="Transparent" Foreground="#FFF0F0F0"
|
||||
BorderThickness="3" Template="{DynamicResource roundedButton}" Tag="14"/>
|
||||
<Button x:Name="SettingsButton" Content="Settings" FontWeight="Bold" FontFamily="Unispace" FontSize="20"
|
||||
Grid.Column="4" Background="Transparent" Foreground="#FFF0F0F0"
|
||||
BorderThickness="3" Template="{DynamicResource roundedButton}" Tag="14"/>
|
||||
|
||||
</Grid>
|
||||
<Grid x:Name="HomeGrid" Visibility="Visible" Grid.Row="3" Grid.Column="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="240"/>
|
||||
<ColumnDefinition Width="10"/>
|
||||
<ColumnDefinition/>
|
||||
<ColumnDefinition Width="10"/>
|
||||
<ColumnDefinition Width="200"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Rectangle Fill="#FF474747" Grid.Column="1" Margin="3,0,3,-10"/>
|
||||
<Rectangle Fill="#FF474747" Grid.Column="3" Margin="3,0,3,-10"/>
|
||||
<ScrollViewer x:Name="ProgramsScrollViever" Template="{DynamicResource myScrollViewer}"
|
||||
Grid.Column="0" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
|
||||
<StackPanel x:Name="ProgramsPanel">
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
<Image x:Name="BackgroundImage" Grid.Column="2" HorizontalAlignment="Stretch" Stretch="Fill" Margin="0,40,0,0" />
|
||||
<Label x:Name="NameLabel" Grid.Column="2" Grid.Row="0" Margin="0,0,0,361"
|
||||
FontSize="16" FontWeight="Bold" FontFamily="Unispace" Foreground="#FFF0F0F0"/>
|
||||
<Button x:Name="InstallButton" Content="Install" FontWeight="Bold" FontFamily="Unispace" FontSize="17"
|
||||
Grid.Column="2" Background="#FFB97523" Foreground="#FFF0F0F0"
|
||||
BorderThickness="3" Template="{DynamicResource roundedButton}" Tag="14" Margin="0,72,162,0"
|
||||
HorizontalAlignment="Right" Width="123" Height="37" VerticalAlignment="Top"/>
|
||||
<Button x:Name="LaunchButton" Content="Launch" FontWeight="Bold" FontFamily="Unispace" FontSize="17"
|
||||
Grid.Column="2" Background="#FFB97523" Foreground="#FFF0F0F0"
|
||||
BorderThickness="3" Template="{DynamicResource roundedButton}" Tag="14" Margin="0,72,20,0"
|
||||
HorizontalAlignment="Right" Width="123" Height="37" VerticalAlignment="Top"/>
|
||||
<TextBox x:Name="DescriptionBox" Template="{DynamicResource myTextBox}" Opacity="0.8"
|
||||
VerticalScrollBarVisibility="Auto" TextWrapping="Wrap" BorderThickness="0"
|
||||
Background="#FF141419" Foreground="#FFF0F0F0" SelectionBrush="#FF3E759E"
|
||||
FontSize="14" IsReadOnly="True" Grid.Column="2" Grid.Row="0" Margin="0,160,0,0"/>
|
||||
<Border BorderBrush="#FF141419" BorderThickness="1" Grid.Column="2" Grid.Row="0" Margin="0,160,0,0"/>
|
||||
<ScrollViewer x:Name="DownloadsScrollViever" Template="{DynamicResource myScrollViewer}" VerticalContentAlignment="Top"
|
||||
Grid.Column="4" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
|
||||
<StackPanel x:Name="DownloadsPanel">
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
</Grid>
|
||||
<Grid x:Name="LogGrid" Visibility="Hidden" Grid.Row="3" Grid.Column="1">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="34"/>
|
||||
<RowDefinition Height="10*"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Label x:Name="LogfileLabel" Content="logfile" Grid.Column="0" Grid.Row="0"
|
||||
FontSize="20" FontWeight="Bold" FontFamily="Unispace" Foreground="#FFF0F0F0"/>
|
||||
<TextBox x:Name="LogBox" Template="{DynamicResource myTextBox}"
|
||||
VerticalScrollBarVisibility="Auto" TextWrapping="Wrap" BorderThickness="0"
|
||||
Background="#FF141419" Foreground="#FFF0F0F0" SelectionBrush="#FF3E759E"
|
||||
FontSize="14" IsReadOnly="True" Grid.Column="0" Grid.Row="1"/>
|
||||
</Grid>
|
||||
<Grid x:Name="SettingsGrid" Visibility="Hidden" Grid.Row="3" Grid.Column="1">
|
||||
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
@ -1,102 +0,0 @@
|
||||
using DTLib;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Windows;
|
||||
|
||||
namespace dtlauncher_client_win
|
||||
{
|
||||
/// <summary>
|
||||
/// Логика взаимодействия для LauncherWindow.xaml
|
||||
/// </summary>
|
||||
public partial class LauncherWindow : Window
|
||||
{
|
||||
public Socket mainSocket;
|
||||
string logfile;
|
||||
public delegate void LaunchDel();
|
||||
public LaunchDel Launch = () => { };
|
||||
public delegate void InstallDel();
|
||||
public LaunchDel Install = () => { };
|
||||
public ProgramLabel[] programsArray;
|
||||
public int PreviousProgramNum = 0;
|
||||
|
||||
public LauncherWindow(Socket _socket, string _logfile, string _log)
|
||||
{
|
||||
InitializeComponent();
|
||||
try
|
||||
{
|
||||
mainSocket = _socket;
|
||||
logfile = _logfile;
|
||||
LogBox.Text += _log;
|
||||
PublicLog.LogDel += Log;
|
||||
// переключение вкладок кнопками
|
||||
var green = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(44, 220, 17));
|
||||
var white = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
|
||||
HomeButton.Click += (s, e) =>
|
||||
{
|
||||
LogGrid.Visibility = Visibility.Hidden;
|
||||
SettingsGrid.Visibility = Visibility.Hidden;
|
||||
HomeGrid.Visibility = Visibility.Visible;
|
||||
LogButton.Foreground = white;
|
||||
SettingsButton.Foreground = white;
|
||||
HomeButton.Foreground = green;
|
||||
};
|
||||
LogButton.Click += (s, e) =>
|
||||
{
|
||||
HomeGrid.Visibility = Visibility.Hidden;
|
||||
SettingsGrid.Visibility = Visibility.Hidden;
|
||||
LogGrid.Visibility = Visibility.Visible;
|
||||
HomeButton.Foreground = white;
|
||||
SettingsButton.Foreground = white;
|
||||
LogButton.Foreground = green;
|
||||
};
|
||||
SettingsButton.Click += (s, e) =>
|
||||
{
|
||||
HomeGrid.Visibility = Visibility.Hidden;
|
||||
LogGrid.Visibility = Visibility.Hidden;
|
||||
SettingsGrid.Visibility = Visibility.Visible;
|
||||
HomeButton.Foreground = white;
|
||||
LogButton.Foreground = white;
|
||||
SettingsButton.Foreground = green;
|
||||
};
|
||||
// считывание дескрипторов программ
|
||||
var descriptors = Directory.GetFiles("descroptors", "*.desc");
|
||||
programsArray = new ProgramLabel[descriptors.Length];
|
||||
Log(descriptors.Length + " descriptors found\n");
|
||||
for (int i = 0; i < descriptors.Length; i++)
|
||||
{
|
||||
programsArray[i] = new ProgramLabel(descriptors[i], i, this);
|
||||
ProgramsPanel.Children.Add(programsArray[i]);
|
||||
Log(programsArray[i].Text + " added to ProgramsPanel\n");
|
||||
}
|
||||
LaunchButton.Click += (s, e) => Launch();
|
||||
InstallButton.Click += (s, e) => Install();
|
||||
//mainSocket.FSP_Download(new FSP_FileObject("share\\file.arc", "downloads\\file.arc"));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
|
||||
}
|
||||
}
|
||||
|
||||
public void Log(string msg)
|
||||
{
|
||||
|
||||
if (LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
|
||||
FileWork.Log(logfile, msg);
|
||||
LogBox.Text += msg;
|
||||
}
|
||||
|
||||
public void Log(params 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
<Window x:Class="dtlauncher_client_win.LoginWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:dtlauncher_client_win"
|
||||
mc:Ignorable="d"
|
||||
Title="DTLauncher login" Width="500" Height="350" Background="#FF232328" MinWidth="500" MinHeight="350">
|
||||
<Grid ScrollViewer.VerticalScrollBarVisibility="Disabled" Margin="0" MinWidth="492" MinHeight="320">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="1*"/>
|
||||
<ColumnDefinition Width="20*"/>
|
||||
<ColumnDefinition Width="1*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="25*"/>
|
||||
<RowDefinition Height="174*"/>
|
||||
<RowDefinition Height="23*"/>
|
||||
<RowDefinition Height="72*"/>
|
||||
<RowDefinition Height="25*"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Canvas Height="200" Margin="20,14,20,8" Width="450" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.ColumnSpan="3" Grid.RowSpan="3">
|
||||
<TextBox x:Name="LoginBox" HorizontalAlignment="Center" Height="30" TextWrapping="Wrap" Text="" VerticalAlignment="Center" Width="300" RenderTransformOrigin="0.534,-0.193" Background="#FF4B4B5A" Foreground="#FFF0F0F0" SelectionBrush="#FF2E628B" FontSize="17" BorderThickness="2" IsUndoEnabled="False" MaxLength="25" MaxLines="1" BorderBrush="#FFF0F0F0" MinWidth="300" MinHeight="29" Canvas.Left="130" Canvas.Top="21"/>
|
||||
<PasswordBox x:Name="PasswBox" HorizontalAlignment="Center" VerticalAlignment="Center" Width="300" Height="30" FontSize="17" Background="#FF4B4B5A" Foreground="#FFF0F0F0" SelectionBrush="#FF2E628B" MaxLength="25" BorderThickness="2" BorderBrush="#FFF0F0F0" MinWidth="300" MinHeight="30" Canvas.Left="130" Canvas.Top="83"/>
|
||||
<Label Content="login:" HorizontalAlignment="Center" VerticalAlignment="Center" Height="40" Width="90" Foreground="#FFF0F0F0" FontSize="20" FontWeight="Bold" RenderTransformOrigin="0.764,0.578" FontFamily="Unispace" MinWidth="74" MinHeight="40" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Canvas.Left="34" Canvas.Top="17"/>
|
||||
<Label Content="password:" HorizontalAlignment="Center" VerticalAlignment="Center" Height="40" Width="119" Foreground="#FFF0F0F0" FontSize="20" FontWeight="Bold" FontFamily="Unispace" MinHeight="40" MinWidth="111" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Canvas.Left="1" Canvas.Top="77"/>
|
||||
<Button x:Name="RegisterButton" Content="register" Width="117" Height="40" FontSize="20"
|
||||
FontWeight="Bold" Foreground="#FFF0F0F0" Background="#FF383844"
|
||||
FontFamily="Unispace" BorderThickness="3" MinHeight="40" MinWidth="117" HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center" Canvas.Left="71" Canvas.Top="138" Template="{DynamicResource roundedButton}" Tag="10"/>
|
||||
<Button x:Name="LoginButton" Content="login" Width="117" Height="40" FontSize="20" FontWeight="Bold"
|
||||
Foreground="#FFF0F0F0" Background="#FFB97523" FontFamily="Unispace"
|
||||
BorderThickness="3" MinHeight="40" MinWidth="117" HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
Canvas.Left="272" Canvas.Top="138" Template="{DynamicResource roundedButton}" Tag="10"/>
|
||||
</Canvas>
|
||||
<TextBox x:Name="LogBox" Template="{DynamicResource myTextBox}"
|
||||
VerticalScrollBarVisibility="Auto" TextWrapping="Wrap" BorderThickness="0"
|
||||
Background="Transparent" Foreground="#FFF0F0F0" SelectionBrush="#FF3E759E"
|
||||
FontSize="14" IsReadOnly="True" Grid.Column="1" Grid.Row="3"/>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
||||
@ -1,122 +0,0 @@
|
||||
using DTLib;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Windows;
|
||||
|
||||
namespace dtlauncher_client_win
|
||||
{
|
||||
/// <summary>
|
||||
/// Логика взаимодействия для LoginWindow.xaml
|
||||
/// </summary>
|
||||
public partial class LoginWindow : Window
|
||||
{
|
||||
public Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
public string logfile = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
|
||||
|
||||
public LoginWindow()
|
||||
{
|
||||
try
|
||||
{
|
||||
InitializeComponent();
|
||||
FileWork.DirCreate("logs");
|
||||
FileWork.DirCreate("downloads");
|
||||
PublicLog.LogDel += Log;
|
||||
LoginButton.Click += Login;
|
||||
RegisterButton.Click += Register;
|
||||
Closed += CloseWindow;
|
||||
Log("[" + DateTime.Now.ToString() + "]: launcher is starting\n");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
|
||||
}
|
||||
}
|
||||
|
||||
void Log(string msg)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
if (LogBox.Text.Length - 1 >= 0 && LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
|
||||
FileWork.Log(logfile, msg);
|
||||
LogBox.Text += msg;
|
||||
}
|
||||
}
|
||||
|
||||
void Log(params string[] input)
|
||||
{
|
||||
var str = new System.Text.StringBuilder();
|
||||
if (input.Length == 1) str.Append(input[0]);
|
||||
else if (input.Length % 2 == 0) for (ushort i = 0; i < input.Length; i++) str.Append(input[++i]);
|
||||
else throw new Exception("error in Log(): every text string must have color string before");
|
||||
lock (new object())
|
||||
{
|
||||
FileWork.Log(logfile, str.ToString());
|
||||
LogBox.Text += str.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
void Register(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
var hasher = new Hasher();
|
||||
File.WriteAllText($"register-{LoginBox.Text}.req",
|
||||
hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512).HashToString()
|
||||
+ ": " + LoginBox.Text);
|
||||
Log($"request file created:{Directory.GetCurrentDirectory()}\\register-{LoginBox.Text}.req {hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()).Length}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("registration error: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
void Login(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (mainSocket.Connected)
|
||||
{
|
||||
mainSocket.Shutdown(SocketShutdown.Both);
|
||||
mainSocket.Close();
|
||||
mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
}
|
||||
mainSocket.Connect(new IPEndPoint(
|
||||
Dns.GetHostAddresses(FileWork.ReadFromConfig("client.cfg", "central server ip"))[0],
|
||||
FileWork.ReadFromConfig("client.cfg", "central server port").ToInt()));
|
||||
mainSocket.ReceiveTimeout = 2000;
|
||||
string request = mainSocket.GetPackage().ToStr();
|
||||
if (request != "requesting hash") throw new Exception($"Login() error: invalid request <{request}> <{request.Length}>");
|
||||
var hasher = new Hasher();
|
||||
mainSocket.SendPackage(hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512));
|
||||
request = mainSocket.GetPackage().ToStr();
|
||||
if (request != "success") throw new Exception($"Login() error: invalid success message <{request}>");
|
||||
Log("succesfully logined\n");
|
||||
// вызов нового окна
|
||||
var lauWin = new LauncherWindow(mainSocket, logfile, LogBox.Text);
|
||||
lauWin.Show();
|
||||
Hide();
|
||||
PublicLog.LogDel -= Log;
|
||||
lauWin.Closed += CloseWindow;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("login error: " + ex.Message + '\n' + ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
void CloseWindow(object sender, EventArgs e)
|
||||
{
|
||||
if (mainSocket.Connected)
|
||||
{
|
||||
mainSocket.Shutdown(SocketShutdown.Both);
|
||||
mainSocket.Close();
|
||||
}
|
||||
Log("DTchat closed");
|
||||
Close();
|
||||
App.Current.Shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
<UserControl x:Class="dtlauncher_client_win.ProgramLabel"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:dtlauncher_client_win"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="25" d:DesignWidth="140" BorderThickness="0">
|
||||
<UserControl.Template>
|
||||
<ControlTemplate TargetType="UserControl">
|
||||
<ContentPresenter />
|
||||
</ControlTemplate>
|
||||
</UserControl.Template>
|
||||
<Grid x:Name="grid" Background="#FF232328" MouseLeftButtonDown="ProgramShow">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="25"/>
|
||||
<ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Border x:Name="Border" Grid.ColumnSpan="2"
|
||||
Background="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"
|
||||
BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"
|
||||
BorderThickness="{Binding BorderThickness, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"
|
||||
CornerRadius="{Binding CornerRadius, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"/>
|
||||
<Image x:Name="IconImage" Grid.Column="0" Stretch="Fill" Margin="3,2,2,3" Width="20" Height="20"
|
||||
Source="{Binding Icon, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"/>
|
||||
<Label Name="NameLabel" Grid.Column="1" VerticalContentAlignment="Center"
|
||||
Content="{Binding Text, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"
|
||||
FontSize="{Binding FontSize, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"
|
||||
FontFamily="{Binding FontFamily,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"
|
||||
FontWeight="{Binding FontWeight, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"
|
||||
Foreground="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:ProgramLabel}}}"/>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@ -1,115 +0,0 @@
|
||||
using DTLib;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace dtlauncher_client_win
|
||||
{
|
||||
/// <summary>
|
||||
/// Логика взаимодействия для ProgramLabel.xaml
|
||||
/// </summary>
|
||||
public partial class ProgramLabel : UserControl
|
||||
{
|
||||
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ProgramLabel));
|
||||
public string Text
|
||||
{
|
||||
get { return (string)GetValue(TextProperty); }
|
||||
set { SetValue(TextProperty, value); }
|
||||
}
|
||||
|
||||
public static DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(System.Windows.Media.Imaging.BitmapImage), typeof(ProgramLabel));
|
||||
public System.Windows.Media.Imaging.BitmapImage Icon
|
||||
{
|
||||
get { return (System.Windows.Media.Imaging.BitmapImage)GetValue(IconProperty); }
|
||||
set { SetValue(IconProperty, value); }
|
||||
}
|
||||
|
||||
public static DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(ProgramLabel));
|
||||
public CornerRadius CornerRadius
|
||||
{
|
||||
get { return (CornerRadius)GetValue(CornerRadiusProperty); }
|
||||
set { SetValue(CornerRadiusProperty, value); }
|
||||
}
|
||||
|
||||
public string BackgroundImage;
|
||||
public string Script;
|
||||
public string InstallDir;
|
||||
public string LaunchFile;
|
||||
public string Arguments;
|
||||
public string Description;
|
||||
public int Number;
|
||||
LauncherWindow Window;
|
||||
|
||||
public ProgramLabel()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public ProgramLabel(string descriptorPath, int number, LauncherWindow window)
|
||||
{
|
||||
try
|
||||
{
|
||||
InitializeComponent();
|
||||
Window = window;
|
||||
Number = number;
|
||||
FontSize = 14;
|
||||
Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
|
||||
Text = FileWork.ReadFromConfig(descriptorPath, "name");
|
||||
NameLabel.Content = FileWork.ReadFromConfig(descriptorPath, "name");
|
||||
IconImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\descroptors\\" + FileWork.ReadFromConfig(descriptorPath, "icon"), UriKind.Absolute));
|
||||
BackgroundImage = Directory.GetCurrentDirectory() + "\\descroptors\\" + FileWork.ReadFromConfig(descriptorPath, "background");
|
||||
Script = FileWork.ReadFromConfig(descriptorPath, "script");
|
||||
InstallDir = FileWork.ReadFromConfig(descriptorPath, "installdir");
|
||||
LaunchFile = FileWork.ReadFromConfig(descriptorPath, "launchfile");
|
||||
Arguments = FileWork.ReadFromConfig(descriptorPath, "arguments");
|
||||
Description = FileWork.ReadFromConfig(descriptorPath, "description").Replace("\\n", "\n");
|
||||
//Window.Log(Text + " " + Icon + " " + Number);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Window.Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
|
||||
}
|
||||
}
|
||||
|
||||
void ProgramShow(object sender, System.Windows.Input.MouseButtonEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
Window.programsArray[Window.PreviousProgramNum].Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
|
||||
Window.programsArray[Window.PreviousProgramNum].FontWeight = FontWeights.Normal;
|
||||
Window.programsArray[Window.PreviousProgramNum].FontSize = 14;
|
||||
Window.PreviousProgramNum = Number;
|
||||
Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(170, 170, 240));
|
||||
FontWeight = FontWeights.Bold;
|
||||
FontSize = 13;
|
||||
Window.NameLabel.Content = Text;
|
||||
Window.DescriptionBox.Text = Description;
|
||||
Window.BackgroundImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(BackgroundImage, UriKind.Absolute));
|
||||
Window.Launch = () =>
|
||||
{
|
||||
var startInfo = new ProcessStartInfo()
|
||||
{
|
||||
FileName = LaunchFile,
|
||||
Arguments = Arguments,
|
||||
};
|
||||
Process.Start(startInfo);
|
||||
};
|
||||
Window.Install = () =>
|
||||
{
|
||||
var scriptrunner = new DTScript.ScriptRunner
|
||||
{
|
||||
debug = false,
|
||||
mainSocket = Window.mainSocket
|
||||
};
|
||||
scriptrunner.RunScriptFile(Directory.GetCurrentDirectory() + "\\scripts\\" + Script);
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Window.Log("error:\n" + ex.Message + "\n" + ex.StackTrace + '\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,53 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
|
||||
// Общие сведения об этой сборке предоставляются следующим набором
|
||||
// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
|
||||
// связанные со сборкой.
|
||||
[assembly: AssemblyTitle("dtlauncher-client-win")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("dtlauncher-client-win")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2021")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
|
||||
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
|
||||
// из модели COM, установите атрибут ComVisible для этого типа в значение true.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
//Чтобы начать создание локализуемых приложений, задайте
|
||||
//<UICulture>CultureYouAreCodingWith</UICulture> в файле .csproj
|
||||
//в <PropertyGroup>. Например, при использовании английского (США)
|
||||
//в своих исходных файлах установите <UICulture> в en-US. Затем отмените преобразование в комментарий
|
||||
//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
|
||||
//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
|
||||
|
||||
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
|
||||
|
||||
|
||||
[assembly: ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
|
||||
//(используется, если ресурс не найден на странице,
|
||||
// или в словарях ресурсов приложения)
|
||||
ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
|
||||
//(используется, если ресурс не найден на странице,
|
||||
// в приложении или в каких-либо словарях ресурсов для конкретной темы)
|
||||
)]
|
||||
|
||||
|
||||
// Сведения о версии для сборки включают четыре следующих значения:
|
||||
//
|
||||
// Основной номер версии
|
||||
// Дополнительный номер версии
|
||||
// Номер сборки
|
||||
// Номер редакции
|
||||
//
|
||||
// Можно задать все значения или принять номера сборки и редакции по умолчанию
|
||||
// используя "*", как показано ниже:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@ -1,70 +0,0 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// Этот код был создан программным средством.
|
||||
// Версия среды выполнения: 4.0.30319.42000
|
||||
//
|
||||
// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
|
||||
// код создан повторно.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace dtlauncher_client_win.Properties
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
|
||||
/// </summary>
|
||||
// Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
|
||||
// класс с помощью таких средств, как ResGen или Visual Studio.
|
||||
// Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
|
||||
// с параметром /str или заново постройте свой VS-проект.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resources
|
||||
{
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resources()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager
|
||||
{
|
||||
get
|
||||
{
|
||||
if ((resourceMan == null))
|
||||
{
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_client_win.Properties.Resources", typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Переопределяет свойство CurrentUICulture текущего потока для всех
|
||||
/// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture
|
||||
{
|
||||
get
|
||||
{
|
||||
return resourceCulture;
|
||||
}
|
||||
set
|
||||
{
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,117 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
</root>
|
||||
@ -1,29 +0,0 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.42000
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace dtlauncher_client_win.Properties
|
||||
{
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
|
||||
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
|
||||
{
|
||||
|
||||
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
|
||||
|
||||
public static Settings Default
|
||||
{
|
||||
get
|
||||
{
|
||||
return defaultInstance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
|
||||
<Profiles>
|
||||
<Profile Name="(Default)" />
|
||||
</Profiles>
|
||||
<Settings />
|
||||
</SettingsFile>
|
||||
@ -1,129 +0,0 @@
|
||||
<?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>{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}</ProjectGuid>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<RootNamespace>dtlauncher_client_win</RootNamespace>
|
||||
<AssemblyName>dtlauncher-client-win</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>none</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<StartupObject>dtlauncher_client_win.App</StartupObject>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ApplicationIcon>
|
||||
</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xaml">
|
||||
<RequiredTargetFramework>4.0</RequiredTargetFramework>
|
||||
</Reference>
|
||||
<Reference Include="WindowsBase" />
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="PresentationFramework" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ApplicationDefinition Include="App.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<SubType>Designer</SubType>
|
||||
</ApplicationDefinition>
|
||||
<Page Include="LauncherWindow.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
<Page Include="LoginWindow.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<SubType>Designer</SubType>
|
||||
</Page>
|
||||
<Compile Include="App.xaml.cs">
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="LauncherWindow.xaml.cs">
|
||||
<DependentUpon>LauncherWindow.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="LoginWindow.xaml.cs">
|
||||
<DependentUpon>LoginWindow.xaml</DependentUpon>
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Page Include="ProgramLabel.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="ProgramLabel.xaml.cs">
|
||||
<DependentUpon>ProgramLabel.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Properties\AssemblyInfo.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Properties\Resources.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Properties\Settings.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Settings.settings</DependentUpon>
|
||||
<DesignTimeSharedInput>True</DesignTimeSharedInput>
|
||||
</Compile>
|
||||
<EmbeddedResource Include="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
<None Include="Properties\Settings.settings">
|
||||
<Generator>SettingsSingleFileGenerator</Generator>
|
||||
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\DTLib\DTLib.csproj">
|
||||
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
|
||||
<Name>DTLib</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\..\dtscript\dtscript.csproj">
|
||||
<Project>{e02ea967-fd29-47d2-b25b-ba684b784aee}</Project>
|
||||
<Name>dtscript</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Resource Include="dtscript.ico" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>del /f /q dtlauncher-client-win.exe.config
|
||||
copy dtlauncher-client-win.exe C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\dtlauncher-client-win.exe
|
||||
copy client.cfg C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\client.cfg</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 9.4 KiB |
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
|
||||
</startup>
|
||||
</configuration>
|
||||
@ -1,167 +0,0 @@
|
||||
using DTLib;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using static DTLib.NetWork;
|
||||
|
||||
namespace dtlauncher_server
|
||||
{
|
||||
class DtlauncherServer
|
||||
{
|
||||
static readonly string logfile = $"logs\\dtlauncher-server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
|
||||
static readonly Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
static Dtsod config;
|
||||
static readonly Dictionary<Socket, Thread> users = new();
|
||||
|
||||
static void Main()
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.Title = "dtlauncher server";
|
||||
Console.InputEncoding = Encoding.Unicode;
|
||||
Console.OutputEncoding = Encoding.Unicode;
|
||||
PublicLog.LogDel += Log;
|
||||
config = config = new(File.ReadAllText("server.dtsod"));
|
||||
int f = (int)config["server_port"];
|
||||
Log("b", "local address: <", "c", config["server_ip"], "b",
|
||||
">\npublic address: <", "c", GetPublicIP(), "b",
|
||||
">\nport: <", "c", config["server_port"].ToString(), "b", ">\n");
|
||||
mainSocket.Bind(new IPEndPoint(IPAddress.Parse(config["server_ip"]), (int)config["server_port"]));
|
||||
mainSocket.Listen(1000);
|
||||
Log("g", "server started succesfully\n");
|
||||
FileWork.CreateManifest("share\\client\\");
|
||||
Log("g", "client files manifest created\n");
|
||||
//
|
||||
/*DTLib.Timer userCkeckTimer = new(true, 3000, () =>
|
||||
{
|
||||
foreach (Socket usr in users.Keys)
|
||||
{
|
||||
if (usr.)
|
||||
{
|
||||
Log("y", $"closing unused user <{usr.RemoteEndPoint.Serialize()[0]}> thread\n");
|
||||
users[usr].Abort();
|
||||
users.Remove(usr);
|
||||
}
|
||||
}
|
||||
});*/
|
||||
// запуск отдельного потока для каждого юзера
|
||||
while (true)
|
||||
{
|
||||
var userSocket = mainSocket.Accept();
|
||||
var userThread = new Thread(new ParameterizedThreadStart((obj) => UserHandle((Socket)obj)));
|
||||
//users.Add(userSocket, userThread);
|
||||
userThread.Start(userSocket);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("r", $"dtlauncher_server.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
|
||||
mainSocket.Close();
|
||||
}
|
||||
Log("press any key to close... ");
|
||||
Console.ReadKey();
|
||||
Log("gray", "\n");
|
||||
}
|
||||
|
||||
// вывод лога в консоль и файл
|
||||
public static void Log(params string[] msg)
|
||||
{
|
||||
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
|
||||
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
|
||||
LogNoTime(msg);
|
||||
}
|
||||
public static void LogNoTime(params string[] msg)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
if (msg.Length == 1) FileWork.Log(logfile, msg[0]);
|
||||
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
|
||||
else FileWork.Log(logfile, SimpleConverter.AutoBuild(msg));
|
||||
ColoredConsole.Write(msg);
|
||||
}
|
||||
}
|
||||
|
||||
// запускается для каждого юзера в отдельном потоке
|
||||
static void UserHandle(Socket handlerSocket)
|
||||
{
|
||||
Log("b", "user connecting... ");
|
||||
//Socket fspSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
//fspSocket.Bind()
|
||||
try
|
||||
{
|
||||
handlerSocket.SendPackage("requesting hash".ToBytes());
|
||||
var hash = handlerSocket.GetPackage();
|
||||
// запрос от апдейтера
|
||||
if (hash.HashToString() == "ffffffffffffffff")
|
||||
{
|
||||
LogNoTime("c", "client is updater\n");
|
||||
handlerSocket.SendPackage("updater".ToBytes());
|
||||
while (true)
|
||||
{
|
||||
if (handlerSocket.Available >= 2)
|
||||
{
|
||||
var request = handlerSocket.GetPackage().ToStr();
|
||||
switch (request)
|
||||
{
|
||||
case "requesting file download":
|
||||
string filePath = "share\\client\\" + handlerSocket.GetPackage().ToStr();
|
||||
handlerSocket.FSP_Upload(filePath);
|
||||
break;
|
||||
default:
|
||||
throw new Exception("unknown request: " + request);
|
||||
}
|
||||
}
|
||||
else Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
// запрос от лаунчера
|
||||
else
|
||||
{
|
||||
LogNoTime("g", "client is launcher\n");
|
||||
string login;
|
||||
lock (new object())
|
||||
{
|
||||
login = FileWork.ReadFromConfig("users.db", hash.HashToString());
|
||||
}
|
||||
handlerSocket.SendPackage("success".ToBytes());
|
||||
Log("g", $"user <{login}> succesfully logged\n");
|
||||
while (true)
|
||||
{
|
||||
if (handlerSocket.Available >= 64)
|
||||
{
|
||||
var request = handlerSocket.GetPackage().ToStr();
|
||||
switch (request)
|
||||
{
|
||||
// ответ на NetWork.Ping()
|
||||
/*case "ping":
|
||||
handlerSocket.Send("pong".ToBytes());
|
||||
break;*/
|
||||
// отправка списка активных серверов
|
||||
/*case "requesting servers list":
|
||||
|
||||
break;*/
|
||||
case "requesting file download":
|
||||
handlerSocket.FSP_Upload("share\\public\\" + handlerSocket.GetPackage().ToStr());
|
||||
break;
|
||||
default:
|
||||
throw new Exception("unknown request: " + request);
|
||||
}
|
||||
}
|
||||
else Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("y", $"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
|
||||
handlerSocket.Shutdown(SocketShutdown.Both);
|
||||
handlerSocket.Close();
|
||||
Thread.CurrentThread.Abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,53 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
|
||||
// Общие сведения об этой сборке предоставляются следующим набором
|
||||
// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
|
||||
// связанные со сборкой.
|
||||
[assembly: AssemblyTitle("dtlauncher-server-win")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("dtlauncher-server-win")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2021")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
|
||||
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
|
||||
// из модели COM, установите атрибут ComVisible для этого типа в значение true.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
//Чтобы начать создание локализуемых приложений, задайте
|
||||
//<UICulture>CultureYouAreCodingWith</UICulture> в файле .csproj
|
||||
//в <PropertyGroup>. Например, при использовании английского (США)
|
||||
//в своих исходных файлах установите <UICulture> в en-US. Затем отмените преобразование в комментарий
|
||||
//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
|
||||
//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
|
||||
|
||||
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
|
||||
|
||||
|
||||
[assembly: ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
|
||||
//(используется, если ресурс не найден на странице,
|
||||
// или в словарях ресурсов приложения)
|
||||
ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
|
||||
//(используется, если ресурс не найден на странице,
|
||||
// в приложении или в каких-либо словарях ресурсов для конкретной темы)
|
||||
)]
|
||||
|
||||
|
||||
// Сведения о версии для сборки включают четыре следующих значения:
|
||||
//
|
||||
// Основной номер версии
|
||||
// Дополнительный номер версии
|
||||
// Номер сборки
|
||||
// Номер редакции
|
||||
//
|
||||
// Можно задать все значения или принять номера сборки и редакции по умолчанию
|
||||
// используя "*", как показано ниже:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@ -1,70 +0,0 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// Этот код был создан программным средством.
|
||||
// Версия среды выполнения: 4.0.30319.42000
|
||||
//
|
||||
// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
|
||||
// код создан повторно.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace dtlauncher_server_win.Properties
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
|
||||
/// </summary>
|
||||
// Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
|
||||
// класс с помощью таких средств, как ResGen или Visual Studio.
|
||||
// Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
|
||||
// с параметром /str или заново постройте свой VS-проект.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resources
|
||||
{
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resources()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager
|
||||
{
|
||||
get
|
||||
{
|
||||
if ((resourceMan == null))
|
||||
{
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_server_win.Properties.Resources", typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Переопределяет свойство CurrentUICulture текущего потока для всех
|
||||
/// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture
|
||||
{
|
||||
get
|
||||
{
|
||||
return resourceCulture;
|
||||
}
|
||||
set
|
||||
{
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,117 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
</root>
|
||||
@ -1,29 +0,0 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.42000
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
|
||||
namespace dtlauncher_server_win.Properties
|
||||
{
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
|
||||
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
|
||||
{
|
||||
|
||||
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
|
||||
|
||||
public static Settings Default
|
||||
{
|
||||
get
|
||||
{
|
||||
return defaultInstance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
|
||||
<Profiles>
|
||||
<Profile Name="(Default)" />
|
||||
</Profiles>
|
||||
<Settings />
|
||||
</SettingsFile>
|
||||
@ -1,112 +0,0 @@
|
||||
<?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>{8B9889A7-93DC-4914-92D1-8209BD3BA71A}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>dtlauncher_server_win</RootNamespace>
|
||||
<AssemblyName>dtlauncher-server-win</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
<InstallFrom>Disk</InstallFrom>
|
||||
<UpdateEnabled>false</UpdateEnabled>
|
||||
<UpdateMode>Foreground</UpdateMode>
|
||||
<UpdateInterval>7</UpdateInterval>
|
||||
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
|
||||
<UpdatePeriodically>false</UpdatePeriodically>
|
||||
<UpdateRequired>false</UpdateRequired>
|
||||
<MapFileExtensions>true</MapFileExtensions>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>none</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<StartupObject>
|
||||
</StartupObject>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xaml">
|
||||
<RequiredTargetFramework>4.0</RequiredTargetFramework>
|
||||
</Reference>
|
||||
<Reference Include="WindowsBase" />
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="PresentationFramework" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="DtlauncherServer.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Properties\Resources.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Properties\Settings.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Settings.settings</DependentUpon>
|
||||
<DesignTimeSharedInput>True</DesignTimeSharedInput>
|
||||
</Compile>
|
||||
<EmbeddedResource Include="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
<None Include="Properties\Settings.settings">
|
||||
<Generator>SettingsSingleFileGenerator</Generator>
|
||||
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\DTLib\DTLib.csproj">
|
||||
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
|
||||
<Name>DTLib</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include=".NETFramework,Version=v4.8">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>Microsoft .NET Framework 4.8 %28x86 и x64%29</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>del /f /q dtlauncher-server-win.exe.config</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@ -1,44 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30907.101
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client-win", "dtlauncher-client-win\dtlauncher-client-win.csproj", "{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server-win", "dtlauncher-server-win\dtlauncher-server-win.csproj", "{8B9889A7-93DC-4914-92D1-8209BD3BA71A}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtscript", "..\dtscript\dtscript.csproj", "{E02EA967-FD29-47D2-B25B-BA684B784AEE}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "updater", "updater\updater.csproj", "{4784D974-A342-4202-9430-90FE5AC00FC7}"
|
||||
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
|
||||
{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.ActiveCfg = Build|Any CPU
|
||||
{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.Build.0 = Build|Any CPU
|
||||
{8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.ActiveCfg = Build|Any CPU
|
||||
{8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.Build.0 = Build|Any CPU
|
||||
{E02EA967-FD29-47D2-B25B-BA684B784AEE}.Build|Any CPU.ActiveCfg = Build|Any CPU
|
||||
{E02EA967-FD29-47D2-B25B-BA684B784AEE}.Build|Any CPU.Build.0 = Build|Any CPU
|
||||
{4784D974-A342-4202-9430-90FE5AC00FC7}.Build|Any CPU.ActiveCfg = Build|Any CPU
|
||||
{4784D974-A342-4202-9430-90FE5AC00FC7}.Build|Any CPU.Build.0 = Build|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {E6569C0C-DD32-4F7D-AD4C-DBC5434D2F8C}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
|
||||
</startup>
|
||||
</configuration>
|
||||
@ -1,53 +0,0 @@
|
||||
using DTLib;
|
||||
using System;
|
||||
|
||||
namespace DTScript
|
||||
{
|
||||
public class MainClass
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
FileWork.DirCreate("dtscript-logs");
|
||||
PublicLog.LogDel += Log;
|
||||
var scripter = new ScriptRunner();
|
||||
if (args.Length == 0 || args.Length > 2) throw new Exception("enter script file path\n");
|
||||
else if (args.Length == 1) scripter.RunScriptFile(args[0]);
|
||||
else if (args.Length == 2 && args[0] == "-debug")
|
||||
{
|
||||
scripter.debug = true;
|
||||
scripter.Debug("y", "debug is enabled\n");
|
||||
scripter.RunScriptFile(args[1]);
|
||||
}
|
||||
else throw new Exception("unknown args\n");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("r", $"dtscript.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
|
||||
}
|
||||
Log("gray", " \n");
|
||||
}
|
||||
|
||||
// вывод лога в консоль и файл
|
||||
static readonly string logfile = $"dtscript-logs\\dtscript-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
|
||||
|
||||
static void Log(params string[] msg)
|
||||
{
|
||||
if (msg.Length == 1)
|
||||
{
|
||||
msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
|
||||
FileWork.Log(logfile, msg[0]);
|
||||
}
|
||||
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
|
||||
else
|
||||
{
|
||||
msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
|
||||
var str = new System.Text.StringBuilder();
|
||||
for (int i = 0; i < msg.Length; i++) str.Append(msg[++i]);
|
||||
FileWork.Log(logfile, str.ToString());
|
||||
}
|
||||
ColoredConsole.Write(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// Общие сведения об этой сборке предоставляются следующим набором
|
||||
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
|
||||
// связанные с этой сборкой.
|
||||
[assembly: AssemblyTitle("dtscript")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("dtscript")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2020")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
|
||||
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
|
||||
// из модели COM задайте для атрибута ComVisible этого типа значение true.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
|
||||
[assembly: Guid("e02ea967-fd29-47d2-b25b-ba684b784aee")]
|
||||
|
||||
// Сведения о версии сборки состоят из указанных ниже четырех значений:
|
||||
//
|
||||
// Основной номер версии
|
||||
// Дополнительный номер версии
|
||||
// Номер сборки
|
||||
// Номер редакции
|
||||
//
|
||||
// Можно задать все значения или принять номера сборки и редакции по умолчанию
|
||||
// используя "*", как показано ниже:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@ -1,447 +0,0 @@
|
||||
using DTLib;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace DTScript
|
||||
{
|
||||
//
|
||||
// основной класс скриптового интерпретатора
|
||||
//
|
||||
public class ScriptRunner
|
||||
{
|
||||
// выводит текст через DTLib если дебаг включен
|
||||
public bool debug = false;
|
||||
public System.Net.Sockets.Socket mainSocket;
|
||||
internal void Debug(params string[] msg)
|
||||
{
|
||||
if (debug) PublicLog.Log(msg);
|
||||
}
|
||||
|
||||
// cчитывание текста из файла и запуск выполнения
|
||||
public void RunScriptFile(string scriptfile)
|
||||
{
|
||||
Debug("g", @"----\ " + scriptfile + " /----\n");
|
||||
try { Execute(SplitScript(File.ReadAllText(scriptfile))); }
|
||||
catch (Exception e) { PublicLog.Log("r", $"dtscript RunScriptFile() error:\n{e.Message}\n{e.StackTrace}\n", "gray", " \n"); }
|
||||
}
|
||||
|
||||
int globalindex = -1;
|
||||
List<Dictionary<string, object>> Storage = new();
|
||||
|
||||
object GetValue(string key)
|
||||
{
|
||||
Debug("m", "GetValue(", "c", "<", "b", key, "c", ">", "m", ")\n");
|
||||
for (int i = 0; i <= globalindex; i++)
|
||||
if (Storage[i].ContainsKey(key)) return Storage[i][key];
|
||||
throw new Exception($"GetValue() exception: storage doesn't contain key<{key}>");
|
||||
}
|
||||
|
||||
void SetValue(string key, object value)
|
||||
{
|
||||
Debug("m", "SetValue(", "c", "<", "b", key, "c", "> ", "c", "<", "b", value.ToString(), "c", ">", "m", ")\n");
|
||||
for (int i = 0; i <= globalindex; i++)
|
||||
if (Storage[i].ContainsKey(key))
|
||||
{
|
||||
Storage[i][key] = value;
|
||||
Debug(Storage[i][key].ToString());
|
||||
return;
|
||||
}//throw new Exception($"SetValue() exception: storage alredy contains key<{key}>");
|
||||
Storage[globalindex].Add(key, value);
|
||||
}
|
||||
|
||||
dynamic Execute(List<Construction> script)
|
||||
{
|
||||
Debug("y", " executing...\n");
|
||||
// создание локального
|
||||
globalindex++;
|
||||
List<Construction> subscript;
|
||||
Storage.Add(new Dictionary<string, object>());
|
||||
// запуск цикла
|
||||
for (int index = 0; index < script.Count; index++)
|
||||
{
|
||||
if (debug)
|
||||
{
|
||||
PublicLog.Log(new string[] {
|
||||
"y","\noperator: ", "m",script[index].Operator, "y"," options: ", "c", "<", "b", script[index].Options[0], "c", ">"});
|
||||
for (ushort n = 1; n < script[index].Options.Length; n++)
|
||||
PublicLog.Log("w", ", ", "c", "<", "b", script[index].Options[n], "c", ">");
|
||||
PublicLog.Log("\n");
|
||||
}
|
||||
switch (script[index].Operator)
|
||||
{
|
||||
case "return":
|
||||
Debug("g", "script ended");
|
||||
return GetValue(script[index].Options[0]);
|
||||
case "Run":
|
||||
var proc = new Process();
|
||||
proc.StartInfo.FileName = script[index].Options[0].Replace("\"", "");
|
||||
proc.StartInfo.Arguments = script[index].Options[1].Replace("\"", "");
|
||||
if (script[index].Options.Length == 3 && script[index].Options[2] == "true")
|
||||
{
|
||||
proc.StartInfo.CreateNoWindow = true;
|
||||
Debug("g", $"process {script[index].Operator} started in hidden mode\n");
|
||||
}
|
||||
else if (script[index].Options.Length == 3 && script[index].Options[2] == "false")
|
||||
{
|
||||
proc.StartInfo.CreateNoWindow = false;
|
||||
Debug("g", $"process {script[index].Operator} started in not hidden mode\n");
|
||||
}
|
||||
else throw new Exception("invalid arguments in Run().\n it must be: Run(string exe_file, string arguments, true/false nowindow)\n");
|
||||
proc.StartInfo.UseShellExecute = false;
|
||||
proc.Start();
|
||||
proc.WaitForExit();
|
||||
proc.Close();
|
||||
break;
|
||||
case "Log":
|
||||
Debug("y", $"Log() has {script[index].Options.Length} args\n");
|
||||
PublicLog.Log(CalcString(script[index].Options.ToList()));
|
||||
break;
|
||||
case "ShowFiles":
|
||||
Debug("y", $"Log() has {script[index].Options.Length} args\n");
|
||||
foreach (string file in Directory.GetFiles(CalcString(script[index].Options.ToList())))
|
||||
PublicLog.Log(file + '\n');
|
||||
break;
|
||||
case "bool":
|
||||
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
|
||||
{
|
||||
List<string> expr = new();
|
||||
for (ushort n = 2; n < script[index].Options.Length; n++)
|
||||
expr.Add(script[index].Options[n]);
|
||||
// сравнение и добавление результата в storage[globalindex]
|
||||
SetValue(script[index].Options[0], Compare(expr));
|
||||
Debug(new string[] {"y"," bool ","b", script[index].Options[0],
|
||||
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
|
||||
}
|
||||
else throw new Exception("error: incorrect bool defination\n");
|
||||
break;
|
||||
case "num":
|
||||
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
|
||||
{
|
||||
List<string> expr = new();
|
||||
for (ushort n = 2; n < script[index].Options.Length; n++)
|
||||
{
|
||||
expr.Add(script[index].Options[n]);
|
||||
}
|
||||
SetValue(script[index].Options[0], (double)Calc(expr));
|
||||
Debug(new string[] {"y"," num ","b", script[index].Options[0],
|
||||
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
|
||||
}
|
||||
else throw new Exception("Execute() error: incorrect double defination\n");
|
||||
break;
|
||||
case "string":
|
||||
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
|
||||
{
|
||||
List<string> expr = new();
|
||||
for (ushort n = 2; n < script[index].Options.Length; n++)
|
||||
{
|
||||
expr.Add(script[index].Options[n]);
|
||||
}
|
||||
SetValue(script[index].Options[0], CalcString(expr));
|
||||
Debug(new string[] {"y"," string ","b", script[index].Options[0],
|
||||
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
|
||||
}
|
||||
break;
|
||||
case "while":
|
||||
if (script[index + 1].Operator != "{") throw new Exception("Execute() error: expect { after for()");
|
||||
subscript = SplitScript(script[index + 1].Options[0]);
|
||||
while (Compare(script[index].Options.ToList()))
|
||||
{
|
||||
Execute(subscript);
|
||||
}
|
||||
index++;
|
||||
break;
|
||||
case "if":
|
||||
if (script[index + 1].Operator != "{") throw new Exception("Execute() error: expect { after for()");
|
||||
subscript = SplitScript(script[index + 1].Options[0]);
|
||||
if (Compare(script[index].Options.ToList()))
|
||||
{
|
||||
Execute(subscript);
|
||||
}
|
||||
index++;
|
||||
break;
|
||||
case "FSP_Download":
|
||||
mainSocket.FSP_Download(script[index].Options[0], script[index].Options[1]);
|
||||
break;
|
||||
default:
|
||||
throw new Exception($"Execute() error: invalid construct: {script[index].Operator}\n");
|
||||
}
|
||||
}
|
||||
Storage.RemoveAt(globalindex);
|
||||
globalindex--;
|
||||
return null;
|
||||
|
||||
// операции со строками
|
||||
string CalcString(List<string> expr)
|
||||
{
|
||||
Debug("m", "CalcString(");
|
||||
foreach (string part in expr)
|
||||
Debug("c", "<", "b", part, "c", ">");
|
||||
Debug("m", ")", "y", " started\n");
|
||||
// извлечение значений переменных
|
||||
for (ushort n = 0; n < expr.Count; n++)
|
||||
{
|
||||
switch (expr[n][0])
|
||||
{
|
||||
case '+':
|
||||
break;
|
||||
case '"':
|
||||
if (!expr[n].EndsWith("\"")) throw new Exception("Calc() error: invalid value <" + expr[n] + ">\n");
|
||||
break;
|
||||
default:
|
||||
expr[n] = GetValue(expr[n]).ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
// вычисление
|
||||
string rezult = "";
|
||||
for (ushort i = 0; i < expr.Count; i++)
|
||||
{
|
||||
|
||||
if (expr[i] == "+")
|
||||
{
|
||||
i++;
|
||||
rezult += expr[i];
|
||||
}
|
||||
else if (i == 0) rezult = expr[0];
|
||||
else throw new Exception($"error in Calc(): arg {expr[i]}\n");
|
||||
}
|
||||
if (rezult.Contains("\\n")) rezult = rezult.Replace("\\n", "\n");
|
||||
if (rezult.Contains("\"")) rezult = rezult.Replace("\"", "");
|
||||
Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
|
||||
return rezult;
|
||||
}
|
||||
// операции с числами
|
||||
double Calc(List<string> expr)
|
||||
{
|
||||
Debug("m", "Calc(");
|
||||
foreach (string part in expr)
|
||||
Debug("c", "<", "b", part, "c", ">");
|
||||
Debug("m", ")", "y", " started\n");
|
||||
// извлечение значений переменных
|
||||
for (ushort n = 0; n < expr.Count; n++)
|
||||
{
|
||||
switch (expr[n][0])
|
||||
{
|
||||
case '0':
|
||||
case '1':
|
||||
case '2':
|
||||
case '3':
|
||||
case '4':
|
||||
case '5':
|
||||
case '6':
|
||||
case '7':
|
||||
case '8':
|
||||
case '9':
|
||||
case '+':
|
||||
case '-':
|
||||
case '*':
|
||||
case '/':
|
||||
break;
|
||||
default:
|
||||
expr[n] = GetValue(expr[n]).ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
// вычисление
|
||||
double rezult = new();
|
||||
for (ushort i = 0; i < expr.Count; i++)
|
||||
switch (expr[i][0])
|
||||
{
|
||||
case '+':
|
||||
i++;
|
||||
rezult += Convert.ToDouble(expr[i]);
|
||||
break;
|
||||
case '-':
|
||||
i++;
|
||||
rezult -= Convert.ToDouble(expr[i]);
|
||||
break;
|
||||
case '*':
|
||||
i++;
|
||||
rezult *= Convert.ToDouble(expr[i]);
|
||||
break;
|
||||
case '/':
|
||||
i++;
|
||||
rezult /= Convert.ToDouble(expr[i]);
|
||||
break;
|
||||
default:
|
||||
if (i == 0) rezult += Convert.ToDouble(expr[i]);
|
||||
else throw new Exception($"error in Calc(): arg {expr[i]}\n");
|
||||
break;
|
||||
}
|
||||
Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
|
||||
return rezult;
|
||||
}
|
||||
// сравнение
|
||||
bool Compare(List<string> expr)
|
||||
{
|
||||
Debug("m", "Compare(");
|
||||
foreach (string part in expr)
|
||||
Debug("c", "<", "b", part, "c", ">");
|
||||
Debug("m", ")", "y", " started\n");
|
||||
// вычисление значений правой и левой части неравенства
|
||||
char act = '\0';
|
||||
double rezult_0 = new(), rezult_1;
|
||||
List<string> _expr = new List<string>();
|
||||
for (ushort n = 0; n < expr.Count; n++)
|
||||
{
|
||||
Debug("m", $" <{expr[n]}>\n");
|
||||
switch (expr[n][0])
|
||||
{
|
||||
case '<':
|
||||
case '>':
|
||||
act = expr[n][0];
|
||||
rezult_0 = Calc(_expr);
|
||||
_expr.Clear();
|
||||
break;
|
||||
case '!':
|
||||
case '=':
|
||||
act = expr[n][0];
|
||||
rezult_0 = Calc(_expr);
|
||||
_expr.Clear();
|
||||
n++;
|
||||
break;
|
||||
default:
|
||||
_expr.Add(expr[n]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Debug("y", " rezult_0 = <", "b", rezult_0.ToString(), "y", ">\n");
|
||||
rezult_1 = Calc(_expr);
|
||||
Debug("y", " rezult_1 = <", "b", rezult_1.ToString(), "y", ">\n");
|
||||
Debug("y", " act = <", "b", act.ToString(), "y", ">\n");
|
||||
bool output = act switch
|
||||
{
|
||||
'<' => rezult_0 < rezult_1,
|
||||
'>' => rezult_0 > rezult_1,
|
||||
'!' => rezult_0 != rezult_1,
|
||||
'=' => rezult_0 == rezult_1,
|
||||
_ => throw new Exception($"error: incorrect comparsion symbol: <{act}>\n"),
|
||||
};
|
||||
Debug("y", " return <", "c", $"{output}", "y", ">\n");
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
List<Construction> SplitScript(string text)
|
||||
{
|
||||
// лист для хранения обработанного текста
|
||||
List<Construction> script = new();
|
||||
string construct = "";
|
||||
string option = "";
|
||||
List<string> options = new();
|
||||
for (int index = 0; index < text.Length; index++)
|
||||
{
|
||||
switch (text[index])
|
||||
{
|
||||
// конец распознания конструкта
|
||||
case ';':
|
||||
Debug(text[index].ToString() + '\n');
|
||||
// добавление конструкта и его параметров в лист
|
||||
if (construct != "") script.Add(new Construction(construct, options));
|
||||
construct = "";
|
||||
option = "";
|
||||
options.Clear();
|
||||
break;
|
||||
// распознание параметров конструкта
|
||||
case '(':
|
||||
Debug(text[index].ToString());
|
||||
while (text[index] != ')')
|
||||
{
|
||||
index++;
|
||||
switch (text[index])
|
||||
{
|
||||
case '"':
|
||||
Debug("g", text[index].ToString());
|
||||
do
|
||||
{
|
||||
option += text[index];
|
||||
index++;
|
||||
Debug("g", text[index].ToString());
|
||||
} while (text[index] != '"');
|
||||
option += text[index];
|
||||
break;
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
case ')':
|
||||
case ',':
|
||||
Debug(text[index].ToString());
|
||||
options.Add(option);
|
||||
option = "";
|
||||
break;
|
||||
// математика
|
||||
case '+':
|
||||
case '-':
|
||||
case '*':
|
||||
case '/':
|
||||
case '!':
|
||||
case '=':
|
||||
Debug(text[index].ToString());
|
||||
if (option != "") options.Add(option);
|
||||
option = "";
|
||||
options.Add(text[index].ToString());
|
||||
break;
|
||||
default:
|
||||
option += text[index];
|
||||
Debug("c", text[index].ToString());
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (debug && text[index + 1] == ';') PublicLog.Log("y", "\n " + options.Count + " options have read\n");
|
||||
break;
|
||||
// очистка конструкта от лишних символов
|
||||
case ' ':
|
||||
case '\t':
|
||||
case '\r':
|
||||
case '\n':
|
||||
break;
|
||||
//
|
||||
case '{':
|
||||
Debug("SplitScript() found <{>");
|
||||
// добавление конструкта и его параметров в лист
|
||||
if (construct != "") script.Add(new Construction(construct, options));
|
||||
options.Clear();
|
||||
option = "";
|
||||
construct = "";
|
||||
index++;
|
||||
short bracketBalance = 1;
|
||||
while (bracketBalance != 0)
|
||||
{
|
||||
if (text[index] == '{') bracketBalance++;
|
||||
if (text[index] == '}') bracketBalance--;
|
||||
option += text[index];
|
||||
index++;
|
||||
}
|
||||
option.Remove(option.Length - 1);
|
||||
script.Add(new Construction("{", new List<string> { option }));
|
||||
option = "";
|
||||
break;
|
||||
case '}':
|
||||
//throw new Exception($"SplitScript() error: unexpected '}}' on line {line}\n");
|
||||
break;
|
||||
default:
|
||||
construct += text[index];
|
||||
Debug("m", text[index].ToString());
|
||||
break;
|
||||
}
|
||||
}
|
||||
// возврат листа
|
||||
return script;
|
||||
}
|
||||
|
||||
class Construction
|
||||
{
|
||||
public string Operator { get; private set; }
|
||||
public string[] Options { get; private set; }
|
||||
public Construction(string oper, List<string> opts)
|
||||
{
|
||||
Operator = oper;
|
||||
Options = opts.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,98 +0,0 @@
|
||||
<?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>{E02EA967-FD29-47D2-B25B-BA684B784AEE}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>dtscript</RootNamespace>
|
||||
<AssemblyName>dtscript</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
<InstallFrom>Disk</InstallFrom>
|
||||
<UpdateEnabled>false</UpdateEnabled>
|
||||
<UpdateMode>Foreground</UpdateMode>
|
||||
<UpdateInterval>7</UpdateInterval>
|
||||
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
|
||||
<UpdatePeriodically>false</UpdatePeriodically>
|
||||
<UpdateRequired>false</UpdateRequired>
|
||||
<MapFileExtensions>true</MapFileExtensions>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>none</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
<LangVersion>preview</LangVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<StartupObject>DTScript.MainClass</StartupObject>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ApplicationIcon>dtscript.ico</ApplicationIcon>
|
||||
</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="MainClass.cs" />
|
||||
<Compile Include="ScriptRunner.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include=".NETFramework,Version=v4.7.2">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>Microsoft .NET Framework 4.7.2 %28x86 и x64%29</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="dtscript.ico" />
|
||||
<Content Include="dtscript_doc.txt" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DTLib\DTLib.csproj">
|
||||
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
|
||||
<Name>DTLib</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>del /q /f dtscript.exe.config
|
||||
copy dtscript.exe C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\dtscript.exe</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<PreBuildEvent>
|
||||
</PreBuildEvent>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 9.4 KiB |
@ -1,26 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30611.23
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtscript", "dtscript.csproj", "{E02EA967-FD29-47D2-B25B-BA684B784AEE}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
build|Any CPU = build|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{E02EA967-FD29-47D2-B25B-BA684B784AEE}.build|Any CPU.ActiveCfg = build|Any CPU
|
||||
{E02EA967-FD29-47D2-B25B-BA684B784AEE}.build|Any CPU.Build.0 = build|Any CPU
|
||||
{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 = {A1D642E1-876E-4187-91D5-526827AE36A2}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@ -1,63 +0,0 @@
|
||||
Мне было лень изучать жабаскрып, потому всего за полгода я сделал вот этот dtscript (как выразился Абикак, "питоний джабаскрып").
|
||||
Синтаксис dtscript не завист от пробелов, табов, переносов строк. Конец одной конструкции определяется по символу ';' или '}' (если перед этим был символ '{')
|
||||
|
||||
|
||||
========================================[переменные]========================================
|
||||
|
||||
объявление переменной и присвоение значения синтаксически никак не отличаются:
|
||||
тип(имя = значение);
|
||||
|
||||
у переменных есть контекст:
|
||||
bool(h=false);
|
||||
if (...)
|
||||
{
|
||||
bool(j=true);
|
||||
Log("w", h); выведет true, так как есть доступ к переменным предыдущих уровней
|
||||
}
|
||||
Log("w", j); выдаст ошибку "KeyNotFoundException", так как вызывается с предшествующего объявлению переменной уровня
|
||||
|
||||
┌────────┬────────────────┬───────────┬───────────────────┐
|
||||
│ тип │ аналог в c# │ операции │ пример │
|
||||
├────────┼────────────────┼───────────┼───────────────────┤
|
||||
│ bool │ System.Boolean │ <,>,==,!= │ bool(a=1<3); │
|
||||
├────────┼────────────────┼───────────┼───────────────────┤
|
||||
│ num │ System.Double │ +,-,*,/ │ num(a=9.6); │
|
||||
├────────┼────────────────┼───────────┼───────────────────┤
|
||||
│ string │ System.String │ + │ string(a="text"); │
|
||||
└────────┴────────────────┴───────────┴───────────────────┘
|
||||
|
||||
|
||||
==========================================[методы]==========================================
|
||||
|
||||
Oбъявлять свои методы пока что нельзя, можно только использовать встроенные:
|
||||
метод; если нет параметров
|
||||
Метод(параметр0, параметр1...); параметрами могут быть значения и переменные, но не выражения
|
||||
|
||||
┌───────────────────────────┬─────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────┐
|
||||
│ метод │ аналог в с# │ шо делает │
|
||||
├───────────────────────────┼─────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
|
||||
│ pause │ System.Console.ReadKey() │ приостанавливает выполнение скрипта до нажатия клавиши │
|
||||
├───────────────────────────┼─────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
|
||||
│ break │ break │ прекращает выполнение уровня скрипта │
|
||||
├───────────────────────────┼─────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
|
||||
│ Log("w", "text", ...) │ DTLib.ColoredConsole.Write(params string[]) │ выводит в консоль цветной текст │
|
||||
├───────────────────────────┼─────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
|
||||
│ Run("файл.ехе аргументы") │ System.Diagnostics.Process.Start(string) │ запускает прогу │
|
||||
├───────────────────────────┼─────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
|
||||
│ Download("f0", "f1") │ DTLib.NetWork.FSP_Download(this Socket, string, string) │ скачивает файл по FSP протоколу │
|
||||
└───────────────────────────┴─────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────┘
|
||||
|
||||
|
||||
=========================================[операторы]========================================
|
||||
|
||||
Параметром может быть переменная, но не выражение.
|
||||
|
||||
while (bool)
|
||||
{
|
||||
...
|
||||
}
|
||||
|
||||
if (bool)
|
||||
{
|
||||
...
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
|
||||
</startup>
|
||||
</configuration>
|
||||
@ -1,35 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// Общие сведения об этой сборке предоставляются следующим набором
|
||||
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
|
||||
// связанные с этой сборкой.
|
||||
[assembly: AssemblyTitle("updater")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("updater")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2021")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
|
||||
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
|
||||
// из модели COM задайте для атрибута ComVisible этого типа значение true.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
|
||||
[assembly: Guid("4784d974-a342-4202-9430-90fe5ac00fc7")]
|
||||
|
||||
// Сведения о версии сборки состоят из указанных ниже четырех значений:
|
||||
//
|
||||
// Основной номер версии
|
||||
// Дополнительный номер версии
|
||||
// Номер сборки
|
||||
// Номер редакции
|
||||
//
|
||||
// Можно задать все значения или принять номера сборки и редакции по умолчанию
|
||||
// используя "*", как показано ниже:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@ -1,110 +0,0 @@
|
||||
using DTLib;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace updater
|
||||
{
|
||||
class Updater
|
||||
{
|
||||
static readonly string logfile = $"logs-updater\\updater-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
|
||||
static Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
static Dtsod config;
|
||||
|
||||
static void Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.Title = "dtlauncher updater";
|
||||
Console.InputEncoding = Encoding.Unicode;
|
||||
Console.OutputEncoding = Encoding.Unicode;
|
||||
PublicLog.LogDel += Log;
|
||||
config = config = new(File.ReadAllText("updater.dtsod"));
|
||||
// подключение к центральному серверу
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
Log("b", "server address: <", "c", config["server_domain"], "b",
|
||||
">\nserver port: <", "c", config["server_port"].ToString(), "b", ">\n");
|
||||
mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(config["server_domain"])[0], (int)config["server_port"]));
|
||||
Log("g", "connected to server\n");
|
||||
break;
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
Log("r", $"updater.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
|
||||
}
|
||||
}
|
||||
var recieved = mainSocket.GetPackage().ToStr();
|
||||
if (recieved != "requesting hash") throw new Exception("invalid server request");
|
||||
mainSocket.SendPackage(new byte[] { 255, 255, 255, 255, 255, 255, 255, 255 });
|
||||
recieved = mainSocket.GetPackage().ToStr();
|
||||
if (recieved != "updater") throw new Exception($"invalid central server answer <{recieved}>");
|
||||
// обновление апдейтера
|
||||
if (args.Length == 0 || args[0] != "updated")
|
||||
{
|
||||
mainSocket.FSP_Download("dtlauncher.exe", "TEMP\\dtlauncher.exe");
|
||||
Log("g", "dtlauncher.exe downloaded\n");
|
||||
mainSocket.FSP_Download("DTLib.dll", "TEMP\\DTLib.dll");
|
||||
Log("g", "DTLib.dll downloaded\n");
|
||||
Process.Start("cmd", "/c timeout 0 && copy TEMP\\dtlauncher.exe dtlauncher.exe && copy TEMP\\DTLib.dll DTLib.dll && start dtlauncher.exe updated");
|
||||
}
|
||||
else
|
||||
{
|
||||
Log("b", "downloading manifest\n");
|
||||
mainSocket.FSP_Download("manifest.dtsod", "TEMP\\manifest.dtsod");
|
||||
var manifest = new Dtsod(File.ReadAllText("TEMP\\manifest.dtsod"));
|
||||
Log("g", $"found {manifest.Values.Count} files in manifest\n");
|
||||
var hasher = new Hasher();
|
||||
foreach (string file in manifest.Values.Keys)
|
||||
{
|
||||
Log("b", "file <", "c", file, "b", ">... ");
|
||||
if (!File.Exists(file))
|
||||
{
|
||||
LogNoTime("y", "doesn't exist\n");
|
||||
mainSocket.FSP_Download(file, file);
|
||||
}
|
||||
else if (hasher.HashFile(file).HashToString() != manifest[file])
|
||||
{
|
||||
LogNoTime("y", "outdated\n");
|
||||
mainSocket.FSP_Download(file, file);
|
||||
}
|
||||
else LogNoTime("g", "without changes\n");
|
||||
}
|
||||
// установка шрифтов
|
||||
Process.Start("fonts\\fontinst.exe");
|
||||
FileWork.DirDelete("TEMP");
|
||||
Console.ReadKey();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("r", $"updater.Main() error:\n{ex.Message}\n{ex.StackTrace}\n", "gray", "press any key to close...");
|
||||
Console.ReadKey();
|
||||
}
|
||||
Log("gray", " \n");
|
||||
}
|
||||
|
||||
// вывод лога в консоль и файл
|
||||
public static void Log(params string[] msg)
|
||||
{
|
||||
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
|
||||
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
|
||||
LogNoTime(msg);
|
||||
}
|
||||
public static void LogNoTime(params string[] msg)
|
||||
{
|
||||
lock (new object())
|
||||
{
|
||||
if (msg.Length == 1) FileWork.Log(logfile, msg[0]);
|
||||
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
|
||||
else FileWork.Log(logfile, SimpleConverter.AutoBuild(msg));
|
||||
ColoredConsole.Write(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,84 +0,0 @@
|
||||
<?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>{4784D974-A342-4202-9430-90FE5AC00FC7}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>updater</RootNamespace>
|
||||
<AssemblyName>dtlauncher</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
<InstallFrom>Disk</InstallFrom>
|
||||
<UpdateEnabled>false</UpdateEnabled>
|
||||
<UpdateMode>Foreground</UpdateMode>
|
||||
<UpdateInterval>7</UpdateInterval>
|
||||
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
|
||||
<UpdatePeriodically>false</UpdatePeriodically>
|
||||
<UpdateRequired>false</UpdateRequired>
|
||||
<MapFileExtensions>true</MapFileExtensions>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>false</DebugSymbols>
|
||||
<DebugType>none</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</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="Updater.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include=".NETFramework,Version=v4.8">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>Microsoft .NET Framework 4.8 %28x86 и x64%29</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\DTLib\DTLib.csproj">
|
||||
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
|
||||
<Name>DTLib</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>del /f /q dtlauncher.exe.config
|
||||
copy dtlauncher.exe C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\dtlauncher.exe
|
||||
copy DTLib.dll C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\DTLib.dll</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
Loading…
Reference in New Issue
Block a user