Example #1
0
 public DataExplorerStartable(IMenuService menuService, IMessageStream messageStream,
                              Func <ExplorerViewModel> explorerViewModelFactory)
 {
     _menuService              = menuService;
     _messageStream            = messageStream;
     _explorerViewModelFactory = explorerViewModelFactory;
 }
Example #2
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            IMessageStream <PublishDocumentMessage> eventStream =
                await _messageReceiver.SubscribeAsync(stoppingToken).ConfigureAwait(false);

            await foreach (PublishDocumentMessage? message in
                           eventStream.WithCancellation(stoppingToken))
            {
                if (message is null)
                {
                    break;
                }

                try
                {
                    foreach (IPublishDocumentHandler handler in _publishDocumentHandlers)
                    {
                        if (await handler.CanHandleAsync(message, stoppingToken).ConfigureAwait(false))
                        {
                            await handler.HandleAsync(message, stoppingToken).ConfigureAwait(false);

                            break;
                        }
                    }

                    await eventStream.CompleteAsync().ConfigureAwait(false);
                }
                catch { }
            }
        }
Example #3
0
 private DBusConnection(IMessageStream stream, IEnumerable <IClientObjectProvider> clientProviders)
 {
     _stream             = stream;
     this.proxyProviders = clientProviders;
     _sendQueue          = new ConcurrentQueue <PendingSend>();
     _sendSemaphore      = new SemaphoreSlim(1);
 }
 private void _lifeStream_OnClientDisconnected(IMessageStream socket)
 {
     if (OnFail != null)
     {
         OnFail();
     }
 }
Example #5
0
        static void Main(string[] args)
        {
            int       port    = 8500;
            IPAddress address = IPAddress.Loopback;

            if (args.Length > 0 && !int.TryParse(args[0], out port))
            {
                Console.WriteLine($"Could not parse {args[0]} to int.");
                port = 8500;
            }
            if (args.Length > 1 && !IPAddress.TryParse(args[1], out address))
            {
                Console.WriteLine($"Could not parse {args[1]} to IPAddress.");
                address = IPAddress.Loopback;
            }
            Console.WriteLine($"Client trying connect to {address}:{port}.");
            IConnectionModule connectionModule = new TcpConnectionModule(new IPEndPoint(address, port));
            IMessageStream    stream           = connectionModule.Connect();

            if (stream == null)
            {
                return;
            }
            Console.WriteLine("Client connected.");
            Counting(3);
            Client client = new Client(stream);

            client.Start();
        }
Example #6
0
        // For testing
        internal static async Task <DBusConnection> CreateAndConnectAsync(IMessageStream stream, Action <Exception> onDisconnect = null)
        {
            var connection = new DBusConnection(stream);
            await connection.ConnectAsync(onDisconnect);

            return(connection);
        }
 public DataExplorerStartable(IMenuService menuService, IMessageStream messageStream,
                              Func<ExplorerViewModel> explorerViewModelFactory)
 {
     _menuService = menuService;
     _messageStream = messageStream;
     _explorerViewModelFactory = explorerViewModelFactory;
 }
Example #8
0
        private async void HandleMethodCall(Message methodCall, IMessageStream peer)
        {
            switch (methodCall.Header.Interface)
            {
            case "org.freedesktop.DBus.Peer":
                switch (methodCall.Header.Member)
                {
                case "Ping":
                {
                    SendMessage(MessageHelper.ConstructReply(methodCall), peer);
                    return;
                }

                case "GetMachineId":
                {
                    SendMessage(MessageHelper.ConstructReply(methodCall, Environment.MachineId), peer);
                    return;
                }
                }
                break;
            }

            MethodHandler methodHandler;

            if (_methodHandlers.TryGetValue(methodCall.Header.Path.Value, out methodHandler))
            {
                var reply = await methodHandler(methodCall);

                reply.Header.ReplySerial = methodCall.Header.Serial;
                reply.Header.Destination = methodCall.Header.Sender;
                SendMessage(reply, peer);
            }
            else
            {
                if (methodCall.Header.Interface == "org.freedesktop.DBus.Introspectable" &&
                    methodCall.Header.Member == "Introspect" &&
                    methodCall.Header.Path.HasValue)
                {
                    var path       = methodCall.Header.Path.Value;
                    var childNames = GetChildNames(path);
                    if (childNames.Length > 0)
                    {
                        var writer = new IntrospectionWriter();

                        writer.WriteDocType();
                        writer.WriteNodeStart(path.Value);
                        foreach (var child in childNames)
                        {
                            writer.WriteChildNode(child);
                        }
                        writer.WriteNodeEnd();

                        var xml = writer.ToString();
                        SendMessage(MessageHelper.ConstructReply(methodCall, xml), peer);
                    }
                }
                SendUnknownMethodError(methodCall, peer);
            }
        }
