Free cookie consent management tool by TermsFeed Policy Generator

Changeset 13739


Ignore:
Timestamp:
03/29/16 17:02:16 (8 years ago)
Author:
jlodewyc
Message:

#2582 Overhaul Login service, done

Location:
branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager
Files:
2 added
12 deleted
21 edited

Legend:

Unmodified
Added
Removed
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/HomeController.cs

    r13733 r13739  
    55using Microsoft.AspNet.Mvc;
    66using System.ServiceModel.Security;
     7using Microsoft.AspNet.Http;
     8using System;
     9using HeuristicLab.Clients.Hive.WebJobManager.ViewModels;
    710
    811namespace HeuristicLab.Clients.Hive.WebJobManager.Controllers
     
    1316    public class HomeController : Controller
    1417    {
    15         private LoginViewModelService loginViewModelService;
     18        private WebLoginService weblog;
    1619        private HiveServiceClient client;
    17         public HomeController(ILoginViewModelService loginViewModelService)
     20        public HomeController()
    1821        {
    19             this.loginViewModelService = (LoginViewModelService)loginViewModelService;
     22            this.weblog = WebLoginService.Instance;
    2023        }
    2124        #region Login
     
    2730        {
    2831            ViewBag.Title = "Login";
    29             loginViewModelService.clear();
    30             return View(loginViewModelService.GetLoginViewModel());
     32            var user = HttpContext.Session.GetString("UserId");
     33            if(user != null && user != "")
     34            {
     35                Guid t = Guid.Parse(user);
     36                weblog.logout(t);
     37                HttpContext.Session.Clear();
     38            }
     39            return View(new LoginViewModel());
     40
    3141        }
    3242        /// <summary>
     
    4050            if (!string.IsNullOrEmpty(loginName) && !string.IsNullOrEmpty(password))
    4151            {
    42                 var model = loginViewModelService.GetLoginViewModel();
    43                 HiveServiceLocatorWeb hiveServiceLocator = (HiveServiceLocatorWeb)HiveServiceLocatorWeb.Instance;
    44                 HeuristicLab.Clients.Common.Properties.Settings.Default.UserName = loginName;
    45                 HeuristicLab.Clients.Common.Properties.Settings.Default.Password = Common.CryptoService.EncryptString(password);
    46                 HeuristicLab.Clients.Common.Properties.Settings.Default.Save();
     52                var passE = Common.CryptoService.EncryptString(password);
     53                var model = new LoginViewModel(loginName, passE);
     54                HiveServiceLocatorWeb hiveServiceLocator = new HiveServiceLocatorWeb();
     55                Common.Properties.Settings.Default.UserName = loginName;
     56                Common.Properties.Settings.Default.Password = passE;
     57                Common.Properties.Settings.Default.Save();
    4758                hiveServiceLocator.Username = loginName;
    4859                hiveServiceLocator.Password = password;
     60                hiveServiceLocator.UserId = model.userId;
    4961
    5062                client = hiveServiceLocator.getHiveServiceClient();
     
    5264                    var test = client.GetJobs();//Throws messageSecurityException if login failss
    5365                    ViewBag.Title = "Login succesful";
    54                    
     66                    weblog.newLogin(model, hiveServiceLocator);
     67                    HttpContext.Session.SetString("UserId", model.userId.ToString());
    5568                    return RedirectToAction("Index","Job");
    5669                }
     
    5871                {
    5972                    ViewBag.Title = "Login";
     73                    model = new LoginViewModel();
    6074                    model.errorMessage = "Wrong login, try again";
    6175                    return View("Index", model);
     
    6680            {
    6781                ViewBag.Title = "Login";
    68                 var model = loginViewModelService.GetLoginViewModel();
     82                var model = new LoginViewModel();
    6983                model.errorMessage = "You should fill in both fields";
    7084                return View("Index", model);
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/JobController.cs

    r13735 r13739  
    2323    public class JobController : Controller
    2424    {
    25         private HiveServiceClient client;
     25        private WebLoginService weblog;
     26
     27        private HiveServiceLocatorWeb serviceLocator;
     28        private HiveServiceClient serviceClient;
     29        private HiveClientWeb clientWeb;
     30        private Guid userId;
     31
    2632        private JobViewModel vm;
    2733        private IHostingEnvironment _environment;
    2834
     35
     36
    2937        public JobController(IHostingEnvironment env)
    3038        {
    31             HiveServiceLocatorWeb hiveServiceLocator = (HiveServiceLocatorWeb)HiveServiceLocatorWeb.Instance;
    32             client = hiveServiceLocator.getHiveServiceClient();
     39            weblog = WebLoginService.Instance;
    3340            vm = new JobViewModel();
    34 
    35 
    3641            _environment = env;
    3742        }
     43
     44        /// <summary>
     45        /// initializes the connection for the right user. Not constructor because httpcontext is needed.
     46        /// </summary>
     47        private void init()
     48        {
     49            var u = HttpContext.Session.GetString("UserId");
     50            if (u == null || u == "" || Guid.Parse(u) == Guid.Empty)
     51            {
     52                userId = Guid.Empty;
     53                serviceLocator = new HiveServiceLocatorWeb();
     54                serviceClient = serviceLocator.getHiveServiceClient();
     55                clientWeb = new HiveClientWeb(serviceLocator, userId);
     56            }
     57            else
     58            {
     59                userId = Guid.Parse(u);
     60                serviceLocator = weblog.getServiceLocator(userId);
     61                serviceClient = serviceLocator.getHiveServiceClient();
     62                clientWeb = weblog.getClientWeb(userId);
     63            }
     64        }
     65
    3866        #region Jobs
    3967        /// <summary>
     
    4573            try
    4674            {
    47                 HiveClientWeb.Instance.Refresh();
    48 
    49                 vm.userJobs = HiveClientWeb.Instance.Jobs.ToList();
     75                init();
     76                clientWeb.Refresh();
     77                vm.userJobs = clientWeb.Jobs.ToList();
    5078            }
    5179            catch (Exception e)
     
    5381                if (e is MessageSecurityException || e is InvalidOperationException)
    5482                {
    55                     HiveServiceLocatorWeb.SetLoginErrorMessage();
    5683                    return RedirectToAction("Index", "Home");
    5784                }
    5885                throw;
    5986            }
     87            ViewBag.SessionId = HttpContext.Session.GetString("UserId");
    6088            ViewBag.Title = "Jobs";
    6189            return View(vm);
     
    6896        public IActionResult Selected(Guid id)
    6997        {
    70             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
    71             {
    72                 HiveClientWeb.Instance.Refresh();
    73                
    74                 vm.userJobs = HiveClientWeb.Instance.Jobs.ToList();
    75                 foreach(var j in vm.userJobs)
    76                 {
    77                     if(j.Id == id)
     98            init();
     99            if (serviceLocator.CheckLogin())
     100            {
     101                clientWeb.Refresh();
     102
     103                vm.userJobs = clientWeb.Jobs.ToList();
     104                foreach (var j in vm.userJobs)
     105                {
     106                    if (j.Id == id)
    78107                    {
    79108                        vm.selectedJob = j;
    80109                    }
    81110                }
    82                 vm.selectedJob.RefreshAutomatically = true;
    83                  HiveClientWeb.LoadJob(vm.selectedJob);
    84                 FileOpeningService.Instance.NewModel();
    85                 FileOpeningService.Instance.Job = vm.selectedJob;
     111                //vm.selectedJob.RefreshAutomatically = true;
     112                clientWeb.LoadJob(vm.selectedJob);
     113                weblog.getFileOpener(userId).NewModel();
     114                weblog.getFileOpener(userId).Job = vm.selectedJob;
    86115                ViewBag.Title = vm.selectedJob.Job.Name + " - Jobs";
     116                ViewBag.SessionId = HttpContext.Session.GetString("UserId");
    87117                return View("Index", vm);
    88118            }
    89119            else
    90120            {
    91                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    92121                return RedirectToAction("Index", "Home");
    93122            }
     
    100129        public IActionResult Delete(Guid id)
    101130        {
    102             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
    103             {
    104 
    105                 vm.message = client.GetJob(id).Name + " deleted";
    106                 client.DeleteJob(id);
    107                 HiveClientWeb.Instance.Refresh();
    108 
    109                 vm.userJobs = HiveClientWeb.Instance.Jobs.ToList();
     131            init();
     132            if (serviceLocator.CheckLogin())
     133            {
     134
     135                vm.message = serviceClient.GetJob(id).Name + " deleted";
     136                serviceClient.DeleteJob(id);
     137                clientWeb.Refresh();
     138
     139                vm.userJobs = clientWeb.Jobs.ToList();
    110140                ViewBag.Title = "Jobs";
    111141                return View("Index", vm);
     
    113143            else
    114144            {
    115                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    116145                return RedirectToAction("Index", "Home");
    117146            }
     
    126155        public IActionResult Uploads()
    127156        {
    128             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
     157            init();
     158            if (serviceLocator.CheckLogin())
    129159            {
    130160                UploadedJobViewModel upper = new UploadedJobViewModel();
    131161                fillUploadsPaths(upper, -1);
    132                 ViewBag.Name = client.ClientCredentials.UserName.UserName;
     162                ViewBag.Name = serviceClient.ClientCredentials.UserName.UserName;
    133163                ViewBag.Title = "Uploaded files";
    134164                return View("Uploads", upper);
     
    136166            else
    137167            {
    138                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    139168                return RedirectToAction("Index", "Home");
    140169            }
     
    147176        public IActionResult UploadDir(int index)
    148177        {
    149             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
     178            init();
     179            if (serviceLocator.CheckLogin())
    150180            {
    151181                UploadedJobViewModel upper = new UploadedJobViewModel();
     
    157187            else
    158188            {
    159                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    160189                return RedirectToAction("Index", "Home");
    161190            }
     
    167196        /// <param name="index">Index selected directory</param>
    168197        private void fillUploadsPaths(UploadedJobViewModel vm, int index)
    169            
    170198        {
    171199            var tempdex = index; //Fix when maps gets deleted
    172             var start = Path.Combine(_environment.WebRootPath, "uploads", client.ClientCredentials.UserName.UserName);
     200            var start = Path.Combine(_environment.WebRootPath, "uploads", serviceClient.ClientCredentials.UserName.UserName);
    173201            var dirs = Directory.GetDirectories(start);
    174202            foreach (string dir in dirs)
     
    205233        public IActionResult DeleteFile(int index, int filedex)
    206234        {
    207             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
     235            init();
     236            if (serviceLocator.CheckLogin())
    208237            {
    209238                UploadedJobViewModel upper = new UploadedJobViewModel();
     
    221250            else
    222251            {
    223                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    224252                return RedirectToAction("Index", "Home");
    225253            }
     
    233261        public IActionResult OpenFile(int index, int filedex)
    234262        {
    235             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
     263            init();
     264            if (serviceLocator.CheckLogin())
    236265            {
    237266                UploadedJobViewModel upper = new UploadedJobViewModel();
    238267                fillUploadsPaths(upper, index);
    239268
    240                 FileOpeningService serve = FileOpeningService.Instance;
     269                var serve = weblog.getFileOpener(userId);
    241270                serve.NewModel();
    242271                serve.env = _environment;
     
    260289                ViewBag.JobsCount = serve.Job.Job.JobCount;
    261290                ViewBag.Title = serve.vm.SelectedTask.ItemTask.Name + " - Open file";
    262 
     291                ViewBag.SessionId = HttpContext.Session.GetString("UserId");
    263292                return View("OpenFile", serve.vm);
    264293            }
    265294            else
    266295            {
    267                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    268296                return RedirectToAction("Index", "Home");
    269297            }
     
    275303        public IActionResult AddToHive()
    276304        {
    277             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
    278             {
    279                     var job = FileOpeningService.Instance.AddCurrentModelToHive();
    280                     while (job.Progress.ProgressValue != 1)
    281                     { }
    282 
    283                     Thread.Sleep(1000);
    284                     job.Progress.Status = "Upload finished";
    285                     Thread.Sleep(2000);
    286                     return RedirectToAction("Index", "Job");
    287             }
    288             else
    289             {
    290                 HiveServiceLocatorWeb.SetLoginErrorMessage();
     305            init();
     306            if (serviceLocator.CheckLogin())
     307            {
     308                var job = weblog.getFileOpener(userId).AddCurrentModelToHive();
     309                while (job.Progress.ProgressValue != 1)
     310                { }
     311
     312                Thread.Sleep(1000);
     313                job.Progress.Status = "Upload finished";
     314                Thread.Sleep(2000);
     315                return RedirectToAction("Index", "Job");
     316            }
     317            else
     318            {
    291319                return RedirectToAction("Index", "Home");
    292320            }
     
    334362        public async Task<IActionResult> Uploader(ICollection<IFormFile> files, string directory)
    335363        {
    336 
     364            init();
    337365            UploadedJobViewModel upper = new UploadedJobViewModel();
    338             var uploads = Path.Combine(_environment.WebRootPath, "uploads", client.ClientCredentials.UserName.UserName,
     366            var uploads = Path.Combine(_environment.WebRootPath, "uploads", serviceClient.ClientCredentials.UserName.UserName,
    339367                directory);
    340368            Directory.CreateDirectory(uploads);
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/ResourceController.cs

    r13733 r13739  
    11using HeuristicLab.Clients.Hive.WebJobManager.Services;
    22using Microsoft.AspNet.Hosting;
     3using Microsoft.AspNet.Http;
    34using Microsoft.AspNet.Mvc;
    45using System;
     
    1213    public class ResourceController : Controller
    1314    {
    14         private HiveServiceClient client;
     15        private WebLoginService weblog;
     16        private HiveServiceLocatorWeb serviceLocator;
     17        private HiveServiceClient serviceClient;
     18        private HiveClientWeb clientWeb;
     19        private Guid userId;
     20
    1521        private IHostingEnvironment _environment;
    1622
    1723        public ResourceController(IHostingEnvironment env)
    1824        {
    19             HiveServiceLocatorWeb hiveServiceLocator = (HiveServiceLocatorWeb)HiveServiceLocatorWeb.Instance;
    20             client = hiveServiceLocator.getHiveServiceClient();
     25            weblog = WebLoginService.Instance;
     26            var u = HttpContext.Session.GetString("UserId");
     27            if (u == null || u == "" || Guid.Parse(u) == Guid.Empty)
     28            {
     29                userId = Guid.Empty;
     30                serviceLocator = new HiveServiceLocatorWeb();
     31                serviceClient = serviceLocator.getHiveServiceClient();
     32                clientWeb = new HiveClientWeb(serviceLocator, userId);
     33            }
     34            else {
     35                userId = Guid.Parse(u);
     36
     37                serviceLocator = weblog.getServiceLocator(userId);
     38                serviceClient = serviceLocator.getHiveServiceClient();
     39                clientWeb = weblog.getClientWeb(userId);
     40            }
    2141
    2242            _environment = env;
     
    2444        public IActionResult Index()
    2545        {
    26             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
     46            if (serviceLocator.CheckLogin())
    2747            {
    2848
     
    3252            else
    3353            {
    34                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    3554                return RedirectToAction("Index", "Home");
    3655            }
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/UserController.cs

    r13733 r13739  
    11using HeuristicLab.Clients.Hive.WebJobManager.Services;
    22using Microsoft.AspNet.Hosting;
     3using Microsoft.AspNet.Http;
    34using Microsoft.AspNet.Mvc;
    45using System;
     
    1213    public class UserController: Controller
    1314    {
    14         private HiveServiceClient client;
     15        private WebLoginService weblog;
     16        private HiveServiceLocatorWeb serviceLocator;
     17        private HiveServiceClient serviceClient;
     18        private HiveClientWeb clientWeb;
     19        private Guid userId;
     20
    1521        private IHostingEnvironment _environment;
    1622
    1723        public UserController(IHostingEnvironment env)
    1824        {
    19             HiveServiceLocatorWeb hiveServiceLocator = (HiveServiceLocatorWeb)HiveServiceLocatorWeb.Instance;
    20             client = hiveServiceLocator.getHiveServiceClient();
     25            weblog = WebLoginService.Instance;
     26            var u = HttpContext.Session.GetString("UserId");
     27            if (u == null || u == "" || Guid.Parse(u) == Guid.Empty)
     28            {
     29                userId = Guid.Empty;
     30                serviceLocator = new HiveServiceLocatorWeb();
     31                serviceClient = serviceLocator.getHiveServiceClient();
     32                clientWeb = new HiveClientWeb(serviceLocator, userId);
     33            }
     34            else {
     35                userId = Guid.Parse(u);
     36
     37                serviceLocator = weblog.getServiceLocator(userId);
     38                serviceClient = serviceLocator.getHiveServiceClient();
     39                clientWeb = weblog.getClientWeb(userId);
     40            }
    2141
    2242            _environment = env;
     
    2444        public IActionResult Index()
    2545        {
    26             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
     46            if (serviceLocator.CheckLogin())
    2747            {
    2848               
     
    3252            else
    3353            {
    34                 HiveServiceLocatorWeb.SetLoginErrorMessage();
    3554                return RedirectToAction("Index", "Home");
    3655            }
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Hubs/JobUpdaterHub.cs

    r13735 r13739  
    11using HeuristicLab.Clients.Hive.WebJobManager.Services;
    22using HeuristicLab.Common;
     3using Microsoft.AspNet.Http;
    34using Microsoft.AspNet.SignalR;
    45using Newtonsoft.Json;
    56using System;
    67using System.Collections.Generic;
     8using System.Threading.Tasks;
    79
    810namespace HeuristicLab.Clients.Hive.WebJobManager
     
    1517       
    1618        private RefreshableJob Job;//Current job (only used as reference, instance gets lost)
    17      
     19
     20        private WebLoginService weblog;
     21        private FileOpeningService fileopener;
     22        private Guid userId;
     23
     24        private void loader()
     25        {
     26            weblog = WebLoginService.Instance;
     27            string uid = Context.QueryString["userid"];
     28            if (uid == null || uid == "" || Guid.Parse(uid) == Guid.Empty)
     29            {
     30                userId = Guid.Empty;
     31            }
     32            else {
     33                userId = Guid.Parse(uid);
     34                fileopener = weblog.getFileOpener(userId);
     35            }
     36        }
    1837        /// <summary>
    1938        /// Initial connection call from client
     
    2140        public void initConnection()
    2241        {
    23             FileOpeningService.Instance.previousids = new List<Guid>();
    24             FileOpeningService.Instance.previousLogs = new List<int>();
    25             Job = FileOpeningService.Instance.Job;
     42            loader();
     43            fileopener.previousids = new List<Guid>();
     44            fileopener.previousLogs = new List<int>();
     45            Job = fileopener.Job;
    2646            updateAll();//start initial update
    2747
     
    3252        public void updateAll()
    3353        {
    34             FileOpeningService.Instance.refreshJob();//refresh all data from job
    35             Job = FileOpeningService.Instance.Job;
     54            loader();
     55            fileopener.refreshJob();//refresh all data from job
     56            Job = fileopener.Job;
    3657            updateJob();
    3758            foreach (var t in Job.HiveTasks)
     
    4566
    4667        }
    47         public void updateJob()
     68        private void updateJob()
    4869        {
    4970            Clients.Caller.processJobData(Job.Job.CalculatingCount, Job.Job.FinishedCount);
     
    5980                int index;
    6081                bool test = false;
    61                 if (FileOpeningService.Instance.previousids.Contains(task.Task.Id))
     82                if (fileopener.previousids.Contains(task.Task.Id))
    6283                {
    63                     index = FileOpeningService.Instance.previousids.IndexOf(task.Task.Id);
     84                    index = fileopener.previousids.IndexOf(task.Task.Id);
    6485                }
    6586                else
    6687                {//initial add to previous list, used to check if updates happened
    67                     FileOpeningService.Instance.previousids.Add(task.Task.Id);
    68                     index = FileOpeningService.Instance.previousids.IndexOf(task.Task.Id);
    69                     FileOpeningService.Instance.previousLogs.Add(task.Task.StateLog.Count);
     88                    fileopener.previousids.Add(task.Task.Id);
     89                    index = fileopener.previousids.IndexOf(task.Task.Id);
     90                    fileopener.previousLogs.Add(task.Task.StateLog.Count);
    7091                    test = true;//initial added task, data must be sent
    7192                }
    72                 var previous = FileOpeningService.Instance.previousLogs[index];
     93                var previous = fileopener.previousLogs[index];
    7394                if (test || previous < task.Task.StateLog.Count)
    7495                {//Checks if change happened so data is not sent unnecessary
    75                     FileOpeningService.Instance.previousLogs[index] = task.Task.StateLog.Count;
     96                    fileopener.previousLogs[index] = task.Task.StateLog.Count;
    7697                    JsonSerializerSettings settings = new JsonSerializerSettings();
    7798                    settings.ContractResolver = new JsonTaskResolver();
     
    94115        public void restartTask(Guid id)
    95116        {
    96             ((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).getHiveServiceClient().RestartTask(id);
     117            loader();
     118            weblog.getServiceLocator(userId).getHiveServiceClient().RestartTask(id);
    97119        }
    98120    }
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Hubs/ProgressHub.cs

    r13735 r13739  
    1515    public class ProgressHub : Hub
    1616    {
    17         private RefreshableJob Job;
     17        private WebLoginService weblog;
     18        private Guid userId;
     19        private FileOpeningService fileopener;
     20        private void loader()
     21        {
     22            weblog = WebLoginService.Instance;
     23            string uid = Context.QueryString["userid"];
     24            if (uid == null || uid == "" || Guid.Parse(uid) == Guid.Empty)
     25            {
     26                userId = Guid.Empty;
     27            }
     28            else {
     29                userId = Guid.Parse(uid);
     30                fileopener = weblog.getFileOpener(userId);
     31            }
     32        }
     33
    1834        /// <summary>
    1935        /// First message from client
     
    2238        public void HandleMessage(string receivedString)
    2339        {
    24 
     40            loader();
    2541            Clients.Caller.processMessage("Connection Established");
    26             Job = FileOpeningService.Instance.Job;
    27             Job.Progress.StatusChanged += runHub;
     42            fileopener.Job.Progress.StatusChanged += runHub;
    2843        }
    2944        /// <summary>
     
    3348        public void ChangeNameResource(string name, string resource)
    3449        {
     50            loader();
    3551            if (name != null)
    36                 FileOpeningService.Instance.Job.Job.Name = name;
     52                fileopener.Job.Job.Name = name;
    3753            if(resource != null && resource != "")
    3854            {
    39                 FileOpeningService.Instance.Job.Job.ResourceNames += "/" + resource;
     55                fileopener.Job.Job.ResourceNames += "/" + resource;
    4056            }
    4157        }
     
    4965        public void ToggleChild(int[][] arr)
    5066        {
    51             Job = FileOpeningService.Instance.Job;
    52             HiveTask current = Job.HiveTasks.ToList()[0];
     67            loader();
     68            HiveTask current = fileopener.Job.HiveTasks.ToList()[0];
    5369            if (arr.Length == 0)
    5470            {//check if upper job
     
    92108        public void ChangePriority(int[][] arr, int prior)
    93109        {
    94             Job = FileOpeningService.Instance.Job;
    95             HiveTask current = Job.HiveTasks.ToList()[0];
     110            loader();
     111            HiveTask current = fileopener.Job.HiveTasks.ToList()[0];
    96112            if (arr.Length == 0)
    97113            {//check if upper job
     
    132148        public void runHub(object sender, EventArgs e)
    133149        {
     150            loader();
    134151            int value = 0;
    135152
    136             switch (Job.Progress.Status)
     153            switch (fileopener.Job.Progress.Status)
    137154            {
    138155                case "Connecting to server...":
     
    152169                    break;
    153170                default://Tasks are uploading individually
    154                     value = (int)(50 + (40 * Job.Progress.ProgressValue));
     171                    value = (int)(50 + (40 * fileopener.Job.Progress.ProgressValue));
    155172                    break;
    156173
    157174            }
    158175            //send info to client
    159             Clients.Caller.processMessage(Job.Progress.Status, value);
     176            Clients.Caller.processMessage(fileopener.Job.Progress.Status, value);
    160177
    161178        }
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/ConcurrentTaskDownloaderWeb.cs

    r13733 r13739  
    3030
    3131    //
    32   /// <summary>
    33   /// Rewritten to use HiveServiceLocatorWeb and HiveClientWeb
    34   /// </summary>
    35   public class ConcurrentTaskDownloaderWeb<T> : IDisposable where T : class, ITask {
    36     private bool abort = false;
    37     // use semaphore to ensure only few concurrenct connections and few SerializedJob objects in memory
    38     private Semaphore downloadSemaphore;
    39     private Semaphore deserializeSemaphore;
     32    /// <summary>
     33    /// Rewritten to use HiveServiceLocatorWeb and HiveClientWeb
     34    /// </summary>
     35    public class ConcurrentTaskDownloaderWeb<T> : IDisposable where T : class, ITask
     36    {
     37        private bool abort = false;
     38        // use semaphore to ensure only few concurrenct connections and few SerializedJob objects in memory
     39        private Semaphore downloadSemaphore;
     40        private Semaphore deserializeSemaphore;
     41        private HiveServiceLocatorWeb serviceLocator;
     42        public ConcurrentTaskDownloaderWeb(int concurrentDownloads, int concurrentDeserializations, HiveServiceLocatorWeb hiv)
     43        {
     44            downloadSemaphore = new Semaphore(concurrentDownloads, concurrentDownloads);
     45            deserializeSemaphore = new Semaphore(concurrentDeserializations, concurrentDeserializations);
     46            serviceLocator = hiv;
     47        }
    4048
    41     public ConcurrentTaskDownloaderWeb(int concurrentDownloads, int concurrentDeserializations) {
    42       downloadSemaphore = new Semaphore(concurrentDownloads, concurrentDownloads);
    43       deserializeSemaphore = new Semaphore(concurrentDeserializations, concurrentDeserializations);
     49        public void DownloadTaskData(Task t, Action<Task, T> onFinishedAction)
     50        {
     51            Task<Tuple<Task, T>> task = Task<Tuple<Task, TaskData>>.Factory.StartNew(DownloadTaskData, t)
     52                                           .ContinueWith((y) => DeserializeTask(y.Result));
     53
     54            task.ContinueWith((x) => OnTaskFinished(x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
     55            task.ContinueWith((x) => OnTaskFailed(x), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
     56        }
     57
     58        public void DownloadTaskDataAndTask(Guid taskId, Action<Task, T> onFinishedAction)
     59        {
     60            Task<Tuple<Task, T>> task = Task<Task>.Factory.StartNew(DownloadTask, taskId)
     61                                           .ContinueWith((x) => DownloadTaskData(x.Result))
     62                                           .ContinueWith((y) => DeserializeTask(y.Result));
     63
     64            task.ContinueWith((x) => OnTaskFinished(x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
     65            task.ContinueWith((x) => OnTaskFailed(x), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
     66        }
     67
     68        private void OnTaskFinished(Task<Tuple<Task, T>> task, Action<Task, T> onFinishedAction)
     69        {
     70            onFinishedAction(task.Result.Item1, task.Result.Item2);
     71        }
     72        private void OnTaskFailed(Task<Tuple<Task, T>> task)
     73        {
     74            task.Exception.Flatten().Handle((e) => { return true; });
     75            OnExceptionOccured(task.Exception.Flatten());
     76        }
     77
     78        private Task DownloadTask(object taskId)
     79        {
     80            Task t = null;
     81            HiveClientWeb.TryAndRepeat(() =>
     82            {
     83                t = serviceLocator.CallHiveService(s => s.GetTask((Guid)taskId));
     84            }, Settings.Default.MaxRepeatServiceCalls, "Failed to download task.");
     85            return t;
     86        }
     87
     88        protected Tuple<Task, TaskData> DownloadTaskData(object taskId)
     89        {
     90            return DownloadTaskData((Task)taskId);
     91        }
     92
     93        protected Tuple<Task, TaskData> DownloadTaskData(Task task)
     94        {
     95            downloadSemaphore.WaitOne();
     96            TaskData result = null;
     97            try
     98            {
     99                if (abort) return null;
     100                HiveClientWeb.TryAndRepeat(() =>
     101                {
     102                    result = serviceLocator.CallHiveService(s => s.GetTaskData(task.Id));
     103                }, Settings.Default.MaxRepeatServiceCalls, "Failed to download task data.");
     104            }
     105            finally
     106            {
     107                downloadSemaphore.Release();
     108            }
     109            return new Tuple<Task, TaskData>(task, result);
     110        }
     111
     112        protected Tuple<Task, T> DeserializeTask(Tuple<Task, TaskData> taskData)
     113        {
     114            deserializeSemaphore.WaitOne();
     115            try
     116            {
     117                if (abort || taskData.Item2 == null || taskData.Item1 == null) return null;
     118                var deserializedJob = PersistenceUtil.Deserialize<T>(taskData.Item2.Data);
     119                taskData.Item2.Data = null; // reduce memory consumption.
     120                return new Tuple<Task, T>(taskData.Item1, deserializedJob);
     121            }
     122            finally
     123            {
     124                deserializeSemaphore.Release();
     125            }
     126        }
     127
     128        public event EventHandler<EventArgs<Exception>> ExceptionOccured;
     129        private void OnExceptionOccured(Exception exception)
     130        {
     131            var handler = ExceptionOccured;
     132            if (handler != null) handler(this, new EventArgs<Exception>(exception));
     133        }
     134
     135        #region IDisposable Members
     136        public void Dispose()
     137        {
     138            deserializeSemaphore.Dispose();
     139            downloadSemaphore.Dispose();
     140        }
     141        #endregion
    44142    }
    45 
    46     public void DownloadTaskData(Task t, Action<Task, T> onFinishedAction) {
    47       Task<Tuple<Task, T>> task = Task<Tuple<Task, TaskData>>.Factory.StartNew(DownloadTaskData, t)
    48                                      .ContinueWith((y) => DeserializeTask(y.Result));
    49 
    50       task.ContinueWith((x) => OnTaskFinished(x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
    51       task.ContinueWith((x) => OnTaskFailed(x), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
    52     }
    53 
    54     public void DownloadTaskDataAndTask(Guid taskId, Action<Task, T> onFinishedAction) {
    55       Task<Tuple<Task, T>> task = Task<Task>.Factory.StartNew(DownloadTask, taskId)
    56                                      .ContinueWith((x) => DownloadTaskData(x.Result))
    57                                      .ContinueWith((y) => DeserializeTask(y.Result));
    58 
    59       task.ContinueWith((x) => OnTaskFinished(x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
    60       task.ContinueWith((x) => OnTaskFailed(x), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
    61     }
    62 
    63     private void OnTaskFinished(Task<Tuple<Task, T>> task, Action<Task, T> onFinishedAction) {
    64       onFinishedAction(task.Result.Item1, task.Result.Item2);
    65     }
    66     private void OnTaskFailed(Task<Tuple<Task, T>> task) {
    67       task.Exception.Flatten().Handle((e) => { return true; });
    68       OnExceptionOccured(task.Exception.Flatten());
    69     }
    70 
    71     private Task DownloadTask(object taskId) {
    72       Task t = null;
    73       HiveClientWeb.TryAndRepeat(() => {
    74         t = HiveServiceLocatorWeb.Instance.CallHiveService(s => s.GetTask((Guid)taskId));
    75       }, Settings.Default.MaxRepeatServiceCalls, "Failed to download task.");
    76       return t;
    77     }
    78 
    79     protected Tuple<Task, TaskData> DownloadTaskData(object taskId) {
    80       return DownloadTaskData((Task)taskId);
    81     }
    82 
    83     protected Tuple<Task, TaskData> DownloadTaskData(Task task) {
    84       downloadSemaphore.WaitOne();
    85       TaskData result = null;
    86       try {
    87         if (abort) return null;
    88         HiveClientWeb.TryAndRepeat(() => {
    89           result = HiveServiceLocatorWeb.Instance.CallHiveService(s => s.GetTaskData(task.Id));
    90         }, Settings.Default.MaxRepeatServiceCalls, "Failed to download task data.");
    91       }
    92       finally {
    93         downloadSemaphore.Release();
    94       }
    95       return new Tuple<Task, TaskData>(task, result);
    96     }
    97 
    98     protected Tuple<Task, T> DeserializeTask(Tuple<Task, TaskData> taskData) {
    99       deserializeSemaphore.WaitOne();
    100       try {
    101         if (abort || taskData.Item2 == null || taskData.Item1 == null) return null;
    102         var deserializedJob = PersistenceUtil.Deserialize<T>(taskData.Item2.Data);
    103         taskData.Item2.Data = null; // reduce memory consumption.
    104         return new Tuple<Task, T>(taskData.Item1, deserializedJob);
    105       }
    106       finally {
    107         deserializeSemaphore.Release();
    108       }
    109     }
    110 
    111     public event EventHandler<EventArgs<Exception>> ExceptionOccured;
    112     private void OnExceptionOccured(Exception exception) {
    113       var handler = ExceptionOccured;
    114       if (handler != null) handler(this, new EventArgs<Exception>(exception));
    115     }
    116 
    117     #region IDisposable Members
    118     public void Dispose() {
    119       deserializeSemaphore.Dispose();
    120       downloadSemaphore.Dispose();
    121     }
    122     #endregion
    123   }
    124143}
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/HiveClientWeb.cs

    r13733 r13739  
    4646    public sealed class HiveClientWeb : IContent
    4747    {
    48         private static HiveClientWeb instance;
    49         public static HiveClientWeb Instance
    50         {
    51             get
    52             {
    53                 if (instance == null) instance = new HiveClientWeb();
    54                 return instance;
    55             }
    56         }
    57         public static IHostingEnvironment CurrentEnv { get; set; } //Current building area
     48       
     49        public IHostingEnvironment CurrentEnv { get; set; } //Current building area
    5850        #region Properties
    5951        private HiveItemCollection<RefreshableJob> jobs;
     
    8678        #endregion
    8779
    88         private HiveClientWeb()
    89         {
    90         }
     80        private HiveServiceLocatorWeb serviceLocator;
     81        public  Guid UserId { get; set; }
     82        public HiveClientWeb(HiveServiceLocatorWeb serv, Guid u)
     83        {
     84            serviceLocator = serv;
     85            UserId = u;
     86        }
     87        /// <summary>
     88        /// Reaches to the webloginservice to get the current instance of the servicelocator.
     89        /// </summary>
     90        public void updateServiceLocator()
     91        {// No idea if needed
     92            serviceLocator = WebLoginService.Instance.getServiceLocator(UserId);
     93        }
     94
    9195
    9296        public void ClearHiveClientWeb()
     
    117121            {
    118122                jobs = new HiveItemCollection<RefreshableJob>();
    119                 var jobsLoaded = HiveServiceLocatorWeb.Instance.CallHiveService<IEnumerable<Job>>(s => s.GetJobs());
     123                var jobsLoaded = serviceLocator.CallHiveService<IEnumerable<Job>>(s => s.GetJobs());
    120124
    121125                foreach (var j in jobsLoaded)
     
    158162
    159163        #region Store
    160         public static void Store(IHiveItem item, CancellationToken cancellationToken)
     164        public void Store(IHiveItem item, CancellationToken cancellationToken)
    161165        {
    162166            if (item.Id == Guid.Empty)
     
    164168                if (item is RefreshableJob)
    165169                {
    166                     HiveClientWeb.Instance.UploadJob((RefreshableJob)item, cancellationToken);
     170                    this.UploadJob((RefreshableJob)item, cancellationToken);
    167171                }
    168172                if (item is JobPermission)
    169173                {
    170174                    var hep = (JobPermission)item;
    171                     hep.GrantedUserId = HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
     175                    hep.GrantedUserId = serviceLocator.CallHiveService((s) => s.GetUserIdByUsername(hep.GrantedUserName));
    172176                    if (hep.GrantedUserId == Guid.Empty)
    173177                    {
    174178                        throw new ArgumentException(string.Format("The user {0} was not found.", hep.GrantedUserName));
    175179                    }
    176                     HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
     180                    serviceLocator.CallHiveService((s) => s.GrantPermission(hep.JobId, hep.GrantedUserId, hep.Permission));
    177181                }
    178182            }
    179183            else {
    180184                if (item is Job)
    181                     HiveServiceLocatorWeb.Instance.CallHiveService(s => s.UpdateJob((Job)item));
    182             }
    183         }
    184         public static void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken)
     185                    serviceLocator.CallHiveService(s => s.UpdateJob((Job)item));
     186            }
     187        }
     188        public void StoreAsync(Action<Exception> exceptionCallback, IHiveItem item, CancellationToken cancellationToken)
    185189        {
    186190            var call = new Func<Exception>(delegate ()
     
    205209
    206210        #region Delete
    207         public static void Delete(IHiveItem item)
     211        public void Delete(IHiveItem item)
    208212        {
    209213            if (item.Id == Guid.Empty && item.GetType() != typeof(JobPermission))
     
    211215
    212216            if (item is Job)
    213                 HiveServiceLocatorWeb.Instance.CallHiveService(s => s.DeleteJob(item.Id));
     217                serviceLocator.CallHiveService(s => s.DeleteJob(item.Id));
    214218            if (item is RefreshableJob)
    215219            {
     
    219223                    job.StopResultPolling();
    220224                }
    221                 HiveServiceLocatorWeb.Instance.CallHiveService(s => s.DeleteJob(item.Id));
     225                serviceLocator.CallHiveService(s => s.DeleteJob(item.Id));
    222226            }
    223227            if (item is JobPermission)
    224228            {
    225229                var hep = (JobPermission)item;
    226                 HiveServiceLocatorWeb.Instance.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
     230                serviceLocator.CallHiveService(s => s.RevokePermission(hep.JobId, hep.GrantedUserId));
    227231            }
    228232            item.Id = Guid.Empty;
     
    251255        #endregion
    252256
    253         public static void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken)
    254         {
    255             HiveClientWeb.StoreAsync(
     257        public void StartJob(Action<Exception> exceptionCallback, RefreshableJob refreshableJob, CancellationToken cancellationToken)
     258        {
     259            this.StoreAsync(
    256260              new Action<Exception>((Exception ex) =>
    257261              {
     
    262266        }
    263267
    264         public static void PauseJob(RefreshableJob refreshableJob)
    265         {
    266             HiveServiceLocatorWeb.Instance.CallHiveService(service =>
     268        public void PauseJob(RefreshableJob refreshableJob)
     269        {
     270            serviceLocator.CallHiveService(service =>
    267271            {
    268272                foreach (HiveTask task in refreshableJob.GetAllHiveTasks())
     
    274278        }
    275279
    276         public static void StopJob(RefreshableJob refreshableJob)
    277         {
    278             HiveServiceLocatorWeb.Instance.CallHiveService(service =>
     280        public void StopJob(RefreshableJob refreshableJob)
     281        {
     282            serviceLocator.CallHiveService(service =>
    279283            {
    280284                foreach (HiveTask task in refreshableJob.GetAllHiveTasks())
     
    286290        }
    287291
    288         public static void ResumeJob(RefreshableJob refreshableJob)
    289         {
    290             HiveServiceLocatorWeb.Instance.CallHiveService(service =>
     292        public void ResumeJob(RefreshableJob refreshableJob)
     293        {
     294            serviceLocator.CallHiveService(service =>
    291295            {
    292296                foreach (HiveTask task in refreshableJob.GetAllHiveTasks())
     
    315319                foreach (var resourceName in resourceNames)
    316320                {
    317                     Guid resourceId = HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.GetResourceId(resourceName));
     321                    Guid resourceId = serviceLocator.CallHiveService((s) => s.GetResourceId(resourceName));
    318322                    if (resourceId == Guid.Empty)
    319323                    {
     
    330334                // upload Job
    331335                refreshableJob.Progress.Status = "Uploading Job...";
    332                 refreshableJob.Job.Id = HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.AddJob(refreshableJob.Job));
    333                 refreshableJob.Job = HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
     336                refreshableJob.Job.Id = serviceLocator.CallHiveService((s) => s.AddJob(refreshableJob.Job));
     337                refreshableJob.Job = serviceLocator.CallHiveService((s) => s.GetJob(refreshableJob.Job.Id)); // update owner and permissions
    334338                cancellationToken.ThrowIfCancellationRequested();
    335339
     
    340344                // upload plugins
    341345                refreshableJob.Progress.Status = "Uploading plugins...";
    342                 this.OnlinePlugins = HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.GetPlugins());
     346                this.OnlinePlugins = serviceLocator.CallHiveService((s) => s.GetPlugins());
    343347                this.AlreadyUploadedPlugins = new List<Plugin>();
    344                 Plugin configFilePlugin = HiveServiceLocatorWeb.Instance.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
     348                Plugin configFilePlugin = serviceLocator.CallHiveService((s) => UploadConfigurationFile(s, onlinePlugins));
    345349                this.alreadyUploadedPlugins.Add(configFilePlugin);
    346350                cancellationToken.ThrowIfCancellationRequested();
     
    371375        /// Uploads the local configuration file as plugin
    372376        /// </summary>
    373         private static Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins)
     377        private Plugin UploadConfigurationFile(IHiveService service, List<Plugin> onlinePlugins)
    374378        {
    375379            string exeFilePath = Path.Combine( CurrentEnv.WebRootPath, "bin"  , HeuristicLab.Clients.Hive.Settings.Default.HLBinaryName);
     
    436440                        lock (pluginLocker)
    437441                        {
    438                             HiveServiceLocatorWeb.Instance.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
     442                            serviceLocator.CallHiveService((s) => hiveTask.Task.PluginsNeededIds = PluginUtil.GetPluginDependencies(s, this.onlinePlugins, this.alreadyUploadedPlugins, plugins));
    439443                        }
    440444                    }
     
    451455                        if (parentHiveTask != null)
    452456                        {
    453                             hiveTask.Task.Id = HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
     457                            hiveTask.Task.Id = serviceLocator.CallHiveService((s) => s.AddChildTask(parentHiveTask.Task.Id, hiveTask.Task, taskData));
    454458                        }
    455459                        else {
    456                             hiveTask.Task.Id = HiveServiceLocatorWeb.Instance.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
     460                            hiveTask.Task.Id = serviceLocator.CallHiveService((s) => s.AddTask(hiveTask.Task, taskData, groups.ToList()));
    457461                        }
    458462                    }
     
    488492
    489493        #region Download Experiment
    490         public static void LoadJob(RefreshableJob refreshableJob)
     494        public void LoadJob(RefreshableJob refreshableJob)
    491495        {
    492496            var hiveExperiment = refreshableJob.Job;
     
    501505                // fetch all task objects to create the full tree of tree of HiveTask objects
    502506                refreshableJob.Progress.Start("Downloading list of tasks...");
    503                 allTasks = HiveServiceLocatorWeb.Instance.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
     507                allTasks = serviceLocator.CallHiveService(s => s.GetLightweightJobTasksWithoutStateLog(hiveExperiment.Id));
    504508                totalJobCount = allTasks.Count();
    505509
    506510                refreshableJob.Progress.Status = "Downloading tasks...";
    507                 downloader = new TaskDownloaderWeb(allTasks.Select(x => x.Id));
     511                downloader = new TaskDownloaderWeb(allTasks.Select(x => x.Id), serviceLocator);
    508512                downloader.StartAsync();
    509513
     
    572576        }
    573577
    574         public static ItemTask LoadItemJob(Guid jobId)
    575         {
    576             TaskData taskData = HiveServiceLocatorWeb.Instance.CallHiveService(s => s.GetTaskData(jobId));
     578        public ItemTask LoadItemJob(Guid jobId)
     579        {
     580            TaskData taskData = serviceLocator.CallHiveService(s => s.GetTaskData(jobId));
    577581            try
    578582            {
     
    603607        }
    604608
    605         public static HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId)
    606         {
    607             return HiveServiceLocatorWeb.Instance.CallHiveService((service) =>
     609        public HiveItemCollection<JobPermission> GetJobPermissions(Guid jobId)
     610        {
     611            return serviceLocator.CallHiveService((service) =>
    608612            {
    609613                IEnumerable<JobPermission> jps = service.GetJobPermissions(jobId);
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/HiveServiceLocatorWeb.cs

    r13733 r13739  
    22using HeuristicLab.Clients.Common.Properties;
    33using HeuristicLab.Clients.Hive.WebJobManager.ViewModels;
     4using Microsoft.AspNet.Http;
    45using Microsoft.AspNet.Mvc;
    56using System;
     
    1718    public class HiveServiceLocatorWeb : IHiveServiceLocator
    1819    {
    19         private static IHiveServiceLocator instance = null;
    2020        private HiveServiceClient clientinst;
    21         public static IHiveServiceLocator Instance
    22         {
    23             get
    24             {
    25                 if (instance == null)
    26                 {
    27                     instance = new HiveServiceLocatorWeb();
    28                 }
    29                 return instance;
    30             }
    31         }
     21        public Guid UserId {get; set; }
    3222        private string username;
    3323        public string Username
     
    4737        public string WorkingEndpoint { get; private set; }
    4838
    49         public static void clear()
    50         {
    51             instance = null;
    52         }
    5339
    5440        #region #unknownCalls
     
    132118            return false;
    133119        }
    134         public static void SetLoginErrorMessage()
    135         {
    136              LoginViewModelService.Instance.GetLoginViewModel().errorMessage = "Login timed out";
    137         }
    138120
    139121        public string GetEndpointInformation()
     
    195177        }
    196178
    197         public void destroy()
     179        public void destroyClient()
    198180        {
    199181            clientinst = null;
    200             instance = null;
    201182        }
    202183    }
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/TaskDownloaderWeb.cs

    r13733 r13739  
    2626using HeuristicLab.Common;
    2727
    28 namespace HeuristicLab.Clients.Hive.WebJobManager.Services.Imports {
     28namespace HeuristicLab.Clients.Hive.WebJobManager.Services.Imports
     29{
    2930
    3031    /// <summary>
    3132    /// Rewritten to use HiveClientWeb and HiveServiceLocatorWeb
    3233    /// </summary>
    33   public class TaskDownloaderWeb : IDisposable {
    34     private IEnumerable<Guid> taskIds;
    35     private ConcurrentTaskDownloaderWeb<ItemTask> taskDownloader;
    36     private IDictionary<Guid, HiveTask> results;
    37     private bool exceptionOccured = false;
    38     private Exception currentException;
    39     private ReaderWriterLockSlim resultsLock = new ReaderWriterLockSlim();
     34    public class TaskDownloaderWeb : IDisposable
     35    {
     36        private HiveServiceLocatorWeb serviceLocator;
     37        private IEnumerable<Guid> taskIds;
     38        private ConcurrentTaskDownloaderWeb<ItemTask> taskDownloader;
     39        private IDictionary<Guid, HiveTask> results;
     40        private bool exceptionOccured = false;
     41        private Exception currentException;
     42        private ReaderWriterLockSlim resultsLock = new ReaderWriterLockSlim();
    4043
    41     public bool IsFinished {
    42       get {
    43         try {
    44           resultsLock.EnterReadLock();
    45           return results.Count == taskIds.Count();
     44        public bool IsFinished
     45        {
     46            get
     47            {
     48                try
     49                {
     50                    resultsLock.EnterReadLock();
     51                    return results.Count == taskIds.Count();
     52                }
     53                finally { resultsLock.ExitReadLock(); }
     54            }
    4655        }
    47         finally { resultsLock.ExitReadLock(); }
    48       }
     56
     57        public bool IsFaulted
     58        {
     59            get
     60            {
     61                return exceptionOccured;
     62            }
     63        }
     64
     65        public Exception Exception
     66        {
     67            get
     68            {
     69                return currentException;
     70            }
     71        }
     72
     73        public int FinishedCount
     74        {
     75            get
     76            {
     77                try
     78                {
     79                    resultsLock.EnterReadLock();
     80                    return results.Count;
     81                }
     82                finally { resultsLock.ExitReadLock(); }
     83            }
     84        }
     85
     86        public IDictionary<Guid, HiveTask> Results
     87        {
     88            get
     89            {
     90                try
     91                {
     92                    resultsLock.EnterReadLock();
     93                    return results;
     94                }
     95                finally { resultsLock.ExitReadLock(); }
     96            }
     97        }
     98
     99        public TaskDownloaderWeb(IEnumerable<Guid> jobIds, HiveServiceLocatorWeb hiv)
     100        {
     101            taskIds = jobIds;
     102            serviceLocator = hiv;
     103            taskDownloader = new ConcurrentTaskDownloaderWeb<ItemTask>(
     104                Settings.Default.MaxParallelDownloads,
     105                Settings.Default.MaxParallelDownloads,
     106                serviceLocator);
     107            taskDownloader.ExceptionOccured += new EventHandler<EventArgs<Exception>>(taskDownloader_ExceptionOccured);
     108            results = new Dictionary<Guid, HiveTask>();
     109           
     110        }
     111
     112        public void StartAsync()
     113        {
     114            foreach (Guid taskId in taskIds)
     115            {
     116                taskDownloader.DownloadTaskDataAndTask(taskId,
     117                  (localTask, itemTask) =>
     118                  {
     119                      if (localTask != null && itemTask != null)
     120                      {
     121                          HiveTask hiveTask = itemTask.CreateHiveTask();
     122                          hiveTask.Task = localTask;
     123                          try
     124                          {
     125                              resultsLock.EnterWriteLock();
     126                              results.Add(localTask.Id, hiveTask);
     127                          }
     128                          finally { resultsLock.ExitWriteLock(); }
     129                      }
     130                  });
     131            }
     132        }
     133
     134        private void taskDownloader_ExceptionOccured(object sender, EventArgs<Exception> e)
     135        {
     136            OnExceptionOccured(e.Value);
     137        }
     138
     139        public event EventHandler<EventArgs<Exception>> ExceptionOccured;
     140        private void OnExceptionOccured(Exception exception)
     141        {
     142            exceptionOccured = true;
     143            currentException = exception;
     144            var handler = ExceptionOccured;
     145            if (handler != null) handler(this, new EventArgs<Exception>(exception));
     146        }
     147
     148        #region IDisposable Members
     149        public void Dispose()
     150        {
     151            taskDownloader.ExceptionOccured -= new EventHandler<EventArgs<Exception>>(taskDownloader_ExceptionOccured);
     152            resultsLock.Dispose();
     153            taskDownloader.Dispose();
     154        }
     155        #endregion
    49156    }
    50 
    51     public bool IsFaulted {
    52       get {
    53         return exceptionOccured;
    54       }
    55     }
    56 
    57     public Exception Exception {
    58       get {
    59         return currentException;
    60       }
    61     }
    62 
    63     public int FinishedCount {
    64       get {
    65         try {
    66           resultsLock.EnterReadLock();
    67           return results.Count;
    68         }
    69         finally { resultsLock.ExitReadLock(); }
    70       }
    71     }
    72 
    73     public IDictionary<Guid, HiveTask> Results {
    74       get {
    75         try {
    76           resultsLock.EnterReadLock();
    77           return results;
    78         }
    79         finally { resultsLock.ExitReadLock(); }
    80       }
    81     }
    82 
    83     public TaskDownloaderWeb(IEnumerable<Guid> jobIds) {
    84       taskIds = jobIds;
    85       taskDownloader = new ConcurrentTaskDownloaderWeb<ItemTask>(Settings.Default.MaxParallelDownloads, Settings.Default.MaxParallelDownloads);
    86       taskDownloader.ExceptionOccured += new EventHandler<EventArgs<Exception>>(taskDownloader_ExceptionOccured);
    87       results = new Dictionary<Guid, HiveTask>();
    88     }
    89 
    90     public void StartAsync() {
    91       foreach (Guid taskId in taskIds) {
    92         taskDownloader.DownloadTaskDataAndTask(taskId,
    93           (localTask, itemTask) => {
    94             if (localTask != null && itemTask != null) {
    95               HiveTask hiveTask = itemTask.CreateHiveTask();
    96               hiveTask.Task = localTask;
    97               try {
    98                 resultsLock.EnterWriteLock();
    99                 results.Add(localTask.Id, hiveTask);
    100               }
    101               finally { resultsLock.ExitWriteLock(); }
    102             }
    103           });
    104       }
    105     }
    106 
    107     private void taskDownloader_ExceptionOccured(object sender, EventArgs<Exception> e) {
    108       OnExceptionOccured(e.Value);
    109     }
    110 
    111     public event EventHandler<EventArgs<Exception>> ExceptionOccured;
    112     private void OnExceptionOccured(Exception exception) {
    113       exceptionOccured = true;
    114       currentException = exception;
    115       var handler = ExceptionOccured;
    116       if (handler != null) handler(this, new EventArgs<Exception>(exception));
    117     }
    118 
    119     #region IDisposable Members
    120     public void Dispose() {
    121       taskDownloader.ExceptionOccured -= new EventHandler<EventArgs<Exception>>(taskDownloader_ExceptionOccured);
    122       resultsLock.Dispose();
    123       taskDownloader.Dispose();
    124     }
    125     #endregion
    126   }
    127157}
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Jobs/FileOpeningService.cs

    r13733 r13739  
    1616    public class FileOpeningService
    1717    {
     18        public Guid UserId { get; set; }
     19
     20        private WebLoginService weblog;
    1821        public RefreshableJob Job { get; set; }
    1922        public FileOpeningViewModel vm { get; set; }
     
    2225            get; set; }
    2326        public List<int> previousLogs { get; set; }
    24         private static FileOpeningService instance;
    25         public static FileOpeningService Instance
     27       
     28
     29        public FileOpeningService(Guid u)
    2630        {
    27             get
    28             {
    29                 if (instance == null)
    30                 {
    31                     instance = new FileOpeningService();
    32                 }
    33                 return instance;
    34             }
     31            weblog = WebLoginService.Instance;
     32            UserId = u;
    3533        }
     34
     35
    3636        /// <summary>
    3737        /// Clears loaded jobs and start new one
     
    5858        {
    5959           // HiveClientWeb.Instance.Refresh();
    60             HiveClientWeb.LoadJob(Job);
     60            weblog.getClientWeb(UserId).LoadJob(Job);
    6161        }
    6262        /// <summary>
     
    6868            if (vm != null)
    6969            {
    70 
    71 
    72 
    73                 HiveServiceLocatorWeb serv = (HiveServiceLocatorWeb)HiveServiceLocatorWeb.Instance;
    74                 //job.Job.Id = serv.getHiveServiceClient().AddJob(job.Job);
    75                 //  job.Job =  serv.getHiveServiceClient().GetJob(job.Job.Id);
    76 
    77                 HiveClientWeb.CurrentEnv = env;
    78                 HiveClientWeb.Instance.Refresh();
    79                 HiveClientWeb.StartJob((ex) => { throw ex; }, Job, CancellationToken.None);
     70                var clientWeb = weblog.getClientWeb(UserId);
     71                clientWeb.CurrentEnv = env;
     72                clientWeb.Refresh();
     73                clientWeb.StartJob((ex) => { throw ex; }, Job, CancellationToken.None);
    8074                return Job;
    8175            }
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Startup.cs

    r13733 r13739  
    77using HeuristicLab.Core;
    88using HeuristicLab.PluginInfrastructure;
    9 
     9using System;
    1010
    1111namespace HeuristicLab.Clients.Hive.WebJobManager
     
    3333
    3434            services.AddMvc();
    35             services.AddSingleton<ILoginViewModelService, LoginViewModelService>();
     35
     36            services.AddCaching();
     37            services.AddSession(options => {
     38                options.IdleTimeout = TimeSpan.FromMinutes(30);
     39                options.CookieName = ".HiveWJM";
     40            });
    3641            services.AddSingleton<IHiveServiceLocator, HiveServiceLocatorWeb>();
    3742            services.AddSignalR();
     
    4550
    4651            app.UseIISPlatformHandler();
    47            
     52            app.UseSession();
    4853            app.UseStaticFiles();
    4954            app.UseSignalR();
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/ViewModels/LoginViewModel.cs

    r13733 r13739  
    1212    public class LoginViewModel
    1313    {
     14        /// <summary>
     15        /// Used only for the WebHive. Identifies logged in users.
     16        /// </summary>
     17        public Guid userId { get; set; }
     18        /// <summary>
     19        /// Login name from the user
     20        /// </summary>
    1421        [Display(Name = "Username")]
    1522        public string loginName { get; set; }
     23        /// <summary>
     24        /// Encrypted password
     25        /// </summary>
    1626        [Display(Name = "Password")]
    1727        public string password { get; set; }
    1828
    1929        public string errorMessage { get; set; }
     30        /// <summary>
     31        /// Initialize the loginViewModel. Creates a unique Guid for the WebHive
     32        /// </summary>
     33        /// <param name="n">Login name</param>
     34        /// <param name="p">Encrypted password</param>
     35        public LoginViewModel(string n, string p)
     36        {
     37            loginName = n;
     38            password = p;
     39            userId = Guid.NewGuid();
     40        }
     41        public LoginViewModel()
     42        {
     43            userId = Guid.Empty;
     44            loginName = "";
     45            password = "";
     46        }
    2047    }
    2148}
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/Index.cshtml

    r13735 r13739  
    11@using HeuristicLab.Clients.Hive.WebJobManager.ViewModels
    22@model JobViewModel
    3 
     3<div id="userId" style="display:none">@ViewBag.SessionId</div>
    44<div>
    55    @Html.Partial("Navbar", new NavbarViewModel("Job"))
     
    165165                    }
    166166                </div>
     167               
    167168
    168169        }
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFile.cshtml

    r13735 r13739  
    1 @model HeuristicLab.Clients.Hive.WebJobManager.ViewModels.FileOpeningViewModel
     1@using Microsoft.AspNet.Http;
     2
     3@model HeuristicLab.Clients.Hive.WebJobManager.ViewModels.FileOpeningViewModel
    24
    35
     
    911      onscroll="showScrolly()"
    1012      style="margin-bottom:500px;margin-left:1px;margin-right:1px;">
    11 
     13    <div id="userId" style="display:none">@ViewBag.SessionId</div>
    1214    @Html.Partial("Navbar", new HeuristicLab.Clients.Hive.WebJobManager.ViewModels.NavbarViewModel("Job"))
    1315
     
    181183        </ul>
    182184    </nav>
     185   
    183186    <script src="~/js/scripts/hubber.js"></script>
    184187    <script>
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/UploaderPartial/_UploaderPartial.cshtml

    r13733 r13739  
    2525        <div class="row" style="margin:10px">
    2626
    27             <div id="selectedfiles"></div>
     27            <div id="selectedfiles">
     28            <h3>Files</h3>
     29            <p>No files selected: press the above button to choose files</p>
     30            </div>
    2831
    29             <div style="display:none; margin-bottom:10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
     32            <button style="margin-bottom:10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    3033                            text-shadow:2px 2px black;"
     34                 type="button"
     35                    disabled
    3136                 id="del"
    3237                 class='btn btn-danger'
     
    3439                <span class='glyphicon glyphicon-trash' aria-hidden='true'></span>
    3540                Remove files
    36             </div>
     41            </button>
    3742
    38             <div id="dir"
    39                  style="display:none; margin-top:20px;margin-bottom:20px">
     43            <div
     44                 style="margin-top:20px;margin-bottom:20px">
    4045
    4146                <label for="basic-url">Directory name</label>
     
    4550                        .../uploads/@ViewBag.Name
    4651                    </span>
    47                     <input type="text"
     52                    <input
     53                           type="text"
     54                           disabled
    4855                           class="form-control"
    4956                           id="directory"
     
    5360                </div>
    5461            </div>
    55             <button style="display:none; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
     62            <button style=" box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    5663                            text-shadow:2px 2px black;"
    57                    id="upl"
     64                   disabled
     65                    id="upl"
    5866                   class="btn btn-lg btn-block btn-success"
    5967                   type="submit"
     
    7078        var div = document.getElementById("selectedfiles");
    7179        var files = document.getElementById("files").files;
    72         div.innerHTML = "";
     80        div.innerHTML = "<h3>Files</h3>";
    7381        if (files.length > 0) {
    74             document.getElementById("upl").style.display = "";
    75             document.getElementById("del").style.display = "";
    76             document.getElementById("dir").style.display = "";
     82            document.getElementById("upl").disabled = false;
     83            document.getElementById("del").disabled = false;
     84            document.getElementById("directory").disabled = false;
    7785
    78             div.innerHTML += "<h3>Files</h3>";
     86           
    7987            for (var i = 0; i < files.length; i++) {
    8088                div.innerHTML += "<p>File " + (i + 1) + ":" + files[i].name +
     
    8492        }
    8593        else {
    86             document.getElementById("upl").style.display = "none";
    87             document.getElementById("del").style.display = "none";
    88             document.getElementById("dir").style.display = "none";
     94            div.innerHTML += "<p>No files selected</p>";
     95            document.getElementById("upl").disabled = true;
     96            document.getElementById("del").disabled = true;
     97            document.getElementById("directory").disabled = true;
    8998        }
    9099
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/Uploads.cshtml

    r13733 r13739  
    4545            <div class="col-sm-4">
    4646                <div class="btn-group-vertical btn-block">
    47                     <a class="btn btn-success btn-lg btn-block
     47                    <a class="btn btn-info btn-lg btn-block disabled"
     48                       style="box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
     49                            text-shadow:2px 2px black;">
     50                        <i class="fa fa-cloud"></i> Uploads
     51                    </a>
     52                    <a class="btn btn-success btn-block
    4853                       @(Model.SelectedIndex == -1 ? "active" : "")
    4954                       "
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Shared/_Layout.cshtml

    r13733 r13739  
    1212    </environment>
    1313    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.0/css/bootstrap-toggle.min.css" rel="stylesheet">
     14    <link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />
    1415    <link rel="stylesheet" href="//rawgithub.com/Caged/d3-tip/master/examples/example-styles.css">
    1516</head>
     
    2829        <script src="~/js/jquery.signalr-2.1.2.js"></script>
    2930        <script src='~/signalr/js'></script>
    30         <script src="~/js/morris.js"></script>
    31         <script src="~/js/npm.js"></script>
    32         <script src="~/js/raphael.js"></script>
    3331        <script src="~/js/plotly.js"></script>
    34         <script src="~/js/moment.js"></script>
    35         <script src="~/js/moment-timezone-with-data.js"></script>
    3632        <script src="~/js/d3.js"></script>
    3733        <script src="~/js/d3.v3.min.js"></script>
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/project.json

    r13689 r13739  
    2222    "Microsoft.AspNet.SignalR.Server": "3.0.0-rc1-final",
    2323    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    24     "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"
     24    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
     25    "Microsoft.AspNet.Session": "1.0.0-rc1-final",
     26    "Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final"
    2527  },
    2628
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/Scripts/Graphs/GraphHubber.js

    r13733 r13739  
    22
    33$(function () {
    4     //$.connection.hub.logging = true;
     4  //  $.connection.hub.logging = true;
     5    var v = document.getElementById("userId").innerHTML;
     6    console.log(v);
     7    $.connection.hub.qs = { 'userid': v };
    58    $.connection.hub.start().done(function () {
    69        hubber.server.initConnection();
  • branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/Scripts/hubber.js

    r13735 r13739  
    22
    33$(function () {
    4     $.connection.hub.logging = true;
     4   // $.connection.hub.logging = true;
     5    var v = document.getElementById("userId").innerHTML;
     6    console.log(v);
     7    $.connection.hub.qs = { 'userid': v };
    58    $.connection.hub.start().done(function () {
    69        $("#progress").css("width", 0 + '%');
Note: See TracChangeset for help on using the changeset viewer.