Skip to content

Commit

Permalink
Optimize for C# 9.0, Color theme Optimize part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Zerumi committed Jan 14, 2022
1 parent 4dd35e1 commit 3892fe3
Show file tree
Hide file tree
Showing 54 changed files with 675 additions and 654 deletions.
18 changes: 18 additions & 0 deletions AMWE Administrator/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,21 @@

# CS0108: Член скрывает унаследованный член: отсутствует новое ключевое слово
dotnet_diagnostic.CS0108.severity = none

# CA5379: Не используйте слабый алгоритм функции формирования ключа.
dotnet_diagnostic.CA5379.severity = none

# IDE0011: Добавить фигурные скобки
csharp_prefer_braces = false

# IDE0045: Преобразовать в условное выражение
dotnet_style_prefer_conditional_expression_over_assignment = false

# CA1707: Идентификаторы не должны содержать символы подчеркивания
dotnet_diagnostic.CA1707.severity = none

# CA1305: Укажите IFormatProvider
dotnet_diagnostic.CA1305.severity = none

# IDE0011: Добавить фигурные скобки
dotnet_diagnostic.IDE0011.severity = none
16 changes: 8 additions & 8 deletions AMWE Administrator/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ public partial class App : Application
public static Cookie AuthCookie;
public static string ServerAddress { get; set; }
public static string Username { get; set; }
public static List<Report> reports = new List<Report>();
public static List<Report> reports = new();
public static DateTime ServerDateTime;

public static Color[] colors = m3md2.ColorThemes.GetColors(ConfigurationRequest.GetValueByKey("ColorTheme"));
public static SolidColorBrush MainColor = new SolidColorBrush(App.colors[(int)ColorIndex.Main]);
public static SolidColorBrush SecondColor = new SolidColorBrush(App.colors[(int)ColorIndex.Second]);
public static SolidColorBrush FontColor = new SolidColorBrush(App.colors[(int)ColorIndex.Font]);
public static SolidColorBrush ExtraColor = new SolidColorBrush(App.colors[(int)ColorIndex.Extra]);
public static SolidColorBrush GreenColor = new SolidColorBrush(App.colors[(int)ColorIndex.Green]);
public static SolidColorBrush RedColor = new SolidColorBrush(App.colors[(int)ColorIndex.Red]);
public static Color[] colors = ColorThemes.GetColors(ConfigurationRequest.GetValueByKey("ColorTheme"));
public static SolidColorBrush MainColor = new(colors[(int)ColorIndex.Main]);
public static SolidColorBrush SecondColor = new(colors[(int)ColorIndex.Second]);
public static SolidColorBrush FontColor = new(colors[(int)ColorIndex.Font]);
public static SolidColorBrush ExtraColor = new(colors[(int)ColorIndex.Extra]);
public static SolidColorBrush GreenColor = new(colors[(int)ColorIndex.Green]);
public static SolidColorBrush RedColor = new(colors[(int)ColorIndex.Red]);
#pragma warning restore CA2211 // Поля, не являющиеся константами, не должны быть видимыми

private void Application_Startup(object sender, StartupEventArgs e)
Expand Down
49 changes: 21 additions & 28 deletions AMWE Administrator/AuthWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,27 @@ public static object AuthUser(string[] authdata, out Cookie cookie)
object returnproduct = default;
try
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler
CookieContainer cookies = new();
HttpClientHandler handler = new()
{
CookieContainer = cookies
};

