Skip to content

Commit

Permalink
fix(ConfigHelper): Fixed the crash issue caused by incorrect service …
Browse files Browse the repository at this point in the history
…configuration
  • Loading branch information
ZGGSONG committed Jan 14, 2024
1 parent fa743e7 commit 9821b43
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 76 deletions.
19 changes: 10 additions & 9 deletions STranslate/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,14 @@ protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

// 1. 检查是否已经具有管理员权限
// 1. 开启日志服务
#if DEBUG
LogService.Register();
#elif !DEBUG
LogService.Register(minLevel: LogLevel.Info);
#endif

// 2. 检查是否已经具有管理员权限
if (NeedAdministrator())
{
// 如果没有管理员权限,可以提示用户提升权限
Expand All @@ -32,27 +39,21 @@ protected override void OnStartup(StartupEventArgs e)
}
}

// 2. 多开检测
// 3. 多开检测
if (IsAnotherInstanceRunning())
{
MessageBox_S.Show($"{Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly()!.Location)} 应用程序已经在运行中。", "多开检测");
Application.Current.Shutdown();
return;
}

// 3. 启动应用程序
#if DEBUG
LogService.Register();
#elif !DEBUG
LogService.Register(minLevel: LogLevel.Info);
#endif
// 4. 开启监听系统代理
ProxyUtil.LoadDynamicProxy();

// 5. 软件配置涉及初始化操作
Singleton<ConfigHelper>.Instance.InitialOperate();

// 6. Open View
// 6. 启动应用程序
StartProgram();

// 7. 全局异常处理
Expand Down
4 changes: 2 additions & 2 deletions STranslate/Helper/ConfigHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,9 @@ internal ConfigModel ReadConfig()
var content = File.ReadAllText(CnfName);
return JsonConvert.DeserializeObject<ConfigModel>(content, settings) ?? throw new Exception("反序列化失败...");
}
catch (Exception)
catch (Exception ex)
{
LogService.Logger.Error("[READCONFIG] 读取配置错误,本次运行加载初始化配置...");
LogService.Logger.Error($"[READCONFIG] 读取配置错误,本次运行加载初始化配置...", ex);
return InitialConfig();
}
}
Expand Down
135 changes: 72 additions & 63 deletions STranslate/ViewModels/InputViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Expand All @@ -8,14 +16,6 @@
using STranslate.Model;
using STranslate.Util;
using STranslate.ViewModels.Preference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace STranslate.ViewModels
{
Expand Down Expand Up @@ -170,7 +170,8 @@ await Parallel.ForEachAsync(
if (translatorList != null)
{
IdentifyLanguage = "缓存";
service.Data = translatorList?.FirstOrDefault(x => x.Identify == service.Identify)?.Data ?? "该服务未获取到缓存Ctrl+Enter更新";
service.Data =
translatorList?.FirstOrDefault(x => x.Identify == service.Identify)?.Data ?? "该服务未获取到缓存Ctrl+Enter更新";
return;
}

Expand All @@ -186,59 +187,64 @@ await Parallel.ForEachAsync(
switch (service.Type)
{
case ServiceType.ApiService:
{
response =
(Task<object>)
await service.TranslateAsync(
new RequestApi()
{
Text = InputContent,
SourceLang = LangDict[source].ToString(),
TargetLang = LangDict[target].ToString()
},
token
);
service.Data = (response.Result as ResponseApi)!.Data;
break;
}
{
response =
(Task<object>)
await service.TranslateAsync(
new RequestApi()
{
Text = InputContent,
SourceLang = LangDict[source].ToString(),
TargetLang = LangDict[target].ToString()
},
token
);
service.Data = (response.Result as ResponseApi)!.Data;
break;
}

case ServiceType.BaiduService:
{
string salt = new Random().Next(100000).ToString();
string sign = StringUtil.EncryptString(service.AppID + InputContent + salt + service.AppKey);
response =
(Task<object>)
await service.TranslateAsync(
new RequestBaidu()
{
Text = InputContent,
From = LangDict[source].ToString(),
TO = LangDict[target].ToString(),
AppId = service.AppID,
Salt = salt,
Sign = sign
},
token
);
var ret = (response.Result as ResponseBaidu)?.TransResult ?? [];
service.Data = ret.Length == 0 ? string.Empty :
string.Join(Environment.NewLine, ret.Where(trans => !string.IsNullOrEmpty(trans.Dst)).Select(trans => trans.Dst));
break;
}
{
string salt = new Random().Next(100000).ToString();
string sign = StringUtil.EncryptString(service.AppID + InputContent + salt + service.AppKey);
response =
(Task<object>)
await service.TranslateAsync(
new RequestBaidu()
{
Text = InputContent,
From = LangDict[source].ToString(),
TO = LangDict[target].ToString(),
AppId = service.AppID,
Salt = salt,
Sign = sign
},
token
);
var ret = (response.Result as ResponseBaidu)?.TransResult ?? [];
service.Data =
ret.Length == 0
? string.Empty
: string.Join(
Environment.NewLine,
ret.Where(trans => !string.IsNullOrEmpty(trans.Dst)).Select(trans => trans.Dst)
);
break;
}

case ServiceType.BingService:
{
var req = new RequestBing
{
var req = new RequestBing
{
From = LangDict[source].ToString(),
To = LangDict[target].ToString(),
Req = [new TextData { Text = InputContent }],
};
response = (Task<object>)await service.TranslateAsync(req, token);
var ret = (response.Result as ResponseBing[])!.FirstOrDefault()?.Translations?.FirstOrDefault()?.Text;
service.Data = string.IsNullOrEmpty(ret) ? string.Empty : ret;
break;
}
From = LangDict[source].ToString(),
To = LangDict[target].ToString(),
Req = [new TextData { Text = InputContent }],
};
response = (Task<object>)await service.TranslateAsync(req, token);
var ret = (response.Result as ResponseBing[])!.FirstOrDefault()?.Translations?.FirstOrDefault()?.Text;
service.Data = string.IsNullOrEmpty(ret) ? string.Empty : ret;
break;
}

default:
break;
Expand Down Expand Up @@ -278,15 +284,18 @@ private void HandleTranslationException(ITranslator service, string errorMessage
service.Data = errorMessage;

if (isDebug)
LogService.Logger.Debug($"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}");
LogService.Logger.Debug(
$"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}"
);
else
LogService.Logger.Error($"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}");
LogService.Logger.Error(
$"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}"
);
}

#endregion Translatehandle

public void Clear()

{
InputContent = string.Empty;
}
Expand Down Expand Up @@ -412,7 +421,7 @@ protected override IList<JsonProperty> CreateProperties(Type type, MemberSeriali

list!
.ToList()
?.ForEach(x =>
.ForEach(x =>
{
if (x.Ignored && x.PropertyName == "Data")
x.Ignored = false; //不忽略
Expand Down Expand Up @@ -465,4 +474,4 @@ public override void WriteJson(JsonWriter writer, ITranslator? value, JsonSerial
}

#endregion JsonConvert
}
}
4 changes: 2 additions & 2 deletions STranslate/Views/MainView.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ private void LoadPosition()
Left = left;
Top = top;
}
catch (Exception ex)
catch (Exception)
{
WindowStartupLocation = WindowStartupLocation.CenterOwner;

LogService.Logger.Warn($"加载上次窗口位置({position})失败,启用默认位置 {ex.Message}");
LogService.Logger.Warn($"加载上次窗口位置({position})失败,启用默认位置");
}
}

Expand Down

0 comments on commit 9821b43

Please sign in to comment.