Exemplo n.º 1
0
        /// <summary>
        /// Groups Transactions/Connections./Connections.
        /// </summary>
        /// <param name="this">Connection Source</param>
        /// <param name="body">Execution body.</param>
        public static T Pool <T>(this IConnectionSource @this, Func <IPool, T> body)
        {
            using var pool = new Pool(@this);
            var res = body(pool);

            return(res);
        }
Exemplo n.º 2
0
 /// <summary>
 /// Groups Transactions/Connections./Connections.
 /// </summary>
 /// <param name="this">Connection Source</param>
 /// <param name="body">Execution body.</param>
 public static void Pool(this IConnectionSource @this, Action <IPool> body)
 {
     @this.Pool(p =>
     {
         body(p);
         return(0);
     });
 }
Exemplo n.º 3
0
 public static void WithConnection <TCon>(this IConnectionSource <TCon> source, Action <TCon> action)
 {
     source.WithConnection(con =>
     {
         action(con);
         return(true);
     });
 }
 public static T CallInTransaction <T>(IConnectionSource source, Func <IConnectionSource, T> runInsideTransaction)
 {
     using (ITransaction transaction = source.StartTransaction())
     {
         var result = runInsideTransaction(source);
         transaction.Commit();
         return(result);
     }
 }
Exemplo n.º 5
0
 /// <summary>
 /// Creates/Rollbacks/Disposes Transaction
 /// </summary>
 /// <param name="body">Use Transaction.</param>
 /// <param name="this">Desired connection source.</param>
 /// <param name="token">Cancellation Token.</param>
 private static void Transaction(this IConnectionSource @this, Action <Transaction> body,
                                 CancellationToken token)
 {
     @this.Transaction(tran =>
     {
         body(tran);
         return(0);
     }, token);
 }
Exemplo n.º 6
0
 // ReSharper disable once MemberCanBePrivate.Global
 // ReSharper disable once MemberCanBePrivate.Global
 /// <summary>
 /// Executes SqlCommand and returns Result.
 /// </summary>
 /// <param name="body">Use to Customize and to execute Command.</param>
 /// <param name="command">CommandText.</param>
 /// <param name="token">Cancellation token.</param>
 /// <param name="this">Desired database context.</param>
 /// <typeparam name="T">Generic Type T</typeparam>
 /// <returns>Database Query Result of Type T.</returns>
 public static Task <T> QueryAsync <T>(this IConnectionSource @this, string command, Func <ICommand <T>, T> body,
                                       CancellationToken token)
 {
     return(@this.TransactionAsync(tran =>
     {
         using var cmd = new Command <T>(command, tran);
         var res = body(cmd);
         return res;
     }, token));
 }
