Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/ClientConsoleCommunicator.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/ClientConsoleCommunicator.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/ClientConsoleCommunicator.cs	(revision 4061)
@@ -0,0 +1,47 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Client.Core.ClientConsoleService.Interfaces;
+using HeuristicLab.Hive.Client.Core.ConfigurationManager;
+using HeuristicLab.Hive.Client.Communication;
+using HeuristicLab.Hive.Client.Common;
+using HeuristicLab.Hive.Contracts;
+using Calendar;
+
+namespace HeuristicLab.Hive.Client.Core.ClientConsoleService {
+  public class ClientConsoleCommunicator: IClientConsoleCommunicator {
+    #region IClientConsoleCommunicator Members
+
+    public StatusCommons GetStatusInfos() {      
+        return ConfigManager.Instance.GetStatusForClientConsole();
+    }
+
+    public void SetConnection(ConnectionContainer container) {
+      ConfigManager.Instance.SetServerIPAndPort(container);
+      WcfService.Instance.Connect(container.IPAdress, container.Port);
+    }
+
+    public void Disconnect() {
+      WcfService.Instance.Disconnect();
+    }   
+
+    public ConnectionContainer GetCurrentConnection() {
+      return new ConnectionContainer { IPAdress = WcfService.Instance.ServerIP, Port = WcfService.Instance.ServerPort };
+    }
+
+    public void ShutdownClient() {
+      MessageQueue.GetInstance().AddMessage(MessageContainer.MessageType.Shutdown);
+    }    
+
+    public void SetUptimeCalendar(List<Appointment> appointments) {
+      UptimeManager.Instance.SetAppointments(true, false, appointments);
+    }
+
+    public List<Appointment> GetUptimeCalendar() {
+      return UptimeManager.Instance.AppContainer.Appointments;
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/ClientConsoleServer.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/ClientConsoleServer.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/ClientConsoleServer.cs	(revision 4061)
@@ -0,0 +1,51 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.ServiceModel.Description;
+using System.ServiceModel;
+using HeuristicLab.PluginInfrastructure;
+using HeuristicLab.Hive.Client.Core.ClientConsoleService.Interfaces;
+using HeuristicLab.Hive.Contracts;
+
+namespace HeuristicLab.Hive.Client.Core.ClientConsoleService {
+  public class ClientConsoleServer {
+
+    private bool AddMexEndpoint(ServiceHost serviceHost) {
+      if (serviceHost != null) {
+        ServiceMetadataBehavior behavior =
+            new ServiceMetadataBehavior();
+        serviceHost.Description.Behaviors.Add(behavior);
+
+        return serviceHost.AddServiceEndpoint(
+          typeof(IMetadataExchange),
+          MetadataExchangeBindings.CreateMexTcpBinding(),
+          "mex") != null;
+      } else
+        return false;
+    }
+    
+    public ServiceHost StartClientConsoleServer(Uri uriTcp) {
+      IEnumerable<IClientConsoleCommunicator> clientConsoleServerInstances =
+        ApplicationManager.Manager.GetInstances<IClientConsoleCommunicator>();
+
+      if (clientConsoleServerInstances.Count() > 0) {
+        ServiceHost serviceHost =
+                new ServiceHost(clientConsoleServerInstances.First().GetType(),
+                  uriTcp);
+
+        serviceHost.AddServiceEndpoint(
+          typeof(IClientConsoleCommunicator),
+              WcfSettings.GetBinding(),
+              "ClientConsoleCommunicator");
+
+        AddMexEndpoint(serviceHost);
+
+        serviceHost.Open();
+        return serviceHost;
+      } else {
+        return null;
+      }
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/Interfaces/IClientConsoleCommunicator.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/Interfaces/IClientConsoleCommunicator.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/Interfaces/IClientConsoleCommunicator.cs	(revision 4061)
@@ -0,0 +1,71 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.ServiceModel;
+using Calendar;
+
+namespace HeuristicLab.Hive.Client.Core.ClientConsoleService.Interfaces {
+  /// <summary>
+  /// Defines the interfaces for the Client Console
+  /// </summary>
+  [ServiceContract]
+  public interface IClientConsoleCommunicator {
+    /// <summary>
+    /// Gets all status information concerning the client Service
+    /// </summary>
+    /// <returns>the StatusCommons Object, filled with the client details</returns>
+    [OperationContract]
+    StatusCommons GetStatusInfos();
+    /// <summary>
+    /// Set the connection settings in the wcfService
+    /// </summary>
+    /// <param name="container">the container with the connection details</param>
+    [OperationContract]
+    void SetConnection(ConnectionContainer container);
+    /// <summary>
+    /// Signals the client to disconnect from the server
+    /// </summary>
+    [OperationContract]
+    void Disconnect();
+    /// <summary>
+    /// Get the current connection details
+    /// </summary>
+    /// <returns>the ConnectionContainer Object</returns>
+    [OperationContract]
+    ConnectionContainer GetCurrentConnection();
+    /// <summary>
+    /// Signals the client to exit all jobs and shutdown
+    /// </summary>
+    [OperationContract]
+    void ShutdownClient();
+
+    [OperationContract]
+    void SetUptimeCalendar(List<Appointment> appointments);
+
+    [OperationContract]
+    List<Appointment> GetUptimeCalendar();
+
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/ConnectionContainer.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/ConnectionContainer.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/ConnectionContainer.cs	(revision 4061)
@@ -0,0 +1,36 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Runtime.Serialization;
+
+namespace HeuristicLab.Hive.Client.Core.ClientConsoleService {
+  [DataContract]
+  public class ConnectionContainer {
+    [DataMember]
+    public string IPAdress { get; set; }
+    [DataMember]
+    public int Port { get; set; }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/JobStatus.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/JobStatus.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/JobStatus.cs	(revision 4061)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Runtime.Serialization;
+
+namespace HeuristicLab.Hive.Client.Core.ClientConsoleService {
+  [DataContract]
+  public class JobStatus {
+    /// <summary>
+    /// Id of the Job
+    /// </summary>
+    [DataMember]
+    public Guid JobId { get; set; }
+    /// <summary>
+    /// When has the calculation of the Job begun?
+    /// </summary>
+    [DataMember]
+    public DateTime Since { get; set; }
+    /// <summary>
+    /// Current progress
+    /// </summary>
+    [DataMember]
+    public double Progress { get; set; }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/StatusCommons.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/StatusCommons.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ClientConsoleService/TransferObjects/StatusCommons.cs	(revision 4061)
@@ -0,0 +1,54 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Client.Common;
+using System.Runtime.Serialization;
+
+namespace HeuristicLab.Hive.Client.Core.ClientConsoleService {
+  /// <summary>
+  /// Various Status Information for the ClientConsole
+  /// </summary>
+  [DataContract]
+  public class StatusCommons {    
+    [DataMember]
+    public Guid ClientGuid { get; set; }
+    [DataMember]
+    public NetworkEnum.WcfConnState Status { get; set; }
+    [DataMember]    
+    public DateTime ConnectedSince { get; set; }
+    [DataMember]
+    public int TotalCores { get; set; }
+    [DataMember]
+    public int FreeCores { get; set; }
+    [DataMember]
+    public int JobsFetched { get; set; }
+    [DataMember]
+    public int JobsDone { get; set; }
+    [DataMember]
+    public int JobsAborted { get; set; }
+    [DataMember]
+    public List<JobStatus> Jobs { get; set; }   
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/AppointmentContainer.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/AppointmentContainer.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/AppointmentContainer.cs	(revision 4061)
@@ -0,0 +1,18 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Calendar;
+
+namespace HeuristicLab.Hive.Client.Core.ConfigurationManager {
+  public class AppointmentContainer {
+    public DateTime Updated { get; set; }
+    public List<Appointment> Appointments { get; set; }
+    public bool IsLocal { get; set; }
+
+    public AppointmentContainer() {
+      Appointments = new List<Appointment>();
+      IsLocal = false;
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/ClientStatusInfo.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/ClientStatusInfo.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/ClientStatusInfo.cs	(revision 4061)
@@ -0,0 +1,14 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace HeuristicLab.Hive.Client.Core.ConfigurationManager {
+  public class ClientStatusInfo {
+    static public int JobsProcessed { get; set; }
+    static public int JobsAborted { get; set; }
+    static public int JobsFetched { get; set; }
+    static public DateTime LoginTime { get; set; }
+    
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/ConfigManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/ConfigManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/ConfigManager.cs	(revision 4061)
@@ -0,0 +1,154 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Client.ExecutionEngine;
+using HeuristicLab.Hive.Client.Core.ClientConsoleService;
+using HeuristicLab.Hive.Client.Communication;
+using HeuristicLab.Hive.Client.Core.Properties;
+using HeuristicLab.Hive.Contracts;
+
+namespace HeuristicLab.Hive.Client.Core.ConfigurationManager {
+  /// <summary>
+  /// accesses the Server and sends his data (uuid, uptimes, hardware config) 
+  /// </summary>
+  public class ConfigManager {
+    private static ConfigManager instance = null;
+    public static ConfigManager Instance {
+      get {
+        if (instance == null) {
+          instance = new ConfigManager();
+        }
+        return instance;
+      }
+    }
+
+    public Core Core { get; set; }    
+    private ClientDto hardwareInfo;        
+
+    /// <summary>
+    /// Constructor for the singleton, must recover Guid, Calendar, ...
+    /// </summary>
+    private ConfigManager() {      
+      hardwareInfo = new ClientDto();
+
+      if (Settings.Default.Guid == Guid.Empty) {
+        hardwareInfo.Id = Guid.NewGuid();
+        Settings.Default.Guid = hardwareInfo.Id;
+        Settings.Default.Save();
+      } else
+        hardwareInfo.Id = Settings.Default.Guid;
+      
+      hardwareInfo.NrOfCores = Environment.ProcessorCount;
+      hardwareInfo.Memory = 1024;
+      hardwareInfo.Name = Environment.MachineName;
+    }
+
+    /// <summary>
+    /// Get all the Information about the client
+    /// </summary>
+    /// <returns>the ClientInfo object</returns>
+    public ClientDto GetClientInfo() {
+      hardwareInfo.Login = WcfService.Instance.ConnectedSince;
+      return hardwareInfo;          
+    }
+
+    /// <summary>
+    /// Returns the connectioncontainer with the IP and Port, storred in the Settings framework
+    /// </summary>
+    /// <returns>The IP and Port of the server</returns>
+    public ConnectionContainer GetServerIPAndPort() {
+      ConnectionContainer cc = new ConnectionContainer();
+      cc.IPAdress = Settings.Default.ServerIP;
+      cc.Port = Settings.Default.ServerPort;
+      return cc;
+    }
+
+    /// <summary>
+    /// Sets and saves IP and Port in the Settings framework
+    /// </summary>
+    /// <param name="cc"></param>
+    public void SetServerIPAndPort(ConnectionContainer cc) {
+      Settings.Default.ServerIP = cc.IPAdress;
+      Settings.Default.ServerPort = cc.Port;
+      Settings.Default.Save();
+    }
+    /// <summary>
+    /// collects and returns information that get displayed by the Client Console
+    /// </summary>
+    /// <returns></returns>
+    public StatusCommons GetStatusForClientConsole() {
+      //Todo: Locking
+      StatusCommons st = new StatusCommons();
+      st.ClientGuid = hardwareInfo.Id;
+      
+      st.Status = WcfService.Instance.ConnState;
+      st.ConnectedSince = WcfService.Instance.ConnectedSince;
+
+      st.TotalCores = hardwareInfo.NrOfCores;
+      st.FreeCores = hardwareInfo.NrOfCores - GetUsedCores();
+
+      st.JobsAborted = ClientStatusInfo.JobsAborted;
+      st.JobsDone = ClientStatusInfo.JobsProcessed;
+      st.JobsFetched = ClientStatusInfo.JobsFetched;      
+
+      Dictionary<Guid, Executor> engines = Core.GetExecutionEngines();
+      st.Jobs = new List<JobStatus>();
+
+      lock (engines) {
+        foreach (KeyValuePair<Guid, Executor> kvp in engines) {
+          Executor e = kvp.Value;
+          st.Jobs.Add(new JobStatus { JobId = e.JobId, Progress = e.Progress, Since = e.CreationTime });
+        }
+      }
+      return st;      
+    }
+
+    public Dictionary<Guid, double> GetProgressOfAllJobs() {
+      Dictionary<Guid, double> prog = new Dictionary<Guid, double>();
+      Dictionary<Guid, Executor> engines = Core.GetExecutionEngines();
+      lock (engines) {
+        foreach (KeyValuePair<Guid, Executor> kvp in engines) {
+          Executor e = kvp.Value;
+          //if (!e.JobIsFinished) 
+          prog[e.JobId] = e.Progress;
+        }
+      }
+      return prog;
+    }
+
+    public int GetUsedCores() {
+      Dictionary<Guid, Executor> engines = Core.GetExecutionEngines();
+      Dictionary<Guid, JobDto> jobs = Core.GetJobs();
+      int usedCores = 0;
+      lock (engines) {        
+        foreach (KeyValuePair<Guid, JobDto> kvp in jobs)
+          usedCores += kvp.Value.CoresNeeded;
+      }
+      return usedCores;
+    }
+
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/UptimeManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/UptimeManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/ConfigurationManager/UptimeManager.cs	(revision 4061)
@@ -0,0 +1,120 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Calendar;
+using System.Xml.Serialization;
+using System.IO;
+using HeuristicLab.Hive.Client.Common;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Tracing;
+
+namespace HeuristicLab.Hive.Client.Core.ConfigurationManager {
+  public class UptimeManager {
+
+    private AppointmentContainer _appContainer = null;
+    public AppointmentContainer AppContainer {
+      get {
+        if (_appContainer == null)
+          RestoreFromHDD();
+        return _appContainer;
+      }
+    }    
+    public bool CalendarAvailable { get; set; }
+
+    private static String path = System.IO.Directory.GetCurrentDirectory() + "\\plugins\\Hive.Client.Jobs\\";
+
+    private static UptimeManager instance = null;
+    public static UptimeManager Instance {
+      get {
+        if (instance == null) {
+          instance = new UptimeManager();
+        }
+        return instance;
+      }
+    }
+
+    public UptimeManager() {
+      RestoreFromHDD();
+    }
+
+    private void PersistToHDD() {
+      XmlSerializer s = new XmlSerializer(typeof(AppointmentContainer));
+      if (!Directory.Exists(path))
+        Directory.CreateDirectory(path);
+      TextWriter w = null;
+      try {
+        w = new StreamWriter(path + "calendar.xml");
+        s.Serialize(w, AppContainer);
+      }
+      catch (Exception e) {
+        Logger.Error("Persistance of the Calendar failed!", e);
+      }
+      finally {
+        if (w != null)
+          w.Close();
+      }
+    }
+
+    private void RestoreFromHDD() {
+      XmlSerializer s = new XmlSerializer(typeof(AppointmentContainer));
+      if (File.Exists(Path.Combine(path, "calendar.xml"))) {
+        TextReader r = null;
+
+        try {
+          r = new StreamReader(path + "calendar.xml");
+          _appContainer = (AppointmentContainer)s.Deserialize(r);
+          CalendarAvailable = true;
+        }
+        catch (Exception e) {
+          Logger.Error("Deserialization of Calendar failed", e);
+          Logger.Info("Starting with a new one");
+          _appContainer = new AppointmentContainer();
+          CalendarAvailable = false;
+        }
+        finally {
+          if (r != null)
+            r.Close();
+        }
+      } else {
+        _appContainer = new AppointmentContainer();
+      }
+    }
+
+    public bool IsOnline() {
+      return AppContainer.Appointments.Any(app => (DateTime.Now >= app.StartDate) && (DateTime.Now <= app.EndDate));
+    }
+
+    public bool SetAppointments(bool isLocal, bool isForced, IEnumerable<Appointment> appointments) {
+      if (!isForced && !isLocal && AppContainer.IsLocal)
+        return false;
+
+      AppContainer.Appointments = new List<Appointment>(appointments);
+      AppContainer.IsLocal = isLocal;
+      AppContainer.Updated = DateTime.Now;
+      CalendarAvailable = true;
+     
+      PersistToHDD();
+      
+      return true;
+    }
+
+    internal bool SetAppointments(bool isLocal, ResponseCalendar response) {
+      IList<Appointment> app = new List<Appointment>();
+      foreach (AppointmentDto appointmentDto in response.Appointments) {
+        app.Add(new Appointment {
+          AllDayEvent = appointmentDto.AllDayEvent,
+          EndDate = appointmentDto.EndDate,
+          StartDate = appointmentDto.StartDate,
+          Recurring = appointmentDto.Recurring,
+
+          RecurringId = appointmentDto.RecurringId,
+          Locked = true,
+          Subject = "Online",
+        });
+      }
+      return SetAppointments(isLocal, response.ForceFetch, app);
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Core.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Core.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Core.cs	(revision 4061)
@@ -0,0 +1,515 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Client.ExecutionEngine;
+using HeuristicLab.Hive.Client.Common;
+using System.Threading;
+using System.Reflection;
+using System.Diagnostics;
+using System.Security.Permissions;
+using System.Security.Policy;
+using System.Security;
+using HeuristicLab.Hive.Client.Communication;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using System.Runtime.Remoting.Messaging;
+using HeuristicLab.PluginInfrastructure;
+using System.ServiceModel;
+using System.ServiceModel.Description;
+using HeuristicLab.Hive.Client.Core.ClientConsoleService;
+using HeuristicLab.Hive.Client.Core.ConfigurationManager;
+using HeuristicLab.Hive.Client.Communication.ServerService;
+using HeuristicLab.Hive.JobBase;
+using HeuristicLab.Hive.Client.Core.JobStorage;
+using HeuristicLab.Tracing;
+
+namespace HeuristicLab.Hive.Client.Core {
+  /// <summary>
+  /// The core component of the Hive Client
+  /// </summary>
+  public class Core : MarshalByRefObject {
+    public static bool abortRequested { get; set; }
+
+    private bool _currentlyFetching;
+    private bool CurrentlyFetching { 
+      get {
+        return _currentlyFetching;
+      } set {        
+        _currentlyFetching = value;
+        Logger.Debug("Set CurrentlyFetching to " + _currentlyFetching);
+      } 
+    }
+
+    private Dictionary<Guid, Executor> engines = new Dictionary<Guid, Executor>();
+    private Dictionary<Guid, AppDomain> appDomains = new Dictionary<Guid, AppDomain>();
+    private Dictionary<Guid, JobDto> jobs = new Dictionary<Guid, JobDto>();
+
+    private WcfService wcfService;
+    private Heartbeat beat;
+
+    /// <summary>
+    /// Main Method for the client
+    /// </summary>
+    public void Start() {
+      abortRequested = false;
+      Logger.Info("Hive Client started");
+      ClientConsoleServer server = new ClientConsoleServer();
+      server.StartClientConsoleServer(new Uri("net.tcp://127.0.0.1:8000/ClientConsole/"));
+
+      ConfigManager manager = ConfigManager.Instance;
+      manager.Core = this;
+
+
+
+      //Register all Wcf Service references
+      wcfService = WcfService.Instance;
+      wcfService.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(wcfService_LoginCompleted);
+      wcfService.SendJobCompleted += new EventHandler<SendJobCompletedEventArgs>(wcfService_SendJobCompleted);
+      wcfService.StoreFinishedJobResultCompleted += new EventHandler<StoreFinishedJobResultCompletedEventArgs>(wcfService_StoreFinishedJobResultCompleted);
+      wcfService.ProcessSnapshotCompleted += new EventHandler<ProcessSnapshotCompletedEventArgs>(wcfService_ProcessSnapshotCompleted);
+      wcfService.ConnectionRestored += new EventHandler(wcfService_ConnectionRestored);
+      wcfService.ServerChanged += new EventHandler(wcfService_ServerChanged);
+      wcfService.Connected += new EventHandler(wcfService_Connected);
+      //Recover Server IP and Port from the Settings Framework
+      ConnectionContainer cc = ConfigManager.Instance.GetServerIPAndPort();
+      if (cc.IPAdress != String.Empty && cc.Port != 0)
+        wcfService.SetIPAndPort(cc.IPAdress, cc.Port);
+
+      if (!UptimeManager.Instance.CalendarAvailable || UptimeManager.Instance.IsOnline())
+        wcfService.Connect();
+
+      //Initialize the heartbeat
+      beat = new Heartbeat { Interval = 10000 };
+      beat.StartHeartbeat();
+
+      MessageQueue queue = MessageQueue.GetInstance();
+
+      //Main processing loop     
+      //Todo: own thread for message handling
+      //Rly?!
+      while (!abortRequested) {
+        MessageContainer container = queue.GetMessage();        
+        DetermineAction(container);
+      }
+      Logger.Info("Program shutdown");
+    }
+
+    /// <summary>
+    /// Reads and analyzes the Messages from the MessageQueue and starts corresponding actions
+    /// </summary>
+    /// <param name="container">The Container, containing the message</param>
+    private void DetermineAction(MessageContainer container) {
+      Logger.Info("Message: " + container.Message.ToString() + " for job: " + container.JobId);        
+      switch (container.Message) {
+        //Server requests to abort a job
+        case MessageContainer.MessageType.AbortJob:          
+          if (engines.ContainsKey(container.JobId))
+            engines[container.JobId].Abort();
+          else
+            Logger.Error("AbortJob: Engine doesn't exist");
+          break;
+        //Job has been successfully aborted
+
+
+        case MessageContainer.MessageType.JobAborted:          
+        //todo: thread this          
+          lock (engines) {
+            Guid jobId = new Guid(container.JobId.ToString());
+            if (engines.ContainsKey(jobId)) {
+              appDomains[jobId].UnhandledException -= new UnhandledExceptionEventHandler(appDomain_UnhandledException);
+              AppDomain.Unload(appDomains[jobId]);
+              appDomains.Remove(jobId);
+              engines.Remove(jobId);
+              jobs.Remove(jobId);
+              GC.Collect();
+            } else
+              Logger.Error("JobAbort: Engine doesn't exist");
+          }
+          break;
+
+
+        //Request a Snapshot from the Execution Engine
+        case MessageContainer.MessageType.RequestSnapshot:          
+          if (engines.ContainsKey(container.JobId))
+            engines[container.JobId].RequestSnapshot();
+          else
+            Logger.Error("RequestSnapshot: Engine doesn't exist");
+          break;
+
+
+        //Snapshot is ready and can be sent back to the Server
+        case MessageContainer.MessageType.SnapshotReady:          
+          ThreadPool.QueueUserWorkItem(new WaitCallback(GetSnapshot), container.JobId);
+          break;
+
+
+        //Pull a Job from the Server
+        case MessageContainer.MessageType.FetchJob:          
+          if (!CurrentlyFetching) {
+            wcfService.SendJobAsync(ConfigManager.Instance.GetClientInfo().Id);
+            CurrentlyFetching = true;
+          } else
+            Logger.Info("Currently fetching, won't fetch this time!");
+          break;          
+        
+        
+        //A Job has finished and can be sent back to the server
+        case MessageContainer.MessageType.FinishedJob:          
+          ThreadPool.QueueUserWorkItem(new WaitCallback(GetFinishedJob), container.JobId);
+          break;
+
+
+        //When the timeslice is up
+        case MessageContainer.MessageType.UptimeLimitDisconnect:
+          Logger.Info("Uptime Limit reached, storing jobs and sending them back");
+
+          //check if there are running jobs
+          if (engines.Count > 0) {
+            //make sure there is no more fetching of jobs while the snapshots get processed
+            CurrentlyFetching = true;
+            //request a snapshot of each running job
+            foreach (KeyValuePair<Guid, Executor> kvp in engines) {
+              kvp.Value.RequestSnapshot();
+            }
+
+          } else {
+            //Disconnect afterwards
+            WcfService.Instance.Disconnect();
+          }
+          break;
+
+          //Fetch or Force Fetch Calendar!
+        case MessageContainer.MessageType.FetchOrForceFetchCalendar:
+          Logger.Info("Fetch Calendar from Server");
+          FetchCalendarFromServer();  
+        break;
+
+        //Hard shutdown of the client
+        case MessageContainer.MessageType.Shutdown:
+          Logger.Info("Shutdown Signal received");
+          lock (engines) {
+            Logger.Debug("engines locked");
+            foreach (KeyValuePair<Guid, AppDomain> kvp in appDomains) {
+              Logger.Debug("Shutting down Appdomain for " + kvp.Key);
+              appDomains[kvp.Key].UnhandledException -= new UnhandledExceptionEventHandler(appDomain_UnhandledException);
+              AppDomain.Unload(kvp.Value);
+            }
+          }
+          Logger.Debug("Stopping heartbeat");
+          abortRequested = true;
+          beat.StopHeartBeat();
+          Logger.Debug("Logging out");
+          WcfService.Instance.Logout(ConfigManager.Instance.GetClientInfo().Id);
+          break;
+      }
+    }
+
+    //Asynchronous Threads for interaction with the Execution Engine
+    #region Async Threads for the EE
+
+    /// <summary>
+    /// serializes the finished job and submits it to the server. If, at the time, a network connection is unavailable, the Job gets stored on the disk. 
+    /// once the connection gets reestablished, the job gets submitted
+    /// </summary>
+    /// <param name="jobId"></param>
+    private void GetFinishedJob(object jobId) {
+      Guid jId = (Guid)jobId;
+      Logger.Info("Getting the finished job with id: " + jId);
+      try {
+        if (!engines.ContainsKey(jId)) {
+          Logger.Info("Engine doesn't exist");
+          return;
+        }
+
+        byte[] sJob = engines[jId].GetFinishedJob();
+
+        if (WcfService.Instance.ConnState == NetworkEnum.WcfConnState.Loggedin) {
+          Logger.Info("Sending the finished job with id: " + jId);
+          wcfService.StoreFinishedJobResultAsync(ConfigManager.Instance.GetClientInfo().Id,
+            jId,
+            sJob,
+            1,
+            null,
+            true);
+        } else {
+          Logger.Info("Storing the finished job with id: " + jId + " to hdd");
+          JobStorageManager.PersistObjectToDisc(wcfService.ServerIP, wcfService.ServerPort, jId, sJob);
+          lock (engines) {
+            appDomains[jId].UnhandledException -= new UnhandledExceptionEventHandler(appDomain_UnhandledException);
+            
+            //Disposing it
+            engines[jId].Dispose();
+            
+            AppDomain.Unload(appDomains[jId]);
+            Logger.Debug("Unloaded appdomain");
+            appDomains.Remove(jId);            
+            engines.Remove(jId);            
+            jobs.Remove(jId);
+            Logger.Debug("Removed job from appDomains, Engines and Jobs");
+          }
+        }
+      }
+      catch (InvalidStateException ise) {
+        Logger.Error("Invalid State while Snapshoting:", ise);
+      }
+    }
+
+    private void GetSnapshot(object jobId) {
+      Logger.Info("Fetching a snapshot for job " + jobId);
+      Guid jId = (Guid)jobId;
+      byte[] obj = engines[jId].GetSnapshot();
+      Logger.Debug("BEGIN: Sending snapshot sync");
+      wcfService.ProcessSnapshotSync(ConfigManager.Instance.GetClientInfo().Id,
+        jId,
+        obj,
+        engines[jId].Progress,
+        null);
+      Logger.Debug("END: Sended snapshot sync");
+      //Uptime Limit reached, now is a good time to destroy this jobs.
+      Logger.Debug("Checking if uptime limit is reached");
+      if (!UptimeManager.Instance.IsOnline()) {
+        Logger.Debug("Uptime limit reached");
+        Logger.Debug("Killing Appdomain");
+        KillAppDomain(jId);
+        //Still anything running?  
+        if (engines.Count == 0) {
+          Logger.Info("All jobs snapshotted and sent back, disconnecting");          
+          WcfService.Instance.Disconnect();
+        } else {
+          Logger.Debug("There are still active Jobs in the Field, not disconnecting");
+        }
+
+      } else {
+        Logger.Debug("Restarting the job" + jobId);
+        engines[jId].StartOnlyJob();
+        Logger.Info("Restarted the job" + jobId);
+      }
+    }
+
+    #endregion
+
+    //Eventhandlers for the communication with the wcf Layer 
+    #region wcfService Events
+    /// <summary>
+    /// Login has returned
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void wcfService_LoginCompleted(object sender, LoginCompletedEventArgs e) {
+      if (e.Result.Success) {
+        CurrentlyFetching = false;
+        Logger.Info("Login completed to Hive Server @ " + DateTime.Now);
+      } else
+        Logger.Error("Error during login: " + e.Result.StatusMessage);
+    }
+
+    /// <summary>
+    /// A new Job from the wcfService has been received and will be started within a AppDomain.
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void wcfService_SendJobCompleted(object sender, SendJobCompletedEventArgs e) {
+      if (e.Result.StatusMessage != ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOBS_LEFT) {
+        Logger.Info("Received new job with id " + e.Result.Job.Id);      
+        bool sandboxed = false;        
+        Logger.Debug("Fetching plugins for job " + e.Result.Job.Id);
+
+        PluginCache.Instance.PreparePlugins(e.Result.Job.PluginsNeeded);
+
+//        foreach (CachedHivePluginInfoDto plugininfo in PluginCache.Instance.GetPlugins(e.Result.Job.PluginsNeeded))
+  //        files.AddRange(plugininfo.PluginFiles);
+        Logger.Debug("Plugins fetched for job " + e.Result.Job.Id);
+        try {
+          AppDomain appDomain =
+            HeuristicLab.PluginInfrastructure.Sandboxing.SandboxManager.CreateAndInitSandbox(
+              e.Result.Job.Id.ToString(), null);
+          appDomain.UnhandledException += new UnhandledExceptionEventHandler(appDomain_UnhandledException);
+          lock (engines) {
+            if (!jobs.ContainsKey(e.Result.Job.Id)) {
+              jobs.Add(e.Result.Job.Id, e.Result.Job);
+              appDomains.Add(e.Result.Job.Id, appDomain);
+              Logger.Debug("Creating AppDomain");
+              Executor engine =
+                (Executor)
+                appDomain.CreateInstanceAndUnwrap(typeof (Executor).Assembly.GetName().Name, typeof (Executor).FullName);
+              Logger.Debug("Created AppDomain");
+              engine.JobId = e.Result.Job.Id;
+              engine.Queue = MessageQueue.GetInstance();
+              Logger.Debug("Starting Engine for job " + e.Result.Job.Id);
+              engine.Start(e.Data);
+              engines.Add(e.Result.Job.Id, engine);
+
+              ClientStatusInfo.JobsFetched++;
+
+              Logger.Info("Increment FetchedJobs to:" + ClientStatusInfo.JobsFetched);
+            }
+          }
+        } catch(Exception exception) {
+          Logger.Error("Creating the Appdomain and loading the job failed for job " + e.Result.Job.Id);
+          Logger.Error("Error thrown is: ", exception);
+          CurrentlyFetching = false;
+          KillAppDomain(e.Result.Job.Id);
+        }
+      } else
+        Logger.Info("No more jobs left!");
+      CurrentlyFetching = false;
+    }
+
+    /// <summary>
+    /// A finished job has been stored on the server
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void wcfService_StoreFinishedJobResultCompleted(object sender, StoreFinishedJobResultCompletedEventArgs e) {
+      Logger.Info("Job submitted with id " + e.Result.JobId);
+      KillAppDomain(e.Result.JobId);
+      if (e.Result.Success) {
+        ClientStatusInfo.JobsProcessed++;
+        Logger.Info("Increased ProcessedJobs to:" + ClientStatusInfo.JobsProcessed);
+      } else {
+        Logger.Error("Sending of job " + e.Result.JobId + " failed, job has been wasted. Message: " + e.Result.StatusMessage);
+      }
+    }
+
+    /// <summary>
+    /// A snapshot has been stored on the server
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void wcfService_ProcessSnapshotCompleted(object sender, ProcessSnapshotCompletedEventArgs e) {
+      Logger.Info("Snapshot " + e.Result.JobId + " has been transmitted according to plan.");
+    }
+
+    /// <summary>
+    /// The server has been changed. All Appdomains and Jobs must be aborted!
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void wcfService_ServerChanged(object sender, EventArgs e) {
+      Logger.Info("ServerChanged has been called");
+      lock (engines) {
+        foreach (KeyValuePair<Guid, Executor> entries in engines) {
+          engines[entries.Key].Abort();
+          //appDomains[entries.Key].UnhandledException -= new UnhandledExceptionEventHandler(appDomain_UnhandledException);
+          //AppDomain.Unload(appDomains[entries.Key]);
+        }
+        //appDomains = new Dictionary<Guid, AppDomain>();
+        //engines = new Dictionary<Guid, Executor>();
+        //jobs = new Dictionary<Guid, Job>();
+      }
+    }
+
+    /// <summary>
+    /// Connnection to the server has been estabilshed => Login and Send the persistet Jobs from the harddisk.
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void wcfService_Connected(object sender, EventArgs e) {
+      Logger.Info("WCF Service got a connection");
+      if (!UptimeManager.Instance.CalendarAvailable) {
+        Logger.Info("No local calendar available, fetch it");
+        FetchCalendarFromServer();
+      }
+      //if the fetching from the server failed - still set the client online... maybe we get 
+      //a result within the next few heartbeats      
+      if (!UptimeManager.Instance.CalendarAvailable || UptimeManager.Instance.IsOnline()) {
+        Logger.Info("CalendarAvailable is " + UptimeManager.Instance.CalendarAvailable + " and IsOnline is: " + UptimeManager.Instance.IsOnline());
+        Logger.Info("Setting client online");
+        wcfService.LoginSync(ConfigManager.Instance.GetClientInfo());
+        JobStorageManager.CheckAndSubmitJobsFromDisc();
+        CurrentlyFetching = false;
+      }
+    }
+
+    private void FetchCalendarFromServer() {
+      ResponseCalendar calres = wcfService.GetCalendarSync(ConfigManager.Instance.GetClientInfo().Id);
+      if(calres.Success) {
+        if (UptimeManager.Instance.SetAppointments(false, calres)) {
+          Logger.Info("Remote calendar installed");
+          wcfService.SetCalendarStatus(ConfigManager.Instance.GetClientInfo().Id, CalendarState.Fetched);
+        } else {
+          Logger.Info("Remote calendar installation failed, setting state to " + CalendarState.NotAllowedToFetch);
+          wcfService.SetCalendarStatus(ConfigManager.Instance.GetClientInfo().Id, CalendarState.NotAllowedToFetch);
+        }
+      } else {
+        Logger.Info("Remote calendar installation failed, setting state to " + CalendarState.NotAllowedToFetch);
+        wcfService.SetCalendarStatus(ConfigManager.Instance.GetClientInfo().Id, CalendarState.NotAllowedToFetch);
+      }
+    }
+
+    //this is a little bit tricky - 
+    void wcfService_ConnectionRestored(object sender, EventArgs e) {
+      Logger.Info("Reconnected to old server - checking currently running appdomains");
+
+      foreach (KeyValuePair<Guid, Executor> execKVP in engines) {
+        if (!execKVP.Value.Running && execKVP.Value.CurrentMessage == MessageContainer.MessageType.NoMessage) {
+          Logger.Info("Checking for JobId: " + execKVP.Value.JobId);
+          Thread finThread = new Thread(new ParameterizedThreadStart(GetFinishedJob));
+          finThread.Start(execKVP.Value.JobId);
+        }
+      }
+    }
+
+    #endregion
+
+    public Dictionary<Guid, Executor> GetExecutionEngines() {
+      return engines;
+    }
+
+    void appDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
+      Logger.Error("Exception in AppDomain: " + e.ExceptionObject.ToString());    
+    }
+
+    internal Dictionary<Guid, JobDto> GetJobs() {
+      return jobs;
+    }
+
+    /// <summary>
+    /// Kill a appdomain with a specific id.
+    /// </summary>
+    /// <param name="id">the GUID of the job</param>
+    private void KillAppDomain(Guid id) {
+      Logger.Debug("Shutting down Appdomain for Job " + id);
+      lock (engines) {
+        try {
+          if(engines.ContainsKey(id))
+            engines[id].Dispose();
+          if (appDomains.ContainsKey(id)) {
+            appDomains[id].UnhandledException -= new UnhandledExceptionEventHandler(appDomain_UnhandledException);
+            AppDomain.Unload(appDomains[id]);
+            appDomains.Remove(id);
+          }
+          engines.Remove(id);
+          jobs.Remove(id);
+          GC.Collect();
+        }
+        catch (Exception ex) {
+          Logger.Error("Exception when unloading the appdomain: ", ex);
+        }
+      }
+      GC.Collect();
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/CoreApplication.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/CoreApplication.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/CoreApplication.cs	(revision 4061)
@@ -0,0 +1,40 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.PluginInfrastructure;
+using System.Diagnostics;
+using HeuristicLab.Hive.Client.Common;
+using System.Timers;
+using System.Threading;
+
+namespace HeuristicLab.Hive.Client.Core {
+  [Application("Hive Client", "Hive Client Core baseclass")]
+  public class CoreApplication : ApplicationBase {
+    public override void Run() {
+      Core core = new Core();
+      core.Start();
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/CorePlugin.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/CorePlugin.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/CorePlugin.cs	(revision 4061)
@@ -0,0 +1,41 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Hive.Client.Core {
+  [Plugin("HeuristicLab.Hive.Client.Core-3.2")]
+  [PluginFile("HeuristicLab.Hive.Client.Core-3.2.dll", PluginFileType.Assembly)]
+  [PluginDependency("HeuristicLab.Core-3.2")]
+  [PluginDependency("HeuristicLab.DataAccess-3.2")]
+  [PluginDependency("HeuristicLab.Hive.Client.Common-3.2")]
+  [PluginDependency("HeuristicLab.Hive.Client.Communication-3.2")]
+  [PluginDependency("HeuristicLab.Hive.Client.ExecutionEngine-3.2")]
+  [PluginDependency("HeuristicLab.Hive.Contracts-3.2")]
+  [PluginDependency("HeuristicLab.Hive.JobBase-3.2")]
+  [PluginDependency("HeuristicLab.Tracing", "3.2.0")]
+  public class CorePlugin: PluginBase {
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Heartbeat.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Heartbeat.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Heartbeat.cs	(revision 4061)
@@ -0,0 +1,120 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Timers;
+using HeuristicLab.Hive.Client.Common;
+using HeuristicLab.Hive.Client.Communication;
+using System.Diagnostics;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Hive.Client.Core.ConfigurationManager;
+using HeuristicLab.Hive.Client.Communication.ServerService;
+using HeuristicLab.Tracing;
+//using BO = HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Client.Core {
+  /// <summary>
+  /// Heartbeat class. It sends every x ms a heartbeat to the server and receives a Message
+  /// </summary>
+  public class Heartbeat {
+
+    private bool offline;
+
+    public double Interval { get; set; }    
+    private Timer heartbeatTimer = null;
+        
+    public Heartbeat() {
+      Interval = 100;
+    }
+
+    public Heartbeat(double interval) {
+      Interval = interval;      
+    }
+
+    private WcfService wcfService;
+
+    /// <summary>
+    /// Starts the Heartbeat signal.
+    /// </summary>
+    public void StartHeartbeat() {
+      heartbeatTimer = new System.Timers.Timer();
+      heartbeatTimer.Interval = this.Interval;
+      heartbeatTimer.AutoReset = true;
+      heartbeatTimer.Elapsed += new ElapsedEventHandler(heartbeatTimer_Elapsed);
+      wcfService = WcfService.Instance;
+      wcfService.ProcessHeartBeatCompleted += new EventHandler<ProcessHeartBeatCompletedEventArgs>(wcfService_ProcessHeartBeatCompleted);
+      heartbeatTimer.Start();
+    }
+
+    /// <summary>
+    /// This Method is called every time the timer ticks
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void heartbeatTimer_Elapsed(object sender, ElapsedEventArgs e) {      
+      ClientDto info = ConfigManager.Instance.GetClientInfo();      
+
+      PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes", true);
+      int mb = (int)(counter.NextValue() / 1024 / 1024);
+
+      HeartBeatData heartBeatData = new HeartBeatData {
+        ClientId = info.Id,
+        FreeCores = info.NrOfCores - ConfigManager.Instance.GetUsedCores(),
+        FreeMemory = mb,
+        JobProgress = ConfigManager.Instance.GetProgressOfAllJobs()      
+      };
+       
+      DateTime lastFullHour = DateTime.Parse(DateTime.Now.Hour.ToString() + ":00");
+      TimeSpan span = DateTime.Now - lastFullHour;
+      if (span.TotalSeconds < (Interval/1000)) {
+        if (UptimeManager.Instance.IsOnline() && UptimeManager.Instance.CalendarAvailable) {
+          //That's quiet simple: Just reconnect and you're good for new jobs
+          if (wcfService.ConnState != NetworkEnum.WcfConnState.Loggedin) {
+            Logger.Info("Client goes online according to timetable");
+            wcfService.Connect();
+          }
+        } else {
+          //We have quit a lot of work to do here: snapshot all jobs, submit them back, then disconnect and then pray to god that nothing goes wrong
+          MessageQueue.GetInstance().AddMessage(MessageContainer.MessageType.UptimeLimitDisconnect);                  
+        }        
+      }
+      if (wcfService.ConnState == NetworkEnum.WcfConnState.Failed) {
+        wcfService.Connect();
+      } else if (wcfService.ConnState == NetworkEnum.WcfConnState.Loggedin) {
+        Logger.Debug("Sending Heartbeat: " + heartBeatData);        
+        wcfService.ProcessHeartBeatAsync(heartBeatData);
+      }
+    }
+
+    void wcfService_ProcessHeartBeatCompleted(object sender, ProcessHeartBeatCompletedEventArgs e) {
+      Logger.Debug("Heartbeat received");
+      e.Result.ActionRequest.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));      
+    }
+
+    public void StopHeartBeat() {
+      heartbeatTimer.Dispose();
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/HeuristicLab.Hive.Client.Core-3.2.csproj
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/HeuristicLab.Hive.Client.Core-3.2.csproj	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/HeuristicLab.Hive.Client.Core-3.2.csproj	(revision 4061)
@@ -0,0 +1,183 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProductVersion>9.0.30729</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{5010BD86-23B7-4F8C-888A-76D21AD5266A}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>HeuristicLab.Hive.Client.Core</RootNamespace>
+    <AssemblyName>HeuristicLab.Hive.Client.Core-3.2</AssemblyName>
+    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <SignAssembly>true</SignAssembly>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>bin\x86\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>bin\x86\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>bin\x64\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>bin\x64\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="Calendar.DayView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\HeuristicLab.Hive.Contracts\3.2\Calendar.DayView.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Core">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Runtime.Serialization">
+      <RequiredTargetFramework>3.0</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.ServiceModel">
+      <RequiredTargetFramework>3.0</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Xml.Linq">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Data.DataSetExtensions">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="ClientConsoleService\ClientConsoleCommunicator.cs" />
+    <Compile Include="ClientConsoleService\ClientConsoleServer.cs" />
+    <Compile Include="ClientConsoleService\Interfaces\IClientConsoleCommunicator.cs" />
+    <Compile Include="ClientConsoleService\TransferObjects\ConnectionContainer.cs" />
+    <Compile Include="ClientConsoleService\TransferObjects\JobStatus.cs" />
+    <Compile Include="ClientConsoleService\TransferObjects\StatusCommons.cs" />
+    <Compile Include="ConfigurationManager\AppointmentContainer.cs" />
+    <Compile Include="ConfigurationManager\ClientStatusInfo.cs" />
+    <Compile Include="ConfigurationManager\ConfigManager.cs" />
+    <Compile Include="ConfigurationManager\UptimeManager.cs" />
+    <Compile Include="Core.cs" />
+    <Compile Include="CoreApplication.cs" />
+    <Compile Include="CorePlugin.cs" />
+    <Compile Include="Heartbeat.cs" />
+    <Compile Include="JobStorage\JobStorageInfo.cs" />
+    <Compile Include="JobStorage\JobStorageManager.cs" />
+    <Compile Include="PluginCache.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Properties\Settings.Designer.cs">
+      <AutoGen>True</AutoGen>
+      <DesignTimeSharedInput>True</DesignTimeSharedInput>
+      <DependentUpon>Settings.settings</DependentUpon>
+    </Compile>
+    <Compile Include="Settings.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="app.config" />
+    <None Include="HeuristicLab.snk" />
+    <None Include="Properties\AssemblyInfo.frame" />
+    <None Include="Properties\Settings.settings">
+      <Generator>PublicSettingsSingleFileGenerator</Generator>
+      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
+    </None>
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\HeuristicLab.Core\3.2\HeuristicLab.Core-3.2.csproj">
+      <Project>{F43B59AB-2B8C-4570-BC1E-15592086517C}</Project>
+      <Name>HeuristicLab.Core-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.DataAccess\3.2\HeuristicLab.DataAccess-3.2.csproj">
+      <Project>{9076697B-C151-46CD-95BC-1D059492B478}</Project>
+      <Name>HeuristicLab.DataAccess-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.Client.Common\3.2\HeuristicLab.Hive.Client.Common-3.2.csproj">
+      <Project>{89F4BC52-C174-481E-9BD2-3814171020E8}</Project>
+      <Name>HeuristicLab.Hive.Client.Common-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.Client.Communication\3.2\HeuristicLab.Hive.Client.Communication-3.2.csproj">
+      <Project>{AEB51212-CDBA-4FC6-A2EE-02359AA53ECE}</Project>
+      <Name>HeuristicLab.Hive.Client.Communication-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.Client.ExecutionEngine\3.2\HeuristicLab.Hive.Client.ExecutionEngine-3.2.csproj">
+      <Project>{1605256A-1CB3-44AB-AAFF-577093EE5789}</Project>
+      <Name>HeuristicLab.Hive.Client.ExecutionEngine-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.Contracts\3.2\HeuristicLab.Hive.Contracts-3.2.csproj">
+      <Project>{134F93D7-E7C8-4ECD-9923-7F63259A60D8}</Project>
+      <Name>HeuristicLab.Hive.Contracts-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.JobBase\3.2\HeuristicLab.Hive.JobBase-3.2.csproj">
+      <Project>{21187322-52DD-4243-80A4-A85F0263E63B}</Project>
+      <Name>HeuristicLab.Hive.JobBase-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.PluginInfrastructure\HeuristicLab.PluginInfrastructure.csproj">
+      <Project>{94186A6A-5176-4402-AE83-886557B53CCA}</Project>
+      <Name>HeuristicLab.PluginInfrastructure</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Tracing\3.2\HeuristicLab.Tracing-3.2.csproj">
+      <Project>{EE2034D9-6E27-48A1-B855-42D45F69A4FC}</Project>
+      <Name>HeuristicLab.Tracing-3.2</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <WCFMetadata Include="Service References\" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+  <PropertyGroup>
+    <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd</PreBuildEvent>
+  </PropertyGroup>
+</Project>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/JobStorage/JobStorageInfo.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/JobStorage/JobStorageInfo.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/JobStorage/JobStorageInfo.cs	(revision 4061)
@@ -0,0 +1,13 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace HeuristicLab.Hive.Client.Core.JobStorage {
+  public class JobStorageInfo {
+    public String ServerIP { get; set; }
+    public long ServerPort { get; set; }
+    public DateTime TimeFinished { get; set; }
+    public Guid JobID { get; set; }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/JobStorage/JobStorageManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/JobStorage/JobStorageManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/JobStorage/JobStorageManager.cs	(revision 4061)
@@ -0,0 +1,107 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.IO;
+using HeuristicLab.Hive.Client.Common;
+using HeuristicLab.Hive.Client.Communication;
+using HeuristicLab.Hive.Client.Core.ConfigurationManager;
+using HeuristicLab.Hive.Contracts;
+using System.Xml.Serialization;
+using System.Diagnostics;
+using System.Xml;
+using HeuristicLab.Tracing;
+
+namespace HeuristicLab.Hive.Client.Core.JobStorage {
+  public class JobStorageManager {
+    
+    private static List<JobStorageInfo> storedJobsList = new List<JobStorageInfo>();
+    
+    private static String path = System.IO.Directory.GetCurrentDirectory()+"\\Hive.Client.Jobs\\";
+    
+    public static void PersistObjectToDisc(String serverIP, long serverPort, Guid jobId, byte[] job) {
+      String filename = serverIP + "." + serverPort + "." + jobId.ToString();
+      JobStorageInfo info = new JobStorageInfo { JobID = jobId, ServerIP = serverIP, ServerPort = serverPort, TimeFinished = DateTime.Now };
+      
+      Stream jobstream = null;
+      try {
+        jobstream = File.Create(path + filename + ".dat");
+        jobstream.Write(job, 0, job.Length);
+        storedJobsList.Add(info);        
+        Logger.Info("Job " + info.JobID + " stored on the harddisc");
+      }
+      catch (Exception e) {
+        Logger.Error("Exception: ", e);
+      }
+      finally {
+        if(jobstream!=null)
+          jobstream.Close();
+      }
+
+      StoreJobList();
+
+    }
+
+    public static void CheckAndSubmitJobsFromDisc() {
+      for(int index=storedJobsList.Count; index > 0; index--) {
+        if (WcfService.Instance.ConnState == NetworkEnum.WcfConnState.Loggedin && (storedJobsList[index-1].ServerIP == WcfService.Instance.ServerIP && storedJobsList[index-1].ServerPort == WcfService.Instance.ServerPort)) {
+          String filename = storedJobsList[index-1].ServerIP + "." + storedJobsList[index-1].ServerPort + "." + storedJobsList[index-1].JobID.ToString();          
+          Logger.Info("Sending stored job " + storedJobsList[index - 1].JobID + " to the server");
+          try {
+            byte[] job = File.ReadAllBytes(path + filename + ".dat");
+            if (WcfService.Instance.IsJobStillNeeded(storedJobsList[index - 1].JobID).StatusMessage == ApplicationConstants.RESPONSE_COMMUNICATOR_SEND_JOBRESULT) {
+              ResponseResultReceived res = WcfService.Instance.StoreFinishedJobResultsSync(ConfigManager.Instance.GetClientInfo().Id, storedJobsList[index - 1].JobID, job, 1.00, null, true);
+              if (!res.Success)
+                Logger.Error("sending of job failed: " + res.StatusMessage);
+              else
+                Logger.Info("Sending of job " + storedJobsList[index - 1].JobID + " done");
+            }
+            ClientStatusInfo.JobsProcessed++;
+            storedJobsList.Remove(storedJobsList[index - 1]);
+            File.Delete(path + filename + ".dat"); 
+          }
+          catch (Exception e) {
+            Logger.Error("Job not on hdd but on list - deleting job from list ", e);
+            storedJobsList.Remove(storedJobsList[index - 1]);
+            StoreJobList();
+          }
+      
+         }
+        }
+    }
+
+    public static void StoreJobList() {
+      XmlSerializer serializer = new XmlSerializer(typeof(List<JobStorageInfo>));
+      TextWriter writer = new StreamWriter(Path.Combine(path ,"list.xml"));
+      serializer.Serialize(writer, storedJobsList);
+      writer.Close();
+    }
+
+    static JobStorageManager() {
+      Logger.Info("Restoring Joblist from Harddisk");
+      if (!Directory.Exists(path))
+        Directory.CreateDirectory(path);
+            
+      XmlSerializer serializer = new XmlSerializer(typeof(List<JobStorageInfo>));
+      FileStream stream = null;
+      if(File.Exists(Path.Combine(path ,"list.xml"))) {
+        try {
+          stream = new FileStream(Path.Combine(path, "list.xml"), FileMode.Open);
+          XmlTextReader reader = new XmlTextReader(stream);
+          storedJobsList = (List<JobStorageInfo>)serializer.Deserialize(reader);
+          Logger.Info("Loaded " + storedJobsList.Count + " Elements");
+        }
+        catch (Exception e) {
+          Logger.Error("Exception while loading the Stored Job List", e);
+        } finally {
+          if(stream != null) 
+            stream.Dispose();
+        }
+      } else {
+        Logger.Info("no stored jobs on harddisk, starting new list");
+        storedJobsList = new List<JobStorageInfo>();
+      }
+    }
+    
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/PluginCache.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/PluginCache.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/PluginCache.cs	(revision 4061)
@@ -0,0 +1,92 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.PluginInfrastructure;
+using HeuristicLab.Hive.Client.Communication;
+using HeuristicLab.Hive.Client.Common;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Tracing;
+using System.IO;
+
+namespace HeuristicLab.Hive.Client.Core {
+  public class PluginCache {
+
+    private static PluginCache instance = null;
+    public static PluginCache Instance {
+      get {
+        if (instance == null)
+          instance = new PluginCache();
+        return instance;
+      }
+    } 
+    
+    private List<CachedHivePluginInfoDto> pluginCache;
+    
+
+    public PluginCache() {
+      pluginCache = new List<CachedHivePluginInfoDto>();
+    }
+    
+    public void AddPlugin(CachedHivePluginInfoDto plugin) {
+      pluginCache.Add(plugin);    
+    }
+
+    public List<CachedHivePluginInfoDto> GetPlugins(List<HivePluginInfoDto> requests) {
+      Logger.Debug("Fetching plugins for job");
+      List<CachedHivePluginInfoDto> neededPlugins = new List<CachedHivePluginInfoDto>();
+      List<HivePluginInfoDto> missingPlugins = new List<HivePluginInfoDto>();
+      bool found = false;
+            
+      foreach (HivePluginInfoDto info in requests) {
+        //we MAY run in problems here - if there is a plugin twice in requests, there may be added two different versions of the plugin
+        foreach (CachedHivePluginInfoDto cache in pluginCache) {
+          if (info.Name.Equals(cache.Name) && info.Version.Equals(cache.Version) && info.BuildDate <= cache.BuildDate) {
+            Logger.Debug("Found plugin " + info.Name + ", " + info.Version);
+            neededPlugins.Add(cache);
+            found = true;
+            break;
+          }
+        }
+        if (!found)
+          Logger.Debug("Found NOT found " + info.Name + ", " + info.Version);
+          missingPlugins.Add(info);
+        found = false;
+      }
+
+      Logger.Debug("Requesting missing plugins");
+      List<CachedHivePluginInfoDto> receivedPlugins = WcfService.Instance.RequestPlugins(missingPlugins);
+      Logger.Debug("Requested missing plugins");
+
+      if (receivedPlugins != null) {
+        neededPlugins.AddRange(receivedPlugins);
+        pluginCache.AddRange(receivedPlugins);
+      } else
+        Logger.Error("Fetching of the plugins failed!");
+
+      return neededPlugins;
+    }
+
+
+    internal void PreparePlugins(List<HivePluginInfoDto> requiredPlugins) {
+      List<HivePluginInfoDto> missingPlugins = new List<HivePluginInfoDto>();
+      foreach (HivePluginInfoDto requiredPlugin in requiredPlugins) {
+        if(ApplicationManager.Manager.Plugins.Count(ipd => ipd.Version.Major == requiredPlugin.Version.Major && ipd.Version.Minor >= requiredPlugin.Version.Minor) == 0) {
+          missingPlugins.Add(requiredPlugin);             
+        }
+      }
+
+      Logger.Debug("Requesting missing plugins");
+      List<CachedHivePluginInfoDto> receivedPlugins = WcfService.Instance.RequestPlugins(missingPlugins);
+      Logger.Debug("Requested missing plugins");
+
+      foreach (CachedHivePluginInfoDto receivedPlugin in receivedPlugins) {
+        foreach (HivePluginFile hpf in receivedPlugin.PluginFiles) {
+          Logger.Info("writing file " + hpf.Name);
+          File.WriteAllBytes("C:\\temp\\" + hpf.Name.Split('\\').Last(), hpf.BinaryFile);
+        }        
+      }
+
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/AssemblyInfo.frame
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/AssemblyInfo.frame	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/AssemblyInfo.frame	(revision 4061)
@@ -0,0 +1,61 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using HeuristicLab.PluginInfrastructure;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.Hive.Client.Core")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2008 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: AllowPartiallyTrustedCallers]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("390a4020-8f30-4c57-b039-6f3647df86b0")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("3.2.0.$WCREV$")]
+[assembly: AssemblyFileVersion("3.2.0.$WCREV$")]
+[assembly: AssemblyBuildDate("$WCNOW$")]
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/Settings.Designer.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/Settings.Designer.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/Settings.Designer.cs	(revision 4061)
@@ -0,0 +1,62 @@
+﻿//------------------------------------------------------------------------------
+// <auto-generated>
+//     This code was generated by a tool.
+//     Runtime Version:2.0.50727.4927
+//
+//     Changes to this file may cause incorrect behavior and will be lost if
+//     the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace HeuristicLab.Hive.Client.Core.Properties {
+    
+    
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
+    public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
+        
+        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+        
+        public static Settings Default {
+            get {
+                return defaultInstance;
+            }
+        }
+        
+        [global::System.Configuration.UserScopedSettingAttribute()]
+        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+        [global::System.Configuration.DefaultSettingValueAttribute("00000000-0000-0000-0000-000000000000")]
+        public global::System.Guid Guid {
+            get {
+                return ((global::System.Guid)(this["Guid"]));
+            }
+            set {
+                this["Guid"] = value;
+            }
+        }
+        
+        [global::System.Configuration.UserScopedSettingAttribute()]
+        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+        [global::System.Configuration.DefaultSettingValueAttribute("")]
+        public string ServerIP {
+            get {
+                return ((string)(this["ServerIP"]));
+            }
+            set {
+                this["ServerIP"] = value;
+            }
+        }
+        
+        [global::System.Configuration.UserScopedSettingAttribute()]
+        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+        [global::System.Configuration.DefaultSettingValueAttribute("0")]
+        public int ServerPort {
+            get {
+                return ((int)(this["ServerPort"]));
+            }
+            set {
+                this["ServerPort"] = value;
+            }
+        }
+    }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/Settings.settings
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/Settings.settings	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Properties/Settings.settings	(revision 4061)
@@ -0,0 +1,15 @@
+﻿<?xml version='1.0' encoding='utf-8'?>
+<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="HeuristicLab.Hive.Client.Core.Properties" GeneratedClassName="Settings">
+  <Profiles />
+  <Settings>
+    <Setting Name="Guid" Type="System.Guid" Scope="User">
+      <Value Profile="(Default)">00000000-0000-0000-0000-000000000000</Value>
+    </Setting>
+    <Setting Name="ServerIP" Type="System.String" Scope="User">
+      <Value Profile="(Default)" />
+    </Setting>
+    <Setting Name="ServerPort" Type="System.Int32" Scope="User">
+      <Value Profile="(Default)">0</Value>
+    </Setting>
+  </Settings>
+</SettingsFile>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Settings.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Settings.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/Settings.cs	(revision 4061)
@@ -0,0 +1,28 @@
+﻿namespace HeuristicLab.Hive.Client.Core.Properties {
+    
+    
+    // This class allows you to handle specific events on the settings class:
+    //  The SettingChanging event is raised before a setting's value is changed.
+    //  The PropertyChanged event is raised after a setting's value is changed.
+    //  The SettingsLoaded event is raised after the setting values are loaded.
+    //  The SettingsSaving event is raised before the setting values are saved.
+    public sealed partial class Settings {
+        
+        public Settings() {
+            // // To add event handlers for saving and changing settings, uncomment the lines below:
+            //
+            // this.SettingChanging += this.SettingChangingEventHandler;
+            //
+            // this.SettingsSaving += this.SettingsSavingEventHandler;
+            //
+        }
+        
+        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
+            // Add code to handle the SettingChangingEvent event here.
+        }
+        
+        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
+            // Add code to handle the SettingsSaving event here.
+        }
+    }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/app.config
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/app.config	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Client.Core/3.3/app.config	(revision 4061)
@@ -0,0 +1,21 @@
+﻿<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+    <configSections>
+        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
+            <section name="HeuristicLab.Hive.Client.Core.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
+        </sectionGroup>
+    </configSections>
+    <userSettings>
+        <HeuristicLab.Hive.Client.Core.Properties.Settings>
+            <setting name="Guid" serializeAs="String">
+                <value>00000000-0000-0000-0000-000000000000</value>
+            </setting>
+            <setting name="ServerIP" serializeAs="String">
+                <value />
+            </setting>
+            <setting name="ServerPort" serializeAs="String">
+                <value>0</value>
+            </setting>
+        </HeuristicLab.Hive.Client.Core.Properties.Settings>
+    </userSettings>
+</configuration>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionManager.cs	(revision 4061)
@@ -0,0 +1,100 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Security.Contracts.Interfaces;
+using HeuristicLab.DataAccess;
+using HeuristicLab.Security.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+using System.ServiceModel;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class HivePermissionManager : IHivePermissionManager {
+
+    private IJobManager jobManager = ServiceLocator.GetJobManager();
+    
+    private IPermissionManager permManager = ServiceLocator.GetPermissionManager();
+
+    private IClientManager clientManager = ServiceLocator.GetClientManager();
+
+    private PermissionCollection permissions = HivePermissions.GetPermissions();
+    private PolicyCollection policyCollection = HivePermissions.GetPolicies();
+
+    /// <summary>
+    /// Authenticates an user and returns a valid guid if success.
+    /// </summary>
+    /// <param name="username"></param>
+    /// <param name="password"></param>
+    /// <returns></returns>
+    public Guid Login(string username, string password) {
+      return permManager.Authenticate(username, password);
+    }
+
+    /// <summary>
+    /// Checks user permission against predefined policy.
+    /// </summary>
+    /// <param name="policyName">Policy Name defines the action.</param>
+    /// <param name="sessionID">Session ID identifies a currently logged on user.</param>
+    /// <param name="entityID">Entity ID can be some resource or emtpy.</param>
+    public void Authorize(string policyName, Guid sessionID, Guid entityID) {
+      #region Use authorization method with scopes
+      //check if this policy has a permission with 'ANY' scope defined
+      Permission p = policyCollection[policyName].GetPermissionByContext("Any");
+      //check if user has 'xxx.Any' permission
+      if (p != null)
+        if (CheckPermission(sessionID, p.Id, entityID)) return;
+      
+      //check if this policy has a permission with 'PROJECT' scope defined
+      p = policyCollection[policyName].GetPermissionByContext("Project");
+      //check if user has 'xxx.Project' permission
+      if ((p != null) && (entityID!=Guid.Empty))
+      {
+          ResponseObject<JobDto> job = jobManager.GetJobById(entityID);
+          if (job.Obj.Project != null)
+              if (CheckPermission(sessionID, p.Id, jobManager.GetJobById(entityID).Obj.Project.Id)) return;
+      }
+      //check if this policy has a permission with 'OWNER' scope defined
+      p = policyCollection[policyName].GetPermissionByContext("User");
+      
+      //check if user has 'xxx.Owner' permission
+      if (p != null)
+        if (CheckPermission(sessionID, p.Id, jobManager.GetJobById(entityID).Obj.UserId)) return;
+      #endregion
+      #region Use authorization method when no scopes are present
+      //when no permission context is available, use primary authentification
+      foreach (KeyValuePair<Permission, PermissionContext> item in policyCollection[policyName].Permissions)
+      {
+          if (CheckPermission(sessionID, item.Key.Id, Guid.Empty)) return;
+      }
+      #endregion
+      //throw an exception when user access fails
+      throw new PermissionException(policyName);
+    }
+
+    /// <summary>
+    /// Checks if a user has permission for a specified action.
+    /// </summary>
+    /// <param name="sessionID">The current session.</param>
+    /// <param name="actionID">A pre-defined action that requires permission.</param>
+    /// <param name="entityID">A resource (Job,...)</param>
+    /// <returns></returns>
+    public bool CheckPermission(Guid sessionID, Guid actionID, Guid entityId) {
+      bool hasPerm = permManager.CheckPermission(sessionID, actionID, entityId);
+      PermissionCollection pc = HivePermissions.GetPermissions();
+      if (!hasPerm)
+          if (CheckPermissionHelper(sessionID, actionID, entityId)) return true;
+      return hasPerm;
+    }
+
+    private bool CheckPermissionHelper(Guid sessionId, Guid actionId, Guid entityId) {
+      if (entityId == Guid.Empty) return true;
+      IList<ClientGroupDto> groups = clientManager.GetAllGroupsOfResource(entityId).Obj;
+      foreach (ClientGroupDto group in groups)
+        if (CheckPermission(sessionId, actionId, group.Id)) return true;
+      return false;
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionPolicy.xml
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionPolicy.xml	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionPolicy.xml	(revision 4061)
@@ -0,0 +1,62 @@
+﻿<?xml version="1.0" encoding="utf-8" ?>
+<Policies>
+  <Policy name="AccessClients">
+    <Permission name="HivePermissions.Usermanagement.Client.Read"/>
+  </Policy>
+  <Policy name="AccessClientGroup">
+    <Permission name="HivePermissions.Usermanagement.ClientGroup.Read"/>
+  </Policy>
+  <Policy name="AccessUserGroup">
+    <Permission name="HivePermissions.Usermanagement.UserGroup.Read"/>
+  </Policy>
+  <Policy name="AccessProjects">
+    <Permission name="HivePermissions.ResourceManagement.Project.Read"/>
+  </Policy>
+  <Policy name="DeleteProjects">
+    <Permission name="HivePermissions.ResourceManagement.Project.Delete"/>
+  </Policy>
+  <Policy name="ChangeProjects">
+    <Permission name="HivePermissions.ResourceManagement.Project.Update"/>
+  </Policy>
+  <Policy name="DeleteClientGroup">
+    <Permission name="HivePermissions.Usermanagement.ClientGroup.Delete"/>
+  </Policy>
+  <Policy name="AccessJobs">
+    <Permission priority="1" name="HivePermissions.Jobmanagement.Read.Any" context="Any"/>
+    <Permission priority="2" name="HivePermissions.Jobmanagement.Read.ProjectOnly" context="Project"/>
+    <Permission priority="3" name="HivePermissions.Jobmanagement.Read.OwnedOnly" context="User"/>
+  </Policy>
+  <Policy name="AddClientGroup">
+    <Permission name="HivePermissions.Usermanagement.ClientGroup.Create"/>
+  </Policy>
+  <Policy name="AddJob">
+    <Permission priority="1" name="HivePermissions.Jobmanagement.Create.Any" context="Any"/>
+    <Permission priority="2" name="HivePermissions.Jobmanagement.Create.ProjectOnly" context="Project"/>
+  </Policy>
+  <Policy name="AddResource">
+    <Permission priority="1" name="HivePermissions.Jobmanagement.Assign.ToAnyResource" context="Any"/>
+    <Permission priority="2" name="HivePermissions.Jobmanagement.Assign.ToProject" context="Project"/>
+  </Policy>
+  <Policy name="AccessStatistics">
+    <Permission priority="1" name="HivePermissions.Jobmanagement.Read.Any" context="Any"/>
+    <Permission priority="2" name="HivePermissions.Jobmanagement.Read.ProjectOnly" context="Project"/>
+    <Permission priority="3" name="HivePermissions.Jobmanagement.Read.OwnedOnly" context="User"/>
+  </Policy>
+  <Policy name="AccessJobResults">
+    <Permission priority="1" name="HivePermissions.Jobmanagement.Read.Any" context="Any"/>
+    <Permission priority="2" name="HivePermissions.Jobmanagement.Read.ProjectOnly" context="Project"/>
+    <Permission priority="3" name="HivePermissions.Jobmanagement.Read.OwnedOnly" context="User"/>
+  </Policy>
+  <Policy name="AbortJob">
+    <Permission priority="1" name="HivePermissions.Jobmanagement.Abort.Any" context="Any"/>
+    <Permission priority="2" name="HivePermissions.Jobmanagement.Abort.ProjectOnly" context="Project"/>
+    <Permission priority="3" name="HivePermissions.Jobmanagement.Abort.OwnedOnly" context="User"/>
+  </Policy>
+
+  <Policy name="RemoveJob">
+    <Permission priority="1" name="HivePermissions.Jobmanagement.Delete.Any" context="Any"/>
+    <Permission priority="2" name="HivePermissions.Jobmanagement.Delete.ProjectOnly" context="Project"/>
+    <Permission priority="3" name="HivePermissions.Jobmanagement.Delete.OwnedOnly" context="User"/>
+  </Policy>
+  
+</Policies>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionSet.xml
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionSet.xml	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionSet.xml	(revision 4061)
@@ -0,0 +1,184 @@
+﻿<?xml version="1.0" encoding="utf-8" ?>
+<Permissions>
+  <Permission name="HivePermissions.Jobmanagement.Create.Any">
+    <ID>A477BEA9-9C05-477f-AD9E-F76C510DDB0B</ID>
+    <Description>Add any job.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name="HivePermissions.Jobmanagement.Create.ProjectOnly">
+    <ID>95276EA1-F97F-4827-B5D0-AE326856585E</ID>
+    <Description>Add only project-related job.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Create.OwnedOnly">
+    <ID>1C47301B-4187-416f-B113-DA433448AA2E</ID>
+    <Description>Add private jobs only.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Assign.ToAnyResource">
+    <ID>48DBBEE7-53FC-4c23-B2C3-5244A5BD7385</ID>
+    <Description>Assign job to any resource.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Assign.ToProject">
+    <ID>34267865-551F-4faf-BAA8-D6821B116EBC</ID>
+    <Description>Assign job to a specific project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Abort.Any">
+    <ID>C6EB36BE-2BE2-40f2-8440-7750759DFD79</ID>
+    <Description>Abort any running job.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Abort.ProjectOnly">
+    <ID>0E4C2FB1-DFAE-4b1d-B54A-4BD64D7BF905</ID>
+    <Description>Abort only jobs belonging to a specific project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Abort.OwnedOnly">
+    <ID>D7C0C293-78E5-44cf-9785-7E2840BFF1AE</ID>
+    <Description>Abort only jobs belonging to self.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Delete.Any">
+    <ID>EBD4CF61-CD1B-4d61-BD8A-9CEC2174E50F</ID>
+    <Description>Delete any jobs.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Delete.ProjectOnly">
+    <ID>04C921A6-8F3E-4add-B6F1-E79C5E1C0724</ID>
+    <Description>Delete only jobs belonging to a specific project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Delete.OwnedOnly">
+    <ID>D4F67946-1013-4d84-8B8F-0EA2E9A3E0D4</ID>
+    <Description>Delete only own jobs.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Read.Any">
+    <ID>E9FBDB1B-C532-49ad-AE1E-BDC33576F4E5</ID>
+    <Description>Read/Get any job.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Read.ProjectOnly">
+    <ID>C778C27F-BAA6-4aed-8495-015A0923E0ED</ID>
+    <Description>Read/Get only jobs belonging to a specific project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Jobmanagement.Read.OwnedOnly">
+    <ID>022B7792-8CED-4f40-9B55-5BBB892338B4</ID>
+    <Description>Read/Get only owned jobs.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.PermissionManagement.Permission.Grant">
+    <ID>5A1A98DE-04CE-4316-9BCA-BBE833EC4E74</ID>
+    <Description>Grant a permission.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.PermissionManagement.Permission.Revoke">
+    <ID>50A3A44F-085C-47c2-AB95-DDA90CEE38B0</ID>
+    <Description>Revoke a permission.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.Client.Create">
+    <ID>90A00F60-1AC2-4928-8EC3-D7667E08D849</ID>
+    <Description>Create new client.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.Client.Read">
+    <ID>5B2AF000-920C-4955-BC27-8EA3EAA14EC6</ID>
+    <Description>Read/Get a client.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.Client.Update">
+    <ID>072CC90A-5831-4ff1-8D2E-C1084AB601DB</ID>
+    <Description>Update a client.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.Client.Delete">
+    <ID>EE39299A-D138-4ec8-89FE-55619FC3C35A</ID>
+    <Description>Delete a client.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.ClientGroup.Create">
+    <ID>134AD38F-8875-4e74-A7B9-F3366B440752</ID>
+    <Description>Create/Add a clientgroup.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.ClientGroup.Read">
+    <ID>3A43FA6F-CB4F-48fc-BB5C-631D1F09AFDA</ID>
+    <Description>Read/Get a clientgroup.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.ClientGroup.Update">
+    <ID>46128AD3-C3E9-4605-B537-45CDB8276E44</ID>
+    <Description>Update a clientgroup.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.ClientGroup.Delete">
+    <ID>6F2BB5DE-3AE9-4108-B537-362F311BAD8A</ID>
+    <Description>Update a clientgroup.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.User.Create">
+    <ID>7681347C-A7FF-4895-AE14-8454A7E05FCA</ID>
+    <Description>Create an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.User.Read">
+    <ID>48168F0B-3F76-4e2c-859F-71DDF0B4D4A4</ID>
+    <Description>Get an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.User.Update">
+    <ID>F44FEC19-5CEE-4f24-8B8C-EDE977DBA154</ID>
+    <Description>Update an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.User.Delete">
+    <ID>DA8F0ECB-97C2-485c-81D7-1A20B725EA47</ID>
+    <Description>Delete an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.UserGroup.Create">
+    <ID>D783D5E5-3DE5-465f-B6EF-A2E6BFA153DF</ID>
+    <Description>Create an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.UserGroup.Read">
+    <ID>16006FA7-C5A9-4185-8724-A2722F01A24A</ID>
+    <Description>Get an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.UserGroup.Update">
+    <ID>AA2F764A-A300-4827-B1DE-BE36CE38A546</ID>
+    <Description>Update an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.Usermanagement.UserGroup.Delete">
+    <ID>6A58925D-03C2-410a-A145-1B5BEDA7FB4A</ID>
+    <Description>Delete an user.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.ResourceManagement.Project.Create">
+    <ID>FA6C3DD1-3D51-4ed5-8C78-F52C4682009A</ID>
+    <Description>Create a project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.ResourceManagement.Project.Read">
+    <ID>BA0EBF0A-FD0E-4439-95B2-ADF74EE7D951</ID>
+    <Description>Get a project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.ResourceManagement.Project.Update">
+    <ID>963B74EF-1673-4eb6-969D-C16E6DBA68FA</ID>
+    <Description>Update a project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+  <Permission name ="HivePermissions.ResourceManagement.Project.Delete">
+    <ID>AC78B93B-66F2-42b2-860E-976C825B11B7</ID>
+    <Description>Delete a project.</Description>
+    <Plugin>HeuristicLab.Hive</Plugin>
+  </Permission>
+
+</Permissions>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionSet.xsd
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionSet.xsd	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissionSet.xsd	(revision 4061)
@@ -0,0 +1,19 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <xs:element name="Permissions">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element maxOccurs="unbounded" name="Permission">
+          <xs:complexType>
+            <xs:sequence>
+              <xs:element name="ID" type="xs:string" />
+              <xs:element name="Description" type="xs:string" />
+              <xs:element name="Plugin" type="xs:string" />
+            </xs:sequence>
+            <xs:attribute name="name" type="xs:string" use="required" />
+          </xs:complexType>
+        </xs:element>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+</xs:schema>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissions.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissions.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/HivePermissions.cs	(revision 4061)
@@ -0,0 +1,241 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Xml.XPath;
+using HeuristicLab.Security.Contracts.BusinessObjects;
+using System.Diagnostics;
+using System.Xml;
+using System.IO;
+using System.Reflection;
+
+namespace HeuristicLab.Hive.Server.Core  {
+  
+  public static class HivePermissions {
+    private const string PERMISSIONFILE = @"HivePermissionSet.xml";
+    private const string POLICIESFILE = @"HivePermissionPolicy.xml";
+
+    public static class Jobmanagement {
+      [Flags]
+      public enum Assign {
+        ToAnyResource = 0x02,
+        ToProject = 0x04
+      }
+      [Flags]
+      public enum Abort {
+        /// <summary>Can abort any job.</summary>
+        Any = 0x02,
+        /// <summary>Can abort jobs from specific project only.</summary>
+        ProjectOnly = 0x04,
+        /// <summary>Can abort only owned jobs.</summary>
+        OwnedOnly = 0x08
+      }
+      [Flags]
+      public enum Create {
+        /// <summary>Can create a job everywhere.</summary>
+        Any = 0x02,
+        /// <summary>Can create a job in project context only.</summary>
+        ProjectOnly = 0x04,
+        /// <summary>Can create a job for owned resources only.</summary>
+        OwnedOnly = 0x08
+      }
+      [Flags]
+      public enum Read {
+        /// <summary>Can read any job.</summary>
+        Any = 0x02,
+        /// <summary>Can read a job in project context only.</summary>
+        ProjectOnly = 0x04,
+        /// <summary>Can read only owned job.</summary>
+        OwnedOnly = 0x08
+      }
+      [Flags]
+      public enum Delete {
+        /// <summary>Can delete any job.</summary>
+        Any = 0x02,
+        /// <summary>Can delete a job in project context only.</summary>
+        ProjectOnly = 0x04,
+        /// <summary>Can delete only owned job.</summary>
+        OwnedOnly = 0x08
+      }
+    }
+
+    public static class Usermanagement {
+      [Flags]
+      public enum User {
+        Create = 0x02,
+        Read = 0x04,
+        Update = 0x08,
+        Delete = 0x16
+      }
+
+      [Flags]
+      public enum UserGroup {
+        Create = 0x02,
+        Read = 0x04,
+        Update = 0x08,
+        Delete = 0x16
+      }
+
+      [Flags]
+      public enum Client {
+        Create = 0x02,
+        Read = 0x04,
+        Update = 0x08,
+        Delete = 0x16
+      }
+
+      [Flags]
+      public enum ClientGroup {
+        Create = 0x02,
+        Read = 0x04,
+        Update = 0x08,
+        Delete = 0x16
+      }
+    }
+
+    public static class PermissionManagement {
+      [Flags]
+      public enum Permission {
+        Grant = 0x02,
+        Revoke = 0x04
+      }
+    }
+
+    public static class ResourceManagement {
+      [Flags]
+      public enum Project {
+        Create = 0x02,
+        Read = 0x04,
+        Update = 0x08,
+        Delete = 0x16
+      }
+    }
+
+    private static PermissionCollection pc;
+
+    private static PolicyCollection pol;
+
+    public static PermissionCollection GetPermissions() {
+      if (pc == null) {
+        pc = new PermissionCollection();
+        LoadFromXml(pc.Permissions, PERMISSIONFILE);
+      }
+      return pc;
+    }
+
+    public static PolicyCollection GetPolicies() {
+      if (pol == null) {
+        pol = new PolicyCollection();
+        LoadFromXml(pol.Policies, POLICIESFILE);
+      }
+      return pol;
+    }
+
+    public static string ConvertEnumType(object obj) {
+      string retVal = string.Empty;
+      Type t = obj.GetType();
+      string value = obj.ToString();
+      retVal = (t.FullName.Replace(t.Namespace + ".", "")).Replace("+", ".") + "." + value;
+      return retVal;
+    }
+
+    /// <summary>
+    /// Permission
+    /// </summary>
+    /// <param name="perm"></param>
+    private static void LoadFromXml(IList<Permission> perm, string filename) {
+      Permission p = null;
+      XPathDocument doc;
+      string assemblyName = Assembly.GetAssembly(typeof(HivePermissions)).GetName().Name;
+      doc = new XPathDocument(filename);
+      XPathNavigator nav = doc.CreateNavigator();
+      nav.MoveToRoot();
+      do {
+        if (nav.NodeType == XPathNodeType.Element && nav.Name == "Permission") {
+          p = new Permission();
+          p.Name = nav.GetAttribute("name", "");
+          nav.MoveToFollowing(XPathNodeType.Element);
+          if (nav.Name == "ID")
+            p.Id = new Guid(nav.Value);
+          nav.MoveToFollowing(XPathNodeType.Element);
+          if (nav.Name == "Description")
+            p.Description = nav.Value;
+          nav.MoveToFollowing(XPathNodeType.Element);
+          if (nav.Name == "Plugin")
+            p.Plugin = nav.Value;
+          perm.Add(p);
+        }
+      } while (nav.MoveToFollowing(XPathNodeType.Element));
+    }
+    /*
+    public static XmlDocument GetEmbeddedXml(Type type, string fileName) {
+      Stream str = GetEmbeddedFile(type, fileName);
+      XmlTextReader tr = new XmlTextReader(str);
+      XmlDocument xml = new XmlDocument();
+      xml.Load(tr);
+      return xml;
+    }
+    */
+
+    /// <summary>
+    /// Extracts an embedded file out of a given assembly.
+    /// </summary>
+    /// <param name="assemblyName">The namespace of you assembly.</param>
+    /// <param name="fileName">The name of the file to extract.</param>
+    /// <returns>A stream containing the file data.</returns>
+    public static Stream GetEmbeddedFile(string assemblyName, string fileName) {
+      try {
+        Assembly a = Assembly.Load(assemblyName);
+        Stream str = a.GetManifestResourceStream(assemblyName + "." + fileName);
+
+        if (str == null)
+          throw new Exception("Could not locate embedded resource '" + fileName + "' in assembly '" + assemblyName + "'");
+        return str;
+      }
+      catch (Exception e) {
+        throw new Exception(assemblyName + ": " + e.Message);
+      }
+    }
+
+   
+    /// <summary>
+    /// Policy
+    /// </summary>
+    /// <param name="pol"></param>
+    /// <param name="filename"></param>
+    private static void LoadFromXml(IList<Policy> policyList, string filename) {
+      PermissionCollection permissionCollection = GetPermissions();
+      string assemblyName = Assembly.GetAssembly(typeof(HivePermissions)).GetName().Name;
+      XPathDocument doc = new XPathDocument(filename);
+      XPathNavigator nav = doc.CreateNavigator();
+      nav.MoveToRoot();
+      //receive all policies -> Element <Policy name="xxx">...</Policy>
+      do {
+        if (nav.NodeType == XPathNodeType.Element && nav.Name == "Policy") {
+          string policyName = nav.GetAttribute("name", "");
+          Policy policy = new Policy(policyName);
+          nav.MoveToFollowing(XPathNodeType.Element);
+          //receive all permissions -> Element <Permission.../>
+          do {
+            if (nav.Name == "Permission" && nav.HasAttributes) {
+              PermissionContext ctx = new PermissionContext();
+              int prior = 0;
+              int.TryParse(nav.GetAttribute("priority", ""), out prior);
+              ctx.Priority = prior;
+              ctx.Elevation = nav.GetAttribute("context", "");
+              string permissionName = nav.GetAttribute("name", "");
+              if (!string.IsNullOrEmpty(permissionName)) {
+                Permission permission = permissionCollection[permissionName];
+                Debug.WriteLineIf(permission == null, "Permission '" + permissionName + "' not found in PermissionCollection!");
+                if (permission != null)
+                  policy.AddPermission(permission, ctx);
+              }
+            }
+          } while (nav.MoveToNext());
+          policyList.Add(policy);
+        }
+      } while (nav.MoveToFollowing(XPathNodeType.Element));
+    }
+  }
+  
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionCollection.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionCollection.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionCollection.cs	(revision 4061)
@@ -0,0 +1,56 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Security.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class PermissionCollection : IEnumerable<Permission> {
+    public IList<Permission> perm = new List<Permission>();
+
+    public PermissionCollection() {
+    }
+
+    public IList<Permission> Permissions {
+      get { return perm; }
+    }
+
+    /// <summary>
+    /// Gets the Permission identified by FQN type.
+    /// </summary>
+    /// <param name="permissionName">eg. 'HivePermissions.Jobmanagement.Create.Any'</param>
+    /// <returns></returns>
+    public Permission this[string permissionName] {
+      get {
+        foreach (Permission item in perm) {
+          if (item.Name == permissionName)
+            return item;
+        }
+        return null;
+      }
+    }
+
+    /// <summary>
+    /// Converts an enumeration to a fully qualified string.
+    /// </summary>
+    /// <param name="obj">Any enumeration type.</param>
+    /// <returns>Type Information in Full Qualified Notation (FQN).</returns>
+    public string Convert(object obj) {
+      string retVal = string.Empty;
+      Type t = obj.GetType();
+      string value = obj.ToString();
+      retVal = (t.FullName.Replace(t.Namespace + ".", "")).Replace("+", ".") + "." + value;
+      return retVal;
+    }
+
+    public IEnumerator<Permission> GetEnumerator() {
+      return perm.GetEnumerator();
+    }
+
+    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+      return perm.GetEnumerator();
+    }
+
+  }
+
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionContext.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionContext.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionContext.cs	(revision 4061)
@@ -0,0 +1,24 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace HeuristicLab.Hive.Server.Core {
+  /// <summary>
+  /// Holds additional information about a certain permission.
+  /// </summary>
+  public class PermissionContext {
+    private int _priority;
+    /// <summary>
+    /// Gets or sets the priority of this permission rule.
+    /// </summary>
+    public int Priority { get { return this._priority; } set { this._priority = value; } }
+
+    private string _elevation;
+    /// <summary>
+    /// Gets or sets the Rights Elevation Information. (Primary Policy Context)
+    /// </summary>
+    public string Elevation { get { return this._elevation; } set { this._elevation = value; } }
+
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionException.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionException.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PermissionException.cs	(revision 4061)
@@ -0,0 +1,17 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.ServiceModel;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class PermissionException : FaultException {
+    public PermissionException()
+      : base("Current user has insufficent rights for this action!") {
+    }
+
+    public PermissionException(string msg)
+      : base("Current user has insufficent rights for this action: " + msg) {
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/Policy.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/Policy.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/Policy.cs	(revision 4061)
@@ -0,0 +1,32 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Security.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class Policy {
+    private string _name;
+    public string Name { get { return _name; } set { this._name = value; } }
+
+    private IDictionary<Permission, PermissionContext> _permissions = new Dictionary<Permission, PermissionContext>();
+    public IDictionary<Permission, PermissionContext> Permissions { get { return this._permissions; } set { this._permissions = value; } }
+
+    public Policy(string name) {
+      this._name = name;
+    }
+
+    public void AddPermission(Permission permission, PermissionContext ctx) {
+      this._permissions.Add(permission, ctx);
+    }
+
+    public Permission GetPermissionByContext(string context) {
+      foreach (KeyValuePair<Permission, PermissionContext> item in _permissions) {
+        if (item.Value.Elevation == context)
+          return item.Key;
+      }
+      return null;
+    }
+
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PolicyCollection.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PolicyCollection.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Authorization/PolicyCollection.cs	(revision 4061)
@@ -0,0 +1,36 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Collections;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class PolicyCollection : IEnumerable<Policy> {
+    private IList<Policy> _policies = new List<Policy>();
+
+    public IList<Policy> Policies { get { return this._policies; } }
+
+    public Policy this[string name] {
+      get {
+        foreach (Policy item in _policies) {
+          if (item.Name == name)
+            return item;
+        }
+        return null;
+      }
+    }
+
+    public IEnumerator<Policy> GetEnumerator() {
+      return this._policies.GetEnumerator();
+    }
+
+    #region IEnumerable Members
+
+    IEnumerator IEnumerable.GetEnumerator()
+    {
+        return this._policies.GetEnumerator();
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientCommunicator.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientCommunicator.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientCommunicator.cs	(revision 4061)
@@ -0,0 +1,747 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Core;
+using HeuristicLab.Hive.Server.DataAccess;
+using System.Resources;
+using System.Reflection;
+using HeuristicLab.Hive.JobBase;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+using System.Threading;
+using HeuristicLab.PluginInfrastructure;
+using HeuristicLab.DataAccess.Interfaces;
+using System.IO;
+using System.Runtime.Serialization.Formatters.Binary;
+using HeuristicLab.Tracing;
+using Linq = HeuristicLab.Hive.Server.LINQDataAccess;
+using System.Transactions;
+using HeuristicLab.Hive.Server.LINQDataAccess;
+
+namespace HeuristicLab.Hive.Server.Core {
+  /// <summary>
+  /// The ClientCommunicator manages the whole communication with the client
+  /// </summary>
+  public class ClientCommunicator : IClientCommunicator,
+    IInternalClientCommunicator {
+    private static Dictionary<Guid, DateTime> lastHeartbeats =
+      new Dictionary<Guid, DateTime>();
+    private static Dictionary<Guid, int> newAssignedJobs =
+      new Dictionary<Guid, int>();
+    private static Dictionary<Guid, int> pendingJobs =
+      new Dictionary<Guid, int>();
+
+    private static ReaderWriterLockSlim heartbeatLock =
+      new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
+
+    //private ISessionFactory factory;
+    private ILifecycleManager lifecycleManager;
+    private IInternalJobManager jobManager;
+    private IScheduler scheduler;
+
+    private static int PENDING_TIMEOUT = 100;
+
+    /// <summary>
+    /// Initialization of the Adapters to the database
+    /// Initialization of Eventhandler for the lifecycle management
+    /// Initialization of lastHearbeats Dictionary
+    /// </summary>
+    public ClientCommunicator() {
+      //factory = ServiceLocator.GetSessionFactory();
+
+      lifecycleManager = ServiceLocator.GetLifecycleManager();
+      jobManager = ServiceLocator.GetJobManager() as
+        IInternalJobManager;
+      scheduler = ServiceLocator.GetScheduler();
+
+      lifecycleManager.RegisterHeartbeat(
+        new EventHandler(lifecycleManager_OnServerHeartbeat));
+    }
+
+    /// <summary>
+    /// Check if online clients send their hearbeats
+    /// if not -> set them offline and check if they where calculating a job
+    /// </summary>
+    /// <param name="sender"></param>
+    /// <param name="e"></param>
+    void lifecycleManager_OnServerHeartbeat(object sender, EventArgs e) {
+      Logger.Debug("Server Heartbeat ticked");
+
+      using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = ApplicationConstants.ISOLATION_LEVEL_SCOPE })) {
+
+        List<ClientDto> allClients = new List<ClientDto>(DaoLocator.ClientDao.FindAll());
+
+        foreach (ClientDto client in allClients) {
+          if (client.State != State.offline && client.State != State.nullState) {
+            heartbeatLock.EnterUpgradeableReadLock();
+
+            if (!lastHeartbeats.ContainsKey(client.Id)) {
+              Logger.Info("Client " + client.Id +
+                              " wasn't offline but hasn't sent heartbeats - setting offline");
+              client.State = State.offline;
+              DaoLocator.ClientDao.Update(client);
+              Logger.Info("Client " + client.Id +
+                              " wasn't offline but hasn't sent heartbeats - Resetting all his jobs");
+              foreach (JobDto job in DaoLocator.JobDao.FindActiveJobsOfClient(client)) {
+                //maybe implementa n additional Watchdog? Till then, just set them offline..
+                DaoLocator.JobDao.SetJobOffline(job);                                
+              }
+            } else {
+              DateTime lastHbOfClient = lastHeartbeats[client.Id];
+
+              TimeSpan dif = DateTime.Now.Subtract(lastHbOfClient);
+              // check if time between last hearbeat and now is greather than HEARTBEAT_MAX_DIF
+              if (dif.TotalSeconds > ApplicationConstants.HEARTBEAT_MAX_DIF) {
+                // if client calculated jobs, the job must be reset
+                Logger.Info("Client timed out and is on RESET");
+                foreach (JobDto job in DaoLocator.JobDao.FindActiveJobsOfClient(client)) {
+                  DaoLocator.JobDao.SetJobOffline(job);
+                  lock (newAssignedJobs) {
+                    if (newAssignedJobs.ContainsKey(job.Id))
+                      newAssignedJobs.Remove(job.Id);
+                  }
+                }
+                Logger.Debug("setting client offline");
+                // client must be set offline
+                client.State = State.offline;
+
+                //clientAdapter.Update(client);
+                DaoLocator.ClientDao.Update(client);
+
+                Logger.Debug("removing it from the heartbeats list");
+                heartbeatLock.EnterWriteLock();
+                lastHeartbeats.Remove(client.Id);
+                heartbeatLock.ExitWriteLock();
+              }
+            }
+
+            heartbeatLock.ExitUpgradeableReadLock();
+          } else {
+            //TODO: RLY neccesary?
+            //HiveLogger.Info(this.ToString() + ": Client " + client.Id + " has wrong state: Shouldn't have offline or nullstate, has " + client.State);
+            heartbeatLock.EnterWriteLock();
+            //HiveLogger.Info(this.ToString() + ": Client " + client.Id + " has wrong state: Resetting all his jobs");
+            if (lastHeartbeats.ContainsKey(client.Id))
+              lastHeartbeats.Remove(client.Id);
+            foreach (JobDto job in DaoLocator.JobDao.FindActiveJobsOfClient(client)) {
+              DaoLocator.JobDao.SetJobOffline(job);
+            }
+            heartbeatLock.ExitWriteLock();
+          }
+        }
+        CheckForPendingJobs();
+        DaoLocator.DestroyContext();
+        scope.Complete();
+      }
+    }
+
+    private void CheckForPendingJobs() {
+      IList<JobDto> pendingJobsInDB = new List<JobDto>(DaoLocator.JobDao.GetJobsByState(State.pending));
+
+      foreach (JobDto currJob in pendingJobsInDB) {
+        lock (pendingJobs) {
+          if (pendingJobs.ContainsKey(currJob.Id)) {
+            if (pendingJobs[currJob.Id] <= 0) {
+              currJob.State = State.offline;
+              DaoLocator.JobDao.Update(currJob);              
+            } else {
+              pendingJobs[currJob.Id]--;
+            }
+          }
+        }
+      }
+    }
+
+    #region IClientCommunicator Members
+
+    /// <summary>
+    /// Login process for the client
+    /// A hearbeat entry is created as well (login is the first hearbeat)
+    /// </summary>
+    /// <param name="clientInfo"></param>
+    /// <returns></returns>
+    public Response Login(ClientDto clientInfo) {
+      Response response = new Response();
+
+      heartbeatLock.EnterWriteLock();
+      if (lastHeartbeats.ContainsKey(clientInfo.Id)) {
+        lastHeartbeats[clientInfo.Id] = DateTime.Now;
+      } else {
+        lastHeartbeats.Add(clientInfo.Id, DateTime.Now);
+      }
+      heartbeatLock.ExitWriteLock();
+
+      ClientDto dbClient = DaoLocator.ClientDao.FindById(clientInfo.Id);
+
+      //Really set offline? 
+      //Reconnect issues with the currently calculating jobs
+      clientInfo.State = State.idle;
+      clientInfo.CalendarSyncStatus = dbClient != null ? dbClient.CalendarSyncStatus : CalendarState.NotAllowedToFetch;
+
+      if (dbClient == null)
+        DaoLocator.ClientDao.Insert(clientInfo);
+      else
+        DaoLocator.ClientDao.Update(clientInfo);
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGIN_SUCCESS;
+      return response;
+    }
+
+    public ResponseCalendar GetCalendar(Guid clientId) {
+      ResponseCalendar response = new ResponseCalendar();
+
+      ClientDto client = DaoLocator.ClientDao.FindById(clientId);
+      if(client == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_RESOURCE_NOT_FOUND;
+        return response;
+      }
+      
+      response.ForceFetch = (client.CalendarSyncStatus == CalendarState.ForceFetch);
+      
+      IEnumerable<AppointmentDto> appointments = DaoLocator.UptimeCalendarDao.GetCalendarForClient(client);
+      if (appointments.Count() == 0) {
+        response.StatusMessage = ApplicationConstants.RESPONSE_UPTIMECALENDAR_NO_CALENDAR_FOUND;
+        response.Success = false;
+      } else {
+        response.Success = true;
+        response.Appointments = appointments;
+      }
+
+      client.CalendarSyncStatus = CalendarState.Fetched;
+      DaoLocator.ClientDao.Update(client);
+      return response;
+    }
+
+    public Response SetCalendarStatus(Guid clientId, CalendarState state) {
+      Response response = new Response();      
+      ClientDto client = DaoLocator.ClientDao.FindById(clientId);
+      if (client == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_RESOURCE_NOT_FOUND;
+        return response;
+      }
+      
+      client.CalendarSyncStatus = state;
+      DaoLocator.ClientDao.Update(client);
+      
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_UPTIMECALENDAR_STATUS_UPDATED;
+      
+      return response;
+    }
+
+    /// <summary>
+    /// The client has to send regulary heartbeats
+    /// this hearbeats will be stored in the heartbeats dictionary
+    /// check if there is work for the client and send the client a response if he should pull a job
+    /// </summary>
+    /// <param name="hbData"></param>
+    /// <returns></returns>
+    public ResponseHB ProcessHeartBeat(HeartBeatData hbData) {
+      Logger.Debug("BEGIN Processing Heartbeat for Client " + hbData.ClientId);
+
+      ResponseHB response = new ResponseHB();
+      response.ActionRequest = new List<MessageContainer>();
+
+      Logger.Debug("BEGIN Started Client Fetching");
+      ClientDto client = DaoLocator.ClientDao.FindById(hbData.ClientId);
+      Logger.Debug("END Finished Client Fetching");
+      // check if the client is logged in
+      if (client.State == State.offline || client.State == State.nullState) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_USER_NOT_LOGGED_IN;
+        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.NoMessage));
+
+        Logger.Error("ProcessHeartBeat: Client state null or offline: " + client);
+
+        return response;
+      }
+
+      client.NrOfFreeCores = hbData.FreeCores;
+      client.FreeMemory = hbData.FreeMemory;
+
+      // save timestamp of this heartbeat
+      Logger.Debug("BEGIN Locking for Heartbeats");
+      heartbeatLock.EnterWriteLock();
+      Logger.Debug("END Locked for Heartbeats");
+      if (lastHeartbeats.ContainsKey(hbData.ClientId)) {
+        lastHeartbeats[hbData.ClientId] = DateTime.Now;
+      } else {
+        lastHeartbeats.Add(hbData.ClientId, DateTime.Now);
+      }
+      heartbeatLock.ExitWriteLock();
+
+      Logger.Debug("BEGIN Processing Heartbeat Jobs");
+      processJobProcess(hbData, response);
+      Logger.Debug("END Processed Heartbeat Jobs");
+
+      //check if new Cal must be loaded
+      if (client.CalendarSyncStatus == CalendarState.Fetch || client.CalendarSyncStatus == CalendarState.ForceFetch) {
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_FETCH_OR_FORCEFETCH_CALENDAR;
+        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.FetchOrForceFetchCalendar));
+        
+        //client.CalendarSyncStatus = CalendarState.Fetching;
+        
+        Logger.Info("fetch or forcefetch sent");        
+      }
+
+      // check if client has a free core for a new job
+      // if true, ask scheduler for a new job for this client
+      Logger.Debug(" BEGIN Looking for Client Jobs");
+      if (hbData.FreeCores > 0 && scheduler.ExistsJobForClient(hbData)) {
+        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.FetchJob));
+      } else {
+        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.NoMessage));
+      }
+      Logger.Debug(" END Looked for Client Jobs");
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_HEARTBEAT_RECEIVED;
+
+      DaoLocator.ClientDao.Update(client);
+
+      //tx.Commit();
+      Logger.Debug(" END Processed Heartbeat for Client " + hbData.ClientId);
+      return response;
+    }
+
+    /// <summary>
+    /// Process the Job progress sent by a client
+    /// </summary>
+    /// <param name="hbData"></param>
+    /// <param name="jobAdapter"></param>
+    /// <param name="clientAdapter"></param>
+    /// <param name="response"></param>
+    private void processJobProcess(HeartBeatData hbData, ResponseHB response) {
+      Logger.Debug("Started for Client " + hbData.ClientId);
+      List<JobDto> jobsOfClient = new List<JobDto>(DaoLocator.JobDao.FindActiveJobsOfClient(DaoLocator.ClientDao.FindById(hbData.ClientId)));
+      if (hbData.JobProgress != null && hbData.JobProgress.Count > 0) {        
+        if (jobsOfClient == null || jobsOfClient.Count == 0) {
+          response.Success = false;
+          response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_IS_NOT_BEEING_CALCULATED;
+          Logger.Error("There is no job calculated by this user " + hbData.ClientId);
+          return;
+        }
+
+        foreach (KeyValuePair<Guid, double> jobProgress in hbData.JobProgress) {
+          JobDto curJob = DaoLocator.JobDao.FindById(jobProgress.Key);
+          curJob.Client = DaoLocator.ClientDao.GetClientForJob(curJob.Id);
+          if (curJob.Client == null || curJob.Client.Id != hbData.ClientId) {
+            response.Success = false;
+            response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_IS_NOT_BEEING_CALCULATED;
+            Logger.Error("There is no job calculated by this user " + hbData.ClientId + " Job: " + curJob);
+          } else if (curJob.State == State.abort) {
+            // a request to abort the job has been set
+            response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.AbortJob, curJob.Id));
+            curJob.State = State.finished;
+          } else {
+            // save job progress
+            curJob.Percentage = jobProgress.Value;
+
+            if (curJob.State == State.requestSnapshot) {
+              // a request for a snapshot has been set
+              response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.RequestSnapshot, curJob.Id));
+              curJob.State = State.requestSnapshotSent;
+            }
+          }
+          DaoLocator.JobDao.Update(curJob);
+        }
+       }
+      foreach (JobDto currJob in jobsOfClient) {
+        bool found = false;
+        if(hbData.JobProgress != null) {
+          foreach (Guid jobId in hbData.JobProgress.Keys) {
+            if (jobId == currJob.Id) {
+              found = true;
+              break;
+            }
+          }
+        }
+        if (!found) {
+          lock (newAssignedJobs) {
+            if (newAssignedJobs.ContainsKey(currJob.Id)) {
+              newAssignedJobs[currJob.Id]--;
+              Logger.Error("Job TTL Reduced by one for job: " + currJob + "and is now: " + newAssignedJobs[currJob.Id] + ". User that sucks: " + currJob.Client);
+              if (newAssignedJobs[currJob.Id] <= 0) {
+                Logger.Error("Job TTL reached Zero, Job gets removed: " + currJob + " and set back to offline. User that sucks: " + currJob.Client);
+
+                currJob.State = State.offline;
+                DaoLocator.JobDao.Update(currJob);
+
+                response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.AbortJob, currJob.Id));
+
+                newAssignedJobs.Remove(currJob.Id);
+              }
+            } else {
+              Logger.Error("Job ID wasn't with the heartbeats:  " + currJob);
+              currJob.State = State.offline;
+              DaoLocator.JobDao.Update(currJob);
+            }
+          } // lock
+        } else {
+          lock (newAssignedJobs) {
+
+            if (newAssignedJobs.ContainsKey(currJob.Id)) {
+              Logger.Info("Job is sending a heart beat, removing it from the newAssignedJobList: " + currJob);
+              newAssignedJobs.Remove(currJob.Id);
+            }
+          }
+        }
+      }
+    }
+
+    /// <summary>
+    /// if the client was told to pull a job he calls this method
+    /// the server selects a job and sends it to the client
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>
+    public ResponseJob SendJob(Guid clientId) {
+
+      ResponseJob response = new ResponseJob();
+
+      JobDto job2Calculate = scheduler.GetNextJobForClient(clientId);
+      if (job2Calculate != null) {
+        response.Job = job2Calculate;        
+        response.Job.PluginsNeeded = DaoLocator.PluginInfoDao.GetPluginDependenciesForJob(response.Job);
+        response.Success = true;
+        Logger.Info("Job pulled: " + job2Calculate + " for user " + clientId);
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_PULLED;
+        lock (newAssignedJobs) {
+          if (!newAssignedJobs.ContainsKey(job2Calculate.Id))
+            newAssignedJobs.Add(job2Calculate.Id, ApplicationConstants.JOB_TIME_TO_LIVE);
+        }
+      } else {                  
+        response.Success = false;
+        response.Job = null;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOBS_LEFT;
+        Logger.Info("No more Jobs left for " + clientId);
+      }
+
+
+
+      return response;
+    }
+
+    public ResponseResultReceived ProcessJobResult(
+      Stream stream,
+      bool finished) {
+
+      Logger.Info("BEGIN Job received for Storage - main method:");
+
+
+      Stream jobResultStream = null;
+      Stream jobStream = null;
+
+      //try {
+      BinaryFormatter formatter =
+        new BinaryFormatter();
+
+      JobResult result =
+        (JobResult)formatter.Deserialize(stream);
+
+      //important - repeatable read isolation level is required here, 
+      //otherwise race conditions could occur when writing the stream into the DB
+      //just removed TransactionIsolationLevel.RepeatableRead
+      //tx = session.BeginTransaction();
+
+      ResponseResultReceived response =
+        ProcessJobResult(
+        result.ClientId,
+        result.JobId,
+        new byte[] { },
+        result.Percentage,
+        result.Exception,
+        finished);
+
+      if (response.Success) {
+        Logger.Debug("Trying to aquire WCF Job Stream");
+        //jobStream = DaoLocator.JobDao.GetSerializedJobStream(result.JobId);
+        //Logger.Debug("Job Stream Aquired");
+        byte[] buffer = new byte[3024];
+        List<byte> serializedJob = new List<byte>();
+        int read = 0;
+        int i = 0;        
+        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) {          
+          for (int j = 0; j < read; j++) {
+            serializedJob.Add(buffer[j]);
+          }
+          if (i% 100 == 0)
+            Logger.Debug("Writing to stream: " + i);         
+          //jobStream.Write(buffer, 0, read);
+          i++;
+        }
+        Logger.Debug("Done Writing, closing the stream!");               
+        //jobStream.Close();
+
+        DaoLocator.JobDao.SetBinaryJobFile(result.JobId, serializedJob.ToArray());
+      }
+      Logger.Info("END Job received for Storage:");
+      stream.Dispose();
+      return response;
+    }
+
+
+    private ResponseResultReceived ProcessJobResult(Guid clientId,
+      Guid jobId,
+      byte[] result,
+      double percentage,
+      Exception exception,
+      bool finished) {
+
+      Logger.Info("BEGIN Job received for Storage - SUB method: " + jobId);
+
+      ResponseResultReceived response = new ResponseResultReceived();
+      ClientDto client =
+        DaoLocator.ClientDao.FindById(clientId);
+
+      SerializedJob job =
+        new SerializedJob();
+
+      if (job != null) {
+        job.JobInfo =
+          DaoLocator.JobDao.FindById(jobId);
+        job.JobInfo.Client = job.JobInfo.Client = DaoLocator.ClientDao.GetClientForJob(jobId);
+      }
+
+      if (job == null && job.JobInfo != null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOB_WITH_THIS_ID;
+        response.JobId = jobId;
+
+        Logger.Error("No job with Id " + jobId);
+
+        //tx.Rollback();
+        return response;
+      }
+      if (job.JobInfo.State == State.abort) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_WAS_ABORTED;
+
+        Logger.Error("Job was aborted! " + job.JobInfo);
+
+        //tx.Rollback();
+        return response;
+      }
+      if (job.JobInfo.Client == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_IS_NOT_BEEING_CALCULATED;
+        response.JobId = jobId;
+
+        Logger.Error("Job is not being calculated (client = null)! " + job.JobInfo);
+
+        //tx.Rollback();
+        return response;
+      }
+      if (job.JobInfo.Client.Id != clientId) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_WRONG_CLIENT_FOR_JOB;
+        response.JobId = jobId;
+
+        Logger.Error("Wrong Client for this Job! " + job.JobInfo + ", Sending Client is: " + clientId);
+
+        //tx.Rollback();
+        return response;
+      }
+      if (job.JobInfo.State == State.finished) {
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOBRESULT_RECEIVED;
+        response.JobId = jobId;
+
+        Logger.Error("Job already finished! " + job.JobInfo + ", Sending Client is: " + clientId);
+
+        //tx.Rollback();
+        return response;
+      }
+      //Todo: RequestsnapshotSent => calculating?
+      if (job.JobInfo.State == State.requestSnapshotSent) {
+        job.JobInfo.State = State.calculating;
+      }
+      if (job.JobInfo.State != State.calculating &&
+        job.JobInfo.State != State.pending) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_WRONG_JOB_STATE;
+        response.JobId = jobId;
+
+        Logger.Error("Wrong Job State, job is: " + job.JobInfo);
+
+        //tx.Rollback();
+        return response;
+      }
+      job.JobInfo.Percentage = percentage;
+
+      if (finished) {
+        job.JobInfo.State = State.finished;
+        job.JobInfo.DateFinished = DateTime.Now;
+      }
+
+      job.SerializedJobData = result;
+
+      DaoLocator.JobDao.Update(job.JobInfo);
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOBRESULT_RECEIVED;
+      response.JobId = jobId;
+      response.finished = finished;
+
+      Logger.Info("END Job received for Storage - SUB method: " + jobId);
+      return response;
+
+    }
+
+
+    /// <summary>
+    /// the client can send job results during calculating 
+    /// and will send a final job result when he finished calculating
+    /// these job results will be stored in the database
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <param name="jobId"></param>
+    /// <param name="result"></param>
+    /// <param name="exception"></param>
+    /// <param name="finished"></param>
+    /// <returns></returns>
+    public ResponseResultReceived StoreFinishedJobResult(Guid clientId,
+      Guid jobId,
+      byte[] result,
+      double percentage,
+      Exception exception) {
+
+      return ProcessJobResult(clientId, jobId, result, percentage, exception, true);
+    }
+
+
+    public ResponseResultReceived ProcessSnapshot(Guid clientId, Guid jobId, byte[] result, double percentage, Exception exception) {
+      return ProcessJobResult(clientId, jobId, result, percentage, exception, false);
+    }
+
+    /// <summary>
+    /// when a client logs out the state will be set
+    /// and the entry in the last hearbeats dictionary will be removed
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>                       
+    public Response Logout(Guid clientId) {
+
+      Logger.Info("Client logged out " + clientId);
+      
+      Response response = new Response();
+
+      heartbeatLock.EnterWriteLock();
+      if (lastHeartbeats.ContainsKey(clientId))
+        lastHeartbeats.Remove(clientId);
+      heartbeatLock.ExitWriteLock();
+
+      ClientDto client = DaoLocator.ClientDao.FindById(clientId);
+      if (client == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGOUT_CLIENT_NOT_REGISTERED;
+        return response;
+      }
+      if (client.State == State.calculating) {
+        // check wich job the client was calculating and reset it
+        IEnumerable<JobDto> jobsOfClient = DaoLocator.JobDao.FindActiveJobsOfClient(client);
+        foreach (JobDto job in jobsOfClient) {
+          if (job.State != State.finished)
+            DaoLocator.JobDao.SetJobOffline(job);
+        }
+      }
+
+      client.State = State.offline;
+      DaoLocator.ClientDao.Update(client);
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGOUT_SUCCESS;
+
+      return response;
+    } 
+
+    /// <summary>
+    /// If a client goes offline and restores a job he was calculating 
+    /// he can ask the client if he still needs the job result
+    /// </summary>
+    /// <param name="jobId"></param>
+    /// <returns></returns>
+    public Response IsJobStillNeeded(Guid jobId) {
+      Response response = new Response();
+      JobDto job = DaoLocator.JobDao.FindById(jobId);
+      if (job == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_DOESNT_EXIST;
+        Logger.Error("Job doesn't exist (anymore)! " + jobId);
+        return response;
+      }
+      if (job.State == State.finished) {
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_ALLREADY_FINISHED;
+        Logger.Error("already finished! " + job);
+        return response;
+      }
+      job.State = State.pending;
+      lock (pendingJobs) {
+        pendingJobs.Add(job.Id, PENDING_TIMEOUT);
+      }
+
+      DaoLocator.JobDao.Update(job);
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_SEND_JOBRESULT;
+      return response;
+    }
+
+    public ResponsePlugin SendPlugins(List<HivePluginInfoDto> pluginList) {
+      ResponsePlugin response = new ResponsePlugin();
+      foreach (HivePluginInfoDto pluginInfo in pluginList) {
+        // TODO: BuildDate deleted, not needed???
+        // TODO: Split version to major, minor and revision number
+        foreach (IPluginDescription currPlugin in ApplicationManager.Manager.Plugins) {
+          if (currPlugin.Name == pluginInfo.Name) {
+
+            CachedHivePluginInfoDto currCachedPlugin = new CachedHivePluginInfoDto {
+              Name = currPlugin.Name,
+              Version = currPlugin.Version,
+              BuildDate = currPlugin.BuildDate
+            };
+
+            foreach (string fileName in from file in currPlugin.Files select file.Name) {
+              currCachedPlugin.PluginFiles.Add(new HivePluginFile(File.ReadAllBytes(fileName), fileName));
+            }
+            response.Plugins.Add(currCachedPlugin);
+          }
+        }
+      }
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_PLUGINS_SENT;
+
+      return response;
+
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientFacade.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientFacade.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientFacade.cs	(revision 4061)
@@ -0,0 +1,154 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.PluginInfrastructure;
+using System.IO;
+using System.Runtime.Serialization.Formatters.Binary;
+using System.ServiceModel;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+using System.Transactions;
+
+namespace HeuristicLab.Hive.Server.Core {
+  [ServiceBehavior(InstanceContextMode =
+    InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
+  public class ClientFacade: IClientFacade {
+
+    public ClientFacade() {      
+    }
+
+    private IClientCommunicator clientCommunicator =
+      ServiceLocator.GetClientCommunicator();
+
+    #region IClientCommunicator Members
+
+    public Response Login(ClientDto clientInfo) {
+      return clientCommunicator.Login(clientInfo);
+    }
+
+    public ResponseHB ProcessHeartBeat(HeartBeatData hbData) {
+      return clientCommunicator.ProcessHeartBeat(hbData);
+    }
+
+
+    public ResponseJob SendJob(Guid clientId) {
+      return clientCommunicator.SendJob(clientId);
+    }
+
+    /*public ResponseSerializedJob SendSerializedJob(Guid clientId) {
+      return clientCommunicator.SendSerializedJob(clientId);
+    } */
+
+    public ResponseResultReceived StoreFinishedJobResult(Guid clientId,
+      Guid jobId,
+      byte[] result,
+      double percentage, 
+      Exception exception) {
+      return clientCommunicator.StoreFinishedJobResult(clientId, jobId, result, percentage, exception);
+    }
+
+    public Response Logout(Guid clientId) {
+      return clientCommunicator.Logout(clientId);
+    }
+
+    public Response IsJobStillNeeded(Guid jobId) {
+      return clientCommunicator.IsJobStillNeeded(jobId);
+    }
+
+    public ResponsePlugin SendPlugins(List<HivePluginInfoDto> pluginList) {
+      return clientCommunicator.SendPlugins(pluginList);
+    }
+
+    public ResponseResultReceived ProcessSnapshot(Guid clientId, Guid jobId, byte[] result, double percentage, Exception exception) {
+      return clientCommunicator.ProcessSnapshot(clientId, jobId, result, percentage, exception);
+    }
+
+
+    public ResponseCalendar GetCalendar(Guid clientId) {
+      return clientCommunicator.GetCalendar(clientId);
+    }
+
+    public Response SetCalendarStatus(Guid clientId, CalendarState state) {
+      return clientCommunicator.SetCalendarStatus(clientId, state);      
+    }
+    #endregion
+
+    #region IClientFacade Members
+
+    [SpringTransaction(UserTransaction = true)]
+    public Stream SendStreamedJob(Guid clientId) {
+      MultiStream stream =
+        new MultiStream();
+
+      ResponseJob job = null;
+
+      job = this.SendJob(clientId);      
+
+      //first send response
+      stream.AddStream(
+        new StreamedObject<ResponseJob>(job));
+
+      IJobManager jobManager = 
+        ServiceLocator.GetJobManager();
+      IInternalJobManager internalJobManager = (IInternalJobManager) jobManager;
+      
+      //second stream the job binary data
+      MemoryStream memoryStream = new MemoryStream();      
+      if(job.Job != null)
+        stream.AddStream(new MemoryStream(internalJobManager.GetSerializedJobDataById(job.Job.Id)));
+      
+      OperationContext clientContext = OperationContext.Current;
+        clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args) {
+          if (stream != null) {
+            stream.Dispose();
+          }
+        });
+
+      return stream;
+    }
+
+    public Stream SendStreamedPlugins(List<HivePluginInfoDto> pluginList) {
+      return
+        new StreamedObject<ResponsePlugin>(
+          this.SendPlugins(pluginList));
+    }
+
+    public ResponseResultReceived StoreFinishedJobResultStreamed(Stream stream) {
+      return ((IInternalClientCommunicator)
+        clientCommunicator).ProcessJobResult(stream, true);
+    } 
+
+    public ResponseResultReceived ProcessSnapshotStreamed(Stream stream) {
+      return ((IInternalClientCommunicator)
+        clientCommunicator).ProcessJobResult(stream, false);
+    }
+
+
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ClientManager.cs	(revision 4061)
@@ -0,0 +1,220 @@
+#region License Information
+
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Hive.Server.DataAccess;
+using HeuristicLab.DataAccess.Interfaces;
+using HeuristicLab.Hive.Server.LINQDataAccess;
+using ClientGroup=HeuristicLab.Hive.Contracts.BusinessObjects.ClientGroupDto;
+
+namespace HeuristicLab.Hive.Server.Core {
+  internal class ClientManager : IClientManager {
+    private List<ClientGroup> clientGroups;
+
+    public ClientManager() {
+      clientGroups = new List<ClientGroup>();
+    }
+
+    #region IClientManager Members
+
+    /// <summary>
+    /// Returns all clients stored in the database
+    /// </summary>
+    /// <returns></returns>
+    public ResponseList<ClientDto> GetAllClients() {
+      ResponseList<ClientDto> response = new ResponseList<ClientDto>();
+
+      response.List = new List<ClientDto>(DaoLocator.ClientDao.FindAll());
+      response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_GET_ALL_CLIENTS;
+      response.Success = true;
+
+      return response;
+    }
+
+    /// <summary>
+    /// returns all client groups stored in the database
+    /// </summary>
+    /// <returns></returns>
+    public ResponseList<ClientGroup> GetAllClientGroups() {
+      ResponseList<ClientGroup> response = new ResponseList<ClientGroup>();
+
+      List<ClientGroup> allClientGroups =
+        new List<ClientGroup>(DaoLocator.ClientGroupDao.FindAllWithSubGroupsAndClients());
+      ClientGroup emptyClientGroup = new ClientGroup();
+      IEnumerable<ClientDto> groupLessClients = DaoLocator.ClientDao.FindAllClientsWithoutGroup();
+      if (groupLessClients != null) {
+        foreach (ClientDto currClient in groupLessClients) {
+          emptyClientGroup.Resources.Add(currClient);
+        }
+      }
+      emptyClientGroup.Id = Guid.Empty;
+      allClientGroups.Add(emptyClientGroup);
+
+      response.List = allClientGroups;
+      response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_GET_ALL_CLIENTGROUPS;
+      response.Success = true;
+
+      return response;
+    }
+
+    public ResponseList<UpTimeStatisticsDto> GetAllUpTimeStatistics() {
+      ResponseList<UpTimeStatisticsDto> response = new ResponseList<UpTimeStatisticsDto>();
+      response.Success = true;
+      return response;
+    }
+
+    /// <summary>
+    /// Add a client group into the database
+    /// </summary>
+    /// <param name="clientGroup"></param>
+    /// <returns></returns>
+    public ResponseObject<ClientGroup> AddClientGroup(ClientGroup clientGroup) {
+      ResponseObject<ClientGroup> response = new ResponseObject<ClientGroup>();
+
+      if (clientGroup.Id != Guid.Empty) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_ID_MUST_NOT_BE_SET;
+      }
+      else {
+        clientGroup = DaoLocator.ClientGroupDao.Insert(clientGroup);
+        //clientGroupAdapter.Update(clientGroup);
+        response.Obj = clientGroup;
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_CLIENTGROUP_ADDED;
+      }
+
+      return response;
+    }
+
+    /// <summary>
+    ///  Add a resource to a group
+    /// </summary>
+    /// <param name="clientGroupId"></param>
+    /// <param name="resource"></param>
+    /// <returns></returns>
+    public Response AddResourceToGroup(Guid clientGroupId, ResourceDto resource) {
+      Response response = new Response();
+
+      ClientGroup clientGroup = DaoLocator.ClientGroupDao.FindById(clientGroupId);
+      if (clientGroup == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_CLIENTGROUP_DOESNT_EXIST;
+        return response;
+      }
+
+      clientGroup.Resources.Add(resource);
+      DaoLocator.ClientGroupDao.AddRessourceToClientGroup(resource.Id, clientGroup.Id);
+
+      //If our resource is in fact a client => set the callendar from the resource as current one.
+      
+      ClientDto dbr = DaoLocator.ClientDao.FindById(resource.Id);
+      if(dbr != null) {
+        DaoLocator.ClientDao.SetServerSideCalendar(dbr, clientGroup.Id);  
+      }
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_RESOURCE_ADDED_TO_GROUP;
+
+      return response;
+    }
+
+    /// <summary>
+    /// Remove a resource from a group
+    /// </summary>
+    /// <param name="clientGroupId"></param>
+    /// <param name="resourceId"></param>
+    /// <returns></returns>
+    public Response DeleteResourceFromGroup(Guid clientGroupId, Guid resourceId) {
+      Response response = new Response();
+
+      ClientGroup clientGroup = DaoLocator.ClientGroupDao.FindById(clientGroupId);
+      if (clientGroup == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_CLIENTGROUP_DOESNT_EXIST;
+        return response;
+      }
+     
+      DaoLocator.ClientGroupDao.RemoveRessourceFromClientGroup(resourceId, clientGroup.Id);
+      
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_RESOURCE_REMOVED;
+      return response;                
+    }
+
+    public ResponseObject<List<ClientGroup>> GetAllGroupsOfResource(Guid resourceId) {
+      ResponseObject<List<ClientGroup>> response = new ResponseObject<List<ClientGroup>>();
+
+      ClientDto client = DaoLocator.ClientDao.FindById(resourceId);
+      if (client != null) {
+        List<ClientGroup> groupsOfClient = new List<ClientGroup>(DaoLocator.ClientGroupDao.MemberOf(client));
+        response.Obj = groupsOfClient;
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_GET_GROUPS_OF_CLIENT;
+      }
+      else {
+        response.Obj = new List<ClientGroup>();
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_RESOURCE_NOT_FOUND;
+      }
+
+      return response;
+    }
+
+    public Response DeleteClientGroup(Guid clientGroupId) {
+      Response response = new Response();
+
+      ClientGroup clientGroup = DaoLocator.ClientGroupDao.FindById(clientGroupId);
+      if (clientGroup == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_CLIENTGROUP_DOESNT_EXIST;
+        return response;
+      }
+
+      DaoLocator.ClientGroupDao.Delete(clientGroup);
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_CLIENT_CLIENTGROUP_DELETED;
+      return response;
+    }
+
+    public ResponseList<AppointmentDto> GetUptimeCalendarForResource(Guid guid) {
+      ResponseList<AppointmentDto> response = new ResponseList<AppointmentDto>();
+      response.List = new List<AppointmentDto>(DaoLocator.UptimeCalendarDao.GetUptimeCalendarForResource(guid));
+      response.Success = true;
+      return response;
+    }
+
+    public Response SetUptimeCalendarForResource(Guid guid, IEnumerable<AppointmentDto> appointments, bool isForced) {
+      DaoLocator.UptimeCalendarDao.SetUptimeCalendarForResource(guid, appointments);
+      DaoLocator.UptimeCalendarDao.NotifyClientsOfNewCalendar(guid, isForced);
+      return new Response {Success = true};
+    }
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DaoLocator.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DaoLocator.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DaoLocator.cs	(revision 4061)
@@ -0,0 +1,73 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Text;
+using HeuristicLab.Hive.Server.DataAccess;
+using HeuristicLab.Hive.Server.LINQDataAccess;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class DaoLocator {
+    
+    [ThreadStatic] private static IClientDao clientDao;
+    [ThreadStatic] private static IClientConfigDao clientConfigDao;
+    [ThreadStatic] private static IClientGroupDao clientGroupDao;
+    [ThreadStatic] private static IJobDao jobDao;
+    [ThreadStatic] private static IPluginInfoDao pluginInfoDao;
+    [ThreadStatic] private static IUptimeCalendarDao uptimeCalendarDao;
+
+    public static IClientDao ClientDao {
+      get {
+        if (clientDao == null)
+          clientDao = new ClientDao();
+        return clientDao;
+      }
+    }
+
+    public static IClientConfigDao ClientConfigDao {
+      get {
+        if(clientConfigDao == null)
+          clientConfigDao = new ClientConfigDao();
+        return clientConfigDao;
+      }
+    }
+
+    public static IClientGroupDao ClientGroupDao {
+      get {
+        if(clientGroupDao == null)
+          clientGroupDao = new ClientGroupDao();
+        return clientGroupDao;
+      }
+    }
+
+    public static IJobDao JobDao {
+      get {
+        if(jobDao == null)
+          jobDao = new JobDao();
+        return jobDao;
+      }
+    }
+
+    public static IPluginInfoDao PluginInfoDao {
+      get {
+        if(pluginInfoDao == null)
+          pluginInfoDao = new PluginInfoDao();
+        return pluginInfoDao;
+      }
+    }
+
+    public static IUptimeCalendarDao UptimeCalendarDao {
+      get {
+        if (uptimeCalendarDao == null)
+          uptimeCalendarDao = new UptimeCalendarDao();
+        return uptimeCalendarDao;
+      }
+    }
+
+    public static void DestroyContext() {
+      if (ContextFactory.Context != null) {
+        ContextFactory.Context.Dispose();
+        ContextFactory.Context = null;
+      }
+    }
+
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DbTestApp.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DbTestApp.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DbTestApp.cs	(revision 4061)
@@ -0,0 +1,372 @@
+﻿#region License Information
+
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Data.SqlClient;
+using System.Text;
+using HeuristicLab.PluginInfrastructure;
+using System.Net;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Server.DataAccess;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using System.Diagnostics;
+using HeuristicLab.DataAccess.Interfaces;
+using System.IO;
+using HeuristicLab.Hive.Server.Core;
+using HeuristicLab.Core;
+using HeuristicLab.Hive.Server.LINQDataAccess;
+using System.Transactions;
+using System.Threading;
+using HeuristicLab.Tracing;
+
+namespace HeuristicLab.Hive.Server {
+  [Application("Hive DB Test App", "Test Application for the Hive DataAccess Layer")]
+  internal class HiveDbTestApplication : ApplicationBase {
+    /*private void TestJobStreaming() {
+      ISessionFactory factory =
+         ServiceLocator.GetSessionFactory();
+
+      ISession session =
+           factory.GetSessionForCurrentThread();
+
+      IJobAdapter jobAdapter =
+        session.GetDataAdapter<HeuristicLab.Hive.Contracts.BusinessObjects.JobDto, IJobAdapter>();
+
+      Stream s = jobAdapter.GetSerializedJobStream(
+        new Guid("1b35f32b-d880-4c76-86af-4b4e283b30e6"), true);
+
+      int length = 0;
+
+      FileStream fs =
+        new FileStream(@"W:\\result.gz", FileMode.Create);
+
+      byte[] buffer = new byte[1024];
+      while ((length = s.Read(buffer, 0, buffer.Length)) > 0) {
+        fs.Write(buffer, 0, length);
+      }
+
+      fs.Close();
+      s.Close();
+
+      session.EndSession();
+    }
+
+    private void TestJobResultStreaming() {
+      ISessionFactory factory =
+         ServiceLocator.GetSessionFactory();
+
+      ISession session =
+           factory.GetSessionForCurrentThread();
+
+      IJobResultsAdapter jobResultsAdapter =
+        session.GetDataAdapter<JobResult, IJobResultsAdapter>();
+
+      Stream s = jobResultsAdapter.GetSerializedJobResultStream(
+        new Guid("c20b11a9-cde1-4d7f-8499-23dedb5a65ed"), true);
+
+      int length = 0;
+
+      FileStream fs =
+        new FileStream(@"W:\\result.gz", FileMode.Create);
+
+      byte[] buffer = new byte[1024];
+      while ((length = s.Read(buffer, 0, buffer.Length)) > 0) {
+        fs.Write(buffer, 0, length);
+      }
+
+      fs.Close();
+      s.Close();
+
+      session.EndSession();
+    }
+
+    /*private void TestJobResultDeserialization() {
+      ExecutionEngineFacade executionEngineFacade =
+        new ExecutionEngineFacade();
+
+      ResponseObject<SerializedJobResult> response =
+        executionEngineFacade.GetLastSerializedResult(
+        new Guid("56ce20bc-067b-424d-a7df-67aaace7c850"), false);
+
+      IStorable restoredJob =
+        PersistenceManager.RestoreFromGZip(response.Obj.SerializedJobResultData);
+    } */
+
+    private ClientDao clientDao = new ClientDao();
+    private ClientGroupDao cgd = new ClientGroupDao();
+
+    private void TestLINQImplementation() {
+      ClientDto c1 = new ClientDto();
+      c1.Id = Guid.NewGuid();
+      c1.FreeMemory = 1000;
+      c1.Login = DateTime.Now;
+      c1.Memory = 1000;
+      c1.Name = "jackie";
+      c1.NrOfCores = 3;
+      c1.NrOfFreeCores = 2;
+      c1.CpuSpeedPerCore = 2500;
+      c1.State = State.idle;
+      c1 = clientDao.Insert(c1);
+
+      clientDao.Update(c1);
+
+      ClientDto c2 = new ClientDto();
+      c2.Id = Guid.NewGuid();
+      c2.FreeMemory = 600;
+      c2.Login = DateTime.Now;
+      c2.Memory = 2048;
+      c2.Name = "HPCs";
+      c2.NrOfCores = 4;
+      c2.NrOfFreeCores = 1;
+      c2.CpuSpeedPerCore = 4000;
+      c2.State = State.idle;
+      c2 = clientDao.Insert(c2);
+
+      ClientGroupDto tg = new ClientGroupDto();
+      tg.Name = "TopGroup";
+      tg = cgd.Insert(tg);
+
+      ClientGroupDto sg = new ClientGroupDto();
+      sg.Name = "Subgroup";
+      sg = cgd.Insert(sg);
+
+      cgd.AddRessourceToClientGroup(sg.Id, tg.Id);
+      cgd.AddRessourceToClientGroup(c1.Id, tg.Id);
+      cgd.AddRessourceToClientGroup(c2.Id, tg.Id);
+
+      JobDto job = new JobDto {
+                                Client = c1,
+                                CoresNeeded = 2,
+                                DateCreated = DateTime.Now,
+                                MemoryNeeded = 500,
+                                Percentage = 0,
+                                Priority = 1,
+                                State = State.offline
+                              };
+
+      job = DaoLocator.JobDao.Insert(job);
+
+
+      DaoLocator.JobDao.AssignClientToJob(c1.Id, job.Id);
+
+      List<ClientGroupDto> list = new List<ClientGroupDto>(cgd.FindAllWithSubGroupsAndClients());
+
+      cgd.RemoveRessourceFromClientGroup(sg.Id, tg.Id);
+
+      cgd.Delete(sg);
+      cgd.Delete(tg);
+      clientDao.Delete(c1);
+      clientDao.Delete(c2);
+    }
+
+    private void StressTest() {
+      //Speed Test
+      Random r = new Random();
+
+
+      for (int i = 0; i < 200; i++) {
+        ClientGroupDto mg = new ClientGroupDto();
+        mg.Name = "MainGroup" + i;
+        mg = cgd.Insert(mg);
+
+        populateMainGroup(mg, 3);
+      }
+    }
+
+    private void populateMainGroup(ClientGroupDto mg, int p) {
+      Random r = new Random();
+
+      for (int j = 0; j < r.Next(15); j++) {
+        ClientDto client = new ClientDto();
+        client.Id = Guid.NewGuid();
+        client.FreeMemory = r.Next(1000);
+        client.Login = DateTime.Now;
+        client.Memory = r.Next(500);
+        client.Name = "client" + mg.Name + "_" + j;
+        client.NrOfCores = 3;
+        client.NrOfFreeCores = 2;
+        client.CpuSpeedPerCore = 2500;
+        client.State = State.idle;
+        client = clientDao.Insert(client);
+        cgd.AddRessourceToClientGroup(client.Id, mg.Id);
+      }
+      for (int i = 0; i < r.Next(p); i++) {
+        ClientGroupDto sg = new ClientGroupDto();
+        sg.Name = "SubGroup " + mg.Name + " - " + p;
+        sg = cgd.Insert(sg);
+        cgd.AddRessourceToClientGroup(sg.Id, mg.Id);
+        populateMainGroup(sg, p - 1);
+      }
+    }
+
+
+    public override void Run() {
+      //TestClientGroupAdapter();
+      //InsertTestClientGroups();
+      //TestJobStreaming();
+      //TestJobResultStreaming();
+      //TestJobResultDeserialization();
+
+      //if (ContextFactory.Context.DatabaseExists())
+      //  ContextFactory.Context.DeleteDatabase();
+      //ContextFactory.Context.CreateDatabase();
+      //TestLINQImplementation();
+      TestLinqFileHandling();
+      //StressTest();
+
+      //SpeedTest();
+      //TestJobBytearrFetching();
+      //TestJobStreamFetching();
+    }
+
+    private void WriteToJobWithByte(object jobid) {
+      using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,
+                                                           new TransactionOptions
+                                                           {IsolationLevel = ApplicationConstants.ISOLATION_LEVEL_SCOPE})
+        ) {
+        Logger.Info("starting bytestuff for job " + jobid);
+        DaoLocator.JobDao.SetBinaryJobFile((Guid)jobid, jobmap[(Guid)jobid]);
+        scope.Complete();
+        Logger.Info("ended bytestuff for job " + jobid);
+      }
+    }
+
+    private void UpdateJobStatus(object jobid) {
+      using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,
+                                                           new TransactionOptions
+                                                           {IsolationLevel = ApplicationConstants.ISOLATION_LEVEL_SCOPE})
+        ) {
+        Thread.Sleep(1500);
+        Logger.Info("starting now");
+        JobDto job = DaoLocator.JobDao.FindById((Guid)jobid);
+        job.Percentage = new Random().NextDouble();
+        DaoLocator.JobDao.Update(job);
+        scope.Complete();
+        Logger.Info("ended");
+      }
+    }
+
+    Dictionary<Guid, byte[]> jobmap = new Dictionary<Guid, byte[]>();
+
+
+    private void TestLinqFileHandling() {
+      List<Thread> jobupdateThreads = new List<Thread>();
+      List<Thread> jobProgressThreads = new List<Thread>();
+      
+      Random r = new Random();
+      Stack<JobDto> jobs = new Stack<JobDto>(DaoLocator.JobDao.FindAll());
+      Logger.Info("Fetched jobs");
+      for (int x = 0; x < 10 && jobs.Count > 0; x++ ) {
+        Logger.Info("Creating data for Job");
+        JobDto job = jobs.Pop();
+        byte[] jobarr = new byte[50*1024*1024];
+        for (int i = 0; i < jobarr.Length; i++) {
+          jobarr[i] = (byte) r.Next(255);
+        }
+        jobmap.Add(job.Id, jobarr);
+      }
+      Logger.Info("filled");
+      foreach(KeyValuePair<Guid, byte[]> kvp in jobmap) {
+        Thread tjob = new Thread(new ParameterizedThreadStart(WriteToJobWithByte));      
+        Thread tupdate = new Thread(new ParameterizedThreadStart(UpdateJobStatus));
+        jobupdateThreads.Add(tupdate);
+        jobProgressThreads.Add(tjob);
+        tupdate.Start(kvp.Key);
+        tjob.Start(kvp.Key);
+      }
+      foreach (Thread t in jobupdateThreads) {
+        t.Join();
+      }
+      foreach (Thread t in jobProgressThreads) {
+        t.Join();
+      }
+    }
+
+
+    private
+      void TestJobStreamFetching() {
+      //using (TransactionScope scope = new TransactionScope()) {
+
+      HiveDataContext context = ContextFactory.Context;
+
+      ContextFactory.Context.Connection.Open
+        ();
+      ContextFactory.Context.Transaction
+        =
+        ContextFactory.Context.Connection.BeginTransaction
+          ();
+
+
+      ClientFacade facade = new ClientFacade();
+
+      Stream stream = facade.SendStreamedJob(new Guid("F5CFB334-66A0-417C-A585-71711BA21D3F"));
+
+
+      byte[] buffer = new byte[3024];
+
+      int read = 0;
+
+      while ((
+               read
+               =
+               stream.Read
+                 (
+                 buffer
+                 , 0,
+                 buffer.Length
+                 )) > 0) {}
+
+      stream.Close
+        ();
+
+      //Stream stream = DaoLocator.JobDao.GetSerializedJobStream(new Guid("bbb51f87-4e2f-4499-a9b6-884e589c78b6"));
+      //}
+    }
+
+    private
+      void TestJobBytearrFetching() {
+      byte[] arr = DaoLocator.JobDao.GetBinaryJobFile(new Guid("A3386907-2B3C-4976-BE07-04D660D40A5B"));
+      Console.WriteLine
+        (
+        arr
+        );
+    }
+
+    private
+      void SpeedTest() {
+      DateTime start = new DateTime();
+
+      List<ClientGroupDto> list = new List<ClientGroupDto>(cgd.FindAllWithSubGroupsAndClients());
+
+      DateTime end = new DateTime();
+
+      TimeSpan used = end - start;
+      Console.WriteLine
+        (
+        used.TotalMilliseconds
+        );
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DefaultScheduler.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DefaultScheduler.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/DefaultScheduler.cs	(revision 4061)
@@ -0,0 +1,62 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Server.DataAccess;
+using System.Threading;
+using HeuristicLab.DataAccess.Interfaces;
+using System.Transactions;
+using HeuristicLab.Hive.Contracts;
+
+namespace HeuristicLab.Hive.Server.Core {
+  internal class DefaultScheduler : IScheduler {
+    //private ISessionFactory factory;
+
+    private static Mutex jobLock =
+      new Mutex();
+
+    #region IScheduler Members
+
+    public DefaultScheduler() {
+      //factory = ServiceLocator.GetSessionFactory();
+    }
+
+    public bool ExistsJobForClient(HeuristicLab.Hive.Contracts.BusinessObjects.HeartBeatData hbData) {
+      List<JobDto> allOfflineJobsForClient =
+        new List<JobDto>(DaoLocator.JobDao.FindFittingJobsForClient(State.offline, hbData.FreeCores, hbData.FreeMemory,
+                                                                    hbData.ClientId));
+      return (allOfflineJobsForClient != null && allOfflineJobsForClient.Count > 0);
+    }
+
+    public HeuristicLab.Hive.Contracts.BusinessObjects.JobDto GetNextJobForClient(Guid clientId) {
+      /// Critical section ///
+      jobLock.WaitOne();
+      JobDto jobToCalculate = null;
+      using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = ApplicationConstants.ISOLATION_LEVEL_SCOPE })) {
+        ClientDto client = DaoLocator.ClientDao.FindById(clientId);
+        LinkedList<JobDto> allOfflineJobsForClient =
+          new LinkedList<JobDto>(DaoLocator.JobDao.FindFittingJobsForClient(State.offline, client.NrOfFreeCores,
+                                                                            client.FreeMemory, client.Id));        
+        if (allOfflineJobsForClient != null && allOfflineJobsForClient.Count > 0) {
+          jobToCalculate = allOfflineJobsForClient.First.Value;
+          jobToCalculate.State = State.calculating;
+          jobToCalculate.Client = client;
+          jobToCalculate.Client.State = State.calculating;
+          jobToCalculate.DateCalculated = DateTime.Now;
+          DaoLocator.JobDao.AssignClientToJob(client.Id, jobToCalculate.Id);
+          DaoLocator.JobDao.Update(jobToCalculate);
+          DaoLocator.ClientDao.Update(jobToCalculate.Client);
+        }
+        scope.Complete();
+      }
+      jobLock.ReleaseMutex();
+      /// End Critical section ///
+
+      return jobToCalculate;
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ExecutionEngineFacade.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ExecutionEngineFacade.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ExecutionEngineFacade.cs	(revision 4061)
@@ -0,0 +1,65 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class ExecutionEngineFacade: IExecutionEngineFacade {
+
+    private IJobManager jobManager =
+      ServiceLocator.GetJobManager();
+
+    public ExecutionEngineFacade() {
+      
+    }
+
+    #region IExecutionEngineFacade Members
+
+    public ResponseObject<JobDto> AddJob(SerializedJob job) {
+      return jobManager.AddNewJob(job);
+    }
+
+    public ResponseObject<JobDto> AddJobWithGroupStrings(SerializedJob job, IEnumerable<string> resources) {      
+      return jobManager.AddJobWithGroupStrings(job, resources);
+    }
+
+    public Response RequestSnapshot(Guid jobId) {
+      return jobManager.RequestSnapshot(jobId);
+    }
+
+    public ResponseObject<SerializedJob> 
+      GetLastSerializedResult(Guid jobId, bool requested, bool snapshot) {
+      return jobManager.GetLastSerializedJobResultOf(jobId, requested, snapshot);
+    }
+
+    public Response AbortJob(Guid jobId) {
+      return jobManager.AbortJob(jobId);
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HeuristicLab.Hive.Server.Core-3.2.csproj
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HeuristicLab.Hive.Server.Core-3.2.csproj	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HeuristicLab.Hive.Server.Core-3.2.csproj	(revision 4061)
@@ -0,0 +1,204 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProductVersion>9.0.30729</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{898B31CF-81DC-453B-AEB3-BDF83197A7EE}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>HeuristicLab.Hive.Server.Core</RootNamespace>
+    <AssemblyName>HeuristicLab.Hive.Server.Core-3.2</AssemblyName>
+    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <SignAssembly>true</SignAssembly>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>bin\x86\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>bin\x86\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>bin\x64\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>bin\x64\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Data.Linq">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.ServiceModel">
+      <RequiredTargetFramework>3.0</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Transactions" />
+    <Reference Include="System.Windows.Forms" />
+    <Reference Include="System.Xml.Linq">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Data.DataSetExtensions">
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Authorization\HivePermissions.cs" />
+    <Compile Include="Authorization\PermissionCollection.cs" />
+    <Compile Include="Authorization\PermissionContext.cs" />
+    <Compile Include="Authorization\PermissionException.cs" />
+    <Compile Include="Authorization\Policy.cs" />
+    <Compile Include="Authorization\PolicyCollection.cs" />
+    <Compile Include="ClientCommunicator.cs" />
+    <Compile Include="ClientFacade.cs" />
+    <Compile Include="ClientManager.cs" />
+    <Compile Include="DaoLocator.cs" />
+    <Compile Include="DbTestApp.cs" />
+    <Compile Include="DefaultScheduler.cs" />
+    <Compile Include="ExecutionEngineFacade.cs" />
+    <Compile Include="Authorization\HivePermissionManager.cs" />
+    <Compile Include="HiveServerCorePlugin.cs" />
+    <Compile Include="HiveServerMessages.Designer.cs" />
+    <Compile Include="InternalInterfaces\IHivePermissionManager.cs" />
+    <Compile Include="InternalInterfaces\IInternalClientCommunicator.cs" />
+    <Compile Include="InternalInterfaces\IInternalJobManager.cs" />
+    <Compile Include="InternalInterfaces\IScheduler.cs" />
+    <Compile Include="JobManager.cs" />
+    <Compile Include="LifecycleManager.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="ServerConsoleFacade.cs" />
+    <Compile Include="ServiceLocator.cs" />
+    <Compile Include="Properties\Settings.Designer.cs">
+      <AutoGen>True</AutoGen>
+      <DesignTimeSharedInput>True</DesignTimeSharedInput>
+      <DependentUpon>Settings.settings</DependentUpon>
+    </Compile>
+    <Compile Include="Settings.cs" />
+    <Compile Include="SpringTransaction.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="app.config" />
+    <None Include="ClassDiagram1.cd" />
+    <None Include="HeuristicLab.snk" />
+    <EmbeddedResource Include="Authorization\HivePermissionSet.xsd">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </EmbeddedResource>
+    <None Include="Properties\AssemblyInfo.frame" />
+    <None Include="Properties\Settings.settings">
+      <Generator>PublicSettingsSingleFileGenerator</Generator>
+      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
+    </None>
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\HeuristicLab.Core\3.2\HeuristicLab.Core-3.2.csproj">
+      <Project>{F43B59AB-2B8C-4570-BC1E-15592086517C}</Project>
+      <Name>HeuristicLab.Core-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.DataAccess\3.2\HeuristicLab.DataAccess-3.2.csproj">
+      <Project>{9076697B-C151-46CD-95BC-1D059492B478}</Project>
+      <Name>HeuristicLab.DataAccess-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.Contracts\3.2\HeuristicLab.Hive.Contracts-3.2.csproj">
+      <Project>{134F93D7-E7C8-4ECD-9923-7F63259A60D8}</Project>
+      <Name>HeuristicLab.Hive.Contracts-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.JobBase\3.2\HeuristicLab.Hive.JobBase-3.2.csproj">
+      <Project>{21187322-52DD-4243-80A4-A85F0263E63B}</Project>
+      <Name>HeuristicLab.Hive.JobBase-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.Server.DataAccess\3.2\HeuristicLab.Hive.Server.DataAccess-3.2.csproj">
+      <Project>{4D5A2A16-66C2-431D-9AA3-BD3041E64B84}</Project>
+      <Name>HeuristicLab.Hive.Server.DataAccess-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Hive.Server.LINQDataAccess\3.2\HeuristicLab.Hive.Server.LINQDataAccess-3.2.csproj">
+      <Project>{A4499DDD-D1B8-414F-98F6-903C2C71BEB0}</Project>
+      <Name>HeuristicLab.Hive.Server.LINQDataAccess-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.PluginInfrastructure\HeuristicLab.PluginInfrastructure.csproj">
+      <Project>{94186A6A-5176-4402-AE83-886557B53CCA}</Project>
+      <Name>HeuristicLab.PluginInfrastructure</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Security.Contracts\3.2\HeuristicLab.Security.Contracts-3.2.csproj">
+      <Project>{D59E852C-F205-4647-8C05-EB9ED1CF44E9}</Project>
+      <Name>HeuristicLab.Security.Contracts-3.2</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Tracing\3.2\HeuristicLab.Tracing-3.2.csproj">
+      <Project>{EE2034D9-6E27-48A1-B855-42D45F69A4FC}</Project>
+      <Name>HeuristicLab.Tracing-3.2</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <EmbeddedResource Include="Authorization\HivePermissionSet.xml">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </EmbeddedResource>
+  </ItemGroup>
+  <ItemGroup>
+    <EmbeddedResource Include="Authorization\HivePermissionPolicy.xml">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </EmbeddedResource>
+  </ItemGroup>
+  <ItemGroup>
+    <WCFMetadata Include="Service References\" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+  <PropertyGroup>
+    <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd</PreBuildEvent>
+  </PropertyGroup>
+</Project>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HivePermissionManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HivePermissionManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HivePermissionManager.cs	(revision 4061)
@@ -0,0 +1,58 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Security.Contracts.Interfaces;
+using HeuristicLab.DataAccess;
+using HeuristicLab.Security.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class HivePermissionManager : IHivePermissionManager {
+    
+    private IPermissionManager permManager = ServiceLocator.GetPermissionManager();
+
+    private IClientManager clientManager = ServiceLocator.GetClientManager();
+
+    /// <summary>
+    /// Authenticates a user and returns a valid guid if success.
+    /// </summary>
+    /// <param name="username"></param>
+    /// <param name="password"></param>
+    /// <returns></returns>
+    public Guid Login(string username, string password) {
+      return permManager.Authenticate(username, password);
+    }
+
+    /// <summary>
+    /// Checks if a user has permission for a specified action.
+    /// </summary>
+    /// <param name="sessionID">The current session.</param>
+    /// <param name="actionID">A pre-defined action that requires permission.</param>
+    /// <param name="entityID">A resource (Job,...)</param>
+    /// <returns></returns>
+    public bool CheckPermission(Guid sessionID, Guid actionID, Guid entityId) {
+      bool hasPerm = permManager.CheckPermission(sessionID, actionID, entityId);
+      
+      if (!hasPerm) {
+        if ((actionID == PermissiveSecurityAction.Add_Job) ||
+            (actionID == PermissiveSecurityAction.Remove_Job) ||
+            (actionID == PermissiveSecurityAction.Request_Snapshot)||
+            (actionID==PermissiveSecurityAction.Abort_Job))
+          if (CheckPermissionHelper(sessionID, actionID, entityId)) return true;
+      }
+
+      return hasPerm;      
+    }
+
+    private bool CheckPermissionHelper(Guid sessionId, Guid actionId, Guid entityId) {
+      IList<ClientGroup> groups = clientManager.GetAllGroupsOfResource(entityId).Obj;
+      foreach (ClientGroup group in groups) 
+        if (CheckPermission(sessionId, actionId, group.Id)) return true;
+      return false;
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HiveServerCorePlugin.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HiveServerCorePlugin.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HiveServerCorePlugin.cs	(revision 4061)
@@ -0,0 +1,40 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Hive.Server {
+  [Plugin("HeuristicLab.Hive.Server.Core-3.2")]
+  [PluginFile("HeuristicLab.Hive.Server.Core-3.2.dll", PluginFileType.Assembly)]
+  [PluginDependency("HeuristicLab.Core-3.2")]
+  [PluginDependency("HeuristicLab.DataAccess-3.2")]
+  [PluginDependency("HeuristicLab.Hive.Contracts-3.2")]
+  [PluginDependency("HeuristicLab.Hive.JobBase-3.2")]
+  [PluginDependency("HeuristicLab.Hive.Server.DataAccess-3.2")]
+  [PluginDependency("HeuristicLab.Hive.Server.LINQDataAccess-3.2")]
+  [PluginDependency("HeuristicLab.Security.Contracts-3.2")]
+  [PluginDependency("HeuristicLab.Tracing", "3.2.0")]
+  public class HiveServerCorePlugin : PluginBase {
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HiveServerMessages.Designer.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HiveServerMessages.Designer.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/HiveServerMessages.Designer.cs	(revision 4061)
@@ -0,0 +1,81 @@
+﻿//------------------------------------------------------------------------------
+// <auto-generated>
+//     This code was generated by a tool.
+//     Runtime Version:2.0.50727.3053
+//
+//     Changes to this file may cause incorrect behavior and will be lost if
+//     the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace HeuristicLab.Hive.Server.Core {
+    using System;
+    
+    
+    /// <summary>
+    ///   A strongly-typed resource class, for looking up localized strings, etc.
+    /// </summary>
+    // This class was auto-generated by the StronglyTypedResourceBuilder
+    // class via a tool like ResGen or Visual Studio.
+    // To add or remove a member, edit your .ResX file then rerun ResGen
+    // with the /str option, or rebuild your VS project.
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
+    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    internal class HiveServerMessages {
+        
+        private static global::System.Resources.ResourceManager resourceMan;
+        
+        private static global::System.Globalization.CultureInfo resourceCulture;
+        
+        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+        internal HiveServerMessages() {
+        }
+        
+        /// <summary>
+        ///   Returns the cached ResourceManager instance used by this class.
+        /// </summary>
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Resources.ResourceManager ResourceManager {
+            get {
+                if (object.ReferenceEquals(resourceMan, null)) {
+                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HeuristicLab.Hive.Server.Core.HiveServerMessages", typeof(HiveServerMessages).Assembly);
+                    resourceMan = temp;
+                }
+                return resourceMan;
+            }
+        }
+        
+        /// <summary>
+        ///   Overrides the current thread's CurrentUICulture property for all
+        ///   resource lookups using this strongly typed resource class.
+        /// </summary>
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Globalization.CultureInfo Culture {
+            get {
+                return resourceCulture;
+            }
+            set {
+                resourceCulture = value;
+            }
+        }
+        
+        /// <summary>
+        ///   Looks up a localized string similar to The Login was successfull.
+        /// </summary>
+        internal static string LoginSuccess {
+            get {
+                return ResourceManager.GetString("LoginSuccess", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   Looks up a localized string similar to A User with this GUID is allready logged in.
+        /// </summary>
+        internal static string UserAllreadyOnline {
+            get {
+                return ResourceManager.GetString("UserAllreadyOnline", resourceCulture);
+            }
+        }
+    }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IClientAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IClientAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IClientAdapter.cs	(revision 4061)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  /// <summary>
+  /// The client database adapter
+  /// </summary>
+  public interface IClientAdapter : IDataAdapter<ClientInfo> {
+    /// <summary>
+    /// Get the client with the specified name
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>
+    ClientInfo GetByName(string name);
+
+    /// <summary>
+    /// Get the client with the specified id
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>
+    ClientInfo GetById(Guid id);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IClientGroupAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IClientGroupAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IClientGroupAdapter.cs	(revision 4061)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  /// <summary>
+  /// The client group database adapter
+  /// </summary>
+  public interface IClientGroupAdapter: IDataAdapter<ClientGroup> {
+    /// <summary>
+    /// Get the client group with the specified name
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>
+    ClientGroup GetByName(string name);
+
+    /// <summary>
+    /// Gets all client groups where the resource is member of
+    /// </summary>
+    /// <param name="permOwner"></param>
+    /// <returns></returns>
+    ICollection<ClientGroup> MemberOf(Resource resource);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IDataAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IDataAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IDataAdapter.cs	(revision 4061)
@@ -0,0 +1,57 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  public interface IDataAdapter<ObjT>
+    where ObjT: IHiveObject
+  {
+    /// <summary>
+    /// Save or update the object
+    /// </summary>
+    /// <param name="user"></param>
+    void Update(ObjT obj);
+
+    /// <summary>
+    /// Get the object with the specified ID
+    /// </summary>
+    /// <param name="userId"></param>
+    /// <returns></returns>
+    ObjT GetById(long id);
+
+    /// <summary>
+    /// Get all objects
+    /// </summary>
+    /// <returns></returns>
+    ICollection<ObjT> GetAll();
+
+    /// <summary>
+    /// Deletes the object
+    /// </summary>
+    /// <param name="user"></param>
+    bool Delete(ObjT obj);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IJobAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IJobAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IJobAdapter.cs	(revision 4061)
@@ -0,0 +1,63 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  public interface IJobAdapter: IDataAdapter<Job> {
+    /// <summary>
+    /// Gets all subjobs of the specified job
+    /// </summary>
+    /// <returns></returns>
+    ICollection<Job> GetAllSubjobs(Job job);
+
+    /// <summary>
+    /// Gets all Jobs with the specified state
+    /// </summary>
+    /// <returns></returns>
+    ICollection<Job> GetJobsByState(State state);
+
+    /// <summary>
+    /// Gets all jobs of the client
+    /// </summary>
+    /// <param name="client"></param>
+    /// <returns></returns>
+    ICollection<Job> GetJobsOf(ClientInfo client);
+
+    /// <summary>
+    /// Gets all active jobs of the client
+    /// </summary>
+    /// <param name="client"></param>
+    /// <returns></returns>
+    ICollection<Job> GetActiveJobsOf(ClientInfo client);
+
+    /// <summary>
+    /// Gets all jobs of the user
+    /// </summary>
+    /// <param name="user"></param>
+    /// <returns></returns>
+    ICollection<Job> GetJobsOf(User user);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IJobResultsAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IJobResultsAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IJobResultsAdapter.cs	(revision 4061)
@@ -0,0 +1,37 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  public interface IJobResultsAdapter: IDataAdapter<JobResult> {
+    /// <summary>
+    /// Gets all results for the specified job
+    /// </summary>
+    /// <param name="job"></param>
+    /// <returns></returns>
+    ICollection<JobResult> GetResultsOf(Job job);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IPermissionOwnerAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IPermissionOwnerAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IPermissionOwnerAdapter.cs	(revision 4061)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  /// <summary>
+  /// The permission owner database adapter
+  /// </summary>
+  public interface IPermissionOwnerAdapter: IDataAdapter<PermissionOwner> {
+    /// <summary>
+    /// Gets the permission owner and updates the values of the object
+    /// </summary>
+    /// <param name="resource"></param>
+    /// <returns></returns>
+    bool GetById(PermissionOwner permOwner);
+
+    /// <summary>
+    /// Get the permission owner with the specified name
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>
+    PermissionOwner GetByName(String name);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IResourceAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IResourceAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IResourceAdapter.cs	(revision 4061)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  /// <summary>
+  /// The resource database adapter
+  /// </summary>
+  public interface IResourceAdapter: IDataAdapter<Resource> {
+    /// <summary>
+    /// Gets the resource and updates the values of the object
+    /// </summary>
+    /// <param name="resource"></param>
+    /// <returns></returns>
+    bool GetById(Resource resource);
+
+    /// <summary>
+    /// Get the resource with the specified name
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>
+    Resource GetByName(string name);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IUserAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IUserAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IUserAdapter.cs	(revision 4061)
@@ -0,0 +1,40 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  /// <summary>
+  /// The user database adapter
+  /// </summary>
+  public interface IUserAdapter: IDataAdapter<User> {
+    /// <summary>
+    /// Get the user with the specified name
+    /// </summary>
+    /// <param name="userId"></param>
+    /// <returns></returns>
+    User GetByName(string name);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IUserGroupAdapter.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IUserGroupAdapter.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/DataAccess/IUserGroupAdapter.cs	(revision 4061)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess {
+  /// <summary>
+  /// The user group database adapter
+  /// </summary>
+  public interface IUserGroupAdapter: IDataAdapter<UserGroup> {
+    /// <summary>
+    /// Get the user group with the specified name
+    /// </summary>
+    /// <param name="clientId"></param>
+    /// <returns></returns>
+    UserGroup GetByName(String name);
+
+    /// <summary>
+    /// Gets all user groups where the permission owner is member of
+    /// </summary>
+    /// <param name="permOwner"></param>
+    /// <returns></returns>
+    ICollection<UserGroup> MemberOf(PermissionOwner permOwner);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IHivePermissionManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IHivePermissionManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IHivePermissionManager.cs	(revision 4061)
@@ -0,0 +1,15 @@
+﻿using System;
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces {
+  public interface IHivePermissionManager {
+    /// <summary>
+    /// Checks user permission against predefined policy in database.
+    /// </summary>
+    /// <param name="permission">the name of policy defined in xml-file</param>
+    /// <param name="sessionID">the users current session ID</param>
+    /// <param name="entityID"></param>
+    /// <exception cref="PermissionException">thrown when access denied</exception>
+    void Authorize(string policyName, Guid sessionID, Guid entityID);
+    bool CheckPermission(Guid sessionID, Guid actionID, Guid entityId);
+    Guid Login(string username, string password);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IInternalClientCommunicator.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IInternalClientCommunicator.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IInternalClientCommunicator.cs	(revision 4061)
@@ -0,0 +1,36 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using System.IO;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces {
+  interface IInternalClientCommunicator {
+    ResponseResultReceived ProcessJobResult(
+      Stream stream,
+      bool finished);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IInternalJobManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IInternalJobManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IInternalJobManager.cs	(revision 4061)
@@ -0,0 +1,35 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using System.IO;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces {
+  interface IInternalJobManager {   
+    Stream GetJobStreamById(Guid jobId);
+    byte[] GetSerializedJobDataById(Guid jobId);
+    void SetSerializedJobDataById(Guid jobId, byte[] data);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IScheduler.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IScheduler.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/InternalInterfaces/IScheduler.cs	(revision 4061)
@@ -0,0 +1,33 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+
+namespace HeuristicLab.Hive.Server.Core.InternalInterfaces {
+  public interface IScheduler {
+    bool ExistsJobForClient(HeartBeatData hbData);
+    JobDto GetNextJobForClient(Guid clientId);
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/JobManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/JobManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/JobManager.cs	(revision 4061)
@@ -0,0 +1,369 @@
+﻿#region License Information
+
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Hive.Server.DataAccess;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+using HeuristicLab.DataAccess.Interfaces;
+using System.Data;
+using System.IO;
+using HeuristicLab.Tracing;
+using System.Transactions;
+using HeuristicLab.Hive.Server.LINQDataAccess;
+using IsolationLevel=System.Transactions.IsolationLevel;
+
+namespace HeuristicLab.Hive.Server.Core {
+  internal class JobManager : IJobManager, IInternalJobManager {
+    //ISessionFactory factory;
+    private ILifecycleManager lifecycleManager;
+
+    #region IJobManager Members
+
+    public JobManager() {
+      //factory = ServiceLocator.GetSessionFactory();
+      lifecycleManager = ServiceLocator.GetLifecycleManager();
+
+      lifecycleManager.RegisterStartup(new EventHandler(lifecycleManager_OnStartup));
+      lifecycleManager.RegisterStartup(new EventHandler(lifecycleManager_OnShutdown));
+    }
+
+    private JobDto GetLastJobResult(Guid jobId) {
+      return DaoLocator.JobDao.FindById(jobId);
+    }
+
+
+    private void checkForDeadJobs() {
+      Logger.Info("Searching for dead Jobs");
+      using (
+        TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,
+                                                      new TransactionOptions
+                                                      {IsolationLevel = ApplicationConstants.ISOLATION_LEVEL_SCOPE})) {
+        List<JobDto> allJobs = new List<JobDto>(DaoLocator.JobDao.FindAll());
+        foreach (JobDto curJob in allJobs) {
+          if (curJob.State != State.calculating && curJob.State != State.finished) {
+            DaoLocator.JobDao.SetJobOffline(curJob);
+          }
+        }
+        scope.Complete();
+      }
+      DaoLocator.DestroyContext();
+    }
+
+    private void lifecycleManager_OnStartup(object sender, EventArgs e) {
+      Logger.Info("Startup Event Fired, Checking DB for consistency");
+      checkForDeadJobs();
+      Logger.Info("Startup Event Done");
+    }
+
+    private void lifecycleManager_OnShutdown(object sender, EventArgs e) {
+      Logger.Info("Startup Event Fired, Checking DB for consistency");
+      checkForDeadJobs();
+      Logger.Info("Startup Event Done");
+    }
+
+    /// <summary>
+    /// returns all jobs stored in the database
+    /// </summary>
+    /// <returns></returns>
+    public ResponseList<JobDto> GetAllJobs() {
+      ResponseList<JobDto> response = new ResponseList<JobDto>();
+
+      response.List = new List<JobDto>(DaoLocator.JobDao.FindAll());
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ALL_JOBS;
+
+      return response;
+    }
+
+    public ResponseList<JobDto> GetAllJobsWithFilter(State jobState, int offset, int count) {
+      ResponseList<JobDto> response = new ResponseList<JobDto>();
+      response.List = new List<JobDto>(DaoLocator.JobDao.FindWithLimitations(jobState, offset, count));
+      response.Success = true;
+      return response;
+    }
+
+    /// <summary>
+    /// Gets the streamed job
+    /// </summary>
+    /// <param name="jobId"></param>
+    /// <returns></returns>
+    public Stream GetJobStreamById(Guid jobId) {
+      return DaoLocator.JobDao.GetSerializedJobStream(jobId);
+    }
+
+    /// <summary>
+    /// returns the job with the specified id
+    /// </summary>
+    /// <returns></returns>
+    public ResponseObject<JobDto> GetJobById(Guid jobId) {
+      ResponseObject<JobDto> response = new ResponseObject<JobDto>();
+
+      response.Obj = DaoLocator.JobDao.FindById(jobId);
+      if (response.Obj != null) {
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_GET_JOB_BY_ID;
+      }
+      else {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
+      }
+
+      return response;
+    }
+
+    public ResponseObject<JobDto> GetJobByIdWithDetails(Guid jobId) {
+      ResponseObject<JobDto> job = new ResponseObject<JobDto>();
+      job.Obj = DaoLocator.JobDao.FindById(jobId);
+      if (job.Obj != null) {
+        job.Success = true;
+        job.StatusMessage = ApplicationConstants.RESPONSE_JOB_GET_JOB_BY_ID;
+
+        job.Obj.Client = DaoLocator.ClientDao.GetClientForJob(jobId);
+      }
+      else {
+        job.Success = false;
+        job.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
+      }
+      return job;
+    }
+
+    public ResponseObject<JobDto> AddJobWithGroupStrings(SerializedJob job, IEnumerable<string> resources) {
+      IClientGroupDao cgd = DaoLocator.ClientGroupDao;
+      foreach (string res in resources) {
+        foreach (ClientGroupDto cg in cgd.FindByName(res)) {
+          job.JobInfo.AssignedResourceIds.Add(cg.Id);
+        }
+      }
+      return AddNewJob(job);
+    }
+
+    /// <summary>
+    /// Adds a new job into the database
+    /// </summary>
+    /// <param name="job"></param>
+    /// <returns></returns>
+    public ResponseObject<JobDto> AddNewJob(SerializedJob job) {
+      ResponseObject<JobDto> response = new ResponseObject<JobDto>();
+
+      if (job != null && job.JobInfo != null) {
+        if (job.JobInfo.State != State.offline) {
+          response.Success = false;
+          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOBSTATE_MUST_BE_OFFLINE;
+          return response;
+        }
+        if (job.JobInfo.Id != Guid.Empty) {
+          response.Success = false;
+          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ID_MUST_NOT_BE_SET;
+          return response;
+        }
+        if (job.SerializedJobData == null) {
+          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_NULL;
+          response.Success = false;
+          return response;
+        }
+
+        job.JobInfo.DateCreated = DateTime.Now;
+        DaoLocator.JobDao.InsertWithAttachedJob(job);
+        DaoLocator.PluginInfoDao.InsertPluginDependenciesForJob(job.JobInfo);
+
+        response.Success = true;
+        response.Obj = job.JobInfo;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_ADDED;
+      }
+      else {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_NULL;
+      }
+
+      return response;
+    }
+
+    /// <summary>
+    /// Removes a job from the database
+    /// </summary>
+    /// <param name="jobId"></param>
+    /// <returns></returns>
+    public Response RemoveJob(Guid jobId) {
+      Response response = new Response();
+
+      JobDto job = DaoLocator.JobDao.FindById(jobId);
+      if (job == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
+        return response;
+      }
+      DaoLocator.JobDao.Delete(job);
+      response.Success = false;
+      response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_REMOVED;
+
+      return response;
+    }
+
+    public ResponseObject<JobDto> GetLastJobResultOf(Guid jobId) {
+      ResponseObject<JobDto> result =
+        new ResponseObject<JobDto>();
+
+      result.Obj =
+        GetLastJobResult(jobId);
+      result.Success =
+        result.Obj != null;
+
+      return result;
+    }
+
+    //Requested means: there MUST be a job result which gets sent back
+    public ResponseObject<SerializedJob>
+      GetLastSerializedJobResultOf(Guid jobId, bool requested, bool snapshot) {
+      ResponseObject<SerializedJob> response =
+        new ResponseObject<SerializedJob>();
+
+      JobDto job = DaoLocator.JobDao.FindById(jobId);
+
+      //if it's a snapshot but the result hasn't reached the server yet...
+      if (snapshot && (job.State == State.requestSnapshot || job.State == State.requestSnapshotSent)) {
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE;
+
+        return response;
+      }
+
+      //if it's NOT a snapshot, NEITHER request NOR is it finished
+      if(!requested && !snapshot && job.State != State.finished) {      
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE;
+
+        return response;
+      }
+
+      //every other case - snapshot, job finished or it's requested
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_RESULT_SENT;
+      response.Obj = new SerializedJob();
+      response.Obj.JobInfo = job;
+
+      response.Obj.SerializedJobData =
+        DaoLocator.JobDao.GetBinaryJobFile(jobId);
+
+      return response;
+    }
+
+
+    public Response RequestSnapshot(Guid jobId) {
+      Response response = new Response();
+
+
+      JobDto job = DaoLocator.JobDao.FindById(jobId);
+      if (job.State == State.requestSnapshot || job.State == State.requestSnapshotSent) {
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_REQUEST_ALLREADY_SET;
+        return response;
+      }
+      if (job.State != State.calculating) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_IS_NOT_BEEING_CALCULATED;
+        return response;
+      }
+      // job is in correct state
+      job.State = State.requestSnapshot;
+      DaoLocator.JobDao.Update(job);
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_JOB_REQUEST_SET;
+
+      return response;
+    }
+
+    public Response AbortJob(Guid jobId) {
+      Response response = new Response();
+
+      JobDto job = DaoLocator.JobDao.FindById(jobId);
+      if (job == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
+        return response; // no commit needed
+      }
+      if (job.State == State.abort) {
+        response.Success = true;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ABORT_REQUEST_ALLREADY_SET;
+        return response; // no commit needed
+      }
+      if (job.State != State.calculating && job.State != State.requestSnapshot && job.State != State.requestSnapshotSent) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_IS_NOT_BEEING_CALCULATED;
+        return response; // no commit needed
+      }
+      // job is in correct state
+      job.State = State.abort;
+      DaoLocator.JobDao.Update(job);
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ABORT_REQUEST_SET;
+
+      return response;
+    }
+
+    public ResponseList<JobResult> GetAllJobResults(Guid jobId) {
+      return new ResponseList<JobResult>();
+    }
+
+    public ResponseList<ProjectDto> GetAllProjects() {
+      return null;
+    }
+
+    private Response createUpdateProject(ProjectDto project) {
+      return null;
+    }
+
+    public Response CreateProject(ProjectDto project) {
+      return createUpdateProject(project);
+    }
+
+    public Response ChangeProject(ProjectDto project) {
+      return createUpdateProject(project);
+    }
+
+    public Response DeleteProject(Guid projectId) {
+      return null;
+    }
+
+    public ResponseList<JobDto> GetJobsByProject(Guid projectId) {
+      return null;
+    }
+
+    public byte[] GetSerializedJobDataById(Guid jobId) {
+      return DaoLocator.JobDao.GetBinaryJobFile(jobId);
+    }
+
+    public void SetSerializedJobDataById(Guid jobId, byte[] data) {
+      DaoLocator.JobDao.SetBinaryJobFile(jobId, data);
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/LifecycleManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/LifecycleManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/LifecycleManager.cs	(revision 4061)
@@ -0,0 +1,74 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Server.DataAccess;
+using System.Timers;
+using HeuristicLab.DataAccess.Interfaces;
+
+namespace HeuristicLab.Hive.Server.Core {
+  class LifecycleManager: ILifecycleManager {
+    private static Timer timer =
+      new Timer();
+
+    private static event EventHandler OnServerHeartbeat;
+    private static event EventHandler OnStartup;
+    private static event EventHandler OnShutdown;
+    #region ILifecycleManager Members
+
+    public void RegisterHeartbeat(EventHandler handler) {
+      OnServerHeartbeat += handler;
+    }
+
+    public void RegisterStartup(EventHandler handler) {
+      OnStartup += handler;
+    }
+
+    public void RegisterShutdown(EventHandler handler) {
+      OnShutdown += handler;
+    }
+
+    public void Init() {
+      timer.Interval = new TimeSpan(0, 0, 10).TotalMilliseconds; // TODO: global constant needed
+      timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
+      timer.Start();
+
+      if (OnStartup != null)
+        OnStartup(this, null);
+    }
+
+    void timer_Elapsed(object sender, ElapsedEventArgs e) {
+      if (OnServerHeartbeat != null)
+        OnServerHeartbeat(this, null);
+    }
+
+    public void Shutdown() {
+      if (OnShutdown != null)
+        OnShutdown(this, null);
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/AssemblyInfo.frame
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/AssemblyInfo.frame	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/AssemblyInfo.frame	(revision 4061)
@@ -0,0 +1,59 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using HeuristicLab.PluginInfrastructure;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.Hive.Server.Core")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2008 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("4D7B8E8F-6A49-499a-87E8-F0537F192295")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("3.2.0.$WCREV$")]
+[assembly: AssemblyFileVersion("3.2.0.$WCREV$")]
+[assembly: AssemblyBuildDate("$WCNOW$")]
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/Settings.Designer.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/Settings.Designer.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/Settings.Designer.cs	(revision 4061)
@@ -0,0 +1,36 @@
+﻿//------------------------------------------------------------------------------
+// <auto-generated>
+//     This code was generated by a tool.
+//     Runtime Version:2.0.50727.4927
+//
+//     Changes to this file may cause incorrect behavior and will be lost if
+//     the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace HeuristicLab.Hive.Server.Core.Properties {
+    
+    
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
+    public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
+        
+        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+        
+        public static Settings Default {
+            get {
+                return defaultInstance;
+            }
+        }
+        
+        [global::System.Configuration.ApplicationScopedSettingAttribute()]
+        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=127.0.0.1;Initial Catalog=HeuristicLab.Hive;Persist Security Info=Tru" +
+            "e;User ID=hive;Password=hive;Pooling=true;MultipleActiveResultSets=true")]
+        public string HiveServerConnectionString {
+            get {
+                return ((string)(this["HiveServerConnectionString"]));
+            }
+        }
+    }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/Settings.settings
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/Settings.settings	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Properties/Settings.settings	(revision 4061)
@@ -0,0 +1,9 @@
+﻿<?xml version='1.0' encoding='utf-8'?>
+<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="HeuristicLab.Hive.Server.Core.Properties" GeneratedClassName="Settings">
+  <Profiles />
+  <Settings>
+    <Setting Name="HiveServerConnectionString" Type="System.String" Scope="Application">
+      <Value Profile="(Default)">Data Source=127.0.0.1;Initial Catalog=HeuristicLab.Hive;Persist Security Info=True;User ID=hive;Password=hive;Pooling=true;MultipleActiveResultSets=true</Value>
+    </Setting>
+  </Settings>
+</SettingsFile>
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ServerConsoleFacade.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ServerConsoleFacade.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ServerConsoleFacade.cs	(revision 4061)
@@ -0,0 +1,196 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Contracts;
+using HeuristicLab.Security.Contracts.Interfaces;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+using System.ServiceModel;
+
+
+namespace HeuristicLab.Hive.Server.Core {
+  public class ServerConsoleFacade: IServerConsoleFacade {
+    private IClientManager clientManager = 
+      ServiceLocator.GetClientManager();
+
+    private IJobManager jobManager = 
+      ServiceLocator.GetJobManager();
+
+    private IHivePermissionManager secMan = ServiceLocator.GetHivePermissionManager();
+
+    public Guid sessionID = Guid.Empty;
+
+    public ServerConsoleFacade() {      
+    }
+
+    public Response Login(string username, string password) {
+      Response resp = new Response();
+     
+      sessionID = secMan.Login(username, password);
+      if (sessionID == Guid.Empty) {
+        resp.Success = false;
+        resp.StatusMessage = ApplicationConstants.RESPONSE_SERVERCONSOLE_LOGIN_FAILED;
+      } else {
+        resp.Success = true;
+        resp.StatusMessage =
+          ApplicationConstants.RESPONSE_SERVERCONSOLE_LOGIN_SUCCESS;
+      }
+      return resp;
+    }
+
+
+    public ResponseList<ClientDto> GetAllClients() {
+      secMan.Authorize("AccessClients", sessionID, Guid.Empty);
+      return clientManager.GetAllClients();
+    }
+
+    public ResponseList<ClientGroupDto> GetAllClientGroups() {
+      //secMan.Authorize("AccessClientGroup", sessionID, Guid.Empty);
+      return clientManager.GetAllClientGroups();
+    }
+
+    public ResponseList<UpTimeStatisticsDto> GetAllUpTimeStatistics() {
+      secMan.Authorize("AccessStatistics", sessionID, Guid.Empty);
+      return clientManager.GetAllUpTimeStatistics();
+    }
+
+    public ResponseObject<ClientGroupDto> AddClientGroup(ClientGroupDto clientGroup) {
+      secMan.Authorize("AddClientGroup", sessionID, Guid.Empty);
+      return clientManager.AddClientGroup(clientGroup);
+    }
+
+    public Response AddResourceToGroup(Guid clientGroupId, ResourceDto resource) {
+      secMan.Authorize("AddResource", sessionID, Guid.Empty);                
+      return clientManager.AddResourceToGroup(clientGroupId, resource);
+    }
+
+    public Response DeleteResourceFromGroup(Guid clientGroupId, Guid resourceId) {
+        return clientManager.DeleteResourceFromGroup(clientGroupId, resourceId);
+    }
+
+    public ResponseList<JobDto> GetAllJobs() {
+      secMan.Authorize("AccessJobs", sessionID, Guid.Empty);
+      return jobManager.GetAllJobs();
+    }
+
+    public ResponseList<JobDto> GetAllJobsWithFilter(State jobState, int offset, int count) {
+      secMan.Authorize("AccessJobs", sessionID, Guid.Empty);
+      return jobManager.GetAllJobsWithFilter(jobState, offset, count);
+    }
+
+    public ResponseObject<JobDto> GetJobById(Guid jobId) {
+      secMan.Authorize("AccessJobs", sessionID, jobId);
+      return jobManager.GetJobById(jobId);
+    }
+
+    public ResponseObject<JobDto> GetJobByIdWithDetails(Guid jobId) {
+      secMan.Authorize("AccessJobs", sessionID, jobId);
+      return jobManager.GetJobByIdWithDetails(jobId);
+    }
+
+    public ResponseObject<JobDto> AddNewJob(SerializedJob job) {
+      secMan.Authorize("AddJob", sessionID, job.JobInfo.Id);
+      return jobManager.AddNewJob(job);
+    }
+
+    public ResponseObject<JobDto> GetLastJobResultOf(Guid jobId) {
+      secMan.Authorize("AccessJobResults", sessionID, jobId);
+      return jobManager.GetLastJobResultOf(jobId);
+    }
+
+    public ResponseObject<SerializedJob> GetLastSerializedJobResultOf(Guid jobId, bool requested, bool snapshot) {
+      secMan.Authorize("AccessJobResults", sessionID, jobId);
+      return jobManager.GetLastSerializedJobResultOf(jobId, requested, snapshot);
+    }
+
+    public ResponseList<JobResult> GetAllJobResults(Guid jobId) {
+      secMan.Authorize("AccessJobResults", sessionID, jobId);  
+      return jobManager.GetAllJobResults(jobId);
+    }
+
+    public Response RemoveJob(Guid jobId) {
+      secMan.Authorize("RemoveJob", sessionID, jobId);
+      return jobManager.RemoveJob(jobId);
+    }
+
+    public Response RequestSnapshot(Guid jobId) {
+      secMan.Authorize("AccessJobResults", sessionID, jobId);  
+      return jobManager.RequestSnapshot(jobId);
+    }
+
+    public Response AbortJob(Guid jobId) {
+      secMan.Authorize("AbortJob", sessionID, Guid.Empty);
+      return jobManager.AbortJob(jobId);
+    }
+
+    public ResponseObject<List<ClientGroupDto>> GetAllGroupsOfResource(Guid resourceId) {
+      secMan.Authorize("AccessUserGroup", sessionID, Guid.Empty);
+      return clientManager.GetAllGroupsOfResource(resourceId);
+    }
+
+    public Response DeleteClientGroup(Guid clientGroupId) {
+      secMan.Authorize("DeleteClientGroup", sessionID, Guid.Empty);
+      return clientManager.DeleteClientGroup(clientGroupId);
+    }
+
+    public ResponseList<ProjectDto> GetAllProjects() {
+      secMan.Authorize("AccessProjects", sessionID, Guid.Empty);
+      return jobManager.GetAllProjects();
+    }
+
+    public Response CreateProject(ProjectDto project) {
+      secMan.Authorize("CreateProjects", sessionID, Guid.Empty);
+      return jobManager.CreateProject(project);
+    }
+
+    public Response ChangeProject(ProjectDto project) {
+      secMan.Authorize("ChangeProjects", sessionID, Guid.Empty);
+      return jobManager.ChangeProject(project);
+    }
+
+    public Response DeleteProject(Guid projectId) {
+      secMan.Authorize("DeleteProjects", sessionID, projectId);
+      return jobManager.DeleteProject(projectId);
+    }
+
+    public ResponseList<JobDto> GetJobsByProject(Guid projectId) {
+      secMan.Authorize("AccessJobs", sessionID, Guid.Empty);
+      return jobManager.GetJobsByProject(projectId);
+    }
+
+    public ResponseList<AppointmentDto> GetUptimeCalendarForResource(Guid guid) {
+      return clientManager.GetUptimeCalendarForResource(guid);
+    }
+
+    public Response SetUptimeCalendarForResource(Guid guid, IEnumerable<AppointmentDto> appointments, bool isForced) {
+      return clientManager.SetUptimeCalendarForResource(guid, appointments, isForced);
+    }
+
+    public ResponseObject<JobDto> AddJobWithGroupStrings(SerializedJob job, IEnumerable<string> resources) {
+      return jobManager.AddJobWithGroupStrings(job, resources);
+    }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ServiceLocator.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ServiceLocator.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/ServiceLocator.cs	(revision 4061)
@@ -0,0 +1,157 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Linq;
+using HeuristicLab.Hive.Server.DataAccess;
+using HeuristicLab.PluginInfrastructure;
+using System.Runtime.CompilerServices;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Server.Core;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces;
+using HeuristicLab.DataAccess.Interfaces;
+using System.Data.SqlClient;
+using HeuristicLab.Security.Contracts.Interfaces;
+
+/// <summary>
+/// The service locator for the server core
+/// </summary>
+public class ServiceLocator {
+  private static IClientManager clientManager = null;
+
+  private static IJobManager jobManager = null;
+
+  private static IClientCommunicator clientCommunicator = null;
+
+  private static ILifecycleManager lifecycleManager = null;
+
+  private static ISessionFactory sessionFactory = null;
+
+  private static IScheduler scheduler = null;
+
+  private static IPermissionManager permManager = null;
+
+  private static IHivePermissionManager hivePermManager = null;
+
+  /// <summary>
+  /// Gets the client manager
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]
+  public static IClientManager GetClientManager() {
+    if (clientManager == null)
+      clientManager = new ClientManager();
+
+    return clientManager;
+  }
+
+  /// <summary>
+  /// Gets the job manager
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]
+  public static IJobManager GetJobManager() {
+    if (jobManager == null)
+      jobManager = new JobManager();
+
+    return jobManager;
+  }
+
+  /// <summary>
+  /// Gets the client Communicator
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]
+  public static IClientCommunicator GetClientCommunicator() {
+    if (clientCommunicator == null)
+      clientCommunicator = new ClientCommunicator();
+
+    return clientCommunicator;
+  }
+
+  /// <summary>
+  /// Gets the lifecycle manager
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]
+  public static ILifecycleManager GetLifecycleManager() {
+    if (lifecycleManager == null) {
+      lifecycleManager = new LifecycleManager();
+    }
+    return lifecycleManager;
+  }
+
+  /// <summary>
+  /// Gets the db session factory
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]
+  public static ISessionFactory GetSessionFactory() {
+    if (sessionFactory == null) {
+      sessionFactory = 
+        ApplicationManager.Manager.GetInstances<ISessionFactory>().First();
+
+      sessionFactory.DbConnectionType =
+        typeof(SqlConnection);
+      
+      sessionFactory.DbConnectionString =
+        HeuristicLab.Hive.Server.Core.Properties.Settings.Default.HiveServerConnectionString;
+    }
+
+    return sessionFactory;
+  }
+
+  /// <summary>
+  /// Gets the scheduler
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]
+  public static IScheduler GetScheduler() {
+    if (scheduler == null) {
+      scheduler = ApplicationManager.Manager.GetInstances<IScheduler>().First();
+    }
+
+    return scheduler;
+  }
+
+  /// <summary>
+  /// Gets the permission manager
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]  
+  public static IPermissionManager GetPermissionManager() {
+    if (permManager == null)
+      permManager = ApplicationManager.Manager.GetInstances<IPermissionManager>().First();
+    return permManager;
+    
+  }
+
+  /// <summary>
+  /// Gets the permission manager
+  /// </summary>
+  /// <returns></returns>
+  [MethodImpl(MethodImplOptions.Synchronized)]
+  public static IHivePermissionManager GetHivePermissionManager() {
+    if (hivePermManager == null)
+      hivePermManager = ApplicationManager.Manager.GetInstances<IHivePermissionManager>().First();
+    return hivePermManager;
+
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Settings.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Settings.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/Settings.cs	(revision 4061)
@@ -0,0 +1,28 @@
+﻿namespace HeuristicLab.Hive.Server.Core.Properties {
+    
+    
+    // This class allows you to handle specific events on the settings class:
+    //  The SettingChanging event is raised before a setting's value is changed.
+    //  The PropertyChanged event is raised after a setting's value is changed.
+    //  The SettingsLoaded event is raised after the setting values are loaded.
+    //  The SettingsSaving event is raised before the setting values are saved.
+    public sealed partial class Settings {
+        
+        public Settings() {
+            // // To add event handlers for saving and changing settings, uncomment the lines below:
+            //
+            // this.SettingChanging += this.SettingChangingEventHandler;
+            //
+            // this.SettingsSaving += this.SettingsSavingEventHandler;
+            //
+        }
+        
+        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
+            // Add code to handle the SettingChangingEvent event here.
+        }
+        
+        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
+            // Add code to handle the SettingsSaving event here.
+        }
+    }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/SpringTransaction.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/SpringTransaction.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/SpringTransaction.cs	(revision 4061)
@@ -0,0 +1,11 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace HeuristicLab.Hive.Server.Core {
+  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
+  public class SpringTransaction : System.Attribute{
+    public Boolean UserTransaction { get; set; }
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/UserRoleManager.cs
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/UserRoleManager.cs	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/UserRoleManager.cs	(revision 4061)
@@ -0,0 +1,259 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Hive.Contracts.Interfaces;
+using HeuristicLab.Hive.Contracts.BusinessObjects;
+using HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess;
+using System.Resources;
+using System.Reflection;
+using HeuristicLab.Hive.Contracts;
+
+namespace HeuristicLab.Hive.Server.Core {
+  class UserRoleManager: IUserRoleManager {
+
+    IUserAdapter userAdapter;
+    IUserGroupAdapter userGroupAdapter;
+    IPermissionOwnerAdapter permissionOwnerAdapter;
+
+    public UserRoleManager() {
+      userAdapter = ServiceLocator.GetUserAdapter();
+      userGroupAdapter = ServiceLocator.GetUserGroupAdapter();
+    }
+
+    #region IUserRoleManager Members
+
+    /// <summary>
+    /// returns all users from the database
+    /// </summary>
+    /// <returns></returns>
+    public ResponseList<User> GetAllUsers() {
+      ResponseList<User> response = new ResponseList<User>();
+
+      List<User> allUsers = new List<User>(userAdapter.GetAll());
+      response.List = allUsers;
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_GET_ALL_USERS;
+
+      return response;
+    }
+
+    /// <summary>
+    /// Adds a new user to the database
+    /// </summary>
+    /// <param name="user"></param>
+    /// <returns></returns>
+    public ResponseObject<User> AddNewUser(User user) {
+      ResponseObject<User> response = new ResponseObject<User>();
+
+      if (user.Id != 0) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_ID_MUST_NOT_BE_SET;
+        return response;
+      }
+      if (userAdapter.GetByName(user.Name) != null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERNAME_EXISTS_ALLREADY;
+        return response;
+      }
+
+      userAdapter.Update(user);
+      response.Obj = user;
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USER_SUCCESSFULLY_ADDED;
+      
+      return response;
+    }
+
+    /// <summary>
+    /// returns all usergroups from the database
+    /// </summary>
+    /// <returns></returns>
+    public ResponseList<UserGroup> GetAllUserGroups() {
+      ResponseList<UserGroup> response = new ResponseList<UserGroup>();
+
+      response.List = new List<UserGroup>(userGroupAdapter.GetAll());
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_GET_ALL_USERGROUPS;
+
+      return response;
+    }
+
+    /// <summary>
+    /// Removes a user from the database
+    /// </summary>
+    /// <param name="userId"></param>
+    /// <returns></returns>
+    public Response RemoveUser(long userId) {
+      Response response = new Response();
+      User user = userAdapter.GetById(userId);
+      if (user == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USER_DOESNT_EXIST;
+        return response;
+      }
+      userAdapter.Delete(user);
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USER_REMOVED;
+                         
+      return response;
+    }
+
+    /// <summary>
+    /// Adds a new usergroup to the database
+    /// </summary>
+    /// <param name="userGroup"></param>
+    /// <returns></returns>
+    public ResponseObject<UserGroup> AddNewUserGroup(UserGroup userGroup) {
+      ResponseObject<UserGroup> response = new ResponseObject<UserGroup>();
+      
+      if (userGroup.Id != 0) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_ID_MUST_NOT_BE_SET;
+        return response;
+      }
+
+      userGroupAdapter.Update(userGroup);
+      response.Obj = userGroup;
+      response.Success = false;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERGROUP_ADDED;
+
+      return response;
+    }
+
+    /// <summary>
+    /// Removes a user group from the database
+    /// </summary>
+    /// <param name="groupId"></param>
+    /// <returns></returns>
+    public Response RemoveUserGroup(long groupId) {
+      Response response = new Response();
+
+      UserGroup userGroupFromDb = userGroupAdapter.GetById(groupId);
+      if (userGroupFromDb == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERGROUP_DOESNT_EXIST;
+        return response;
+      }
+      userGroupAdapter.Delete(userGroupFromDb);
+      response.Success = false;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERGROUP_ADDED;
+
+      return response;
+    }
+
+    /// <summary>
+    /// Adds a user into a user group
+    /// </summary>
+    /// <param name="groupId"></param>
+    /// <param name="userId"></param>
+    /// <returns></returns>
+    public Response AddUserToGroup(long groupId, long userId) {
+      Response response = new Response();
+
+      User user = userAdapter.GetById(userId);
+      if (user == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USER_DOESNT_EXIST;
+        return response;
+      }
+
+      UserGroup userGroup = userGroupAdapter.GetById(groupId);
+      if (userGroup == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERGROUP_DOESNT_EXIST;
+        return response;
+      }
+      userGroup.Members.Add(user);
+      userGroupAdapter.Update(userGroup);
+
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_PERMISSIONOWNER_ADDED;
+
+      return response;
+    }
+
+    /// <summary>
+    /// Adds a user group to a user group
+    /// </summary>
+    /// <param name="groupId"></param>
+    /// <param name="groupToAddId"></param>
+    /// <returns></returns>
+    public Response AddUserGroupToGroup(long groupId, long groupToAddId) {
+      Response response = new Response();
+
+      UserGroup userGroup = userGroupAdapter.GetById(groupId);
+      UserGroup userGroupToAdd = userGroupAdapter.GetById(groupToAddId);
+
+      if (userGroup == null || userGroupToAdd == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERGROUP_DOESNT_EXIST;
+        return response;
+      }
+      userGroup.Members.Add(userGroupToAdd);
+      response.Success = true;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERGROUP_ADDED_TO_USERGROUP;
+
+      return response;
+    }
+
+    /// <summary>
+    /// Removes a permission owner (user, user group) from a user group
+    /// </summary>
+    /// <param name="groupId"></param>
+    /// <param name="permissionOwnerId"></param>
+    /// <returns></returns>
+    public Response RemovePermissionOwnerFromGroup(long groupId, long permissionOwnerId) {
+      Response response = new Response();
+
+      UserGroup userGroup = userGroupAdapter.GetById(groupId);
+      if (userGroup == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_USERGROUP_DOESNT_EXIST;
+        return response;
+      }
+      User user = userAdapter.GetById(permissionOwnerId);
+      if (user == null) {
+        response.Success = false;
+        response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_PERMISSIONOWNER_DOESNT_EXIST;
+        return response;
+      }
+      foreach (PermissionOwner permissionOwner in userGroup.Members) {
+        if (permissionOwner.Id == permissionOwnerId) {
+          userGroup.Members.Remove(permissionOwner);
+          userGroupAdapter.Update(userGroup);
+          response.Success = true;
+          response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_PERMISSIONOWNER_REMOVED;
+          return response;
+        }
+      }
+      response.Success = false;
+      response.StatusMessage = ApplicationConstants.RESPONSE_USERROLE_PERMISSIONOWNER_DOESNT_EXIST;
+      
+      return response;
+    }
+
+    #endregion
+  }
+}
Index: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/app.config
===================================================================
--- branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/app.config	(revision 4061)
+++ branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive 3.3/HeuristicLab.Hive.Server.Core/3.3/app.config	(revision 4061)
@@ -0,0 +1,44 @@
+﻿<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+  <configSections>  
+    <sectionGroup name="spring">
+      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
+      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
+    </sectionGroup>    
+    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
+      <section name="HeuristicLab.Hive.Server.Core.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
+    </sectionGroup>
+  </configSections>
+  <applicationSettings>
+    <HeuristicLab.Hive.Server.Core.Properties.Settings>
+      <setting name="HiveServerConnectionString" serializeAs="String">
+        <value>Data Source=127.0.0.1;Initial Catalog=HeuristicLab.Hive;Persist Security Info=True;User ID=hive;Password=hive;Pooling=true;MultipleActiveResultSets=true</value>
+      </setting>
+    </HeuristicLab.Hive.Server.Core.Properties.Settings>
+  </applicationSettings>
+  <spring>
+    <context>
+      <resource uri="config://spring/objects"/>
+    </context>
+    
+    <objects xmlns="http://www.springframework.net"
+         xmlns:aop="http://www.springframework.net/aop">
+      <object id="calculator" singleton="false"
+              type="HeuristicLab.Hive.Server.Core.ClientFacade, HeuristicLab.Hive.Server.Core-3.2" />
+
+      <object id="serviceOperation" type="Spring.Aop.Support.SdkRegularExpressionMethodPointcut, Spring.Aop">
+        <property name="patterns">
+          <list>
+            <value>HeuristicLab.Hive.Server.Core.ClientFacade.*</value>
+          </list>
+        </property>
+      </object>
+
+      <object id="sci" type="HeuristicLab.Hive.Server.ServiceCallInterception, HeuristicLab.Hive.Server-3.2" />
+
+      <aop:config>
+        <aop:advisor pointcut-ref="serviceOperation" advice-ref="sci"/>
+      </aop:config>
+    </objects>
+  </spring>
+</configuration>