Example #9
0
 public CRMStartable(ILog log, IMenuService menuService, IMessageStream messageStream,
                     Func <ClientEditViewModel> clientEditViewModelFactory)
 {
     _log           = log;
     _menuService   = menuService;
     _messageStream = messageStream;
     _clientEditViewModelFactory = clientEditViewModelFactory;
 }
Example #10
0
 public CRMStartable(ILog log, IMenuService menuService, IMessageStream messageStream,
                     Func<ClientEditViewModel> clientEditViewModelFactory)
 {
     _log = log;
     _menuService = menuService;
     _messageStream = messageStream;
     _clientEditViewModelFactory = clientEditViewModelFactory;
 }
Example #11
0
 public Messenger(IConnecter <IDialog> connecter, IMessageStream <IMessage> messageStream,
                  IUsersManager usersManager, IInteracter interacter)
 {
     this.connecter     = connecter;
     this.messageStream = messageStream;
     this.usersManager  = usersManager;
     this.interacter    = interacter;
 }
 public static MessageStreamToCsvActivity WriteDataTo(IMessageStream reader, TextWriter writer)
 {
     var p = new MessageStreamToCsvActivity(reader, writer);
      p.WriteHeader();
      p.WriteData();
      writer.Flush();
      return p;
 }
Example #13
0
 private void EmitDisconnected(IMessageStream peer, Exception e)
 {
     lock (_gate)
     {
         _onDisconnect?.Invoke(e);
         _onDisconnect = null;
     }
 }
Example #14
0
 private void SendMessage(Message message, IMessageStream peer)
 {
     if (message.Header.Serial == 0)
     {
         message.Header.Serial = GenerateSerial();
     }
     peer.TrySendMessage(message);
 }
Example #15
0
 public DBusConnection(bool localServer)
 {
     if (localServer != true)
     {
         throw new ArgumentException("Constructor for LocalServer.", nameof(localServer));
     }
     _stream        = new LocalServer(this);
     ConnectionInfo = new ConnectionInfo(string.Empty);
 }
Example #16
0
        public IProcessedMessage Send(Object model, IMessageStream stream, MessageCallback callback)
        {
            MessageProcessorWorker processThread = new MessageProcessorWorker(model, stream, callback);
            Thread thread = new Thread(processThread.SendMessage);

            processThread.ThreadId = thread.ManagedThreadId;
            thread.Start();
            return(processThread);
        }
Example #17
0
        public IProcessedMessage Receive(byte[] message, IMessageStream stream, MessageCallback callback)
        {
            MessageProcessorWorker processThread = new MessageProcessorWorker(message, stream, callback);
            Thread thread = new Thread(processThread.ReceiveMessage);

            processThread.ThreadId = thread.ManagedThreadId;
            thread.Start();
            return(processThread);
        }
Example #18
0
 public EmployeeStartable(ILog log, IDispatcherSchedulerProvider scheduler, IMenuService menuService, IMessageStream messageStream,
                          Func <ReportViewModel> reportViewModelFactory)
 {
     _log                    = log;
     _scheduler              = scheduler;
     _menuService            = menuService;
     _messageStream          = messageStream;
     _reportViewModelFactory = reportViewModelFactory;
 }
