Exemplo n.º 1
0
        public async Task TestImageServiceAsync()
        {
            var wrappedImageService = new ImageServiceAsync();
            var imageService        = ServiceRef.Create <IImageService>(wrappedImageService);

            Assert.IsTrue(ServiceRef.TryGetWrappedObject <ImageServiceAsync>(imageService, out var returnedWrappedObject));
            Assert.AreSame(wrappedImageService, returnedWrappedObject);
            //await imageService.GetOrDownloadAsync("https://myimage");

            //Assert.AreEqual(1, imageService.Images.Count);
            //Assert.AreEqual("https://myimage", imageService.Images[0].Url);
            //Assert.IsTrue(imageService.Images[0].Data.Length > 0);

            var callTracer = new SimpleCallMonitorTracer();

            ActionQueue.BeginMonitor(callTracer);

            try
            {
                await imageService.GetOrDownloadAsync("https://myimage");

                Assert.AreEqual(1, imageService.Images.Count);
            }
            finally
            {
                ActionQueue.ExitMonitor(callTracer);
            }
        }
Exemplo n.º 2
0
        public void TestImageServiceAsyncMultiple()
        {
            var imageService = ServiceRef.Create <IImageService>(new ImageServiceAsync());

            var callTracer = new SimpleCallMonitorTracer();

            ActionQueue.BeginMonitor(callTracer);

            try
            {
                Task.WaitAll(
                    Enumerable
                    .Range(1, 5)
                    .Select(i => Task.Factory.StartNew(async() =>
                {
                    await imageService.GetOrDownloadAsync("https://myimage" + i);
                }))
                    .ToArray());

                Assert.AreEqual(5, imageService.Images.Count);
            }
            finally
            {
                ActionQueue.ExitMonitor(callTracer);
            }
        }
        public async Task TestImageServiceAsync()
        {
            var imageService = ServiceRef.Create <IImageService>(new ImageServiceAsync());

            //await imageService.GetOrDownloadAsync("https://myimage");

            //Assert.AreEqual(1, imageService.Images.Count);
            //Assert.AreEqual("https://myimage", imageService.Images[0].Url);
            //Assert.IsTrue(imageService.Images[0].Data.Length > 0);

            var callTracer = new SimpleCallMonitorTracer();

            ActionQueue.BeginMonitor(callTracer);

            try
            {
                await imageService.GetOrDownloadAsync("https://myimage");

                Assert.AreEqual(1, imageService.Images.Count);
            }
            finally
            {
                ActionQueue.ExitMonitor(callTracer);
            }
        }
Exemplo n.º 4
0
        public async Task TestImageServiceWithPendingOperation()
        {
            var imageService = ServiceRef.Create <IImageService>(new ImageServiceWithPendingOperation());

            await imageService.GetOrDownloadAsync("https://myimage");

            Assert.AreEqual(1, imageService.Images.Count);
            Assert.AreEqual("https://myimage", imageService.Images[0].Url);
            Assert.IsTrue(imageService.Images[0].Data.Length > 0);
        }
Exemplo n.º 5
0
        public void TestPendingOperations()
        {
            var pendingOpsTestService = ServiceRef.Create <IPendingOpsService>(new PendingOpsService());

            Assert.IsFalse(pendingOpsTestService.OperationCompleted);

            pendingOpsTestService.BeginOperation();

            Assert.IsTrue(pendingOpsTestService.OperationCompleted);
        }
Exemplo n.º 6
0
        public async Task TestPendingOperationsAsyncVersion()
        {
            var pendingOpsTestService = ServiceRef.Create <IPendingOpsServiceAsync>(new PendingOpsServiceAsync());

            Assert.IsFalse(pendingOpsTestService.OperationCompleted);

            await pendingOpsTestService.BeginOperationAsync();

            Assert.IsTrue(pendingOpsTestService.OperationCompleted);
        }
