aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/Views/FirmwareUpgradeView.xaml.cs
blob: 17220e6150cb413938ed2360d7814b2395ea8bf5 (plain)
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Tango.MachineStudio.UI.Views
{
    /// <summary>
    /// Interaction logic for FirmwareUpgradeView.xaml
    /// </summary>
    public partial class FirmwareUpgradeView : UserControl
    {
        public FirmwareUpgradeView()
        {
            InitializeComponent();
        }
    }
}
ng.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Hosting;
using System.Web.Http;
using Tango.BL;
using Tango.Core.DB;
using Tango.Core.Helpers;
using Tango.Core.IO;
using Tango.PMR.Stubs;
using Tango.PMR.Synchronization;
using Tango.Synchronization.Local;
using Tango.Synchronization.Remote;

namespace Tango.MachineService.Controllers
{
    public class SynchronizationController : ApiController
    {
        /// <summary>
        /// Expects a DB synchronization request from a remote machine and returns the synchronized version of the machine database.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        [HttpPost]
        public SynchronizeDBResponse Synchronize(SynchronizeDBRequest request)
        {
            var tempFolder = TemporaryManager.Default.CreateFolder();

            try
            {
                //File path for the reflected remote data base SQLite.
                String masterSQLiteFile = Path.Combine(tempFolder, "Remote.db");
                //File path for the received machine SQLite db.
                String slaveSQLiteFile = Path.Combine(tempFolder, "Local.db");

                //Save the machine db to file.
                File.WriteAllBytes(slaveSQLiteFile, request.LocalDB.ToByteArray());

                //Copy an SQLite db template.
                File.Copy(HostingEnvironment.MapPath(@"~/App_Data/Tango.db"), masterSQLiteFile);

                //Synchronize the SQL Server db with the new SQLite template. (Overwrite basically)
                RemoteDBSynchronizer.Synchronize(masterSQLiteFile, request.SerialNumber, true);

                //Synchronize the received machine db with the filled template.
                LocalDBSynchronizer.Synchronize(masterSQLiteFile, slaveSQLiteFile);

                //Send the synchronized machine db to the machine to the machine.
                SynchronizeDBResponse response = new SynchronizeDBResponse();
                response.RemoteDB = ByteString.CopyFrom(File.ReadAllBytes(slaveSQLiteFile));

                return response;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                //Remove all temporary files and folder.
                tempFolder.Delete();
            }
        }

        [HttpPost]
        public MachineSetupResponse MachineSetup(MachineSetupRequest request)
        {
            MachineSetupResponse response = new MachineSetupResponse();

            try
            {
                using (ObservablesContext db = ObservablesContext.CreateDefault(GetLocalServerAddress()))
                {
                    db.Configuration.LazyLoadingEnabled = false;
                    String serial_number = request.SerialNumber;

                    var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number);
                    var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid);

                    if (machine == null)
                    {
                        OnError(HttpStatusCode.NotFound, "The specified serial number could not be found.");
                    }

                    var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();

                    response.Version = latest_machine_version.Version;

                    response.FtpAddress = GetFtpAddress();
                    response.FtpFilePath = latest_machine_version.FtpFilePath;
                    response.FtpUserName = GetFtpUserName();
                    response.FtpPassword = GetFtpPassword();

                    DbCredentials credentials = new DbCredentials();

                    using (DbManager manager = DbManager.FromAddressAndName(GetDbAddress(), "Tango"))
                    {
                        credentials = manager.CreateRandomLoginAndUser("Tango");

                        Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) =>
                        {
                            using (DbManager m = DbManager.FromAddressAndName(GetDbAddress(), "Tango"))
                            {
                                m.DeleteLoginAndUser(credentials.UserName, "Tango");
                            }
                        });
                    }

                    response.DbAddress = GetDbAddress();
                    response.DbUserName = credentials.UserName;
                    response.DbPassword = credentials.Password;
                }
            }
            catch (Exception ex)
            {
                OnError(HttpStatusCode.InternalServerError, ex.Message);
            }

            return response;
        }

        #region Helpers

        private void OnError(HttpStatusCode code, String message)
        {
            throw new HttpResponseException(Request.CreateErrorResponse(code, message));
        }

        private String GetLocalServerAddress()
        {
            return ConfigurationManager.AppSettings["LocalServerAddress"].ToString();
        }

        private String GetDbAddress()
        {
            return ConfigurationManager.AppSettings["DbAddress"].ToString();
        }

        private String GetFtpAddress()
        {
            return ConfigurationManager.AppSettings["FtpAddress"].ToString();
        }

        private String GetFtpUserName()
        {
            return ConfigurationManager.AppSettings["FtpUserName"].ToString();
        }

        private String GetFtpPassword()
        {
            return ConfigurationManager.AppSettings["FtpPassword"].ToString();
        }

        #endregion
    }
}