Example #19
0
 public EmployeeStartable(ILog log, IDispatcherSchedulerProvider scheduler, IMenuService menuService, IMessageStream messageStream,
                         Func<ReportViewModel> reportViewModelFactory)
 {
     _log = log;
     _scheduler = scheduler;
     _menuService = menuService;
     _messageStream = messageStream;
     _reportViewModelFactory = reportViewModelFactory;
 }
Example #20
0
 public TradingStartable(ILog log, IMenuService menuService, IMessageStream messageStream,
                         Func<QuoteBlotterViewModel> quoteBlotterViewModelFactory,
                         Func<ChartViewModel> chartViewModelFactory)
 {
     _log = log;
     _menuService = menuService;
     _messageStream = messageStream;
     _quoteBlotterViewModelFactory = quoteBlotterViewModelFactory;
     _chartViewModelFactory = chartViewModelFactory;
 }
Example #21
0
 public TradingStartable(ILog log, IMenuService menuService, IMessageStream messageStream,
                         Func <QuoteBlotterViewModel> quoteBlotterViewModelFactory,
                         Func <ChartViewModel> chartViewModelFactory)
 {
     _log           = log;
     _menuService   = menuService;
     _messageStream = messageStream;
     _quoteBlotterViewModelFactory = quoteBlotterViewModelFactory;
     _chartViewModelFactory        = chartViewModelFactory;
 }
Example #22
0
        private void HandleMessage(Message msg, IMessageStream peer)
        {
            uint?serial = msg.Header.ReplySerial;

            if (serial != null)
            {
                uint serialValue = (uint)serial;
                TaskCompletionSource <Message> pending = null;
                lock (_gate)
                {
                    if (_pendingMethods?.TryGetValue(serialValue, out pending) == true)
                    {
                        _pendingMethods.Remove(serialValue);
                    }
                }
                if (pending != null)
                {
                    pending.SetResult(msg);
                }
                else
                {
                    throw new ProtocolException("Unexpected reply message received: MessageType = '" + msg.Header.MessageType + "', ReplySerial = " + serialValue);
                }
                return;
            }

            switch (msg.Header.MessageType)
            {
            case MessageType.MethodCall:
                HandleMethodCall(msg, peer);
                break;

            case MessageType.Signal:
                HandleSignal(msg);
                break;

            case MessageType.Error:
                string errMsg = String.Empty;
                if (msg.Header.Signature.Value.Value.StartsWith("s", StringComparison.Ordinal))
                {
                    MessageReader reader = new MessageReader(msg, null);
                    errMsg = reader.ReadString();
                }
                throw new DBusException(msg.Header.ErrorName, errMsg);

            case MessageType.Invalid:
            default:
                throw new ProtocolException("Invalid message received: MessageType='" + msg.Header.MessageType + "'");
            }
        }
Example #23
0
        private void SendUnknownMethodError(Message callMessage, IMessageStream peer)
        {
            if (!callMessage.Header.ReplyExpected)
            {
                return;
            }

            string errMsg = String.Format("Method \"{0}\" with signature \"{1}\" on interface \"{2}\" doesn't exist",
                                          callMessage.Header.Member,
                                          callMessage.Header.Signature?.Value,
                                          callMessage.Header.Interface);

            SendErrorReply(callMessage, "org.freedesktop.DBus.Error.UnknownMethod", errMsg, peer);
        }
Example #24
0
        /// <summary>
        /// Close the stream part
        /// </summary>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task CloseStreamAsync(CancellationToken ct)
        {
            IConnection    connection = _connection;
            IMessageStream stream     = _stream;

            _connection = null;
            _stream     = null;
            try {
                await stream.SendAsync(new Message(_socket.Id, RemoteId,
                                                   new CloseRequest()), ct).ConfigureAwait(false);
            }
            finally {
                await connection.CloseAsync().ConfigureAwait(false);
            }
        }