Exemplo n.º 7
0
        public void TestPendingOperationsT()
        {
            var pendingOpsTestService = ServiceRef.Create <IPendingOpsService <string> >(new PendingOpsService <string>("DONE"));

            Assert.IsFalse(pendingOpsTestService.OperationCompleted);
            Assert.IsNull(pendingOpsTestService.Result);

            pendingOpsTestService.BeginOperation();

            Assert.IsTrue(pendingOpsTestService.OperationCompleted);
            Assert.AreEqual("DONE", pendingOpsTestService.Result);
        }
Exemplo n.º 8
0
            public void BeginOperation()
            {
                _pendingOperation = ServiceRef.RegisterPendingOperation(this);

                Task.Factory.StartNew(() =>
                {
                    //simulate some work
                    Task.Delay(1000).Wait();
                    ServiceRef.Create <IPendingOpsService>(this)
                    .CompleteOperation();
                });
            }
Exemplo n.º 9
0
            public Task <bool> BeginOperationAsync()
            {
                _pendingOperation = ServiceRef.RegisterPendingOperation(this, () => OperationCompleted);

                Task.Run(async() =>
                {
                    //simulate some work
                    await Task.Delay(1000);
                    await ServiceRef.Create <IPendingOpsServiceAsync>(this)
                    .CompleteOperationAsync();
                });

                return(Task.FromResult(false));
            }
Exemplo n.º 10
0
        private async Task OnReceivedDataFromChildChannel(IConnection connection, Stream networkStream, CancellationToken cancellationToken)
        {
            int messageCounter = BitConverter.ToInt32(await networkStream.ReadBytesAsync(4), 0);

            if (messageCounter == _receivedMessageCounter + 1)
            {
                //ok new message in sync arrived
                _receivedMessageCounter++;

#pragma warning disable IDE0068 // Use recommended dispose pattern
                var thisRef = ServiceRef.Create <IConnection>(this);
#pragma warning restore IDE0068 // Use recommended dispose pattern

                if (_receivedActionStreamAsync != null)
                {
                    await _receivedActionStreamAsync(thisRef, networkStream, cancellationToken);

                    await networkStream.FlushAsync();
                }
                else
                {
                    var messageData = await networkStream.ReadBytesAsync((int)networkStream.Length - 4 /* messageCounter size */);

                    if (_receivedActionAsync != null)
                    {
                        await _receivedActionAsync(thisRef, messageData, cancellationToken);
                    }
                    else
                    {
                        _receivedAction?.Invoke(thisRef, messageData);
                    }
                }
            }
            else if (messageCounter <= _receivedMessageCounter)
            {
                //ok it's an old message from slow or reconnected channel
                //nothing to do
            }
            else //if (messageCounter > _receivedMessageCounter)
            {
                //not good: I'm no more in sync with other peer
                //a reconnection is required
                _connectionStateMachine.Fire(ConnectionTrigger.LinkError);
            }
        }
