Index: /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/Settings.Designer.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/Settings.Designer.cs	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/Settings.Designer.cs	(revision 8326)
@@ -52,4 +52,14 @@
             }
         }
+        
+        [global::System.Configuration.ApplicationScopedSettingAttribute()]
+        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+        [global::System.Configuration.DefaultSettingValueAttribute("HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionSt" +
+            "ring")]
+        public string HiveConnectionStringName {
+            get {
+                return ((string)(this["HiveConnectionStringName"]));
+            }
+        }
     }
 }
Index: /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/Settings.settings
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/Settings.settings	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/Settings.settings	(revision 8326)
@@ -17,4 +17,7 @@
       <Value Profile="(Default)">HL.Hive</Value>
     </Setting>
+    <Setting Name="HiveConnectionStringName" Type="System.String" Scope="Application">
+      <Value Profile="(Default)">HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString</Value>
+    </Setting>
   </Settings>
 </SettingsFile>
Index: /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/TransactionManager.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/TransactionManager.cs	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/TransactionManager.cs	(revision 8326)
@@ -28,8 +28,8 @@
       int n = 10;
       while (n > 0) {
-        //TransactionScope transaction = CreateTransaction(serializable, longRunning);
+        TransactionScope transaction = CreateTransaction(serializable, longRunning);
         try {
           call();
-          //transaction.Complete();
+          transaction.Complete();
           n = 0;
         }
@@ -40,5 +40,5 @@
         }
         finally {
-          //transaction.Dispose();
+          transaction.Dispose();
         }
       }
@@ -48,8 +48,8 @@
       int n = 10;
       while (n > 0) {
-        //TransactionScope transaction = CreateTransaction(serializable, longRunning);
+        TransactionScope transaction = CreateTransaction(serializable, longRunning);
         try {
           T result = call();
-          //transaction.Complete();
+          transaction.Complete();
           n = 0;
           return result;
@@ -61,5 +61,5 @@
         }
         finally {
-          //transaction.Dispose();
+          transaction.Dispose();
         }
       }
Index: /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/app.config
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/app.config	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive.DataAccess/3.3/app.config	(revision 8326)
@@ -8,5 +8,5 @@
   <connectionStrings>
     <add name="HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString"
-      connectionString="Data Source=localhost;Initial Catalog=HeuristicLab.Hive-3.3;Integrated Security=True;"
+        connectionString="Data Source=localhost;Initial Catalog=HeuristicLab.Hive-3.3;Integrated Security=True;"      
       providerName="System.Data.SqlClient" />
   </connectionStrings>
@@ -19,4 +19,7 @@
         <value>HL.Hive</value>
       </setting>
+      <setting name="HiveConnectionStringName" serializeAs="String">
+        <value>HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString</value>
+      </setting>
     </HeuristicLab.Services.Hive.DataAccess.Settings>
   </applicationSettings>
Index: /branches/OaaS/HeuristicLab.Services.Hive.WebRole/Web.config
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive.WebRole/Web.config	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive.WebRole/Web.config	(revision 8326)
@@ -23,5 +23,5 @@
     <add name="HeuristicLab.Authentication" connectionString="Server=tcp:pok6rtjc5c.database.windows.net,1433;Database=HeuristicLab.Authentication;User ID=cloudia@pok6rtjc5c;Password=d1fFntitafvX;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"/>
     <!-- <add name="HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HeuristicLab.Hive-3.3;Integrated Security=True;" providerName="System.Data.SqlClient" /> -->
-    <add name="HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString" connectionString="Server=tcp:pok6rtjc5c.database.windows.net,1433;Database=HeuristicLab.Hive-3.3;User ID=cloudia@pok6rtjc5c;Password=d1fFntitafvX;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
+    <add name="HeuristicLab.Services.Hive.DataAccess.Settings.HeuristicLab_Hive_LinqConnectionString" connectionString="Server=tcp:pok6rtjc5c.database.windows.net,1433;Database=HeuristicLab.Hive-3.3;User ID=cloudia@pok6rtjc5c;Password=d1fFntitafvX;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;Enlist=false;" providerName="System.Data.SqlClient" />
   </connectionStrings>
   <!--  To collect diagnostic traces, uncomment the section below or merge with existing system.diagnostics section.
