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
|
using FluentFTP;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
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.MachineSetup
{
/// <summary>
/// Represents the PPC machine setup manager.
/// </summary>
/// <seealso cref="Tango.Core.ExtendedObject" />
/// <seealso cref="Tango.PPC.Common.MachineSetup.IMachineSetupManager" />
public class MachineSetupManager : ExtendedObject, IMachineSetupManager
{
#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<MachineSetupSteps> ProgressStep;
#endregion
#region Properties
private MachineSetupSteps _currentStep;
/// <summary>
/// Gets the current setup step.
/// </summary>
public MachineSetupSteps 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
#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<MachineSetupResult> Setup(string serialNumber, string machineServiceAddress)
{
return Task.Factory.StartNew<MachineSetupResult>(() =>
{
LogManager.Log($"Starting machine setup for serial number {serialNumber}...");
//Connect to machine service and get matching packages for this machine.
CurrentStep = MachineSetupSteps.DownloadingPackage;
DownloadingPackagesProgress = 0;
DownloadingPackagesStatus = "Connecting to machine service...";
LogManager.Log($"Connecting to machine service on {machineServiceAddress}...");
MachineSetupRequest request = new MachineSetupRequest();
request.SerialNumber = serialNumber;
MachineSetupResponse setup_response = null;
using (var http = new ProtoWebClient())
{
setup_response = http.Post<MachineSetupRequest, MachineSetupResponse>(machineServiceAddress + "/api/Synchronization/MachineSetup", request).Result;
}
LogManager.Log($"Machine setup response received: {Environment.NewLine}{setup_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(setup_response.FtpAddress, setup_response.FtpUserName, setup_response.FtpPassword))
{
LogManager.Log("FTP: Connecting to site: " + setup_response.FtpAddress);
ftp.ConnectAsync().Wait();
LogManager.Log("FTP: Retrieving download size...");
fileSize = (int)ftp.GetFileSize(setup_response.FtpFilePath);
LogManager.Log("FTP: Download size: " + fileSize + " bytes.");
LogManager.Log("FTP: Starting download...");
ftp.DownloadAsync(fs, setup_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 = MachineSetupSteps.SynchronizingSchema;
String db_name = "Tango";
String localAddress = SettingsManager.Default.GetOrCreate<CoreSettings>().DataSource.Address;
String remote_address = setup_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("Clearing database...");
db.ClearDb();
LogManager.Log("Disposing database manager.");
db.Dispose();
LogManager.Log($"Initializing {nameof(ExaminerSequenceConfigurationRunner)}...");
ExaminerSequenceConfigurationRunner runner = new ExaminerSequenceConfigurationRunner(
Path.Combine(_newPackageTempFolder, "Provision Scripts", "config.xml"),
Path.Combine(_newPackageTempFolder, "Provision Scripts"),
new ExaminerSequenceDataSource()
{
Address = remote_address,
DataBaseName = db_name,
IntegratedSecurity = false,
UserName = setup_response.DbUserName,
Password = setup_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 = MachineSetupSteps.SynchronizingMachineConfiguration;
}
else if (item.Type == ExaminerSequenceItemType.Data)
{
CurrentStep = MachineSetupSteps.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 MachineSetupResult()
{
UpdatePackagePath = _newPackageTempFolder,
};
});
}
#endregion
}
}
|