Exemplo n.º 7
0
        public Pool(IConnectionSource connectionSource)
        {
            switch (connectionSource)
            {
            case Transaction t:
                _transactions.Add(t.Connection.Context.Name, t);
                break;
            }

            _connectionSource = connectionSource ?? ContextController.DefaultContext;
            _connectionSource.CommandCreated += OnCommandCreated;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates/Rollbacks/Disposes Transaction
        /// </summary>
        /// <param name="body">Use Transaction.</param>
        /// <param name="this">Desired connection source.</param>
        /// <param name="token">Cancellation Token.</param>
        /// <typeparam name="T">Generic Type T.</typeparam>
        /// <returns>Query Results of Type T.</returns>
        private static T Transaction <T>(this IConnectionSource @this, Func <Transaction, T> body, CancellationToken token)
        {
            if (body.Method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null)
            {
                throw new InvalidOperationException("Async Lambdas not supported, please use a Pool.");
            }
            var transaction = @this as ManagedTransaction;
            var ts          = @this as IPool;
            var tran        = transaction ?? @this?.Transaction() ?? new Transaction(ContextController.DefaultContext)
            {
                Token = token
            };
            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            var handleTransaction = transaction == null && ts == null && @this == null;
            var conn = tran.Connection;

            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            tran.OnTransactionCreated(tran);
            if (tran.DbTransaction == null)
            {
                tran.DbTransaction = conn.BeginTransaction();
            }
            try
            {
                var res = body(tran);
                if (handleTransaction)
                {
                    tran.Commit();
                }
                return(res);
            }
            catch (Exception)
            {
                if (handleTransaction)
                {
                    tran.Rollback();
                }
                throw;
            }
            finally
            {
                if (handleTransaction)
                {
                    tran.Dispose();
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
Exemplo n.º 9
0
        protected async Task <TCommandResult> ExecuteCommandAsync(
            IConnectionSource connectionSource,
            ReadPreference readPreference,
            TimeSpan timeout,
            CancellationToken cancellationToken)
        {
            var slidingTimeout = new SlidingTimeout(timeout);

            using (var connection = await connectionSource.GetConnectionAsync(slidingTimeout, cancellationToken))
            {
                var protocol = CreateProtocol(connectionSource.ServerDescription, readPreference);
                return(await protocol.ExecuteAsync(connection, slidingTimeout, cancellationToken));
            }
        }
Exemplo n.º 10
0
        public static async Task <TResult> ExecuteAsync <TResult>(
            this IWireProtocol <TResult> protocol,
            IConnectionSource connectionSource,
            TimeSpan timeout = default(TimeSpan),
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(protocol, "protocol");
            var slidingTimeout = new SlidingTimeout(timeout);

            using (var connection = await connectionSource.GetConnectionAsync(slidingTimeout, cancellationToken))
            {
                return(await protocol.ExecuteAsync(connection, slidingTimeout, cancellationToken));
            }
        }
Exemplo n.º 11
0
        public void RegisterConnectionSource(string name, IConnectionSource connectionSource)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentException("name is null or empty.", "name");

            if (connectionSource == null)
                throw new ArgumentNullException("connectionSource", "connectionSource is null.");

            if (connectionSources.ContainsKey(name))
                throw new ArgumentException(
                    string.Format("A connection source has already been registered with the name: {0}", name),
                    "name");

            connectionSources.Add(name, connectionSource);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Groups Transactions/Connections.
        /// </summary>
        /// <param name="this">Connection Source</param>
        /// <param name="body">Execution body.</param>
        public static Task <T> PoolAsync <T>(this IConnectionSource @this, Func <IPool, Task <T> > body)
        {
            var source = new CancellationTokenSource();
            var token  = source.Token;

            return(Task.Run(async() =>
            {
                using var pool = new Pool(@this)
                      {
                          TokenSource = source
                      };
                var res = await body(pool);
                pool.Commit();
                return res;
            }, token));
        }
Exemplo n.º 13
0
        // constructors
        public Cursor(
            IConnectionSource connectionSource,
            CollectionNamespace collectionNamespace,
            BsonDocument query,
            IReadOnlyList <TDocument> firstBatch,
            long cursorId,
            int batchSize,
            int limit,
            IBsonSerializer <TDocument> serializer,
            MessageEncoderSettings messageEncoderSettings,
            TimeSpan timeout,
            CancellationToken cancellationToken)
        {
            _connectionSource    = Ensure.IsNotNull(connectionSource, "connectionSource");
            _collectionNamespace = Ensure.IsNotNull(collectionNamespace, "collectionNamespace");
            _query                  = Ensure.IsNotNull(query, "query");
            _firstBatch             = Ensure.IsNotNull(firstBatch, "firstBatch");
            _cursorId               = cursorId;
            _batchSize              = Ensure.IsGreaterThanOrEqualToZero(batchSize, "batchSize");
            _limit                  = Ensure.IsGreaterThanOrEqualToZero(limit, "limit");
            _serializer             = Ensure.IsNotNull(serializer, "serializer");
            _messageEncoderSettings = messageEncoderSettings;
            _timeout                = timeout;
            _cancellationToken      = cancellationToken;

            if (_limit == 0)
            {
                _limit = int.MaxValue;
            }
            if (_firstBatch.Count > _limit)
            {
                _firstBatch = _firstBatch.Take(_limit).ToList();
            }
            _count = _firstBatch.Count;

            // if we aren't going to need the connection source we can go ahead and Dispose it now
            if (_cursorId == 0)
            {
                _connectionSource.Dispose();
                _connectionSource = null;
            }
        }
Exemplo n.º 14
0
 // constructors
 public Cursor(
     IConnectionSource connectionSource,
     string databaseName,
     string collectionName,
     BsonDocument query,
     IReadOnlyList <TDocument> firstBatch,
     long cursorId,
     int batchSize,
     IBsonSerializer <TDocument> serializer,
     TimeSpan timeout,
     CancellationToken cancellationToken)
 {
     _connectionSource  = cursorId == 0 ? connectionSource : Ensure.IsNotNull(connectionSource, "connectionSource");
     _databaseName      = Ensure.IsNotNullOrEmpty(databaseName, "databaseName");
     _collectionName    = Ensure.IsNotNullOrEmpty(collectionName, "collectionName");
     _query             = Ensure.IsNotNull(query, "query");
     _firstBatch        = Ensure.IsNotNull(firstBatch, "firstBatch");
     _cursorId          = cursorId;
     _batchSize         = Ensure.IsGreaterThanOrEqualToZero(batchSize, "batchSize");
     _serializer        = Ensure.IsNotNull(serializer, "serializer");
     _timeout           = timeout;
     _cancellationToken = cancellationToken;
 }
Exemplo n.º 15
0
 /// <summary>
 /// Creates/Rollbacks/Disposes Transaction
 /// </summary>
 /// <param name="body">Use Transaction.</param>
 /// <param name="this">Desired connection source.</param>
 /// <param name="token">Cancellation Token.</param>
 /// <returns>Awaitable Task</returns>
 public static Task TransactionAsync(this IConnectionSource @this, Action <Transaction> body,
                                     CancellationToken token)
 {
     return(Task.Run(() => @this.Transaction(body, token), token));
 }
Exemplo n.º 16
0
 internal ManagedTransaction(IConnectionSource connection, string databaseName) : base(connection, databaseName)
 {
     TransactionCreated += connection.OnTransactionCreated;
     CommandCreated     += connection.OnCommandCreated;
     ConnectionSource    = connection;
 }
Exemplo n.º 17
0
 // constructors
 public ConnectionSourceHandle(IConnectionSource connectionSource)
     : this(new ReferenceCounted <IConnectionSource>(connectionSource))
 {
 }
Exemplo n.º 18
0
 public bool Execute(IConnectionSource source, out int rowsAltered, params Value[] parameters)
 {
     return(Execute(source.QueryCompiler, out rowsAltered, parameters));
 }
Exemplo n.º 19
0
 internal Transaction(IConnectionSource connection)
 {
     Connection       = connection.Connection();
     ConnectionSource = connection;
     CommandCreated  += connection.OnCommandCreated;
 }
Exemplo n.º 20
0
 internal Transaction(IConnectionSource connection, string databaseName)
 {
     Connection      = connection.Connection(databaseName);
     CommandCreated += connection.OnCommandCreated;
 }
Exemplo n.º 21
0
 public object Execute(IConnectionSource source, Type type, params Value[] parameters)
 {
     return(Execute(source.QueryCompiler, type, parameters));
 }
 public void Setup()
 {
     _connectionSource = Substitute.For <IConnectionSource>();
 }
 public void Setup()
 {
     _connectionSource = Substitute.For<IConnectionSource>();
 }
 // constructors
 public ConnectionSourceHandle(IConnectionSource connectionSource)
     : this(new ReferenceCounted<IConnectionSource>(connectionSource))
 {
 }
Exemplo n.º 25
0
 /// <summary>
 /// Creates/Rollbacks/Disposes Transaction on desired database context.
 /// </summary>
 /// <param name="this">Database context.</param>
 /// <param name="body">Use Transaction.</param>
 /// <typeparam name="T">Generic Type T.</typeparam>
 /// <returns>QueryResult of Type T</returns>
 // ReSharper disable once MemberCanBePrivate.Global
 public static Task <T> TransactionAsync <T>(this IConnectionSource @this, Func <Transaction, T> body)
 {
     return(Task.Run(() => Transaction(@this, body)));
 }
Exemplo n.º 26
0
 /// <summary>
 /// Creates/Rollbacks/Disposes Transaction on desired database context.
 /// </summary>
 /// <param name="this">Database context.</param>
 /// <param name="body">Use Transaction.</param>
 /// <param name="token">Cancellation Token.</param>
 /// <typeparam name="T">Generic Type T.</typeparam>
 /// <returns>QueryResult of Type T</returns>
 // ReSharper disable once MemberCanBePrivate.Global
 public static Task <T> TransactionAsync <T>(this IConnectionSource @this, Func <Transaction, T> body, CancellationToken token)
 {
     return(Task.Run(() => Transaction(@this, body, token), token));
 }
Exemplo n.º 27
0
 // static methods
 public static IConnectionHandle GetConnection(this IConnectionSource connectionSource, TimeSpan timeout = default(TimeSpan), CancellationToken cancellationToken = default(CancellationToken))
 {
     return(connectionSource.GetConnectionAsync(timeout, cancellationToken).GetAwaiter().GetResult());
 }
Exemplo n.º 28
0
 public IPreparedStatement Prepare(IConnectionSource source)
 {
     return(Prepare(source.QueryCompiler));
 }
 public StudentRepositoryService(IConnectionSource connectionSource)
 {
     _connectionSource = connectionSource;
 }
Exemplo n.º 30
0
 /// <summary>
 /// Creates/Rollbacks/Disposes Transaction
 /// </summary>
 /// <param name="body">Use Transaction.</param>
 /// <param name="this">Desired connection source.</param>
 /// <typeparam name="T">Generic Type T.</typeparam>
 /// <returns>Query Results of Type T.</returns>
 // ReSharper disable once MemberCanBePrivate.Global
 public static T Transaction <T>(this IConnectionSource @this, Func <Transaction, T> body)
 {
     return(@this.Transaction(body, CancellationToken.None));
 }
Exemplo n.º 31
0
 /// <summary>
 /// Creates/Rollbacks/Disposes Transaction
 /// </summary>
 /// <param name="body">Use Transaction.</param>
 /// <param name="this">Desired connection source.</param>
 // ReSharper disable once MemberCanBePrivate.Global
 public static void Transaction(this IConnectionSource @this, Action <Transaction> body)
 {
     @this.Transaction(body, CancellationToken.None);
 }
Exemplo n.º 32
0
 public IEnumerable <string[]> Execute(IConnectionSource source, params Value[] parameters)
 {
     return(Execute(source.QueryCompiler, parameters));
 }
Exemplo n.º 33
0
 internal ManagedTransaction(IConnectionSource connection) : base(connection)
 {
     TransactionCreated += connection.OnTransactionCreated;
     CommandCreated     += connection.OnCommandCreated;
     ConnectionSource    = connection;
 }