Index: /branches/OaaS/HeuristicLab.Services.Hive/3.3/ConnectionProvider.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive/3.3/ConnectionProvider.cs	(revision 8326)
+++ /branches/OaaS/HeuristicLab.Services.Hive/3.3/ConnectionProvider.cs	(revision 8326)
@@ -0,0 +1,181 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2012 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.Services.Hive.Interfaces;
+using System.Configuration;
+using System.Data.Common;
+using System.ServiceModel;
+using System.Transactions;
+
+namespace HeuristicLab.Services.Hive {
+  public class ConnectionProvider : IConnectionProvider {
+    public System.Data.Common.DbConnection GetOpenConnection(string connectionStringName) {
+      ConnectionStringSettings connSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
+      DbProviderFactory dbProvFact = DbProviderFactories.GetFactory(connSettings.ProviderName);
+      return ConnectionUtilsStorage.Current.GetOpenConnection(dbProvFact, connSettings.ConnectionString);
+    }
+
+
+    public void ReleaseConnection(DbConnection connection) {
+      ConnectionUtilsStorage.Current.ReleaseConnection(connection);
+    }
+  }
+
+  /// <summary>
+  /// Based on the connection management developed by jheinzelreiter,
+  /// this class stores transactions + connections, closing connections
+  /// after a transaction has been closed.
+  /// A non-transacted connection might be closed by the user by calling
+  /// ReleaseConnection(connection).
+  /// </summary>
+  class ConnectionUtilsStorage : IExtension<OperationContext> {
+    private readonly IDictionary<Transaction, IDictionary<string, DbConnection>>
+      transactedConnections = new Dictionary<Transaction, IDictionary<string, DbConnection>>();
+
+    /// <summary>
+    /// Returns an opened DbConnection. If a transaction is present, for
+    /// each unique connection string the same connection is returned.
+    /// </summary>
+    /// <param name="providerFactory">DbProviderFactory, which should be used to create 
+    /// connection</param>
+    /// <param name="connectionString">connection string of the connection</param>
+    /// <returns>A <see cref="DbConnection"/> instance</returns>
+    public DbConnection GetOpenConnection(DbProviderFactory providerFactory, string connectionString) {
+      DbConnection connection = null;
+      Transaction currentTransaction = Transaction.Current;
+      if (currentTransaction == null) {
+        // no transaction context -> return "ordinary" connection
+        connection = CreateOpenConnection(providerFactory, connectionString);
+      }
+      else {
+        // transaction present
+        IDictionary<string, DbConnection> connections = null;
+        lock (transactedConnections) {
+          // check if current transaction already has at least one connection assigned
+          if (!transactedConnections.TryGetValue(currentTransaction, out connections)) {
+            connections = new Dictionary<string, DbConnection>();
+            transactedConnections[currentTransaction] = connections;
+          }
+
+          if (!connections.TryGetValue(connectionString, out connection)) {
+            // no connection for this connection string in the current transaction
+            connection = CreateOpenConnection(providerFactory, connectionString);
+
+            connections[connectionString] = connection;
+            currentTransaction.TransactionCompleted +=
+              new TransactionCompletedEventHandler(OnTransactionCompleted);
+          }
+        }
+      }
+      return connection;
+    }
+
+    /// <summary>
+    /// Creates a new, opened DbConnection
+    /// </summary>
+    /// <param name="connectionString">connection string of the connection</param>
+    /// <param name="providerFactory">DbProviderFactory, which should be used to create 
+    /// connection</param>
+    /// <returns>A <see cref="DbConnection"/> instance </returns>
+    private DbConnection CreateOpenConnection(DbProviderFactory providerFactory,
+                                                     string connectionString) {
+      DbConnection connection = providerFactory.CreateConnection();
+      connection.ConnectionString = connectionString;
+      connection.Open();
+      return connection;
+    }
+
+    /// <summary>
+    /// Releases a connection. 
+    /// (Remark: The connection is closed only when not used in a transaction)
+    /// </summary>
+    /// <param name="connection">connection to release</param>
+    public void ReleaseConnection(DbConnection connection) {
+      if (connection == null)
+        return;
+
+      Transaction currentTransaction = Transaction.Current;
+      // close connection if no transaction is active
+      if (currentTransaction == null)
+        connection.Close();
+    }
+
+    /// <summary>
+    /// Determines, if custom connection handling code should close a connection.
+    /// (Remark: Used for DataReader.CommandBehavior)
+    /// </summary>
+    /// <returns></returns>
+    public bool ShouldCloseConnection() {
+      return Transaction.Current == null;
+    }
+
+    /// <summary>
+    /// Eventhandler for TransactionScope.TransactionCompleted.
+    /// Closes connections and removes transaction from observed connections.
+    /// </summary>
+    /// <param name="sender">sender</param>
+    /// <param name="e">TransactionEventArgs</param>
+    private void OnTransactionCompleted(object sender, TransactionEventArgs e) {
+      lock (transactedConnections) {
+        IDictionary<string, DbConnection> connections = null;
+        if (transactedConnections.TryGetValue(e.Transaction, out connections)) {
+          foreach (DbConnection conn in connections.Values)
+            conn.Close();
+          transactedConnections.Remove(e.Transaction);
+        }
+      }
+    }
+    private static object monitor = new object();
+    private static ConnectionUtilsStorage _context = new ConnectionUtilsStorage();
+
+    public static ConnectionUtilsStorage Current {
+      get {
+        ConnectionUtilsStorage context;
+        if (OperationContext.Current != null) {
+          context = OperationContext.Current.Extensions.Find<ConnectionUtilsStorage>();
+          if (context == null) {
+            lock (monitor) {
+              context = OperationContext.Current.Extensions.Find<ConnectionUtilsStorage>();
+              if (context == null) {
+                context = new ConnectionUtilsStorage();
+                OperationContext.Current.Extensions.Add(context);
+              }
+            }
+          }
+        }
+        else {
+          context = _context;
+        }
+        return context;
+      }
+    }
+
+    public void Attach(OperationContext owner) {
+    }
+
+    public void Detach(OperationContext owner) {
+    }
+  }
+}
Index: /branches/OaaS/HeuristicLab.Services.Hive/3.3/HeuristicLab.Services.Hive-3.3.csproj
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive/3.3/HeuristicLab.Services.Hive-3.3.csproj	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive/3.3/HeuristicLab.Services.Hive-3.3.csproj	(revision 8326)
@@ -97,4 +97,5 @@
     </Reference>
     <Reference Include="System" />