Exemplo n.º 11
0
        private async Task ReceiveLoopAsync(CancellationToken cancellationToken)
        {
#pragma warning disable IDE0068 // Use recommended dispose pattern
            var refToThis = ServiceRef.Create <IConnection>(this);
#pragma warning restore IDE0068 // Use recommended dispose pattern
            try
            {
                //if (_receiveLoopCancellationTokenSource != null)
                //{
                //    _receiveLoopCancellationTokenSource.Dispose();
                //    _receiveLoopCancellationTokenSource = null;
                //}

                //_receiveLoopCancellationTokenSource = new CancellationTokenSource();
                _receiveLoopTaskIsRunningEvent.Set();

                //var cancellationToken = _receiveLoopCancellationTokenSource.Token;
                while (true)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    int messageLength = -1;
                    if (_messageFramingEnabled)
                    {
                        await _receivingStream.ReadBufferedAsync(_messageSizeBuffer, cancellationToken).ConfigureAwait(false);

                        messageLength = BitConverter.ToInt32(_messageSizeBuffer, 0);
                        if (messageLength == 0)
                        {
                            continue;
                        }

                        cancellationToken.ThrowIfCancellationRequested();
                    }

                    if (messageLength == -1)
                    {
                        if (_receivedActionStreamAsync != null)
                        {
                            //await ServiceRef.CallAndWaitAsync(this, () =>
                            //    _receivedActionStreamAsync(refToThis, _receivingStream, cancellationToken)).ConfigureAwait(false);
                            await _receivedActionStreamAsync(refToThis, _receivingStream, cancellationToken);
                        }
                        else
                        {
                            throw new InvalidOperationException("ReceiveActionStreamAsync must be specified to handle variable length messages");
                        }
                    }
                    else
                    {
                        if (_receivedActionStreamAsync != null)
                        {
#pragma warning disable IDE0067 // Dispose objects before losing scope
                            var bufferedStream = new NetworkBufferedReadStream(_receivingStream, messageLength);
#pragma warning restore IDE0067 // Dispose objects before losing scope
                            await ServiceRef.CallAndWaitAsync(this, async() =>
                                                              await _receivedActionStreamAsync(refToThis, bufferedStream, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);

                            await bufferedStream.FlushAsync().ConfigureAwait(false);
                        }
                        else
                        {
                            var messageBuffer = new byte[messageLength];

                            await _receivingStream.ReadBufferedAsync(messageBuffer, cancellationToken).ConfigureAwait(false);

                            if (_receivedActionAsync != null)
                            {
                                await ServiceRef.CallAndWaitAsync(this, async() =>
                                                                  await _receivedActionAsync(refToThis, messageBuffer, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
                            }
                            else //if (_receivedAction != null)
                            {
                                ServiceRef.CallAndWait(this, () => _receivedAction(refToThis, messageBuffer));
                            }
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                System.Diagnostics.Debug.WriteLine($"{GetType()} ReceiveLoopAsync Cancelled");
            }
#if DEBUG
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"{GetType()}{Environment.NewLine}{ex}");
#else
            catch (Exception)
            {
#endif
                //_receiveLoopCancellationTokenSource = null;

                ServiceRef.Call(this, () =>
                {
                    if (State == ConnectionState.Connected)
                    {
                        SetState(ConnectionTrigger.LinkError);
                    }
                });
            }
            finally
            {
                //_receiveLoopCancellationTokenSource = null;
            }
        }
Exemplo n.º 12
0
        protected virtual void SetState(ConnectionTrigger connectionTrigger)
        {
            var currentState = State;
            var newState     = State;

            System.Diagnostics.Debug.WriteLine($"{GetType()} SetState({currentState}) -> {connectionTrigger}");

            switch (currentState)
            {
            case ConnectionState.Connecting:
            {
                if (connectionTrigger == ConnectionTrigger.Disconnect)
                {
                    _connectCancellationTokenSource?.Cancel();
                    OnDisconnect();
                    newState = ConnectionState.Disconnected;
                }
                else if (connectionTrigger == ConnectionTrigger.LinkError)
                {
                    _connectCancellationTokenSource?.Cancel();
                    OnDisconnect();
                    newState = ConnectionState.LinkError;
                }
                else if (connectionTrigger == ConnectionTrigger.Connected)
                {
                    newState = ConnectionState.Connected;
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
            break;

            case ConnectionState.Disconnected:
            {
                if (connectionTrigger == ConnectionTrigger.Connect)
                {
                    BeginConnection();
                    newState = ConnectionState.Connecting;
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
            break;

            case ConnectionState.Connected:
            {
                if (connectionTrigger == ConnectionTrigger.LinkError)
                {
                    _receiveLoopCancellationTokenSource?.Cancel();
                    _sendKeepAliveLoopCancellationTokenSource?.Cancel();
                    _sendKeepAliveResetEvent?.Set();
                    OnDisconnect();
                    newState = ConnectionState.LinkError;
                }
                else if (connectionTrigger == ConnectionTrigger.Disconnect)
                {
                    _connectCancellationTokenSource?.Cancel();
                    _receiveLoopCancellationTokenSource?.Cancel();
                    _sendKeepAliveLoopCancellationTokenSource?.Cancel();
                    _sendKeepAliveResetEvent?.Set();
                    OnDisconnect();
                    newState = ConnectionState.Disconnected;
                }
            }
            break;

            case ConnectionState.LinkError:
            {
                if (connectionTrigger == ConnectionTrigger.Disconnect)
                {
                    _connectCancellationTokenSource?.Cancel();
                    _receiveLoopCancellationTokenSource?.Cancel();
                    _sendKeepAliveLoopCancellationTokenSource?.Cancel();
                    _sendKeepAliveResetEvent?.Set();
                    newState = ConnectionState.Disconnected;
                }
                else if (connectionTrigger == ConnectionTrigger.Connected)
                {
                    newState = ConnectionState.Connected;
                }
            }
            break;
            }

            if (newState == currentState)
            {
                return;
            }

            State = newState;

            System.Diagnostics.Debug.WriteLine($"{GetType()} SetState({currentState}) -> {connectionTrigger} -> {newState}");

            _connectionStateChangedAction?.Invoke(ServiceRef.Create <IConnection>(this), currentState, newState);
        }
 private static IConnection CreateServer(NamedPipeConnectionEndPoint connectionEndPoint)
 => ServiceRef.Create <IConnection>(new NamedPipeServerConnection(connectionEndPoint));
 public static IConnectionListener CreateMultiPeerServer(string localNamedPipeName, ConnectionListenerSettings settings = null)
 => ServiceRef.Create <IConnectionListener>(new NamedPipeConnectionListener(localNamedPipeName, settings));
Exemplo n.º 15
0
 public static IConnectionListener CreateMultiPeerServer(IPEndPoint localEndPoint, ConnectionListenerSettings settings = null)
 => ServiceRef.Create <IConnectionListener>(new TcpConnectionListener(localEndPoint, settings));
Exemplo n.º 16
0
 private static IConnection CreateServer(TcpConnectionEndPoint connectionEndPoint)
 => ServiceRef.Create <IConnection>(new TcpServerConnection(connectionEndPoint));
Exemplo n.º 17
0
 private static IConnection CreateSslServer(TcpConnectionEndPoint endPoint)
 => ServiceRef.Create <IConnection>(new SslTcpServerConnection(endPoint));
Exemplo n.º 18
0
 private static IConnection CreateSslClient(TcpConnectionEndPoint endPoint)
 => ServiceRef.Create <IConnection>(new SslTcpClientConnection(endPoint));
Exemplo n.º 19
0
 public static IConnection CreateRedundantServer(IPEndPoint[] localEndPoints, ServerConnectionSettings connectionSettings = null)
 => ServiceRef.Create <IConnection>(new RedundantConnection(localEndPoints.Select(ipEndpoint => CreateServer(ipEndpoint, connectionSettings)).ToArray()));
Exemplo n.º 20
0
 public static IConnection CreateRedundantClient(IPAddress[] remoteAddresses, int remotePort, ClientConnectionSettings connectionSettings = null)
 => ServiceRef.Create <IConnection>(new RedundantConnection(remoteAddresses.Select(remoteAddress => CreateClient(remoteAddress, remotePort, connectionSettings: connectionSettings)).ToArray()));
Exemplo n.º 21
0
 public static IConnection CreateRedundantClient(IPEndPoint[] remoteEndPoints, ClientConnectionSettings connectionSettings = null)
 => ServiceRef.Create <IConnection>(new RedundantConnection(remoteEndPoints.Select(ipEndpoint => CreateClient(ipEndpoint, connectionSettings: connectionSettings)).ToArray()));
Exemplo n.º 22
0
 private static IConnection CreateRedundantClient(TcpConnectionEndPoint[] endPoints)
 => ServiceRef.Create <IConnection>(new RedundantConnection(endPoints.Select(endpoint => CreateClient(endpoint)).ToArray()));
Exemplo n.º 23
0
 public static IConnection CreateRedundantServer(IPAddress[] localAddresses, int localPort, ServerConnectionSettings connectionSettings = null)
 => ServiceRef.Create <IConnection>(new RedundantConnection(localAddresses.Select(localAddress => CreateServer(localAddress, localPort, connectionSettings: connectionSettings)).ToArray()));