HttpClient client = new HttpClient(handler)
HttpClient client = new(handler)
{
BaseAddress = new Uri(App.ServerAddress)
};
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
string json = Newtonsoft.Json.JsonConvert.SerializeObject(authdata);
HttpResponseMessage response = client.PostAsync($"auth", new StringContent(json, Encoding.UTF8, "application/json")).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
_ = response.EnsureSuccessStatusCode();
returnproduct = response.Content.ReadAsAsync<object>().GetAwaiter().GetResult();
try
{
Uri uri = new Uri($"{App.ServerAddress}auth");
Uri uri = new($"{App.ServerAddress}auth");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
CookieCollection collection = new CookieCollection();
CookieCollection collection = new();
responseCookies.ToList().ForEach(x =>
{
collection.Add(x);
Expand All @@ -72,14 +72,7 @@ public static object AuthUser(string[] authdata, out Cookie cookie)

public string ResponseText
{
get
{
if (cbShow.IsChecked.GetValueOrDefault())
{
return sResponseTextBox.Text;
}
return ResponseTextBox.Password;
}
get => cbShow.IsChecked.GetValueOrDefault() ? sResponseTextBox.Text : ResponseTextBox.Password;
set
{
if (cbShow.IsChecked.GetValueOrDefault())
Expand All @@ -92,8 +85,8 @@ public string ResponseText

public string ServerText
{
get { return ServerTextBox.Text; }
set { ServerTextBox.Text = value; }
get => ServerTextBox.Text;
set => ServerTextBox.Text = value;
}

private void OKButton_Click(object sender, RoutedEventArgs e)
Expand Down Expand Up @@ -123,10 +116,10 @@ private async void Load()
App.ServerDateTime = (await m3md2.ApiRequest.GetProductAsync<DateTime>("time")).ToLocalTime();
AuthButton.Content = "Проверка...";
object authresult = default;
var nocryptpass = ResponseText;
await Task.Run(() =>
string nocryptpass = ResponseText;
await Task.Run(() =>
{
authresult = AuthUser(new string[] { App.Username, Encryption.Encrypt(nocryptpass), Assembly.GetExecutingAssembly().GetName().Version.ToString(), Assembly.LoadFrom("ReportHandler.dll").GetName().Version.ToString(), Assembly.LoadFrom("m3md2.dll").GetName().Version.ToString()}, out App.AuthCookie);
authresult = AuthUser(new string[] { App.Username, Encryption.Encrypt(nocryptpass), Assembly.GetExecutingAssembly().GetName().Version.ToString(), Assembly.LoadFrom("ReportHandler.dll").GetName().Version.ToString(), Assembly.LoadFrom("m3md2.dll").GetName().Version.ToString() }, out App.AuthCookie);
});
AuthButton.Content = "Загрузка...";
if (authresult is List<VersionFile>)
Expand All @@ -135,29 +128,29 @@ await Task.Run(() =>
}
switch (authresult)
{
case bool _:
case bool:
{
if ((bool)authresult)
{
ConfigurationRequest.WriteValueByKey("MainUri", ServerText);
MainWindow mainWindow = new MainWindow();
MainWindow mainWindow = new();
mainWindow.Show();
Application.Current.MainWindow.Close();
}
else
{
MessageBox.Show("Неправильный пароль");
_ = MessageBox.Show("Неправильный пароль");
}

break;
}

case string _:
case string:
{
if ((string)authresult == "Developer")
{
ConfigurationRequest.WriteValueByKey("MainUri", ServerText);
DeveloperControlPanel controlPanel = new DeveloperControlPanel();
DeveloperControlPanel controlPanel = new();
controlPanel.Show();
Application.Current.MainWindow.Close();
}
Expand All @@ -167,7 +160,7 @@ await Task.Run(() =>

default:
{
MessageBox.Show($"Мы получили странный объект, с которым не знаем, что делать: {authresult}");
_ = MessageBox.Show($"Мы получили странный объект, с которым не знаем, что делать: {authresult}");

break;
}
Expand All @@ -193,7 +186,7 @@ private void CheckBox_Checked(object sender, RoutedEventArgs e)
ResponseTextBox.Visibility = Visibility.Collapsed;
sResponseTextBox.Visibility = Visibility.Visible;
sResponseTextBox.Text = ResponseTextBox.Password;
sResponseTextBox.Focus();
_ = sResponseTextBox.Focus();
}
catch (Exception ex)
{
Expand All @@ -208,7 +201,7 @@ private void CbShow_Unchecked(object sender, RoutedEventArgs e)
sResponseTextBox.Visibility = Visibility.Collapsed;
ResponseTextBox.Visibility = Visibility.Visible;
ResponseTextBox.Password = sResponseTextBox.Text;
ResponseTextBox.Focus();
_ = ResponseTextBox.Focus();
}
catch (Exception ex)
{
Expand All @@ -220,7 +213,7 @@ private void Window_Loaded(object sender, RoutedEventArgs e)
{
UsernameTextBox.Text = Environment.UserName;
ServerText = ConfigurationRequest.GetValueByKey("MainUri");
ResponseTextBox.Focus();
_ = ResponseTextBox.Focus();
}
}
}
21 changes: 7 additions & 14 deletions AMWE Administrator/Chat.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
using Microsoft.AspNetCore.SignalR.Client;
using ReportHandler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AMWE_Administrator
{
Expand All @@ -21,10 +13,10 @@ namespace AMWE_Administrator
/// </summary>
public partial class Chat : Window
{
readonly HubConnection hubConnection;
public uint ChatID;
public Client Client;
public bool chatClosed;
private readonly HubConnection hubConnection;
public uint ChatID { get; set; }
public Client Client { get; set; }
public bool ChatClosed { get; set; }

public Chat(HubConnection chatHubConnection, uint _ChatID, Client client)
{
Expand All @@ -47,7 +39,7 @@ public void AddMessage(DateTime timestamp, string user, string Message)

private async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!chatClosed)
if (!ChatClosed)
{
await hubConnection.InvokeAsync("CloseChat", ChatID);
}
Expand All @@ -69,7 +61,8 @@ private async void Field_KeyDown(object sender, KeyEventArgs e)
private async Task Send()
{
await hubConnection.InvokeAsync("SendMessageToChat", ChatID, tbMessage.Text);
await Dispatcher.BeginInvoke((Action)(() => {
await Dispatcher.BeginInvoke((Action)(() =>
{
tbMessage.Text = string.Empty;
}));
}
Expand Down
4 changes: 2 additions & 2 deletions AMWE Administrator/ConfigurationRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ public static class ConfigurationRequest
{
public static void WriteValueByKey(string key, string value)
{
var appSettings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Configuration appSettings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

var item = Array.Find(appSettings.AppSettings.Settings.OfType<KeyValueConfigurationElement>().ToArray(), x => x.Key == key);
KeyValueConfigurationElement item = Array.Find(appSettings.AppSettings.Settings.OfType<KeyValueConfigurationElement>().ToArray(), x => x.Key == key);
item.Value = value;
appSettings.Save(ConfigurationSaveMode.Minimal);
ConfigurationManager.RefreshSection("appSettings");
Expand Down
10 changes: 2 additions & 8 deletions AMWE Administrator/ConnectionType.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AMWE_Administrator
namespace AMWE_Administrator
{
enum ConnectionType
internal enum ConnectionType
{
WebSockets = 3,
ServerSentEvents = 2,
Expand Down
24 changes: 10 additions & 14 deletions AMWE Administrator/DeveloperControlPanel.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ namespace AMWE_Administrator
/// </summary>
public partial class DeveloperControlPanel : Window
{
readonly string[] FilesPath;
readonly HubConnection connection;
private readonly string[] FilesPath;
private readonly HubConnection connection;

public DeveloperControlPanel()
{
InitializeComponent();

string FilesInDir = string.Empty;
FilesPath = Directory.GetFiles(Directory.GetCurrentDirectory()).Select(System.IO.Path.GetFileName).ToArray();
FilesPath = Directory.GetFiles(Directory.GetCurrentDirectory()).Select(Path.GetFileName).ToArray();
Array.ForEach(FilesPath, x => FilesInDir += $"\n{x}");
tb_FilesInDir.Text = $"Current files in {Directory.GetCurrentDirectory()}: {FilesInDir}";

Expand Down Expand Up @@ -60,38 +60,34 @@ public DeveloperControlPanel()
return Task.CompletedTask;
};

connection.StartAsync();
_ = connection.StartAsync();
serverStatus.Content = $"Server status for {connection.ConnectionId}: {connection.State}";
Task.Run(async() => {
_ = Task.Run(async () =>
{
await Task.Run(() =>
{
while (true)
{
serverStatus.Dispatcher.BeginInvoke(new Action(() => Content = $"Server status for {connection.ConnectionId}: {connection.State}"));
_ = serverStatus.Dispatcher.BeginInvoke(new Action(() => Content = $"Server status for {connection.ConnectionId}: {connection.State}"));
Thread.Sleep(3000);
}
});
});
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{

}

private async void Button_Click(object sender, RoutedEventArgs e)
{
List<VersionFile> version = new List<VersionFile>();
List<VersionFile> version = new();
for (int i = 0; i < FilesPath.Length; i++)
{
version.Add(new VersionFile() { filename = FilesPath[i], filebytes = File.ReadAllBytes(FilesPath[i]) });
version.Add(new VersionFile() { Filename = FilesPath[i], Filebytes = File.ReadAllBytes(FilesPath[i]) });
}
bool overwritesave = false;
if (await connection.InvokeAsync<bool>("CheckConflict", "admin", Assembly.GetExecutingAssembly().GetName().Version.ToString()))
{
overwritesave = MessageBox.Show("Обнаружен конфликт версий. Версия с таким же кодом уже загружена на сервере. Вы хотите перезаписать версию?", "Конфликт версий", MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) == MessageBoxResult.Yes;
}
MessageBox.Show(Convert.ToString(await connection.InvokeAsync<object>("NewLatestVersion", "admin", Assembly.GetExecutingAssembly().GetName().Version.ToString(), version, overwritesave)));
_ = MessageBox.Show(Convert.ToString(await connection.InvokeAsync<object>("NewLatestVersion", "admin", Assembly.GetExecutingAssembly().GetName().Version.ToString(), version, overwritesave)));
}

private void Moverect_Drop(object sender, DragEventArgs e)
Expand Down
Loading

0 comments on commit 3892fe3

Please sign in to comment.