Ejemplo n.º 1
0
        private void Execute <T>(Func <IDbCommand, Task <T> > commandFunc, DispatchingTaskCompletionSource <T> tcs)
        {
            IDbConnection connection = null;

            try
            {
                connection = _dbProviderFactory.CreateConnection();
                connection.ConnectionString = ConnectionString;
                var command = CreateCommand(connection);

                connection.Open();

                commandFunc(command)
                .Then(result => tcs.SetResult(result))
                .Catch(ex => tcs.SetUnwrappedException(ex), Trace)
                .Finally(state =>
                {
                    var conn = (DbConnection)state;
                    if (conn != null)
                    {
                        conn.Dispose();
                    }
                }, connection);
            }
            catch (Exception)
            {
                if (connection != null)
                {
                    connection.Dispose();
                }
                throw;
            }
        }
Ejemplo n.º 2
0
        private Task ExecuteHubEvent(IRequest request, string connectionId, Func <IHub, Task> action)
        {
            var hubs       = GetHubs(request, connectionId).ToList();
            var operations = hubs.Select(instance => action(instance).OrEmpty().Catch(Trace)).ToArray();

            if (operations.Length == 0)
            {
                DisposeHubs(hubs);
                return(TaskAsyncHelper.Empty);
            }

            var tcs = new DispatchingTaskCompletionSource <object>();

            Task.Factory.ContinueWhenAll(operations, tasks =>
            {
                DisposeHubs(hubs);
                var faulted = tasks.FirstOrDefault(t => t.IsFaulted);
                if (faulted != null)
                {
                    tcs.SetUnwrappedException(faulted.Exception);
                }
                else if (tasks.Any(t => t.IsCanceled))
                {
                    tcs.SetCanceled();
                }
                else
                {
                    tcs.SetResult(null);
                }
            });

            return(tcs.Task);
        }
        public static Task <string> ReadAsString(this IResponse response, Func <ArraySegment <byte>, bool> onChunk)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            var stream    = response.GetStream();
            var reader    = new AsyncStreamReader(stream);
            var result    = new StringBuilder();
            var resultTcs = new DispatchingTaskCompletionSource <string>();

            reader.Data = buffer =>
            {
                if (onChunk(buffer))
                {
                    result.Append(Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count));
                }
            };

            reader.Closed = exception =>
            {
                response.Dispose();
                resultTcs.SetResult(result.ToString());
            };

            reader.Start();

            return(resultTcs.Task);
        }
Ejemplo n.º 4
0
 private void Execute <T>(Func <IQuery, Task <T> > commandFunc, DispatchingTaskCompletionSource <T> tcs)
 {
     using (var session = SessionFactoryInfo.SessionFactory.OpenSession())
     {
         var command = CreateCommand(session);
         commandFunc(command)
         .Then(result => tcs.SetResult(result))
         .Catch(ex => tcs.SetUnwrappedException(ex), Trace);
     }
 }
Ejemplo n.º 5
0
        private void ResolveTransport(IConnection connection, string data, CancellationToken disconnectToken, DispatchingTaskCompletionSource <object> tcs, int index)
        {
            // Pick the current transport
            IClientTransport transport = _transports[index];

            transport.Start(connection, data, disconnectToken).ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Exception ex;
                    if (task.IsCanceled)
                    {
                        ex = new OperationCanceledException(Resources.Error_TaskCancelledException);
                    }
                    else
                    {
                        ex = task.Exception.GetBaseException();
                    }

                    connection.Trace(TraceLevels.Events, "Auto: Failed to connect to using transport {0}. {1}", transport.Name, ex);

                    // If that transport fails to initialize, then fallback.
                    // If it is that /start request that failed, do not fallback.
                    var next = index + 1;
                    if (next < _transports.Count && !(ex is StartException))
                    {
                        // Try the next transport
                        ResolveTransport(connection, data, disconnectToken, tcs, next);
                    }
                    else
                    {
                        // If there's nothing else to try then just fail
                        tcs.SetException(ex);
                    }
                }
                else
                {
                    // Set the active transport
                    _transport = transport;

                    // Complete the process
                    tcs.SetResult(null);
                }
            },
                                                                            TaskContinuationOptions.ExecuteSynchronously);
        }
Ejemplo n.º 6
0
        public virtual Task <int> ExecuteNonQueryAsync()
        {
            var tcs = new DispatchingTaskCompletionSource <int>();

            return(new Task <int>(() =>
            {
                int a;
                try
                {
                    a = ExecuteNonQuery();
                    tcs.SetResult(a);
                    return a;
                }
                catch (Exception ex)
                {
                    tcs.SetUnwrappedException(ex);
                    throw;
                }
            }));
        }
Ejemplo n.º 7
0
        private Task StartTransport()
        {
            return(_transport.Start(this, _connectionData, _disconnectCts.Token)
                   .RunSynchronously(() =>
            {
                // NOTE: We have tests that rely on this state change occuring *BEFORE* the start task is complete
                ChangeState(ConnectionState.Connecting, ConnectionState.Connected);

                // Now that we're connected complete the start task that the
                // receive queue is waiting on
                _startTcs.SetResult(null);

                // Start the monitor to check for server activity
                _lastMessageAt = DateTime.UtcNow;
                _lastActiveAt = DateTime.UtcNow;
                Monitor.Start();
            })
                   // Don't return until the last receive has been processed to ensure messages/state sent in OnConnected
                   // are processed prior to the Start() method task finishing
                   .Then(() => _lastQueuedReceiveTask));
        }