aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs
blob: 6b4190313c0c8123167e90d088ecfe7dd394c74b (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
29
30
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.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 System;
using System.Text;
using System.Linq;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Tango.PMR.Stubs;
using Tango.Stubs;

public void OnExecute(StubManager stubManager)
{

    // Request ----
    // Int32 : Amount
    // Int32 : Delay

    // Response ----
    // Double : Progress


    ProgressRequest request = new ProgressRequest();
    request.Amount = 100;
    request.Delay = 1;

    stubManager.RunContinuous<ProgressResponse>(request, (response) =>
    {

        stubManager.WriteLine(response.Progress);

    });

}
id='n308' href='#n308'>308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
using Google.Protobuf;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.SqlServer.Management.Smo;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System.Web.Hosting;
using System.Web.Http;
using Tango.BL;
using Tango.BL.Builders;
using Tango.BL.Entities;
using Tango.BL.Enumerations;
using Tango.Core;
using Tango.Core.DB;
using Tango.Core.Helpers;
using Tango.Core.IO;
using Tango.Logging;
using Tango.MachineService.Models;
using Tango.PMR.Stubs;
using Tango.PMR.Synchronization;
using Tango.PPC.Common.MachineSetup;
using Tango.PPC.Common.MachineUpdate;
using Tango.PPC.Common.Update;
using Tango.Synchronization.Local;
using Tango.Synchronization.Remote;
using Tango.Web.Controllers;
using Tango.Web.Helpers;
using Tango.Web.SMO;
using Tango.Web.Storage;

namespace Tango.MachineService.Controllers
{
    public class PPCController : JsonController
    {
        private static List<PPCPendingUpload> _pendingUploads;

        #region Constructors

        static PPCController()
        {
            _pendingUploads = new List<PPCPendingUpload>();
        }

        #endregion

        #region Setup & Update

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

            LogManager.Log("Setup request received: " + request.ToString());

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                db.Configuration.LazyLoadingEnabled = false;
                String serial_number = request.SerialNumber;

                var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number);

                if (machine == null)
                {
                    throw new AuthenticationException("The specified serial number could not be found.");
                }

                if (machine.SetupActivation && machine.OsKey == null)
                {
                    throw new InvalidDataException("The specified machine is configured to perform an OS activation but is not associated with an OS activation key.");
                }

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

                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;

                var manager = new StorageManager();
                var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER);
                var blob = container.GetBlockBlobReference(latest_machine_version.BlobName);

                response.BlobAddress = blob.GenerateReadSignature(TimeSpan.FromMinutes(60));

                DbCredentials credentials = new DbCredentials();

                using (SmoManager smo = new SmoManager())
                {
                    credentials = smo.CreateRandomLoginAndUser();

                    Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) =>
                    {
                        using (SmoManager m = new SmoManager())
                        {
                            m.DeleteLoginAndUser(credentials.UserName);
                        }
                    });
                }

                response.DataSource = new DataSource()
                {
                    Address = MachineServiceConfig.DB_ADDRESS,
                    Catalog = MachineServiceConfig.DB_CATALOG,
                    UserName = credentials.UserName,
                    Password = credentials.Password,
                    IntegratedSecurity = false,
                    Type = DataSourceType.SQLServer,
                };

                response.OSKey = machine.OsKey;
                response.SetupActivation = machine.SetupActivation;
                response.SetupRemoteAssistance = machine.SetupRemoteAssistance;
                response.SetupUWF = machine.SetupUwf;
                response.SetupFirmware = machine.SetupFirmware;
                response.IsDemo = machine.IsDemo;

            }

            return response;
        }

        [HttpPost]
        public DownloadUpdateResponse MachineUpdate(DownloadUpdateRequest request)
        {
            DownloadUpdateResponse response = new DownloadUpdateResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                db.Configuration.LazyLoadingEnabled = false;
                String serial_number = request.SerialNumber;

                var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number);

                if (machine == null)
                {
                    throw new AuthenticationException("The specified serial number could not be found.");
                }

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

                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;

                var manager = new StorageManager();
                var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER);
                var blob = container.GetBlockBlobReference(latest_machine_version.BlobName);

                response.BlobAddress = blob.GenerateReadSignature(TimeSpan.FromMinutes(60));

                DbCredentials credentials = new DbCredentials();

                using (SmoManager smo = new SmoManager())
                {
                    credentials = smo.CreateRandomLoginAndUser();

                    Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) =>
                    {
                        using (SmoManager m = new SmoManager())
                        {
                            m.DeleteLoginAndUser(credentials.UserName);
                        }
                    });
                }

                response.DataSource = new DataSource()
                {
                    Address = MachineServiceConfig.DB_ADDRESS,
                    Catalog = MachineServiceConfig.DB_CATALOG,
                    UserName = credentials.UserName,
                    Password = credentials.Password,
                    IntegratedSecurity = false,
                    Type = DataSourceType.SQLServer,
                };
            }

            return response;
        }

        [HttpPost]
        public CheckForUpdateResponse CheckForUpdate(CheckForUpdateRequest request)
        {
            CheckForUpdateResponse response = new CheckForUpdateResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                db.Configuration.LazyLoadingEnabled = false;

                var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == request.SerialNumber);

                if (machine == null)
                {
                    throw new AuthenticationException("The specified serial number could not be found.");
                }

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

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

                if (Version.Parse(latest_machine_version.Version) > Version.Parse(request.Version))
                {
                    response.IsUpdateAvailable = true;
                }

                response.Version = latest_machine_version.Version;
            }

            return response;
        }

        [HttpPost]
        public UpdateDBResponse UpdateDB(UpdateDBRequest request)
        {
            UpdateDBResponse response = new UpdateDBResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                db.Configuration.LazyLoadingEnabled = false;
                String serial_number = request.SerialNumber;

                var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == serial_number);

                if (machine == null)
                {
                    throw new AuthenticationException("The specified serial number could not be found.");
                }

                DbCredentials credentials = new DbCredentials();

                using (SmoManager manager = new SmoManager())
                {
                    credentials = manager.CreateRandomLoginAndUser();

                    Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) =>
                    {
                        using (SmoManager m = new SmoManager())
                        {
                            m.DeleteLoginAndUser(credentials.UserName);
                        }
                    });
                }

                response.DataSource = new DataSource()
                {
                    Address = MachineServiceConfig.DB_ADDRESS,
                    Catalog = MachineServiceConfig.DB_CATALOG,
                    UserName = credentials.UserName,
                    Password = credentials.Password,
                    IntegratedSecurity = false,
                    Type = DataSourceType.SQLServer,
                };
            }

            return response;
        }

        #endregion

        #region Version Upload

        [HttpPost]
        public LatestVersionResponse GetLatestVersion(LatestVersionRequest request)
        {
            LatestVersionResponse response = new LatestVersionResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                var versions = db.TangoVersions.ToList();

                if (versions.Count == 0)
                {
                    return new LatestVersionResponse()
                    {
                        Version = "0.0.0.0",
                    };
                }

                var machine_versions = versions.Where(x => x.MachineVersionGuid == request.MachineVersionGuid).ToList();

                if (machine_versions.Count > 0)
                {
                    response.Version = db.TangoVersions.Where(x => x.MachineVersionGuid == request.MachineVersionGuid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault().Version;
                }
                else
                {
                    throw new ArgumentException("The specified machine version was not found!");
                }
            }

            return response;
        }

        [HttpPost]
        public UploadVersionResponse UploadVersion(UploadVersionRequest request)
        {
            UploadVersionResponse response = new UploadVersionResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                //Load relations first...
                db.Roles.ToList();
                db.Permissions.ToList();
                db.UsersRoles.ToList();
                db.RolesPermissions.ToList();

                var user = db.Users.SingleOrDefault(x => x.Email.ToLower() == request.Email.ToLower() && x.Password == request.Password);

                if (user != null && user.HasPermission(Permissions.PublishPPCVersions))
                {
                    var versions = db.TangoVersions.ToList().Where(x => x.MachineVersionGuid == request.MachineVersionGuid).OrderByDescending(x => Version.Parse(x.Version)).ToList();

                    TangoVersion latestVersion = new TangoVersion();
                    latestVersion.Version = "0.0.0.0";

                    if (versions.Count > 0)
                    {
                        latestVersion = versions.FirstOrDefault();
                    }

                    Version currentVersion = Version.Parse(request.Version);

                    if (currentVersion > Version.Parse(latestVersion.Version))
                    {
                        String newVersionFileName = "Tango Version" + " " + currentVersion.ToString() + ".zip";

                        var manager = new StorageManager();
                        var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER);
                        var blob = container.CreateEmptyBlob(newVersionFileName);

                        response.Token = Guid.NewGuid().ToString();
                        response.BlobAddress = blob.GenerateWriteSignature(TimeSpan.FromMinutes(30));

                        _pendingUploads.Add(new PPCPendingUpload()
                        {
                            UserGuid = user.Guid,
                            Comments = request.Comments,
                            Token = response.Token,
                            Version = request.Version,
                            BlobName = blob.Name,
                            MachineVersionGuid = request.MachineVersionGuid,
                        });
                    }
                    else
                    {
                        throw new ArgumentException("New version must be greater than latest version.");
                    }
                }
                else
                {
                    throw new AuthenticationException("Invalid user credentials.");
                }
            }

            return response;
        }

        [HttpPost]
        public UploadCompletedResponse NotifyUploadCompleted(UploadCompletedRequest request)
        {
            PPCPendingUpload upload = _pendingUploads.FirstOrDefault(x => x.Token == request.Token);

            if (upload != null)
            {
                _pendingUploads.RemoveAll(x => x.Token == upload.Token);

                using (ObservablesContext db = ObservablesContextHelper.CreateContext())
                {
                    db.TangoVersions.Add(new TangoVersion()
                    {
                        Comments = upload.Comments,
                        BlobName = upload.BlobName,
                        UserGuid = upload.UserGuid,
                        Version = upload.Version,
                        MachineVersionGuid = upload.MachineVersionGuid
                    });

                    db.SaveChanges();
                }

                return new UploadCompletedResponse();
            }
            else
            {
                throw new AuthenticationException("Invalid upload token.");
            }
        }

        #endregion

        [HttpPost]
        public Machine PersonTest(Person p)
        {
            using (var db = ObservablesContextHelper.CreateContext())
            {
                var machine = new MachineBuilder(db)
                    .Set(x => x.SerialNumber == "1111")
                    .WithOrganization()
                    .WithConfiguration().Build();

                return machine;
            }
        }
    }
}