-
Notifications
You must be signed in to change notification settings - Fork 0
/
Updater.cs
220 lines (203 loc) · 7.33 KB
/
Updater.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mime;
using System.Threading.Tasks;
using Newtonsoft.Json;
using static System.Int64;
namespace GenericUpdater.SDK
{
public sealed class Updater
{
private readonly WebClient _webClient;
private readonly string _configUrl;
private readonly string _updatesPath = Path.Combine(Directory.GetCurrentDirectory(), "Software Updates");
public string UpdateLocalFileName { get; private set; }
public ConfigFile ConfigFile { get; set; }
public event DownloadProgressChangedEventHandler DownloadProgressChanged;
public event AsyncCompletedEventHandler DownloadCompleted;
/// <summary>
/// Initialize Updater
/// </summary>
/// <param name="configFileUrl">Config file Url
/// Make sure this is the .json file download link
/// </param>
public Updater(string configFileUrl)
{
_configUrl = configFileUrl;
_webClient = new WebClient();
}
public async Task<bool> CheckUpdate(string actualVersion)
{
try
{
if (!Utils.IsConnectedToInternet())
throw new NoInternetConnectionException(
"Error connecting to server, please check your internet connection");
// get info from Url
var jsonText = await GetJsonConfigFromUrl();
ConfigFile = GenerateConfigFromJsonFile(jsonText);
// file Path
UpdateLocalFileName = Path.Combine(_updatesPath + "//" + ConfigFile?.FileName);
// comparing versions
var actVersion = new Version(actualVersion);
var serverVersion = new Version(ConfigFile?.Version ?? string.Empty);
return serverVersion > actVersion;
}
catch (NoInternetConnectionException ex)
{
throw new NoInternetConnectionException(ex.Message);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
public bool UpdateJustDownloaded()
{
try
{
if (!File.Exists(UpdateLocalFileName)) return false;
var info = new FileInfo(UpdateLocalFileName);
var vInfo = FileVersionInfo.GetVersionInfo(UpdateLocalFileName);
var vLocal = new Version(vInfo.ProductVersion);
var v1 = new Version(ConfigFile.Version);
return v1 == vLocal && Math.Abs(info.Length - ConfigFile.FileSize) < 1;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// get JSON Text From Cloud File
/// </summary>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private async Task<string> GetJsonConfigFromUrl()
{
try
{
var request = WebRequest.Create(_configUrl);
var reply = await request.GetResponseAsync();
var returning = new StreamReader(reply.GetResponseStream() ?? new MemoryStream());
return await returning.ReadToEndAsync();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// Serialize a Config File to Json
/// </summary>
/// <param name="configFile"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static string GenerateJsonFromConfig(ConfigFile configFile)
{
try
{
return JsonConvert.SerializeObject(configFile);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// Deserialize a Config File From a Json Text
/// </summary>
/// <param name="jsonText"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static ConfigFile GenerateConfigFromJsonFile(string jsonText)
{
try
{
return JsonConvert.DeserializeObject<ConfigFile>(jsonText);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// Cancel async download operation
/// </summary>
public void CancelDownloadOperation()
{
_webClient?.CancelAsync();
}
/// <summary>
/// install the app when download is finished
/// </summary>
/// <param name="current">Application process to be killed</param>
public void InstallUpdate(Process current = null)
{
try
{
if (!File.Exists(UpdateLocalFileName)) return;
Process.Start(UpdateLocalFileName);
if (current == null) return;
// kill all application process instances
Process.GetProcessesByName(current.ProcessName)
.Where(t => t.Id != current.Id)
.ToList()
.ForEach(t => t.Kill());
current.Kill();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// Download de updater File
/// </summary>
/// <exception cref="Exception"></exception>
public void DownloadFile()
{
try
{
//chek internet connection
if (!Utils.IsConnectedToInternet())
throw new NoInternetConnectionException(
"Error connecting to server, please check your internet connection");
// handling download progress event
_webClient.DownloadProgressChanged += (sender, args) => OnDownloadProgressChanged(args);
_webClient.DownloadFileCompleted += (sender, args) => OnDownloadCompleted(args);
// download file
if (!Directory.Exists(_updatesPath))
Directory.CreateDirectory(_updatesPath);
_webClient.DownloadFileAsync(new Uri(ConfigFile.FileUrl),
UpdateLocalFileName);
}
catch (UriFormatException)
{
throw new UriFormatException("The file download address is not in the correct format");
}
catch (NoInternetConnectionException ex)
{
throw new NoInternetConnectionException(ex.Message);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
private void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e)
{
DownloadProgressChanged?.Invoke(this, e);
}
private void OnDownloadCompleted(AsyncCompletedEventArgs e)
{
DownloadCompleted?.Invoke(this, e);
}
}
}