U:调整结构性目录

This commit is contained in:
jimmy committed 2025-06-18 09:19:25 +08:00
1 parent 693b390df0
commit c255419412
172 files changed
+839 -18898

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
<Application x:Class="Shell.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Shell"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
+128
View File
@@ -0,0 +1,128 @@
using System.Configuration;
using System.Data;
using System.Net.Http;
using System.Windows;
using System.Windows.Threading;
using Application.Utils;
using Common;
using Common.Logger;
using Common.Net.WebSocketConn;
using Microsoft.Extensions.Logging;
using Serilog.Events;
namespace Shell;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
protected override void OnStartup(StartupEventArgs e)
{
// 异常处理
ExceptionCatch();
// 初始化日志
var configModelLogging = AppConfig.Instance.ConfigModel.Logging;
Log.Initialize(configModelLogging);
base.OnStartup(e);
// ✅ 启动你的服务(如 WebSocket、HTTP、端口监听等)
StartMyServer();
}
/// <summary>
/// 异常捕捉
/// </summary>
private void ExceptionCatch()
{
DispatcherUnhandledException += App_DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// 注册全局异常处理
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
/// <summary>
/// 处理异常
/// </summary>
/// <param name="exception"></param>
private void HandleException(Exception? exception)
{
Log.Error("未捕获异常", exception);
// 错误记录,错误处理
if (exception != null)
{
// todo:2023年10月29日 恭喜你发现了BUG页面
MessageBox.Show($"恭喜你发现了BUG,请联系管理员解决:{exception.Message}");
}
}
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "UI线程异常");
HandleException(e.Exception);
// 根据异常类型决定是否继续运行
if (CanRecover(e.Exception))
{
e.Handled = true; // 标记为已处理,防止应用崩溃
// ShowUserFriendlyMessage("操作失败,请重试");
}
else
{
// ShowCriticalErrorDialog(e.Exception);
// 让应用正常关闭而不是崩溃
}
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
foreach (var ex in e.Exception.InnerExceptions)
{
Log.Error(e.Exception, "UI线程异常");
}
e.SetObserved(); // 标记异常已被观察,防止应用终止
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
Log.Error(exception, "非UI线程异常");
if (e.IsTerminating)
{
// 应用即将终止,进行紧急清理
// EmergencyCleanup();
Log.Fatal("应用程序即将因未处理异常而终止");
}
}
private bool CanRecover(Exception exception)
{
return exception switch
{
ArgumentException => true,
InvalidOperationException => true,
HttpRequestException => true,
TimeoutException => true,
OutOfMemoryException => false,
StackOverflowException => false,
AccessViolationException => false,
_ => true
};
}
private void StartMyServer()
{
int port = SysHelper.GetAvailablePort();
AppConfig.Instance.WebSocketPort = port;
AppConfig.Instance.WebSocketPath = $"ws://127.0.0.1:{port}";
Log.Information4Ctx($"服务启动在端口: {AppConfig.Instance.WebSocketPort}");
Log.Information($"服务完整地址: {AppConfig.Instance.WebSocketPath}");
// TODO 2025年5月28日 22点25分 :开启 Http 网络本地服务,提供网页访问
// 启动WebSocket服务器
WebSocketManager.Instance.Start(AppConfig.Instance.WebSocketPath);
}
}
@@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
@@ -0,0 +1,13 @@
<Window x:Class="Shell.MainWindow"
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:Shell"
xmlns:views="clr-namespace:Shell.Views"
mc:Ignorable="d"
Title="MainWindow" Height="700" Width="1300">
<Grid>
<views:WebPanel/>
</Grid>
</Window>
@@ -0,0 +1,14 @@
using System.Windows;
namespace Shell;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
+48
View File
@@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3240.44" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Application\Application.csproj" />
<ProjectReference Include="..\Common.Net\Common.Net.csproj" />
<ProjectReference Include="..\Data\Data.csproj" />
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />
<ProjectReference Include="..\Utils.ETW\Utils.ETW.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="WinDivert64.sys">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Update="WinDivert.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.Production.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
@@ -0,0 +1,35 @@
namespace Shell.Utils;
using System;
using System.Runtime.InteropServices;
public static class TaskbarHelper
{
[DllImport("shell32.dll", SetLastError = true)]
static extern UInt32 SHAppBarMessage(UInt32 dwMessage, ref APPBARDATA pData);
[StructLayout(LayoutKind.Sequential)]
public struct APPBARDATA
{
public UInt32 cbSize;
public IntPtr hWnd;
public UInt32 uCallbackMessage;
public UInt32 uEdge;
public RECT rc;
public Int32 lParam;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left, top, right, bottom;
}
public static RECT GetTaskbarPosition()
{
APPBARDATA data = new APPBARDATA();
data.cbSize = (UInt32)Marshal.SizeOf(typeof(APPBARDATA));
SHAppBarMessage(0x00000005, ref data); // ABM_GETTASKBARPOS
return data.rc;
}
}
@@ -0,0 +1,21 @@
<Window x:Class="Shell.Views.TaskbarWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStyle="None"
AllowsTransparency="True"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="Transparent"
mc:Ignorable="d"
Topmost="True"
ShowInTaskbar="False"
Title="MainWindow"
ResizeMode="NoResize"
Width="100" Height="50">
<Grid>
<TextBlock Text="↑ 0.1 MB/s&#x0a;↓ 1.8 MB/s"
Foreground="White"
FontSize="14"
FontFamily="Consolas"/>
</Grid>
</Window>
@@ -0,0 +1,20 @@
using System.Runtime.InteropServices;
using System.Windows;
using Shell.Utils;
namespace Shell.Views;
public partial class TaskbarWindow : Window
{
public TaskbarWindow()
{
InitializeComponent();
// 获取任务栏位置
var rect = TaskbarHelper.GetTaskbarPosition();
// 将窗口贴在任务栏右下角
this.Left = rect.right - this.Width;
this.Top = rect.bottom - this.Height;
}
}
@@ -0,0 +1,14 @@
<UserControl
x:Class="Shell.Views.WebPanel"
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:Shell.Views"
xmlns:webview2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300">
<webview2:WebView2
Name="webView" />
</UserControl>
@@ -0,0 +1,165 @@
using System.Windows.Controls;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
using Application.Utils;
using Common;
using Common.Logger;
using Common.Net;
using Common.Net.WebSocketConn;
using Infrastructure.utils;
using Utils.ETW;
using Utils.ETW.Core;
using WinDivertNet.WinDivertWrapper;
namespace Shell.Views;
public partial class WebPanel : UserControl
{
public WebPanel()
{
InitializeComponent();
// Class1.Main2();
InitWebView();
// 注册管理 WebSocket 事件
WebSocketManger();
}
private void WebSocketManger()
{
var webSocketManager = WebSocketManager.Instance;
// 获取网络状态
webSocketManager.RegisterHandler("etwNetworkManger", async (cmd, socket) =>
{
Console.WriteLine("开始测试");
// 创建监听实例
var etwNetworkManger = new EtwNetworkManger();
// 设置 ETW 监听
etwNetworkManger.SetupEtwHandlers();
// 开始监听
etwNetworkManger.StartCapture();
});
}
private async void InitWebView()
{
// 初始化 WebView2
await webView.EnsureCoreWebView2Async();
// 加载前端页面:可以是本地文件或服务器地址
// 示例 1:加载本地 HTML
// string htmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "frontend", "index.html");
// webView.CoreWebView2.Navigate($"file:///{htmlPath.Replace("\\", "/")}");
// 示例 2:加载远程网页
webView.CoreWebView2.Navigate("http://localhost:3000");
webView.CoreWebView2.WebMessageReceived += (sender, args) =>
{
string json = args.WebMessageAsJson;
// 反序列化为 C# 对象
var msg = JsonSerializer.Deserialize<JsMessage>(json);
Log.Information(json);
Log.Information(msg?.Channel);
switch (msg?.Channel)
{
case "showMessage":
MessageBox.Show(msg.Payload?.Content ?? "无内容", msg.Payload?.Title ?? "提示");
InitWebView1();
break;
case "GetNetInfo":
NetUtils.GetNetInfo();
break;
case "GetProgramDiagnostics":
var programDiagnostics = SysInfoUtils.GetProgramDiagnostics();
Log.Information(programDiagnostics);
break;
case "InspectProcess":
SysInfoUtils.InspectProcess(23192);
break;
case "GetAllTcpConnections":
NetUtils.GetAllTcpConnections();
break;
case "PacketSnifferStart":
PacketSniffer.Start();
break;
case "GetWebSocketPath":
WebSocketPath();
break;
case "CloseWebSocket":
CloseWebSocket();
break;
case "OpenWebSocket":
OpenWebSocket();
break;
default:
Log.Information("没有任何函数被触发...");
break;
}
};
}
private void OpenWebSocket()
{
int port = SysHelper.GetAvailablePort();
AppConfig.Instance.WebSocketPort = port;
AppConfig.Instance.WebSocketPath = $"ws://127.0.0.1:{port}";
WebSocketManager.Instance.Start(AppConfig.Instance.WebSocketPath);
}
private void CloseWebSocket()
{
WebSocketManager.Instance.Stop();
}
private async void InitWebView1()
{
await webView.ExecuteScriptAsync("""
window.externalFunctions.__BRIDGE_LISTEN__('showMessage','来自 C# 的问候');
""");
}
private async void WebSocketPath()
{
var instanceWebSocketPath = AppConfig.Instance.WebSocketPath;
Log.Information($"instanceWebSocketPath -> :{instanceWebSocketPath}");
string result = await webView.ExecuteScriptAsync($"""
window.externalFunctions.__BRIDGE_LISTEN__('ListenWebSocketPath','{instanceWebSocketPath}');
""");
string result1 = await webView.ExecuteScriptAsync($"""
window.externalFunctions.__BRIDGE_LISTEN__('GetWebSocketPath','{instanceWebSocketPath}');
""");
}
}
public class JsMessage
{
[JsonPropertyName("channel")] public string Channel { get; set; }
[JsonPropertyName("payload")] public JsData Payload { get; set; }
public override string ToString()
{
return $"Channel:{Channel}, Payload:{Payload}";
}
}
public class JsData
{
[JsonPropertyName("title")] public string Title { get; set; }
[JsonPropertyName("content")] public string Content { get; set; }
public override string ToString()
{
return $"Title:{Title}, Content:{Content}";
}
}
@@ -0,0 +1,5 @@
{
"AppSettings": {
"MaxConnection": 321
}
}
@@ -0,0 +1,5 @@
{
"AppSettings": {
"MaxConnection": 123
}
}
@@ -0,0 +1,19 @@
{
"AppSettings": {
"AppName": "MyApp",
"MaxConnection": 444,
"Version": "0.0.1",
"Logging": {
"EnableConsole": true,
"EnableFile": false,
"LogPath": "logs",
"MaxFileSizeMB": 1,
"RetentionDays": 30,
"CompressDaysThreshold": 3,
"MinimumLevel": "Information",
"OutputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] [{ThreadId}] {Message:lj}{NewLine}{Exception}",
"UseJsonFormat": false,
"CompressCheckIntervalHours": 24
}
}
}