프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / MarkusAutoUpdate / src / NetSparkle.Samples.NetFramework.WPF / MainWindow.xaml.cs @ d8f5045e

이력 | 보기 | 이력해설 | 다운로드 (10.8 KB)

1
using NetSparkleUpdater.Events;
2
using NetSparkleUpdater.SignatureVerifiers;
3
using System;
4
using System.Diagnostics;
5
using System.Drawing;
6
using System.IO;
7
using System.IO.Compression;
8
using System.Linq;
9
using System.Security;
10
using System.Threading.Tasks;
11
using System.Windows;
12

    
13

    
14
namespace NetSparkleUpdater.Samples.NetFramework.WPF
15
{
16
    /// <summary>
17
    /// Interaction logic for MainWindow.xaml
18
    /// </summary>
19
    public partial class MainWindow : Window
20
    {
21
        private SparkleUpdater _sparkle;
22
        private const string InstallPath = @"C:\Program Files\Doftech\MARKUS";
23
        private string KcomPath = @"C:\Program Files\Doftech\MARKUS\KCOM.exe";
24

    
25
        private string downloadFile;
26
        private string tempStoragePath;
27

    
28
        private NetSparkle.TestAppWPF.ViewModels.MainViewModel viewModel;
29

    
30
        public MainWindow()
31
        {
32
            InitializeComponent();
33
            viewModel = new NetSparkle.TestAppWPF.ViewModels.MainViewModel();
34
            this.DataContext = viewModel;
35

    
36
            //remove the netsparkle key from registry z
37
            //try
38
            //{
39
            //    Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree("Software\\Microsoft\\NetSparkle.TestAppNetCoreWPF");
40
            //}
41
            //catch (Exception ex)
42
            //{
43
            //    System.Diagnostics.Debug.WriteLine(ex);
44
            //}
45

    
46
            // set icon in project properties!
47
            try
48
            {
49
                string manifestModuleName = System.Reflection.Assembly.GetEntryAssembly().ManifestModule.FullyQualifiedName;
50
                var icon = System.Drawing.Icon.ExtractAssociatedIcon(manifestModuleName);
51

    
52
                tempStoragePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "MARKUS", System.IO.Path.GetRandomFileName());
53

    
54
                App.logger.Info($"Temp Strorage Create : {tempStoragePath}");
55

    
56
                if (!Directory.Exists(tempStoragePath))
57
                {
58
                    Directory.CreateDirectory(tempStoragePath);
59
                }
60

    
61
                //File.Copy(KcomPath, System.IO.Path.Combine(tempStoragePath, "Kcom.exe"));
62

    
63
                //KcomPath = System.IO.Path.Combine(tempStoragePath, "Kcom.exe");
64

    
65
                if (!File.Exists(KcomPath))
66
                {
67
                    File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "kcom.exe"), KcomPath);
68
                }
69

    
70
                _sparkle = new SparkleUpdater(App.AppCastUri, new Ed25519Checker(Enums.SecurityMode.Strict, null, "NetSparkle_Ed25519.pub"), KcomPath)
71
                {
72
                    UIFactory = new NetSparkleUpdater.UI.WPF.UIFactory(NetSparkleUpdater.UI.WPF.IconUtilities.ToImageSource(icon)),
73
                    ShowsUIOnMainThread = true,
74
                    TmpDownloadFilePath = tempStoragePath,
75
                    UserInteractionMode = Enums.UserInteractionMode.DownloadNoInstall,
76
                    //UseNotificationToast = true
77
                    RelaunchAfterUpdate = true,
78
                };
79

    
80
                // TLS 1.2 required by GitHub (https://developer.github.com/changes/2018-02-01-weak-crypto-removal-notice/)
81
                _sparkle.SecurityProtocolType = System.Net.SecurityProtocolType.Tls12;
82
                _sparkle.DownloadFinished += FullUpdate_DownloadFileIsReady;
83
                _sparkle.UpdateCheckFinished += _sparkle_UpdateCheckFinished;
84
                _sparkle.DownloadHadError += _sparkle_DownloadError;
85
                _sparkle.DownloadMadeProgress += _sparkle_DownloadMadeProgress;
86
                //_sparkle.StartLoop(true, true);
87
                Updater();
88
                App.logger.Info("main Initialize");
89

    
90
                this.Loaded += MainWindow_Loaded;
91
            }
92
            catch (Exception ex)
93
            {
94
                App.logger.Error("main Initialize", ex);
95
            }
96

    
97
        }
98

    
99
        private void _sparkle_DownloadMadeProgress(object sender, AppCastItem item, ItemDownloadProgressEventArgs args)
100
        {
101
            viewModel.DownloadProgress = args.ProgressPercentage;
102
        }
103

    
104
        private void _sparkle_DownloadError(AppCastItem item, string path, Exception exception)
105
        {
106
            App.logger.Error($"Download Error", exception);
107
        }
108

    
109
        private async void Updater()
