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
{
///
/// Represents the PPC machine setup manager.
///
///
///
public class MachineSetupManager : ExtendedObject, IMachineSetupManager
{
#region Events
///
/// Occurs when there is a text log message available.
///
public event EventHandler ProgressLog;
///
/// Occurs when the has changed.
///
public event EventHandler ProgressStep;
#endregion
#region Properties
private MachineSetupSteps _currentStep;
///
/// Gets the current setup step.
///
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;
///
/// Gets the downloading packages step progress.
///
public double DownloadingPackagesProgress
{
get { return _downloadProgress; }
private set { _downloadProgress = value; RaisePropertyChangedAuto(); }
}
private String _updatingPackagesStatus;
///
/// Gets the downloading packages step status.
///
public String DownloadingPackagesStatus
{
get { return _updatingPackagesStatus; }
set { _updatingPackagesStatus = value; RaisePropertyChangedAuto(); }
}
#endregion
#region Public Methods
///
/// Performs a machine setup using the specified serial number and machine service address.
///
/// The serial number.
/// The machine service address.
///
public Task Setup(string serialNumber, string machineServiceAddress)
{
return Task.Factory.StartNew(() =>
{
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(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(10); //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().DataBaseSource;
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, "Synchronization Scripts", "config.xml"),
Path.Combine(_newPackageTempFolder, "Synchronization 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
}
}