Example #1
0
        public async Task ServerCanAwaitForClient()
        {
            var name = GetUniqueName();

            OutboundChannel outboundChannel = null;

            InboundChannel inboundChannel = null;

            try
            {
                var outboundChannelResult = Channel.CreateOutboundLocal(name);

                outboundChannel = outboundChannelResult.Data;

                InconclusiveWhenNotCompleted(outboundChannelResult);

                var task = outboundChannel.WhenClientConnectedAsync(TimeSpan.FromSeconds(1));

                var inboundChannelResult = Channel.OpenInboundLocalNoncontainerized(name);

                inboundChannel = inboundChannelResult.Data;

                InconclusiveWhenNotCompleted(inboundChannelResult);

                var status = await task;

                Assert.AreEqual(OperationStatus.Completed, status);
            }
            finally
            {
                inboundChannel?.Dispose();

                outboundChannel?.Dispose();
            }
        }
Example #2
0
        public void InboundChannelCanBeOpened()
        {
            var name = GetUniqueName();

            OutboundChannel outboundChannel = null;

            InboundChannel inboundChannel = null;

            try
            {
                var outboundChannelResult = Channel.CreateOutboundLocal(name);

                outboundChannel = outboundChannelResult.Data;

                InconclusiveWhenNotCompleted(outboundChannelResult);

                var inboundChannelResult = Channel.OpenInboundLocalNoncontainerized(name);

                inboundChannel = inboundChannelResult.Data;

                Assert.AreEqual(OperationStatus.Completed, inboundChannelResult.Status);
            }
            finally
            {
                inboundChannel?.Dispose();

                outboundChannel?.Dispose();
            }
        }
Example #3
0
        public void InboundChannelNameCanBeReused()
        {
            var name = GetUniqueName();

            InboundChannel channel = null;

            try
            {
                var result = Channel.CreateInboundLocal(name);

                channel = result.Data;

                InconclusiveWhenNotCompleted(result);

                channel.Dispose();

                result = Channel.CreateInboundLocal(name);

                channel = result.Data;

                Assert.AreEqual(OperationStatus.Completed, result.Status);
            }
            finally
            {
                channel?.Dispose();
            }
        }
Example #4
0
        public void MemoryManagerReusesFreeSpaceOnExactMatch()
        {
            var name = GetUniqueName();

            OutboundChannel outboundChannel = null;

            InboundChannel inboundChannel = null;

            try
            {
                var outboundChannelResult = Channel.CreateOutboundLocal(name);

                outboundChannel = outboundChannelResult.Data;

                InconclusiveWhenNotCompleted(outboundChannelResult);

                var data = new byte[5];

                // Write two nodes

                var writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(outboundChannelResult);

                writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(writingResult);

                var previousAllocatedSpace = writingResult.Data.AllocatedSpace;

                var inboundChannelResult = Channel.OpenInboundLocalNoncontainerized(name);

                inboundChannel = inboundChannelResult.Data;

                InconclusiveWhenNotCompleted(inboundChannelResult);

                // Remove node #1

                var readingResult = inboundChannel.Read((stream) => { });

                InconclusiveWhenNotCompleted(readingResult);

                // Write node #3 in place of #1

                writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(writingResult);

                var allocatedSpace = writingResult.Data.AllocatedSpace;

                Assert.AreEqual(previousAllocatedSpace, allocatedSpace);
            }
            finally
            {
                inboundChannel?.Dispose();

                outboundChannel?.Dispose();
            }
        }
Example #5
0
 public void Start(string vrAddress)
 {
     _vrAddress            = vrAddress;
     _joystickStateChannel = new InboundChannel <JoystickState>(
         this.GetSimulator().JoystickStatePort);
     _boardStateChannel = new OutboundChannel <BoardState>(
         vrAddress, this.GetSimulator().BoardStatePort);
 }
Example #6
0
        public async Task InboundChannelCanReadAsynchronously()
        {
            var name = GetUniqueName();

            OutboundChannel outboundChannel = null;

            InboundChannel inboundChannel = null;

            try
            {
                var outboundChannelResult = Channel.CreateOutboundLocal(name);

                outboundChannel = outboundChannelResult.Data;

                InconclusiveWhenNotCompleted(outboundChannelResult);

                var data = new byte[5] {
                    1, 2, 3, 4, 5
                };

                var writingResult = outboundChannel.Write((stream) =>
                {
                    stream.Write(data, 0, data.Length);

                    return(OperationStatus.Completed);
                },
                                                          data.Length);

                InconclusiveWhenNotCompleted(writingResult);

                var inboundChannelResult = Channel.OpenInboundLocalNoncontainerized(name);

                inboundChannel = inboundChannelResult.Data;

                InconclusiveWhenNotCompleted(inboundChannelResult);

                var buffer = new byte[data.Length];

                var readingResult = await inboundChannel.ReadAsync(async (stream) =>
                {
                    await stream.ReadAsync(buffer, 0, data.Length);

                    return(OperationStatus.Completed);
                });

                CollectionAssert.AreEqual(data, buffer);

                Assert.AreEqual(0, readingResult.Data.MessagesCount, "Message counter should decrease after reading");
            }
            finally
            {
                inboundChannel?.Dispose();

                outboundChannel?.Dispose();
            }
        }
