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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
|
using FluentFTP;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.DB;
using Tango.Core.Helpers;
using Tango.Core.IO;
using Tango.PMR.Synchronization;
using Tango.PPC.Common.Application;
using Tango.Settings;
using Tango.SQLExaminer;
using Tango.Transport.Web;
namespace Tango.PPC.Common.MachineUpdate
{
public class MachineUpdateManager : ExtendedObject, IMachineUpdateManager
{
private IPPCApplicationManager _app_manager;
#region Events
/// <summary>
/// Occurs when there is a text log message available.
/// </summary>
public event EventHandler<string> ProgressLog;
/// <summary>
/// Occurs when the <see cref="CurrentStep" /> has changed.
/// </summary>
public event EventHandler<MachineUpdateSteps> ProgressStep;
#endregion
#region Properties
private MachineUpdateSteps _currentStep;
/// <summary>
/// Gets the current setup step.
/// </summary>
public MachineUpdateSteps CurrentStep
{
get { return _currentStep; }
set
{
if (_currentStep != value)
{
_currentStep = value;
RaisePropertyChangedAuto();
ProgressStep?.Invoke(this, _currentStep);
LogManager.Log("Machine Setup Manager Step: " + value.ToString());
}
}
}
private double _downloadProgress;
/// <summary>
/// Gets the downloading packages step progress.
/// </summary>
public double DownloadingPackagesProgress
{
get { return _downloadProgress; }
private set { _downloadProgress = value; RaisePropertyChangedAuto(); }
}
private String _updatingPackagesStatus;
/// <summary>
/// Gets the downloading packages step status.
/// </summary>
public String DownloadingPackagesStatus
{
get { return _updatingPackagesStatus; }
set { _updatingPackagesStatus = value; RaisePropertyChangedAuto(); }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="MachineUpdateManager"/> class.
/// </summary>
/// <param name="applicationManager">The application manager.</param>
public MachineUpdateManager(IPPCApplicationManager applicationManager)
{
_app_manager = applicationManager;
}
#region Public Methods
/// <summary>
/// Performs a machine setup using the specified serial number and machine service address.
/// </summary>
/// <param name="serialNumber">The serial number.</param>
/// <param name="machineServiceAddress">The machine service address.</param>
/// <returns></returns>
public Task<MachineUpdateResult> Update(string serialNumber, string machineServiceAddress)
{
return Task.Factory.StartNew<MachineUpdateResult>(() =>
{
LogManager.Log($"Starting machine update for serial number {serialNumber}...");
//Connect to machine service and get matching packages for this machine.
CurrentStep = MachineUpdateSteps.DownloadingPackage;
DownloadingPackagesProgress = 0;
DownloadingPackagesStatus = "Connecting to machine service...";
LogManager.Log($"Connecting to machine service on {machineServiceAddress}...");
DownloadUpdateRequest request = new DownloadUpdateRequest();
request.SerialNumber = serialNumber;
DownloadUpdateResponse update_response = null;
using (var http = new ProtoWebClient())
{
update_response = http.Post<DownloadUpdateRequest, DownloadUpdateResponse>(machineServiceAddress + "/api/Synchronization/MachineUpdate", request).Result;
}
LogManager.Log($"Machine update response received: {Environment.NewLine}{update_response.ToJsonString()}");
//Create temporary folders for packages.
var _newPackageTempFolder = TemporaryManager.CreateFolder();
_newPackageTempFolder.Persist = true;
LogManager.Log($"Temporary package folder created: {_newPackageTempFolder}.");
//Download software package.
var tempFile = TemporaryManager.CreateFile(".zip");
LogManager.Log($"Temporary package zip file created: {tempFile}.");
DownloadingPackagesStatus = "Downloading software package...";
LogManager.Log("Downloading software package...");
int fileSize = 0;
DownloadingPackagesProgress = 0;
using (FileStreamWrapper fs = new FileStreamWrapper(tempFile.Path, FileMode.Create, (current) =>
{
InvokeUINow(() =>
{
Thread.Sleep(2); //TODO: this is necessary only for visibility...
DownloadingPackagesProgress = ((double)current / (double)fileSize) * 100d;
});
}))
{
using (FtpClient ftp = new FtpClient(update_response.FtpAddress, update_response.FtpUserName, update_response.FtpPassword))
{
LogManager.Log("FTP: Connecting to site: " + update_response.FtpAddress);
ftp.ConnectAsync().Wait();
LogManager.Log("FTP: Retrieving download size...");
fileSize = (int)ftp.GetFileSize(update_response.FtpFilePath);
LogManager.Log("FTP: Download size: " + fileSize + " bytes.");
LogManager.Log("FTP: Starting download...");
ftp.DownloadAsync(fs, update_response.FtpFilePath).Wait();
}
}
LogManager.Log("Extracting downloaded zip file...");
//Extract software package.
ZipFile.ExtractToDirectory(tempFile, _newPackageTempFolder);
LogManager.Log("Copying latest updater utility to application path...");
//Copy new updater utility to app path.
File.Copy(Path.Combine(_newPackageTempFolder, "Tango.PPC.Updater.exe"), Path.Combine(PathHelper.GetStartupPath(), "Tango.PPC.Updater.exe"), true);
//Synchronize database
CurrentStep = MachineUpdateSteps.SynchronizingSchema;
String db_name = "Tango";
String localAddress = SettingsManager.Default.GetOrCreate<CoreSettings>().DataSource.Address;
String remote_address = update_response.DbAddress;
LogManager.Log($"Synchronizing database '{remote_address}\\{db_name}' => '{localAddress}\\{db_name}'...");
LogManager.Log("Initializing database manager...");
DbManager db = DbManager.FromAddressAndName(localAddress, db_name);
LogManager.Log("Checking Tango database exists on the local machine...");
if (!db.Exists(db_name))
{
throw new InvalidProgramException("Database tango does not exists.");
}
LogManager.Log("Disposing database manager.");
db.Dispose();
LogManager.Log($"Initializing {nameof(ExaminerSequenceConfigurationRunner)}...");
ExaminerSequenceConfigurationRunner runner = new ExaminerSequenceConfigurationRunner(
Path.Combine(_newPackageTempFolder, "Update Scripts", "config.xml"),
Path.Combine(_newPackageTempFolder, "Update Scripts"),
new ExaminerSequenceDataSource()
{
Address = remote_address,
DataBaseName = db_name,
IntegratedSecurity = false,
UserName = update_response.DbUserName,
Password = update_response.DbPassword,
},
new ExaminerSequenceDataSource()
{
Address = localAddress,
DataBaseName = db_name,
IntegratedSecurity = true,
}, serialNumber);
runner.Log += (x, msg) =>
{
LogManager.Log(msg);
ProgressLog?.Invoke(this, msg);
};
runner.ScriptExecuting += (x, item) =>
{
LogManager.Log($"Executing script {item.ToString()}...");
if (item.Type == ExaminerSequenceItemType.Data && item.RequiresSerialNumber)
{
CurrentStep = MachineUpdateSteps.SynchronizingMachineConfiguration;
}
else if (item.Type == ExaminerSequenceItemType.Data)
{
CurrentStep = MachineUpdateSteps.SynchronizingData;
}
};
LogManager.Log("Starting synchronization process...");
try
{
runner.Run().Wait();
LogManager.Log("Synchronization completed successfully!");
}
catch (Exception ex)
{
throw LogManager.Log(ex, "Setup manager error while trying to synchronize database.");
}
return new MachineUpdateResult()
{
UpdatePackagePath = _newPackageTempFolder,
};
});
}
/// <summary>
/// Checks if any update are available for the specified machine serial number.
/// </summary>
/// <param name="serialNumber">The serial number.</param>
/// <param name="machineServiceAddress">The machine service address.</param>
/// <returns></returns>
public Task<CheckForUpdateResponse> CheckForUpdate(string serialNumber, string machineServiceAddress)
{
return Task.Factory.StartNew<CheckForUpdateResponse>(() =>
{
LogManager.Log($"Connecting to machine service on {machineServiceAddress}...");
LogManager.Log($"Checking if updates available...");
CheckForUpdateRequest request = new CheckForUpdateRequest();
request.SerialNumber = serialNumber;
request.Version = _app_manager.Version.ToString();
CheckForUpdateResponse update_response = null;
using (var http = new ProtoWebClient())
{
update_response = http.Post<CheckForUpdateRequest, CheckForUpdateResponse>(machineServiceAddress + "/api/Synchronization/CheckForUpdate", request).Result;
}
LogManager.Log($"Check for update response received: {Environment.NewLine}{update_response.ToJsonString()}");
return update_response;
});
}
#endregion
}
}
|