+    <Reference Include="System.configuration" />
     <Reference Include="System.Core" />
     <Reference Include="System.Data.Linq" />
@@ -112,4 +113,5 @@
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="ConnectionProvider.cs" />
     <Compile Include="Convert.cs" />
     <Compile Include="DataTransfer\Command.cs" />
@@ -138,4 +140,5 @@
     <Compile Include="HiveDao.cs" />
     <Compile Include="HiveJanitor.cs" />
+    <Compile Include="Interfaces\IConnectionProvider.cs" />
     <Compile Include="Interfaces\IHiveDao.cs" />
     <Compile Include="Settings.cs" />
Index: /branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveDao.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveDao.cs	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveDao.cs	(revision 8326)
@@ -25,30 +25,67 @@
 using System.Linq.Expressions;
 using DT = HeuristicLab.Services.Hive.DataTransfer;
+using System.ServiceModel;
+using HeuristicLab.Services.Hive.Interfaces;
+using System.Data.Common;
 
 namespace HeuristicLab.Services.Hive.DataAccess {
   public class HiveDao : IHiveDao {
-    public static HiveDataContext CreateContext(bool longRunning = false) {
-      var context = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
+    
+    public HiveDataContext CreateContext(bool longRunning = false) {
+      //var context = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
+      var context = new HiveDataContext(provider.GetOpenConnection(Settings.Default.HiveConnectionStringName));      
       if (longRunning) context.CommandTimeout = (int)Settings.Default.LongRunningDatabaseCommandTimeout.TotalSeconds;
       return context;
     }
 
-    public HiveDao() { }
+    private IConnectionProvider provider;
+
+    public HiveDao(IConnectionProvider provider) { this.provider = provider; }
+
+    private delegate T ExecuteWithContextDelegate<T>(HiveDataContext context);
+    private delegate void ExecuteWithContextDelegate(HiveDataContext context);
+
+    private void ExecuteWithContext(ExecuteWithContextDelegate call) {
+      DbConnection con = null;
+      try {
+        using (var db = CreateContext()) {
+          con = db.Connection;
+          call(db);
+        }
+      }
+      finally {
+        provider.ReleaseConnection(con);
+      }
+    }
+
+    private T ExecuteWithContext<T>(ExecuteWithContextDelegate<T> call) {
+      DbConnection con = null;
+      try {
+        using (var db = CreateContext()) {
+          con = db.Connection;
+          T result = call(db);
+          return result;
+        }
+      }
+      finally {
+        provider.ReleaseConnection(con);
+      }
+    }
 
     #region Task Methods
     public DT.Task GetTask(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Task>((db) => {
         return DT.Convert.ToDto(db.Tasks.SingleOrDefault(x => x.TaskId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.Task> GetTasks(Expression<Func<Task, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
         return db.Tasks.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddTask(DT.Task dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.Tasks.InsertOnSubmit(entity);
@@ -59,9 +96,9 @@
         db.SubmitChanges();
         return entity.TaskId;
-      }
+      });
     }
 
     public void UpdateTask(DT.Task dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Tasks.FirstOrDefault(x => x.TaskId == dto.Id);
         if (entity == null) db.Tasks.InsertOnSubmit(DT.Convert.ToEntity(dto));
@@ -73,13 +110,13 @@
         }
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteTask(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Tasks.FirstOrDefault(x => x.TaskId == id);
         if (entity != null) db.Tasks.DeleteOnSubmit(entity);
         db.SubmitChanges(); // taskData and child tasks are deleted by db-trigger
-      }
+      });
     }
 
@@ -92,5 +129,5 @@
     /// <returns></returns>
     public IEnumerable<DT.Task> GetParentTasks(IEnumerable<Guid> resourceIds, int count, bool finished) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
         var query = from ar in db.AssignedResources
                     where resourceIds.Contains(ar.ResourceId)
@@ -109,9 +146,9 @@
                     select DT.Convert.ToDto(ar.Task);
         return count == 0 ? query.ToArray() : query.Take(count).ToArray();
-      }
+      });
     }
 
     public IEnumerable<DT.Task> GetWaitingTasks(DT.Slave slave, int count) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
         var resourceIds = GetParentResources(slave.Id).Select(r => r.Id);
         //Originally we checked here if there are parent tasks which should be calculated (with GetParentTasks(resourceIds, count, false);).
@@ -129,9 +166,9 @@
         var waitingTasks = (count == 0 ? query : query.Take(count)).ToArray();
         return waitingTasks;
-      }
+      });
     }
 
     public DT.Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Task>((db) => {
         var job = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
         job.State = taskState;
@@ -147,5 +184,5 @@
         job = db.Tasks.SingleOrDefault(x => x.TaskId == taskId);
         return DT.Convert.ToDto(job);
-      }
+      });
     }
     #endregion
