chr
2024-10-09 1f645778ae80a3a8801b8bb4d0fcf8feb244ad43
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Controls;
using System.Windows;
using PdmSwPlugin.Common.Entity;
using System.Threading.Tasks;
using VersionControl;
using PdmSwPlugin.Common.Util.Http;
using PdmSwPlugin.Common.Entity.System;
using PdmSwPlugin.Commmon.Util.UI;
using PdmSwPlugin.Common.Util;
using PdmSwPlugin.Common.Interface;
using SolidWorks.Interop.sldworks;
using System.Windows.Threading;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using PdmSwPlugin.Main.Tcp;
 
namespace PdmSwPlugin.Main
{
    /// <summary>
    /// MainControl.xaml 的交互逻辑
    /// UI 相关
    /// </summary>
    public partial class MainControl : UserControl, ISwAppSetter
    {
        private TcpServer tcpServer;
        public void InitTcpServer()
        {
            tcpServer = new TcpServer();
            tcpServer.NewRequestReceived += new RequestHandler<TcpSession, StringRequestInfo>(HandleRequest);
            if (!tcpServer.Setup(5678))
            {
                Logger.Error("Tcp Server Setup Error.");
            }
            if (!tcpServer.Start())
            {
                Logger.Error("Tcp Server Start Error.");
            }
        }
 
        public void StopTcpServer()
        {
            tcpServer?.Stop();
            tcpServer = null;
        }
 
        public void HandleRequest(TcpSession session, StringRequestInfo info)
        {
            byte[] msg = new byte[1];
            if (PdmUser.LoginUser != null)
            {
                // 登录返回1
                msg[0] = 1;
            }
            else
            {
                // 没登录返回0
                msg[0] = 0;
            }
            session.Send(msg, 0, 1);
        }
 
        #region 检查更新相关
        /// <summary>
        /// 检查更新
        /// </summary>
        public async void CheckUpdate()
        {
            // 主进程ID,自动更新时要Kill
            int mainProcessId = Process.GetCurrentProcess().Id;
            try
            {
                Dictionary<string, object> datas = new Dictionary<string, object>
                {
                    {
                        "params", new List<Dictionary<string, string>>
                        {
                           new Dictionary<string, string>
                           {
                               {"appId", PluginConst.AppId},
                               {"currentVersion", PluginConst.Version},
                           }
                        }
                    }
                };
 
                Result<List<PluginInfo>> result =
                    await HttpClientCreator.PostAsyncAction<List<PluginInfo>>("plugin/openApi/checkUpdate", datas);
                List<PluginInfo> updates = result.HandleResult();
                if (updates != null && updates.Count > 0)
                {
 
                    PluginInfo update = updates[0];
                    if (update.required)
                    {
                        DoUpdateNotRequired(mainProcessId);
                    }
                    else
                    {
                        DoUpdateNotRequired(mainProcessId);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error("检查更新错误!", e);
                this.Error("检查更新错误!");
            }
        }
 
        /// <summary>
        /// 非必要更新
        /// </summary>
        /// <param name="mainProcessId">SoliWorks进程ID</param>
        private void DoUpdateNotRequired(int mainProcessId)
        {
            string updaterPath = "AutoUpdater\\AutoUpdater.exe";
            string exePath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName;
            string exeFileName = $"{exePath}\\{updaterPath}";
            // 非必要更新
            new Task(() =>
            {
                MessageBoxResult dr = MessageBox.Show("检测到插件更新,是否立刻更新?(请注意保存当前工作)", "插件更新", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                if (dr == MessageBoxResult.OK)
                {
                    Process updaterProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = exeFileName,
                            Arguments = mainProcessId + ""
                        }
                    };
                    updaterProcess.Start();
                }
            }).Start();
        }
 
        /// <summary>
        /// 当前版本写入注册表
        /// </summary>
        private void WriteVersionToReg()
        {
            try
            {
                // 加载完先写版本注册表,保证版本统一,版本写入失败提示并退出
                VersionUtil.SetPluginVersion(PluginConst.AppId, PluginConst.Version);
            }
            catch (Exception ex)
            {
                this.Error("插件版本写入失败!");
                Logger.Error("Plugin version write to reg failed!", ex);
            }
        }
 
        /// <summary>
        /// 更新自动更新程序
        /// </summary>
        public void UpdateAutoUpdater()
        {
            try
            {
                string dllPath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName;
                string waitingPath = Path.Combine(dllPath, "WaitingUpdate");
                if (Directory.Exists(waitingPath))
                {
                    // 如果存在WaitingUpdate文件夹,把这个文件夹重命名为AutoUpdater
                    string targetPath = Path.Combine(dllPath, "AutoUpdater");
                    string delPath = Path.Combine(dllPath, "AutoUpdaterBak");
 
                    Directory.Move(targetPath, delPath);
                    Directory.Move(waitingPath, targetPath);
                    Directory.Delete(delPath, true);
                }
            }
            catch (Exception ex)
            {
                this.Error($"更新自动更新程序失败!{ex.StackTrace}");
                Logger.Error("Update AutoUpdater failed.", ex);
            }
        }
        #endregion
 
        /// <summary>
        /// 加载插件主Tab
        /// </summary>
        public void LoginSuccess()
        {
            // 自动登录成功
            clientCreator = new HttpClientCreator();
            if (mainTab == null)
            {
                mainTab = new MainTab(Logout);
                mainTab.SetSwApp(SwApp);
            }
            AddPlugin();
            mainBorder.Child = mainTab;
            if (mainTab.tabControl.Items.Count > 0)
            {
                TabItem tabItem = mainTab.tabControl.Items[0] as TabItem;
                tabItem.Focus();
                (tabItem.Content as UIElement).Focus();
            }
        }
 
        public void Logout()
        {
            string binPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "HengXin", "PdmSwPlugin", "bin");
            File.Delete(binPath);
            DeActiveHandler();
            mainTab.tabControl.Items.Clear();
            PdmUser.SetLoginUser(null);
            mainBorder.Child = new LoginControl(LoginSuccess);
        }
 
        public void MainControl_Loaded(object sender, RoutedEventArgs e)
        {
            // 加载完先把版本写入注册表
            WriteVersionToReg();
            // 然后更新AutoUpdater
            UpdateAutoUpdater();
            // 最后检查更新
            CheckUpdate();
 
            mainBorder.Child = new LoginControl(LoginSuccess);
        }
 
 
 
        public void SetSwApp(SldWorks SwApp)
        {
            this.SwApp = SwApp;
        }
 
        private void self_Unloaded(object sender, RoutedEventArgs e)
        {
            StopTcpServer();
        }
    }
}