Example #25
0
        async void HandleMethodCall(Message methodCall, IMessageStream peer)
        {
            bool           pathKnown     = false;
            IMethodHandler methodHandler = null;

            if (methodCall.Header.Path.HasValue && !string.IsNullOrEmpty(methodCall.Header.Interface))
            {
                var pathHandler = PartHandlerForPath(methodCall.Header.Path.Value);
                if (pathHandler != null)
                {
                    pathKnown = true;
                    if (!pathHandler.InterfaceHandlers.TryGetValue(methodCall.Header.Interface, out methodHandler))
                    {
                        methodHandler = GlobalInterfaceHandlers.GetValueOrDefault(methodCall.Header.Interface);
                    }
                    if (methodHandler != null && !methodHandler.CheckExposure(methodCall.Header.Path.Value))
                    {
                        methodHandler = null;
                    }
                }
            }
            if (methodHandler != null)
            {
                var reply = await methodHandler.HandleMethodCall(methodCall);

                if (reply != null)
                {
                    reply.Header.ReplySerial = methodCall.Header.Serial;
                    reply.Header.Destination = methodCall.Header.Sender;
                    SendMessage(reply, peer);
                }
                else if (methodCall.Header.ReplyExpected)
                {
                    SendMessage(MessageHelper.ConstructReply(methodCall), peer);
                }
            }
            else if (methodCall.Header.ReplyExpected)
            {
                if (!pathKnown)
                {
                    SendErrorReply(methodCall, DBusErrors.UnknownObject, $"No objects at path {methodCall.Header.Path}", peer);
                }
                else
                {
                    SendErrorReply(methodCall, DBusErrors.UnknownInterface, $"No interface {methodCall.Header.Interface} at path {methodCall.Header.Path}", peer);
                }
            }
        }
Example #26
0
        public static async Task <DBusConnection> CreateAndConnectAsync(IMessageStream stream, Action <Exception> onDisconnect, IEnumerable <IClientObjectProvider> clientProviders, bool sayHelloToServer = true, TimeSpan?initialTimeout = null)
        {
            var dbusConnection = new DBusConnection(stream, clientProviders);

            if (initialTimeout.HasValue)
            {
                dbusConnection.Timeout = initialTimeout.Value;
            }
            foreach (var prov in clientProviders)
            {
                prov.DBusConnection = dbusConnection;
            }
            await dbusConnection.ConnectAsync(onDisconnect, default(CancellationToken), sayHelloToServer);

            return(dbusConnection);
        }
Example #27
0
        /// <summary>
        /// Close the stream part
        /// </summary>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task CloseStreamAsync(CancellationToken ct)
        {
            IConnection    connection = _connection;
            IMessageStream stream     = _stream;

            _connection = null;
            _stream     = null;
            try {
                ProxyEventSource.Log.StreamClosing(this, _stream);
                await stream.SendAsync(new Message(_socket.Id, RemoteId,
                                                   new CloseRequest()), ct).ConfigureAwait(false);
            }
            finally {
                await connection.CloseAsync().ConfigureAwait(false);

                ProxyEventSource.Log.StreamClosed(this, null);
            }
        }
Example #28
0
 public void ClientDisconnected(IMessageStream messageStream)
 {
     lock (this)
     {
         if (ClientToName.Remove(messageStream, out string name))
         {
             var previousRoom = Rooms.FirstOrDefault(p => p.Value.Contains(messageStream));
             if (!previousRoom.Equals(new KeyValuePair <string, HashSet <IMessageStream> >()))
             {
                 previousRoom.Value.Remove(messageStream);
                 foreach (var stream in previousRoom.Value)
                 {
                     stream.SendMessageAsync(new ClientExitedMessage {
                         ClientName = name
                     });
                 }
             }
         }
     }
 }
Example #29
0
        internal async void ReceiveMessages(IMessageStream peer, Action <IMessageStream, Exception> disconnectAction)
        {
            try
            {
                while (true)
                {
                    Message msg = await peer.ReceiveMessageAsync();

                    if (msg == null)
                    {
                        throw new IOException("Connection closed by peer");
                    }
                    HandleMessage(msg, peer);
                }
            }
            catch (Exception e)
            {
                disconnectAction?.Invoke(peer, e);
            }
        }