110
        {
111
            App.logger.Info("main Load");
112
            try
113
            {
114
                var _updateInfo = await _sparkle.CheckForUpdatesQuietly();
115

    
116
                if (_updateInfo != null)
117
                {
118
                    App.logger.Info("Update Status : " + _updateInfo.Status);
119

    
120
                    switch (_updateInfo.Status)
121
                    {
122
                        case Enums.UpdateStatus.UpdateAvailable:
123
                            this.Visibility = Visibility.Visible;
124
                            //string a = "There's an update available!";
125
                            var castitem = _updateInfo.Updates.First();
126

    
127
                            viewModel.UpdateVersion = castitem.Version;
128
                            System.Threading.Thread.Sleep(1000);
129

    
130
                            await _sparkle.InitAndBeginDownload(castitem);
131

    
132
                            App.logger.Info($"Update available Version : {castitem.Version} Link : {castitem.DownloadLink}");
133

    
134
                            break;
135
                        case Enums.UpdateStatus.UpdateNotAvailable:
136
                        case Enums.UpdateStatus.CouldNotDetermine:
137
                            _sparkle.CloseApplication += () =>
138
                            {
139
                                App.logger.Info($"Start Markus : {App.KcomParam}");
140

    
141
                                Process.Start(KcomPath, App.KcomParam);
142
                                Application.Current.Shutdown();
143
                            };
144

    
145
                            App.logger.Info($"Update Not available. Application Exit.");
146
                            await _sparkle.QuitApplication();
147

    
148
                            break;
149
                    }
150
                }
151
                else
152
                {
153
                    if (_updateInfo != null)
154
                    {
155
                        App.logger.Error("Update Is Null");
156
                        Process.Start(KcomPath, App.KcomParam);
157
                    }
158
                }
159
            }
160
            catch (Exception ex)
161
            {
162
                App.logger.Error($"main Load", ex);
163
            }
164

    
165
        }
166

    
167
        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
168
        {
169

    
170
        }
171

    
172
        private void _sparkle_UpdateCheckFinished(object sender, Enums.UpdateStatus status)
173
        {
174

    
175
        }
176

    
177
        //[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
178
        private void FullUpdate_DownloadFileIsReady(AppCastItem item, string downloadPath)
179
        {
180
            viewModel.IsWait = true;
181

    
182
            ExtractFiles(InstallPath,tempStoragePath,downloadPath,KcomPath, App.KcomParam);
183

    
184
            //ExtractProcess(item, downloadPath);
185
        }
186

    
187
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
188
        private void ExtractFiles(string InstallPath, string tempStoragePath, string downloadFile, string KcomPath, string Param)
189
        {
190
            viewModel.IsWait = true;
191
            try
192
            {
193
                var extractFolder = Path.Combine(tempStoragePath, "Extract");
194

    
195
                ZipFile.ExtractToDirectory(downloadFile, extractFolder);
196

    
197
                foreach (var file in Directory.EnumerateFiles(extractFolder, "*.*", SearchOption.AllDirectories))
198
                {
199
                    var target = System.IO.Path.Combine(InstallPath, file.Replace(extractFolder, "").Substring(1));
200

    
201
                    var dir = Path.GetDirectoryName(target);
202

    
203
                    if (!Directory.Exists(dir))
204
                    {
205
                        Directory.CreateDirectory(dir);
206
                    }
207

    
208
                    File.Copy(file, target, FileExits(target));
209
                    App.logger.Info($"Copy - {target}");
210
                }
211

    
212
                Process.Start(KcomPath, Param);
213
            }
214
            catch (Exception ex)
215
            {
216
                App.logger.Error($"ExtractFile Error", ex);
217

    
218
                if (ex.InnerException != null)
219
                {
220
                    App.logger.Error($"ExtractFile Error InnerException", ex.InnerException);
221
                }
222
            }
223
            finally
224
            {
225
                Application.Current.Shutdown();
226
            }
227
        }
228

    
229
        private static bool FileExits(string fileName)
230
        {
231
            try
232
            {
233
                return File.Exists(fileName);
234
            }
235
            catch (Exception)
236
            {
237
                return false;
238
            }
239
        }
240

    
241
        private void ExtractProcess(AppCastItem item, string downloadPath)
242
        { 
243
            try
244
            {
245
                downloadFile = downloadPath;
246

    
247
                //var args = $"{InstallPath} {tempStoragePath} {downloadFile} {KcomPath} {App.KcomParam}";
248

    
249
                string endpoint = IIpc.Commons.shortGuid();
250

    
251
                var wcfServer = new IIpc.WcfServer(endpoint + "M");
252
                wcfServer.Start();
253

    
254
                wcfServer.ProcessStart += (snd, ect) =>
255
                {
256
                    var ipcClient = new IIpc.WcfClient(endpoint + "E");
257
                    try
258
                    {
259
                        ipcClient.ParamReceived(InstallPath, tempStoragePath, downloadFile, KcomPath, App.KcomParam);
260

    
261
                        //Application.Current.Shutdown();
262
                    }
263
                    catch (Exception ex)
264
                    {
265
                        App.logger.Error($"ParamReceived ", ex);
266
                    }
267
                };
268

    
269
                //MarkusExtract.GetFile();
270

    
271
                var exrtractFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "MarkusExtractUpdate", @"MarkusUpdateExtract.exe");
272

    
273
                Process DownloadProcess = new Process();
274

    
275
                ProcessStartInfo startInfo = new ProcessStartInfo
276
                {
277
                    UseShellExecute = false,
278
                    FileName = exrtractFile,
279
                    WindowStyle = ProcessWindowStyle.Hidden,
280
                    CreateNoWindow = true,
281
                    ErrorDialog = false,
282
                    Verb = "runas",
283
                    RedirectStandardInput = false,
284
                    RedirectStandardError = false,
285
                    Arguments = endpoint
286
                };
287

    
288
                //$"{ InstallPath} {tempStoragePath} {downloadFile} {KcomPath} {param}"
289

    
290
                DownloadProcess.StartInfo = startInfo;
291
                DownloadProcess.EnableRaisingEvents = false;
292

    
293
                DownloadProcess.Start();
294
            }
295
            catch (Exception ex)
296
            {
297
                App.logger.Error($"DownloadFileIsReady ", ex);
298
            }
299

    
300
        }
301
    }
302
}
클립보드 이미지 추가 (최대 크기: 500 MB)