Example #7
0
    // Start is called before the first frame update
    public async Task Start(IMqttClient mqttClient)
    {
        await mqttClient.PublishAsync(
            new Mqtt.SystemOnline {
            address = this.GetLocalIPAddress()
        }.AsMessage("labyrinth/board/online"),
            MqttQualityOfService.AtLeastOnce);

        _joystickStateChannel = new InboundChannel <JoystickState>(this.GetSimulator().JoystickStatePort);
    }
Example #8
0
        public void InboundChannelCanBeCreatedAndDisposed()
        {
            InboundChannel channel = null;

            try
            {
                var result = Channel.CreateInboundLocal(GetUniqueName());

                channel = result.Data;

                Assert.AreEqual(OperationStatus.Completed, result.Status);
            }
            finally
            {
                channel?.Dispose();
            }
        }
Example #9
0
        public async Task OutboundChannelCanAwaitWhenQueueIsEmpty()
        {
            var name = GetUniqueName();

            OutboundChannel outboundChannel = null;

            InboundChannel inboundChannel = null;

            try
            {
                var data = new byte[5];

                var outboundChannelResult = Channel.CreateOutboundLocal(name);

                outboundChannel = outboundChannelResult.Data;

                InconclusiveWhenNotCompleted(outboundChannelResult);

                var inboundChannelResult = Channel.OpenInboundLocalNoncontainerized(name);

                inboundChannel = inboundChannelResult.Data;

                InconclusiveWhenNotCompleted(inboundChannelResult);

                var writingResult = await outboundChannel.WriteAsync(async (stream) => { await stream.WriteAsync(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(writingResult);

                var task = outboundChannel.WhenQueueIsEmptyAsync(TimeSpan.FromSeconds(1));

                var readingResult = await inboundChannel.ReadAsync(async (stream) => { await stream.ReadAsync(data, 0, data.Length); });

                InconclusiveWhenNotCompleted(readingResult);

                var status = await task;

                Assert.AreEqual(OperationStatus.Completed, status);
            }
            finally
            {
                inboundChannel?.Dispose();

                outboundChannel?.Dispose();
            }
        }
Example #10
0
        private void EndAccept(IAsyncResult res)
        {
            if (!_listening)
            {
                return;
            }

            StartListen();

            Socket socket = _socket.EndAccept(res);

            socket.NoDelay     = true;
            socket.LingerState = new LingerOption(true, 1);
            Binding        binding      = GetBinding(socket.RemoteEndPoint);
            InboundChannel boundChannel = _factory.CreateInboundChannel(socket, binding);

            IncomingChannel(boundChannel);
        }
Example #11
0
        public void ChannelCanGetChannelState()
        {
            InboundChannel channel = null;

            try
            {
                var inboundChannelResult = Channel.CreateInboundLocal(GetUniqueName());

                channel = inboundChannelResult.Data;

                InconclusiveWhenNotCompleted(inboundChannelResult);

                var state = channel.GetChannelState();

                Assert.AreEqual(Marshal.SizeOf <Header>(), state.AllocatedSpace);

                Assert.AreEqual(0, state.MessagesCount);
            }
            finally
            {
                channel?.Dispose();
            }
        }
        private async Task ListenAndSendFiles()
        {
            const long megabyte = 1024 * 1024;

            var cancellationToken = _cts.Token;

            OutboundChannel fileChannel = null;

            InboundChannel pathChannel = null;

            try
            {
                var acl = new[] { new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), new SecurityIdentifier(AppContainerSid) };

                var pathChannelOperationResult = Channel.CreateInboundGlobal("sample_path", megabyte, acl);

                var fileChannelOperationResult = Channel.CreateOutboundGlobal("sample_file", megabyte, acl);

                pathChannel = pathChannelOperationResult.Data;

                fileChannel = fileChannelOperationResult.Data;

                if (pathChannelOperationResult.Status == OperationStatus.ObjectAlreadyInUse || fileChannelOperationResult.Status == OperationStatus.ObjectAlreadyInUse)
                {
                    _eventLog.WriteEntry("Channel wasn't disposed during previous run of the service.");

                    return;
                }

                if (pathChannelOperationResult.Status == OperationStatus.ElevationRequired || fileChannelOperationResult.Status == OperationStatus.ElevationRequired)
                {
                    _eventLog.WriteEntry("Process doesn't have permission to create global shared objects. See https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-global-objects for details.");

                    return;
                }

                while (!cancellationToken.IsCancellationRequested)
                {
                    var waitingForPathStatus = await pathChannel.WhenQueueHasMessagesAsync(cancellationToken, Timeout.InfiniteTimeSpan);

                    if (waitingForPathStatus == OperationStatus.Cancelled)
                    {
                        return;
                    }

                    string path = null;

                    var pathOperationResult = await pathChannel.ReadAsync(async (stream) =>
                    {
                        using (var reader = new StreamReader(stream)) path = await reader.ReadLineAsync();

                        return(OperationStatus.Completed);
                    },
                                                                          cancellationToken, Timeout.InfiniteTimeSpan);

                    if (pathOperationResult.Status == OperationStatus.Cancelled)
                    {
                        return;
                    }

                    // Actually app is already connected, line below is just example of waiting for connection

                    var waitingForClientStatus = await fileChannel.WhenClientConnectedAsync(cancellationToken, Timeout.InfiniteTimeSpan);

                    if (waitingForClientStatus == OperationStatus.Cancelled)
                    {
                        return;
                    }

                    FileStream fileStream = null;

                    try
                    {
                        var fileOpened = false;

                        try
                        {
                            fileStream = File.OpenRead(path);

                            fileOpened = true;
                        }
                        catch (Exception e)
                        {
                            _eventLog.WriteEntry(e.ToString());

                            await TryWriteString(fileChannel, "Cannot open this file. Please check Event Log for details.");
                        }

                        if (fileOpened)
                        {
                            var writingOperationResult = await fileChannel.WriteAsync(async (targetStream, parameter, token) =>
                            {
                                try
                                {
                                    var sourceStream = (Stream)parameter;

                                    await sourceStream.CopyToAsync(targetStream, 4096, token);

                                    return(OperationStatus.Completed);
                                }
                                catch (Exception e)
                                {
                                    if (!(e is OperationCanceledException))
                                    {
                                        _eventLog.WriteEntry(e.ToString());                                     // WriteAsync does not throw, it returns OperationStatus.DelegateFailed
                                    }
                                    throw;
                                }
                            },
                                                                                      fileStream, fileStream.Length, cancellationToken, Timeout.InfiniteTimeSpan);

                            if (writingOperationResult.Status == OperationStatus.Cancelled)
                            {
                                return;
                            }

                            if (writingOperationResult.Status == OperationStatus.DelegateFailed)
                            {
                                await TryWriteString(fileChannel, "Cannot send file. Please check Event Log for details.");
                            }

                            if (writingOperationResult.Status == OperationStatus.RequestedLengthIsGreaterThanLogicalAddressSpace ||
                                writingOperationResult.Status == OperationStatus.RequestedLengthIsGreaterThanVirtualAddressSpace ||
                                writingOperationResult.Status == OperationStatus.OutOfSpace)
                            {
                                await TryWriteString(fileChannel, "File is too large.");

                                _eventLog.WriteEntry($"Failed to send file {path} because it is too large.");
                            }
                        }
                    }
                    finally
                    {
                        fileStream?.Close();
                    }
                }
            }
            catch (Exception e)
            {
                _eventLog.WriteEntry(e.ToString());

                Stop();
            }
            finally
            {
                pathChannel?.Dispose();

                fileChannel?.Dispose();
            }
        }
Example #13
0
        public void MemoryManagerReusesFreeSpaceWhenAllocationRequired()
        {
            var name = GetUniqueName();

            OutboundChannel outboundChannel = null;

            InboundChannel inboundChannel = null;

            const int messageSize = 5;

            try
            {
                var outboundChannelResult = Channel.CreateOutboundLocal(name);

                outboundChannel = outboundChannelResult.Data;

                InconclusiveWhenNotCompleted(outboundChannelResult);

                var data = new byte[messageSize];

                // Write two nodes

                var writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(outboundChannelResult);

                writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(writingResult);

                var inboundChannelResult = Channel.OpenInboundLocalNoncontainerized(name);

                inboundChannel = inboundChannelResult.Data;

                InconclusiveWhenNotCompleted(inboundChannelResult);

                // Remove one node ...

                var readingResult = inboundChannel.Read((stream) => { });

                InconclusiveWhenNotCompleted(readingResult);

                // ... to write node #3 in place of first node

                writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(writingResult);

                // Remove node #2

                readingResult = inboundChannel.Read((stream) => { });

                InconclusiveWhenNotCompleted(readingResult);

                // To force MM write next large node #4 in place of #2

                var previousAllocatedSpace = readingResult.Data.AllocatedSpace;

                var largeData = new byte[messageSize + 1];

                writingResult = outboundChannel.Write((stream) => { stream.Write(largeData, 0, largeData.Length); }, largeData.Length);

                InconclusiveWhenNotCompleted(writingResult);

                var allocatedSpace = writingResult.Data.AllocatedSpace;

                // It is one byte larger than #2, so MM should allocate one additional byte after free node

                Assert.AreEqual(previousAllocatedSpace + 1, allocatedSpace);
            }
            finally
            {
                inboundChannel?.Dispose();

                outboundChannel?.Dispose();
            }
        }
Example #14
0
        public void MemoryManagerReusesFreeSpaceWhenItCanSplitFreeNode()
        {
            var name = GetUniqueName();

            OutboundChannel outboundChannel = null;

            InboundChannel inboundChannel = null;

            var sizeOfNode = Marshal.SizeOf <Node>();

            try
            {
                var outboundChannelResult = Channel.CreateOutboundLocal(name);

                outboundChannel = outboundChannelResult.Data;

                InconclusiveWhenNotCompleted(outboundChannelResult);

                var data = new byte[sizeOfNode];

                // Write two nodes having data with length >= size of node's header

                var writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                InconclusiveWhenNotCompleted(outboundChannelResult);

                writingResult = outboundChannel.Write((stream) => { stream.Write(data, 0, data.Length); }, data.Length);

                var previousAllocatedSpace = writingResult.Data.AllocatedSpace;

                InconclusiveWhenNotCompleted(writingResult);

                var inboundChannelResult = Channel.OpenInboundLocalNoncontainerized(name);

                inboundChannel = inboundChannelResult.Data;

                InconclusiveWhenNotCompleted(inboundChannelResult);

                // Remove one

                var readingResult = inboundChannel.Read((stream) => { });

                InconclusiveWhenNotCompleted(readingResult);

                // Write third empty node

                writingResult = outboundChannel.Write((stream) => { stream.Write(new byte[0], 0, 0); }, data.Length);

                InconclusiveWhenNotCompleted(writingResult);

                // MM should split free node into active node and new free list node

                var allocatedSpace = writingResult.Data.AllocatedSpace;

                Assert.AreEqual(previousAllocatedSpace, allocatedSpace);
            }
            finally
            {
                inboundChannel?.Dispose();

                outboundChannel?.Dispose();
            }
        }
Example #15
0
        private async Task Initialize()
        {
            const string ChannelIsBroken = "Last time when app connected to the service, channel wasn't disposed, now it is broken";

            const string AccessDenied = "Access to the channel denied";

            FileContent = "Connecting to Windows Service...";

            do
            {
                try
                {
                    if (_pathChannel == null)
                    {
                        var pathChannelOperationResult = Channel.OpenOutboundGlobalNoncontainerized("sample_path");

                        if (pathChannelOperationResult.Status == OperationStatus.ObjectAlreadyInUse)
                        {
                            FileContent = ChannelIsBroken;

                            return;
                        }

                        if (pathChannelOperationResult.Status == OperationStatus.AccessDenied)
                        {
                            FileContent = AccessDenied;

                            return;
                        }

                        if (pathChannelOperationResult.Status == OperationStatus.ObjectDoesNotExist)
                        {
                            await Task.Delay(TimeSpan.FromMilliseconds(100));
                        }
                        else
                        {
                            _pathChannel = pathChannelOperationResult.Data;
                        }
                    }

                    if (_fileChannel == null)
                    {
                        var fileChannelOperationResult = Channel.OpenInboundGlobalNoncontainerized("sample_file");

                        if (fileChannelOperationResult.Status == OperationStatus.ObjectAlreadyInUse)
                        {
                            FileContent = ChannelIsBroken;

                            return;
                        }

                        if (fileChannelOperationResult.Status == OperationStatus.AccessDenied)
                        {
                            FileContent = AccessDenied;

                            return;
                        }

                        if (fileChannelOperationResult.Status == OperationStatus.ObjectDoesNotExist)
                        {
                            await Task.Delay(TimeSpan.FromMilliseconds(100));
                        }
                        else
                        {
                            _fileChannel = fileChannelOperationResult.Data;
                        }
                    }
                }
                catch (Exception e)
                {
                    FileContent += "\n\n" + e.ToString();

                    return;
                }
            }while (_pathChannel == null || _fileChannel == null);

            FileContent = string.Empty;

            AreChannelsOpened = true;
        }