Example #30
0
        private void RemoveStream(IMessageStream client, Exception e)
        {
            lock (_gate)
            {
                if (IsDisposed)
                {
                    return;
                }

                var clientsUpdated = new IMessageStream[_clients.Length - 1];
                for (int i = 0, j = 0; i < _clients.Length; i++)
                {
                    if (_clients[i] != client)
                    {
                        clientsUpdated[j++] = _clients[i];
                    }
                }
                _clients = clientsUpdated;
            }
            client.Dispose();
        }
Example #31
0
        public ShellViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog,
                              IToolBarService toolBarService, IMenuService menuService,
                              BindableCollection <IViewModel> itemsCollection,
                              BindableCollection <Link> lnkCollection,
                              IMessageStream messageStream,
                              IUserInteraction userInteraction,
                              Func <IUserInteractionHostViewModel> userInteractionHostViewModelFactory)
            : base(log, scheduler, standardDialog)
        {
            _userInteractionHostViewModelFactory = userInteractionHostViewModelFactory;
            ToolBarItems = toolBarService.Items;
            MenuItems    = menuService.Items;

            TitleLinks = lnkCollection;
            Items      = itemsCollection;

            messageStream.Of <IViewModel>()
            .ObserveOn(Scheduler.Dispatcher.RX)
            .Subscribe(x => Items.Add(x));

            userInteraction.RegisterHandler(UserInteractionModalHandler);
        }
Example #32
0
        public async void AcceptConnections()
        {
            while (true)
            {
                Socket clientSocket = null;
                try
                {
                    try
                    {
                        clientSocket = await _serverSocket.AcceptAsync().ConfigureAwait(false);
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }

                    var client = await Transport.AcceptAsync(clientSocket,
                                                             supportsFdPassing : _serverSocket.AddressFamily == AddressFamily.Unix).ConfigureAwait(false);

                    lock (_gate)
                    {
                        if (IsDisposed)
                        {
                            client.Dispose();
                            break;
                        }
                        var clientsUpdated = new IMessageStream[_clients.Length + 1];
                        Array.Copy(_clients, clientsUpdated, _clients.Length);
                        clientsUpdated[clientsUpdated.Length - 1] = client;
                        _clients = clientsUpdated;
                    }
                    _connection.ReceiveMessages(client, RemoveStream);
                }
                catch
                {
                    clientSocket?.Dispose();
                }
            }
        }
Example #33
0
        public static async Task <DBusConnection> ConnectAsync(ClientSetupResult connectionContext, Action <Exception> onDisconnect, CancellationToken cancellationToken, IEnumerable <IClientObjectProvider> clientProviders)
        {
            var _entries = AddressEntry.ParseEntries(connectionContext.ConnectionAddress);

            if (_entries.Length == 0)
            {
                throw new ArgumentException("No addresses were found", nameof(connectionContext.ConnectionAddress));
            }

            Guid           _serverId = Guid.Empty;
            IMessageStream stream    = null;
            var            index     = 0;

            while (index < _entries.Length)
            {
                AddressEntry entry = _entries[index++];

                _serverId = entry.Guid;
                try
                {
                    stream = await Transport.ConnectAsync(entry, connectionContext, cancellationToken)
                             .TimeoutAfter(connectionContext.InitialTimeout)
                             .ConfigureAwait(false);
                }
                catch
                {
                    if (index < _entries.Length)
                    {
                        continue;
                    }
                    throw;
                }

                break;
            }
            return(await CreateAndConnectAsync(stream, onDisconnect, clientProviders, true, connectionContext.InitialTimeout));
        }
Example #34
0
 public void Setup()
 {
     m_MessageStream = new ReactiveMessageStream <String>("test-stream");
 }
 public MessageWriter(IMessageStream messageStream) => _messageStream = messageStream;
 public MessageContentStreamToCsvActivity(IMessageStream stream, TextWriter writer)
 {
     this.stream = stream;
      var config = new CsvConfiguration { Encoding = Encoding.UTF8, HasHeaderRecord = true, };
      csv = new CsvWriter(writer, config);
 }