@@ -153,39 +190,39 @@
     #region TaskData Methods
     public DT.TaskData GetTaskData(Guid id) {
-      using (var db = CreateContext(true)) {
+      return ExecuteWithContext<DT.TaskData>((db) => {
         return DT.Convert.ToDto(db.TaskDatas.SingleOrDefault(x => x.TaskId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.TaskData> GetTaskDatas(Expression<Func<TaskData, bool>> predicate) {
-      using (var db = CreateContext(true)) {
+      return ExecuteWithContext<IEnumerable<DT.TaskData>>((db) => {
         return db.TaskDatas.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddTaskData(DT.TaskData dto) {
-      using (var db = CreateContext(true)) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.TaskDatas.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.TaskId;
-      }
+      });
     }
 
     public void UpdateTaskData(DT.TaskData dto) {
-      using (var db = CreateContext(true)) {
+      ExecuteWithContext((db) => {
         var entity = db.TaskDatas.FirstOrDefault(x => x.TaskId == dto.TaskId);
         if (entity == null) db.TaskDatas.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteTaskData(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.TaskDatas.FirstOrDefault(x => x.TaskId == id); // check if all the byte[] is loaded into memory here. otherwise work around to delete without loading it
         if (entity != null) db.TaskDatas.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -193,39 +230,39 @@
     #region StateLog Methods
     public DT.StateLog GetStateLog(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.StateLog>((db) => {
         return DT.Convert.ToDto(db.StateLogs.SingleOrDefault(x => x.StateLogId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.StateLog> GetStateLogs(Expression<Func<StateLog, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.StateLog>>((db) => {
         return db.StateLogs.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddStateLog(DT.StateLog dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.StateLogs.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.StateLogId;
-      }
+      });
     }
 
     public void UpdateStateLog(DT.StateLog dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.StateLogs.FirstOrDefault(x => x.StateLogId == dto.Id);
         if (entity == null) db.StateLogs.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteStateLog(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.StateLogs.FirstOrDefault(x => x.StateLogId == id);
         if (entity != null) db.StateLogs.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -233,7 +270,7 @@
     #region Job Methods
     public DT.Job GetJob(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Job>((db) => {
         return AddStatsToJob(db, DT.Convert.ToDto(db.Jobs.SingleOrDefault(x => x.JobId == id)));
-      }
+      });
     }
 
@@ -250,33 +287,33 @@
 
     public IEnumerable<DT.Job> GetJobs(Expression<Func<Job, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Job>>((db) => {
         return db.Jobs.Where(predicate).Select(x => AddStatsToJob(db, DT.Convert.ToDto(x))).ToArray();
-      }
+      });
     }
 
     public Guid AddJob(DT.Job dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.Jobs.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.JobId;
-      }
+      });
     }
 
     public void UpdateJob(DT.Job dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Jobs.FirstOrDefault(x => x.JobId == dto.Id);
         if (entity == null) db.Jobs.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteJob(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Jobs.FirstOrDefault(x => x.JobId == id);
         if (entity != null) db.Jobs.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -284,38 +321,38 @@
     #region JobPermission Methods
     public DT.JobPermission GetJobPermission(Guid jobId, Guid grantedUserId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.JobPermission>((db) => {
         return DT.Convert.ToDto(db.JobPermissions.SingleOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId));
-      }
+      });
     }
 
     public IEnumerable<DT.JobPermission> GetJobPermissions(Expression<Func<JobPermission, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.JobPermission>>((db) => {
         return db.JobPermissions.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public void AddJobPermission(DT.JobPermission dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.JobPermissions.InsertOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void UpdateJobPermission(DT.JobPermission dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.JobPermissions.FirstOrDefault(x => x.JobId == dto.JobId && x.GrantedUserId == dto.GrantedUserId);
         if (entity == null) db.JobPermissions.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteJobPermission(Guid jobId, Guid grantedUserId) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.JobPermissions.FirstOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId);
         if (entity != null) db.JobPermissions.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
 
@@ -324,5 +361,5 @@
     /// </summary>
     public void SetJobPermission(Guid jobId, Guid grantedByUserId, Guid grantedUserId, Permission permission) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         JobPermission jobPermission = db.JobPermissions.SingleOrDefault(x => x.JobId == jobId && x.GrantedUserId == grantedUserId);
         if (jobPermission != null) {
@@ -330,10 +367,12 @@
             // not allowed, delete
             db.JobPermissions.DeleteOnSubmit(jobPermission);
-          } else {
+          }
+          else {
             // update
             jobPermission.Permission = permission;
             jobPermission.GrantedByUserId = grantedByUserId; // update grantedByUserId, always the last "granter" is stored
           }
-        } else {
+        }
+        else {
           // insert
           if (permission != Permission.NotAllowed) {
@@ -343,5 +382,5 @@
         }
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -349,39 +388,39 @@
     #region Plugin Methods
     public DT.Plugin GetPlugin(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Plugin>((db) => {
         return DT.Convert.ToDto(db.Plugins.SingleOrDefault(x => x.PluginId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.Plugin> GetPlugins(Expression<Func<Plugin, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Plugin>>((db) => {
         return db.Plugins.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddPlugin(DT.Plugin dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.Plugins.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.PluginId;
-      }
+      });
     }
 
     public void UpdatePlugin(DT.Plugin dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Plugins.FirstOrDefault(x => x.PluginId == dto.Id);
         if (entity == null) db.Plugins.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeletePlugin(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Plugins.FirstOrDefault(x => x.PluginId == id);
         if (entity != null) db.Plugins.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -389,39 +428,39 @@
     #region PluginData Methods
     public DT.PluginData GetPluginData(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.PluginData>((db) => {
         return DT.Convert.ToDto(db.PluginDatas.SingleOrDefault(x => x.PluginDataId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.PluginData> GetPluginDatas(Expression<Func<PluginData, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext <IEnumerable<DT.PluginData>>((db) => {
         return db.PluginDatas.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddPluginData(DT.PluginData dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.PluginDatas.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.PluginDataId;
-      }
+      });
     }
 
     public void UpdatePluginData(DT.PluginData dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.PluginDatas.FirstOrDefault(x => x.PluginId == dto.PluginId);
         if (entity == null) db.PluginDatas.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeletePluginData(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.PluginDatas.FirstOrDefault(x => x.PluginDataId == id);
         if (entity != null) db.PluginDatas.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -429,39 +468,39 @@
     #region Slave Methods
     public DT.Slave GetSlave(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Slave>((db) => {
         return DT.Convert.ToDto(db.Resources.OfType<Slave>().SingleOrDefault(x => x.ResourceId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.Slave> GetSlaves(Expression<Func<Slave, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Slave>>((db) => {
         return db.Resources.OfType<Slave>().Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddSlave(DT.Slave dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.Resources.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.ResourceId;
-      }
+      });
     }
 
     public void UpdateSlave(DT.Slave dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Resources.OfType<Slave>().FirstOrDefault(x => x.ResourceId == dto.Id);
         if (entity == null) db.Resources.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteSlave(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Resources.OfType<Slave>().FirstOrDefault(x => x.ResourceId == id);
         if (entity != null) db.Resources.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -469,17 +508,17 @@
     #region SlaveGroup Methods
     public DT.SlaveGroup GetSlaveGroup(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.SlaveGroup>((db) => {
         return DT.Convert.ToDto(db.Resources.OfType<SlaveGroup>().SingleOrDefault(x => x.ResourceId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.SlaveGroup> GetSlaveGroups(Expression<Func<SlaveGroup, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.SlaveGroup>>((db) => {
         return db.Resources.OfType<SlaveGroup>().Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddSlaveGroup(DT.SlaveGroup dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         if (dto.Id == Guid.Empty)
           dto.Id = Guid.NewGuid();
@@ -488,18 +527,18 @@
         db.SubmitChanges();
         return entity.ResourceId;
-      }
+      });
     }
 
     public void UpdateSlaveGroup(DT.SlaveGroup dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Resources.OfType<SlaveGroup>().FirstOrDefault(x => x.ResourceId == dto.Id);
         if (entity == null) db.Resources.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteSlaveGroup(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Resources.OfType<SlaveGroup>().FirstOrDefault(x => x.ResourceId == id);
         if (entity != null) {
@@ -510,5 +549,5 @@
         }
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -516,54 +555,54 @@
     #region Resource Methods
     public DT.Resource GetResource(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Resource>((db) => {
         return DT.Convert.ToDto(db.Resources.SingleOrDefault(x => x.ResourceId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.Resource> GetResources(Expression<Func<Resource, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
         return db.Resources.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddResource(DT.Resource dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.Resources.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.ResourceId;
-      }
+      });
     }
 
     public void UpdateResource(DT.Resource dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Resources.FirstOrDefault(x => x.ResourceId == dto.Id);
         if (entity == null) db.Resources.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteResource(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Resources.FirstOrDefault(x => x.ResourceId == id);
         if (entity != null) db.Resources.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void AssignJobToResource(Guid jobId, Guid resourceId) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var job = db.Tasks.Where(x => x.TaskId == jobId).Single();
         job.AssignedResources.Add(new AssignedResource() { TaskId = jobId, ResourceId = resourceId });
         db.SubmitChanges();
-      }
+      });
     }
 
     public IEnumerable<DT.Resource> GetAssignedResources(Guid jobId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext <IEnumerable<DT.Resource>>((db) => {
         var job = db.Tasks.Where(x => x.TaskId == jobId).Single();
         return job.AssignedResources.Select(x => DT.Convert.ToDto(x.Resource)).ToArray();
-      }
+      });
     }
 
@@ -572,9 +611,9 @@
     /// </summary>
     public IEnumerable<DT.Resource> GetParentResources(Guid resourceId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
         var resources = new List<Resource>();
         CollectParentResources(resources, db.Resources.Where(r => r.ResourceId == resourceId).Single());
         return resources.Select(r => DT.Convert.ToDto(r)).ToArray();
-      }
+      });
     }
 
@@ -589,5 +628,5 @@
     /// </summary>
     public IEnumerable<DT.Resource> GetChildResources(Guid resourceId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Resource>>((db) => {
         var childs = new List<DT.Resource>();
         foreach (var child in db.Resources.Where(x => x.ParentResourceId == resourceId)) {
@@ -596,9 +635,9 @@
         }
         return childs;
-      }
+      });
     }
 
     public IEnumerable<DT.Task> GetJobsByResourceId(Guid resourceId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Task>>((db) => {
         var resources = GetChildResources(resourceId).Select(x => x.Id).ToList();
         resources.Add(resourceId);
@@ -609,5 +648,5 @@
           resources.Contains(j.StateLogs.OrderByDescending(x => x.DateTime).First().SlaveId.Value));
         return jobs.Select(j => DT.Convert.ToDto(j)).ToArray();
-      }
+      });
     }
     #endregion
@@ -615,37 +654,37 @@
     #region ResourcePermission Methods
     public DT.ResourcePermission GetResourcePermission(Guid resourceId, Guid grantedUserId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext <DT.ResourcePermission> ((db) => {
         return DT.Convert.ToDto(db.ResourcePermissions.SingleOrDefault(x => x.ResourceId == resourceId && x.GrantedUserId == grantedUserId));
-      }
+      });
     }
 
     public IEnumerable<DT.ResourcePermission> GetResourcePermissions(Expression<Func<ResourcePermission, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.ResourcePermission>>((db) => {
         return db.ResourcePermissions.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public void AddResourcePermission(DT.ResourcePermission dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.ResourcePermissions.SingleOrDefault(x => x.ResourceId == dto.ResourceId && x.GrantedUserId == dto.GrantedUserId);
         if (entity == null) { db.ResourcePermissions.InsertOnSubmit(DT.Convert.ToEntity(dto)); db.SubmitChanges(); }
-      }
+      });
     }
 
     public void UpdateResourcePermission(DT.ResourcePermission dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.ResourcePermissions.FirstOrDefault(x => x.ResourceId == dto.ResourceId && x.GrantedUserId == dto.GrantedUserId);
         if (entity == null) db.ResourcePermissions.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteResourcePermission(Guid resourceId, Guid grantedUserId) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.ResourcePermissions.FirstOrDefault(x => x.ResourceId == resourceId && x.GrantedUserId == grantedUserId);
         if (entity != null) db.ResourcePermissions.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -653,11 +692,11 @@
     #region Authorization Methods
     public Permission GetPermissionForTask(Guid taskId, Guid userId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Permission>((db) => {
         return GetPermissionForJob(GetJobForTask(taskId), userId);
-      }
+      });
     }
 
     public Permission GetPermissionForJob(Guid jobId, Guid userId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Permission>((db) => {
         Job job = db.Jobs.SingleOrDefault(x => x.JobId == jobId);
         if (job == null) return Permission.NotAllowed;
@@ -665,11 +704,11 @@
         JobPermission permission = db.JobPermissions.SingleOrDefault(p => p.JobId == jobId && p.GrantedUserId == userId);
         return permission != null ? permission.Permission : Permission.NotAllowed;
-      }
+      });
     }
 
     public Guid GetJobForTask(Guid taskId) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         return db.Tasks.Single(j => j.TaskId == taskId).JobId;
-      }
+      });
     }
     #endregion
@@ -677,16 +716,17 @@
     #region Lifecycle Methods
     public DateTime GetLastCleanup() {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DateTime>((db) => {
         var entity = db.Lifecycles.SingleOrDefault();
         return entity != null ? entity.LastCleanup : DateTime.MinValue;
-      }
+      });
     }
 
     public void SetLastCleanup(DateTime datetime) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Lifecycles.SingleOrDefault();
         if (entity != null) {
           entity.LastCleanup = datetime;
-        } else {
+        }
+        else {
           entity = new Lifecycle();
           entity.LifecycleId = 0; // always only one entry with ID:0
@@ -695,5 +735,5 @@
         }
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -701,39 +741,39 @@
     #region Downtime Methods
     public DT.Downtime GetDowntime(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Downtime>((db) => {
         return DT.Convert.ToDto(db.Downtimes.SingleOrDefault(x => x.DowntimeId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.Downtime> GetDowntimes(Expression<Func<Downtime, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Downtime>>((db) => {
         return db.Downtimes.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddDowntime(DT.Downtime dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.Downtimes.InsertOnSubmit(entity);
         db.SubmitChanges();
         return entity.DowntimeId;
-      }
+      });
     }
 
     public void UpdateDowntime(DT.Downtime dto) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Downtimes.FirstOrDefault(x => x.DowntimeId == dto.Id);
         if (entity == null) db.Downtimes.InsertOnSubmit(DT.Convert.ToEntity(dto));
         else DT.Convert.ToEntity(dto, entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public void DeleteDowntime(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Downtimes.FirstOrDefault(x => x.DowntimeId == id);
         if (entity != null) db.Downtimes.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
     #endregion
@@ -741,17 +781,17 @@
     #region Statistics Methods
     public DT.Statistics GetStatistic(Guid id) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<DT.Statistics>((db) => {
         return DT.Convert.ToDto(db.Statistics.SingleOrDefault(x => x.StatisticsId == id));
-      }
+      });
     }
 
     public IEnumerable<DT.Statistics> GetStatistics(Expression<Func<Statistics, bool>> predicate) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<IEnumerable<DT.Statistics>>((db) => {
         return db.Statistics.Where(predicate).Select(x => DT.Convert.ToDto(x)).ToArray();
-      }
+      });
     }
 
     public Guid AddStatistics(DT.Statistics dto) {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<Guid>((db) => {
         var entity = DT.Convert.ToEntity(dto);
         db.Statistics.InsertOnSubmit(entity);
@@ -769,17 +809,17 @@
         db.SubmitChanges();
         return entity.StatisticsId;
-      }
+      });
     }
 
     public void DeleteStatistics(Guid id) {
-      using (var db = CreateContext()) {
+      ExecuteWithContext((db) => {
         var entity = db.Statistics.FirstOrDefault(x => x.StatisticsId == id);
         if (entity != null) db.Statistics.DeleteOnSubmit(entity);
         db.SubmitChanges();
-      }
+      });
     }
 
     public List<DT.UserStatistics> GetUserStatistics() {
-      using (var db = CreateContext()) {
+      return ExecuteWithContext<List<DT.UserStatistics>>((db) => {
         var userStats = new Dictionary<Guid, DT.UserStatistics>();
 
@@ -853,5 +893,5 @@
 
         return userStats.Values.ToList();
-      }
+      });
     }
     #endregion
Index: /branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveService.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveService.cs	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive/3.3/HiveService.cs	(revision 8326)
@@ -28,4 +28,5 @@
 using DA = HeuristicLab.Services.Hive.DataAccess;
 using DT = HeuristicLab.Services.Hive.DataTransfer;
+using System.Transactions;
 
 
@@ -63,4 +64,5 @@
     public Guid AddTask(Task task, TaskData taskData, IEnumerable<Guid> resourceIds) {
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
+      Guid currentUserId = userManager.CurrentUserId;
       return trans.UseTransaction(() => {
         task.Id = dao.AddTask(task);
@@ -71,5 +73,5 @@
         }
         dao.AddTaskData(taskData);
-        dao.UpdateTaskState(task.Id, DA.TaskState.Waiting, null, userManager.CurrentUserId, null);
+        dao.UpdateTaskState(task.Id, DA.TaskState.Waiting, null, currentUserId, null);
         return taskData.TaskId;
       }, false, true);
@@ -181,6 +183,8 @@
 
     public Task UpdateTaskState(Guid taskId, TaskState taskState, Guid? slaveId, Guid? userId, string exception) {
-      authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
-      author.AuthorizeForTask(taskId, Permission.Full);
+      using (var ts = new TransactionScope(TransactionScopeOption.Suppress)) {
+        authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
+        author.AuthorizeForTask(taskId, Permission.Full);
+      }
       return trans.UseTransaction(() => {
         Task task = dao.UpdateTaskState(taskId, DataTransfer.Convert.ToEntity(taskState), slaveId, userId, exception);
@@ -245,6 +249,7 @@
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client, HiveRoles.Slave);
       author.AuthorizeForTask(taskId, Permission.Full);
-      trans.UseTransaction(() => {
-        Task task = dao.UpdateTaskState(taskId, DA.TaskState.Waiting, null, userManager.CurrentUserId, string.Empty);
+      Guid currentUserId = userManager.CurrentUserId;
+      trans.UseTransaction(() => {
+        Task task = dao.UpdateTaskState(taskId, DA.TaskState.Waiting, null, currentUserId, string.Empty);
         task.Command = null;
         dao.UpdateTask(task);
@@ -320,10 +325,11 @@
     public void GrantPermission(Guid jobId, Guid grantedUserId, Permission permission) {
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
+      Guid currentUserId = userManager.CurrentUserId;
       trans.UseTransaction(() => {
         Job job = dao.GetJob(jobId);
         if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
-        Permission perm = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, userManager.CurrentUserId));
+        Permission perm = DT.Convert.ToDto(dao.GetPermissionForJob(job.Id, currentUserId));
         if (perm != Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
-        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DT.Convert.ToEntity(permission));
+        dao.SetJobPermission(jobId, currentUserId, grantedUserId, DT.Convert.ToEntity(permission));
       });
     }
@@ -331,10 +337,11 @@
     public void RevokePermission(Guid jobId, Guid grantedUserId) {
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
+      Guid currentUserId = userManager.CurrentUserId;
       trans.UseTransaction(() => {
         Job job = dao.GetJob(jobId);
         if (job == null) throw new FaultException<FaultReason>(new FaultReason("Could not find task with id " + jobId));
-        DA.Permission perm = dao.GetPermissionForJob(job.Id, userManager.CurrentUserId);
+        DA.Permission perm = dao.GetPermissionForJob(job.Id, currentUserId);
         if (perm != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permissions for this experiment"));
-        dao.SetJobPermission(jobId, userManager.CurrentUserId, grantedUserId, DA.Permission.NotAllowed);
+        dao.SetJobPermission(jobId, currentUserId, grantedUserId, DA.Permission.NotAllowed);
       });
     }
@@ -342,6 +349,7 @@
     public IEnumerable<JobPermission> GetJobPermissions(Guid jobId) {
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
-      return trans.UseTransaction(() => {
-        DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, userManager.CurrentUserId);
+      Guid currentUserId = userManager.CurrentUserId;
+      return trans.UseTransaction(() => {
+        DA.Permission currentUserPermission = dao.GetPermissionForJob(jobId, currentUserId);
         if (currentUserPermission != DA.Permission.Full) throw new FaultException<FaultReason>(new FaultReason("Not allowed to list permissions for this experiment"));
         return dao.GetJobPermissions(x => x.JobId == jobId);
@@ -421,5 +429,7 @@
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
       return trans.UseTransaction(() => {
-        plugin.UserId = userManager.CurrentUserId;
+        using (var ts = new TransactionScope(TransactionScopeOption.Suppress)) {
+          plugin.UserId = userManager.CurrentUserId;
+        }
         plugin.DateCreated = DateTime.Now;
 
@@ -476,10 +486,11 @@
     public void GrantResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
+      Guid currentUserId = userManager.CurrentUserId;
       trans.UseTransaction(() => {
         Resource resource = dao.GetResource(resourceId);
         if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
-        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permission for this resource"));
+        if (resource.OwnerUserId != currentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to grant permission for this resource"));
         foreach (Guid id in grantedUserIds)
-          dao.AddResourcePermission(new ResourcePermission { ResourceId = resourceId, GrantedByUserId = userManager.CurrentUserId, GrantedUserId = id });
+          dao.AddResourcePermission(new ResourcePermission { ResourceId = resourceId, GrantedByUserId = currentUserId, GrantedUserId = id });
       });
     }
@@ -487,8 +498,9 @@
     public void RevokeResourcePermissions(Guid resourceId, Guid[] grantedUserIds) {
       authen.AuthenticateForAnyRole(HiveRoles.Administrator, HiveRoles.Client);
+      Guid currentUserId = userManager.CurrentUserId;
       trans.UseTransaction(() => {
         Resource resource = dao.GetResource(resourceId);
         if (resource == null) throw new FaultException<FaultReason>(new FaultReason("Could not find resource with id " + resourceId));
-        if (resource.OwnerUserId != userManager.CurrentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to revoke permission for this resource"));
+        if (resource.OwnerUserId != currentUserId && !authen.IsInRole(HiveRoles.Administrator)) throw new FaultException<FaultReason>(new FaultReason("Not allowed to revoke permission for this resource"));
         foreach (Guid id in grantedUserIds)
           dao.DeleteResourcePermission(resourceId, id);
Index: /branches/OaaS/HeuristicLab.Services.Hive/3.3/Interfaces/IConnectionProvider.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive/3.3/Interfaces/IConnectionProvider.cs	(revision 8326)
+++ /branches/OaaS/HeuristicLab.Services.Hive/3.3/Interfaces/IConnectionProvider.cs	(revision 8326)
@@ -0,0 +1,58 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2012 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.Data.Common;
+
+namespace HeuristicLab.Services.Hive.Interfaces {
+  /// <summary>
+  /// This interface provides functionality to create transactionscoped and non-transactionscoped database connection.
+  /// It also helps to clean the connections after their last usage.
+  /// </summary>
+  public interface IConnectionProvider {
+    /// <summary>
+    /// Creates or returns an already opened database connection for the given connectionStringName.
+    /// If there is no surrounding transaction, a new connection will be returned. This connection
+    /// must be closed by using the ReleaseConnection method.
+    /// If there is a surrounding transaction and no connection exists for the connectionStringName,
+    /// a new connection will be returned.
+    /// If there is a surrounding transaction and an existing connection for the connectionStringName,
+    /// the existing connection will be returned.
+    /// </summary>
+    /// <param name="connectionStringName">The name of the connectionString within the app.config (or web.config) file</param>
+    /// <returns>
+    /// A new connection to the database. If a transaction is already open for this connectionString, 
+    /// the same connection will be returned. Whenever a connection is not needed anymore, call the 
+    /// ReleaseConnection to release it properly.
+    /// </returns>
+    DbConnection GetOpenConnection(string connectionStringName);
+    /// <summary>
+    /// Releases a given database connection only if there is no active transaction.
+    /// Note: Connections within transactions will be released automatically after the transaction ended,
+    /// if the user created the connection with GetOpenConnection within a transaction.
+    /// </summary>
+    /// <param name="connection"></param>
+    void ReleaseConnection(DbConnection connection);
+  }
+}
Index: /branches/OaaS/HeuristicLab.Services.Hive/3.3/ServiceLocator.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Hive/3.3/ServiceLocator.cs	(revision 8325)
+++ /branches/OaaS/HeuristicLab.Services.Hive/3.3/ServiceLocator.cs	(revision 8326)
@@ -21,4 +21,5 @@
 
 using HeuristicLab.Services.Hive.DataAccess;
+using HeuristicLab.Services.Hive.Interfaces;
 
 namespace HeuristicLab.Services.Hive {
@@ -34,8 +35,16 @@
     }
 
+    private IConnectionProvider connProvider;
+    public IConnectionProvider ConnectionProvider {
+      get {
+        if (connProvider == null) connProvider = new ConnectionProvider();
+        return connProvider;
+      }
+    }
+
     private IHiveDao hiveDao;
     public IHiveDao HiveDao {
       get {
-        if (hiveDao == null) hiveDao = new HiveDao();
+        if (hiveDao == null) hiveDao = new HiveDao(ConnectionProvider);
         return hiveDao;
       }
