예제 #1
0
        private void CreateRpcConnection(string server, RpcProtocol protocol, NetworkCredential credential = null)
        {
            EndpointBindingInfo binding;

            switch (protocol)
            {
            case RpcProtocol.TCP:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_ip_tcp, server, null);
                break;

            case RpcProtocol.SMB:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_np, server, DrsNamedPipeName);
                if (credential != null)
                {
                    // Connect named pipe
                    this.npConnection = new NamedPipeConnection(server, credential);
                }
                break;

            default:
                // TODO: Custom exception type
                // TODO: Extract as string
                throw new Exception("Unsupported RPC protocol");
            }
            NetworkCredential rpcCredential = credential ?? Client.Self;

            this.rpcConnection = new NativeClient(binding);
            this.rpcConnection.AuthenticateAs(rpcCredential);
        }
예제 #2
0
 private void OnDisconnected(NamedPipeConnection <string, string> connection)
 {
     richTextBoxMessages.Invoke(new Action(delegate
     {
         AddLine("<b>Disconnected from server</b>");
     }));
 }
예제 #3
0
 private void OnServerMessage(NamedPipeConnection<string, string> connection, string message)
 {
     richTextBoxMessages.Invoke(new Action(delegate
         {
             AddLine("<b>Server</b>: " + message);
         }));
 }
예제 #4
0
        private void TheClient_ServerMessage(NamedPipeConnection <ContextContent, ContextContent> connection, ContextContent message)
        {
            if (!this.initialised)
            {
                this.Log("[SharedContext Client] " + (this._lock ? "Client" : "Trigger") + " initialised: " + connection.Name + " > " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fffff tt"));
                this.initialised = true;
                if (!this._lock)
                {
                    return;
                }
            }

            if (this.expectingLastMessage)
            {
                this.lastMessageReceived = true;
            }

            this.Log("[SharedContext " + (this._lock ? "Client" : "Trigger") + "] Message received . " + connection.Name + " > Message: " + message.ToString() + " > " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fffff tt"));
            this.deserialisedContextContents = message;

            if (EventHandler != null)
            {
                EventHandler.Invoke((object)connection, message);
            }
        }
예제 #5
0
 private void OnServerMessage(NamedPipeConnection <string, string> connection, string message)
 {
     richTextBoxMessages.Invoke(new Action(delegate
     {
         AddLine("<b>Server</b>: " + message);
     }));
 }
예제 #6
0
 private void OnClientConnected(NamedPipeConnection<string, string> connection)
 {
     _clients.Add(connection.Name);
     AddLine("<b>" + connection.Name + "</b> connected!");
     UpdateClientList();
     connection.PushMessage("Welcome!  You are now connected to the server.");
 }
예제 #7
0
        /// <summary>
        /// Thread method for a single listener thread
        /// </summary>
        private void ListenerThreadProc(object listenerInfo)
        {
            ListenerInfo myListenerInfo = (ListenerInfo)listenerInfo;

            try
            {
                NamedPipeServerStream serverPipe = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, _maxClients, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                serverPipe.WaitForConnection();

                _logger.InfoFormat("New client connection to '{0}'", _pipeName);

                //Once the client is connected we "convert" the listener to a simple connection,
                //there is no need to know afterwards that this was a Listener...sometime ago...
                NamedPipeConnection pipe = new NamedPipeConnection(serverPipe);
                RaiseClientConnectedEvent(pipe);

                lock (_listeners)
                {
                    _listeners.Remove(myListenerInfo);
                }

                Listen();
            }
            catch (ThreadAbortException)
            {
            }
        }
예제 #8
0
 private void OnDisconnected(NamedPipeConnection<string, string> connection)
 {
     richTextBoxMessages.Invoke(new Action(delegate
         {
             AddLine("<b>Disconnected from server</b>");
         }));
 }
예제 #9
0
파일: BeSafe.cs 프로젝트: morristech/BeSafe
        private void OnClientCommandReceived(NamedPipeConnection <BeSafePipeCommand, BeSafePipeCommand> connection, BeSafePipeCommand command)
        {
            try
            {
                switch (command.Command)
                {
                case PipeCommands.ComponentConfiguration:
                {
                    bool sotreSettingResult = new ServiceSetting().StoreConfigFilePath(command.ConfigFilePath);
                    if (sotreSettingResult)
                    {
                        ConfigApplier();
                    }
                }
                break;

                case PipeCommands.ReloadPlugins:
                {
                }
                break;

                case PipeCommands.Notification:
                {
                }
                break;
                }
            }
            catch (Exception ex)
            {
                ex.Log();
            }
        }
예제 #10
0
        private static void PipeClient_ServerMessage(NamedPipeConnection <string, string> connection, string message)
        {
            if (pipeCancellation != null)
            {
                return;
            }
            PipeCommandReceived?.Invoke(null, new PipeEventArgs(message));
            int res = -1;

            switch (message)
            {
            case PipeCommands.ExecuteScenario:
                pipeCancellation = new CancellationTokenSource();
                res = Scenario.Execute(pipeCancellation);
                break;

            case PipeCommands.LoopScenario:
                pipeCancellation = new CancellationTokenSource();
                res = Scenario.Loop(pipeCancellation);
                break;

            case PipeCommands.StopScenario:
                pipeCancellation.Cancel();
                break;

            default:
                break;
            }
            pipeCancellation = null;
            pipeClient.PushMessage(res.ToString());
        }
예제 #11
0
 private void OnClientMessage(NamedPipeConnection <MyMessage, MyMessage> connection, MyMessage message)
 {
     if (NewLightMngtOrder != null)
     {
         NewLightMngtOrder(message.RoomId, message.FixId, message.Level);
     }
 }
        private void CreateRpcConnection(string server, RpcProtocol protocol, NetworkCredential credential = null)
        {
            EndpointBindingInfo binding;

            switch (protocol)
            {
            case RpcProtocol.TCP:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_ip_tcp, server, null);
                break;

            case RpcProtocol.SMB:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_np, server, DrsNamedPipeName);
                if (credential != null)
                {
                    // Connect named pipe
                    this.npConnection = new NamedPipeConnection(server, credential);
                }
                break;

            default:
                // TODO: Extract as string
                throw new NotImplementedException("The requested RPC protocol is not supported.");
            }
            this.rpcConnection = new NativeClient(binding);

            NetworkCredential rpcCredential = credential ?? Client.Self;
            string            spn           = String.Format(ServicePrincipalNameFormat, server);

            this.rpcConnection.AuthenticateAs(spn, rpcCredential, RPC_C_AUTHN_LEVEL.RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN.RPC_C_AUTHN_GSS_NEGOTIATE);
        }
예제 #13
0
 private void CheckExit(NamedPipeConnection <Message, Message> connection, Message message)
 {
     if (message.Command == IPC.Command.Exit)
     {
         SignalExit();
     }
 }
예제 #14
0
        private void server_ClientMessage(NamedPipeConnection <string, string> connection, string message)
        {
            if (!_shortcutCallbackMap.ContainsKey(message))
            {
                switch (message)
                {
                case "sentcopy":
                    _sentCopyToken.Cancel();
                    break;

                case "sentcut":
                    _sentCutToken.Cancel();
                    break;

                case "sentpaste":
                    _sentPasteToken.Cancel();
                    break;

                default:
                    break;
                }
            }

            _shortcutCallbackMap.GetValueOrDefault(message)?.Invoke();
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (this.drsConnection != null)
            {
                this.drsConnection.Dispose();
                this.drsConnection = null;
            }

            if (this.rpcConnection != null)
            {
                this.rpcConnection.Dispose();
                this.rpcConnection = null;
            }

            if (this.npConnection != null)
            {
                this.npConnection.Dispose();
                this.npConnection = null;
            }
        }
예제 #16
0
 private void ServerOnClientMessage(NamedPipeConnection <byte[], byte[]> connection, byte[] message)
 {
     Logger.DebugFormat("Received {0} bytes from the client", message.Length);
     _actualData = message;
     _actualHash = Hash(message);
     _barrier.Set();
 }
예제 #17
0
 private void ServerOnClientMessage(NamedPipeConnection <TestCollection, TestCollection> connection, TestCollection message)
 {
     Logger.DebugFormat("Received collection with {0} items from the client", message.Count);
     _actualData = message;
     _actualHash = message.GetHashCode();
     _barrier.Set();
 }
예제 #18
0
 private void CheckPropertyChangedMessage(NamedPipeConnection <Message, Message> connection, Message message)
 {
     if (message.Command == Command.PropertyChanged)
     {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(message.Property));
     }
 }
예제 #19
0
파일: Server.cs 프로젝트: 15831944/SDM
        private void ClientMessage(NamedPipeConnection <string, string> connection, string message)
        {
            var logMessage = $"Received the following message from client: {message}";

            Logger.Get().Log(logMessage); this.DoWork(message);
            this._serverPipe.PushMessage(string.Empty);
        }
 private void OnAttachDebuggerMessageReceived(NamedPipeConnection <AttachDebuggerMessage, AttachDebuggerMessage> connection,
                                              AttachDebuggerMessage message)
 {
     try
     {
         message.DebuggerAttachedSuccessfully = _debuggerAttacher.AttachDebugger(message.ProcessId);
         if (!message.DebuggerAttachedSuccessfully)
         {
             message.ErrorMessage = $"Could not attach debugger to process {message.ProcessId} for unknown reasons";
         }
     }
     catch (Exception e)
     {
         message.DebuggerAttachedSuccessfully = false;
         message.ErrorMessage = $"Could not attach debugger to process {message.ProcessId} because of exception on server side:{Environment.NewLine}{e}";
     }
     finally
     {
         try
         {
             _server.PushMessage(message);
         }
         catch (Exception e)
         {
             _logger.LogError($"Exception on server side while sending debugging response message:{Environment.NewLine}{e}");
         }
     }
 }
예제 #21
0
 private void _pipeServer_ClientMessage(NamedPipeConnection <PipeClass, PipeClass> connection, PipeClass message)
 {
     if (message.Current == KeyEnum.Message)
     {
         _serverMessages.Add((string)message.Data);
     }
     else if (message.Current == KeyEnum.Kick)
     {
         _serverKicks.Add((string)message.Data);
     }
     else if (message.Current == KeyEnum.Ban)
     {
         var data = (NameReason)message.Data;
         if (!_serverBans.Any(x => string.Equals(x.Key, data.Name, StringComparison.CurrentCultureIgnoreCase)))
         {
             _serverBans.Add(data.Name, data.Reason);
         }
     }
     else if (message.Current == KeyEnum.Unban)
     {
         _serverUnbans.Add((string)message.Data);
     }
     else if (message.Current == KeyEnum.Mute)
     {
         var data = (NameMinutes)message.Data;
         if (!_serverMutes.Any(x => string.Equals(x.Key, data.Name, StringComparison.CurrentCultureIgnoreCase)))
         {
             _serverMutes.Add(data.Name, data.Minutes);
         }
     }
     else if (message.Current == KeyEnum.UnMute)
     {
         _serverUnMutes.Add((string)message.Data);
     }
 }
예제 #22
0
 private void OnClientConnected(NamedPipeConnection <string, string> connection)
 {
     _clients.Add(connection.Name);
     AddLine("<b>" + connection.Name + "</b> connected!");
     UpdateClientList();
     connection.PushMessage("Welcome!  You are now connected to the server.");
 }
예제 #23
0
 private void TheServer_ClientConnected(NamedPipeConnection <ContextContent, ContextContent> connection)
 {
     // Send current context
     this.Log("[SharedContext Server] Client connected. " + connection.Name + " > " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fffff tt"));
     this.Log("[SharedContext Server] Sending context: " + this.deserialisedContextContents.ToString() + " > " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fffff tt"));
     connection.PushMessage(this.deserialisedContextContents);
 }
예제 #24
0
        private static void HandleReceivedMessage(NamedPipeConnection <Message, Message> conn, Message message, string serverName)
        {
            List <string> argumentTokens = new List <string>(message.Text.Split(new string[] { "--" }, StringSplitOptions.None));

            if (argumentTokens.Count > 0)
            {
                string command     = argumentTokens.FirstOrDefault().Trim();
                var    commandType = AvailableCommandLookup.All.FirstOrDefault(x => x.Key == command);

                if (!commandType.Equals(default(KeyValuePair <string, Type>)))
                {
                    IDictionary <string, string> parameters = argumentTokens.Skip(1).Select(x => x.Split('=')).ToDictionary(y => y[0].Trim(), z => z[1].Trim());
                    ICommand commandInstance = (ICommand)Activator.CreateInstance(commandType.Value, parameters);

                    try
                    {
                        commandInstance.Handle();
                    }
                    catch (Exception ex)
                    {
                        // todo: we probably don't want to shutdown on every single exception but let's just do a
                        // catch all for now
                        ExceptionService.HandleException(ex, commandInstance.Name);
                        Program.Terminate();
                    }
                }
            }
        }
예제 #25
0
        private void OnClientMessage(NamedPipeConnection <ServerCommand, ServerCommand> connection,
                                     ServerCommand command)
        {
            if (command.Action == ServerAction.RebootServer)
            {
                GlobalSettings.Load();
                _fileServer.Stop();
                Thread.Sleep(3000);
                _fileServer.Start();
            }

            if (command.Action == ServerAction.StopServer)
            {
                _fileServer.Stop();
                Thread.Sleep(3000);
            }

            if (command.Action == ServerAction.StartServer)
            {
                GlobalSettings.Load();
                Thread.Sleep(3000);
                _fileServer.Start();
                Thread.Sleep(3000);
            }
        }
예제 #26
0
        private void Server_ClientConnected(NamedPipeConnection<PipeMessage, PipeMessage> connection)
        {
            Console.WriteLine("Client {0} is now connected.", connection.Id);

            if (!CancelToken.IsCancellationRequested)
                connection.PushMessage(new PipeMessage() { Ack = true });
        }
예제 #27
0
        private void OnClientMessage(NamedPipeConnection <PipeMessageCommand, PipeMessageCommand> connection, PipeMessageCommand message)
        {
            stopwatchLastCommand.Restart();

            if (message.Command == "Quit!")
            {
                KeepRunning = false;
            }
            if (message.Command.StartsWith("File"))
            {
                string fullFilePath = message.FullFileName;
                WriteResponseLine("Client {" + connection.Id + "} Proccessing file: {" + fullFilePath + "}");
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                Metadata metadata = databaseWindowsLivePhotGallery.Read(MetadataBrokerType.WindowsLivePhotoGallery, fullFilePath);

                WriteResponseLine(
                    "Client ID: {" + connection.Id + "}, " +
                    (metadata == null ? "File not found" : "Data found") + " " +
                    "File: {" + fullFilePath + "}, " +
                    "Time Elapsed Milliseconds: {" + stopwatch.ElapsedMilliseconds.ToString() + "}");

                PipeMessageCommand pipeMessageCommand = new PipeMessageCommand();
                pipeMessageCommand.FullFileName = fullFilePath;
                pipeMessageCommand.Command      = "File";
                pipeMessageCommand.Message      = "File:" + fullFilePath;
                pipeMessageCommand.Metadata     = metadata;
                connection.PushMessage(pipeMessageCommand);
            }
            else
            {
                WriteResponseLine("Unknown command: " + message.Command);
            }
        }
예제 #28
0
 private static void Error(NamedPipeConnection <Message, Message> conn)
 {
     conn.PushMessage(new Message()
     {
         Command = Command.Error,
         Data    = null
     });
 }
예제 #29
0
 static void server_ClientMessage(NamedPipeConnection <string, string> connection, string message)
 {
     Console.WriteLine("Client {0} says: {1}", connection.Id, message);
     //if (message.job2print != 0)
     //{
     //    jobs.print(message.job2print);
     //}
 }
예제 #30
0
 private void OnServerMessage(NamedPipeConnection <byte[], byte[]> connection, byte[] message)
 {
     if (message.Length > 0)
     {
         _answers.Enqueue(message);
     }
     _messageWasReceived = true;
 }
예제 #31
0
 /// <summary>
 /// Handles client connection
 /// </summary>
 /// <param name="connection"></param>
 private static void OnClientConnected(NamedPipeConnection <SerializedFunction, SerializedResult> connection)
 {
     lock (client_lock)
     {
         // TODO: create new client
         Log.WriteLine("Client connected [{0}]...", connection.Id);
     }
 }
예제 #32
0
 private void Server_ClientMessage(NamedPipeConnection<PipeMessage, PipeMessage> connection, PipeMessage message)
 {
     if (message.ShutdownRequest)
     {
         Console.WriteLine("Shutdown requested by client " + connection.Id);
         _cancellationTokenSource.Cancel();
     }
 }
 private void PipeClient_Disconnected(NamedPipeConnection <PipeMessageCommand, PipeMessageCommand> connection)
 {
     Logger.Trace("[Windows Live Photo Gallery | Pipe Client] Disconnected - Id: {" + connection.Id + "} Disconnect Pipe");
     lock (_PipeClientLock)
     {
         pipeClientDiconnected = true;
     }
 }
예제 #34
0
 private void OnClientConnected(NamedPipeConnection<MyMessage, MyMessage> connection)
 {
     Console.WriteLine("Client {0} is now connected!", connection.Id);
     connection.PushMessage(new MyMessage
         {
             Id = new Random().Next(),
             Text = "Welcome!"
         });
 }
예제 #35
0
        private void OnNamedPipeClientMessage(NamedPipeConnection <string[], string[]> conn, string[] message)
        {
            ThemeManager.importPaths.AddRange(message);

            if (!ThemeManager.importMode)
            {
                notifyIcon.ContextMenuStrip.BeginInvoke(new Action(() => ThemeManager.SelectTheme()));
            }
        }
예제 #36
0
 private void OnClientConnected(NamedPipeConnection <MyMessage, MyMessage> connection)
 {
     Console.WriteLine("Client {0} is now connected!", connection.Id);
     connection.PushMessage(new MyMessage
     {
         Id   = new Random().Next(),
         Text = "Welcome!"
     });
 }
예제 #37
0
        private void Client_ServerMessage(NamedPipeConnection<PipeMessage, PipeMessage> connection, PipeMessage message)
        {
            if (message.Ack)
            {
                _ack = true;
            }

            if (message.ShuttedDown)
            {
                _waitToken.Cancel(false);
            }
        }
예제 #38
0
파일: Events.cs 프로젝트: jaywick/pastr
        private void server_ClientMessage(NamedPipeConnection<string, string> connection, string message)
        {
            if (!_shortcutCallbackMap.ContainsKey(message))
            {
                switch (message)
                {
                    case "sentcopy":
                        _sentCopyToken.Cancel();
                        break;
                    case "sentcut":
                        _sentCutToken.Cancel();
                        break;
                    case "sentpaste":
                        _sentPasteToken.Cancel();
                        break;
                    default:
                        break;
                }
            }

            _shortcutCallbackMap[message].Invoke();
        }
예제 #39
0
 private void OnClientDisconnected(NamedPipeConnection<string, string> connection)
 {
     _clients.Remove(connection.Name);
     AddLine("<b>" + connection.Name + "</b> disconnected!");
     UpdateClientList();
 }
예제 #40
0
            /// <summary>
            /// Initializes a new instance of the <see cref="ConnectedCommand" /> class.
            /// </summary>
            /// <param name="connectionGuid">The connection unique identifier.</param>
            /// <param name="service">The service.</param>
            /// <param name="connection">The connection.</param>
            /// <param name="request">The request.</param>
            /// <param name="token">The cancellation token.</param>
            public ConnectedCommand(
                Guid connectionGuid,
                [NotNull] BaseService service,
                [NotNull] NamedPipeConnection connection,
                [NotNull] CommandRequest request,
                CancellationToken token = default(CancellationToken))
            {
                ConnectionGuid = connectionGuid;
                _connection = connection;
                _request = request;
                _cancellationTokenSource = token.ToCancelable();
                ID = _request.ID;

                token = _cancellationTokenSource.Token;

                Task.Run(
                    async () =>
                    {
                        try
                        {
                            do
                            {
                                // ReSharper disable once PossibleNullReferenceException
                                await Task.Delay(250, token).ConfigureAwait(false);
                                if (token.IsCancellationRequested) return;
                                await Flush(0, token).ConfigureAwait(false);
                            } while (true);
                        }
                        catch (TaskCanceledException)
                        {
                        }
                    },
                    token);
                // Kick of task to run command.
                Task.Run(
                    async () =>
                    {
                        Exception exception = null;
                        bool cancelled = false;
                        try
                        {
                            await
                                service.ExecuteAsync(ConnectionGuid, _request.CommandLine, this, token)
                                    .ConfigureAwait(false);
                            if (!token.IsCancellationRequested)
                                await Flush(-1, token).ConfigureAwait(false);
                            else
                                cancelled = true;
                        }
                        catch (OperationCanceledException)
                        {
                            cancelled = true;
                        }
                        catch (Exception e)
                        {
                            exception = e;
                        }

                        if (cancelled)
                            using (await _flushLock.LockAsync(token).ConfigureAwait(false))
                            {
                                try
                                {
                                    using (CancellationTokenSource cts = Constants.FireAndForgetTokenSource)
                                        await connection.Send(
                                            new CommandCancelResponse(
                                                _cancelRequest != null ? _cancelRequest.ID : Guid.Empty,
                                                ID),
                                            cts.Token)
                                            .ConfigureAwait(false);
                                }
                                catch (OperationCanceledException)
                                {
                                }
                                return;
                            }

                        if (exception != null)
                            try
                            {
                                await Flush(0, token).ConfigureAwait(false);
                                _builder.Append(exception.Message);
                                await Flush(-2, token).ConfigureAwait(false);
                            }
                                // ReSharper disable once EmptyGeneralCatchClause
                            catch
                            {
                            }

                        Dispose(true);
                    },
                    token);
            }
예제 #41
0
 private void ServerOnClientDisconnected(NamedPipeConnection<byte[], byte[]> connection)
 {
     Logger.Warn("Client disconnected");
     _clientDisconnected = true;
     _barrier.Set();
 }
예제 #42
0
 private void OnClientMessage(NamedPipeConnection<MyMessage, MyMessage> connection, MyMessage message)
 {
     Console.WriteLine("Client {0} says: {1}", connection.Id, message);
 }
        void mediaScribeServer_ServerMessage(NamedPipeConnection<string, string> connection, string message)
        {
            Task.Factory.StartNew(() =>
            {
                if (message == "ABORT")
                {
                    if(generator.State == ThumbnailGenerator.GeneratorState.Running)
                        generator.State = ThumbnailGenerator.GeneratorState.Cancelling;
                }
                else
                {
                    string[] args = message.Split(new[] { '|' });
                    if (args.Length != 4)
                    {
                        Console.WriteLine("Expected 4 args: thumbnail width, second step, thumbnail dir, and path to video file");
                        return;
                    }
                    int thumbnailWidth = Int32.Parse(args[0]);
                    int secondStep = Int32.Parse(args[1]);
                    string thumbnailDir = args[2];
                    string filepath = args[3];

                    if (false == File.Exists(filepath))
                    {
                        generator.State = ThumbnailGenerator.GeneratorState.Stopped;
                        Debug.WriteLine(string.Format("ThumbnailGenerator: the file '{0}' does not exist. Generation aborted.", filepath));
                        return;
                    }

                    bool successfulGeneration = false;
                    do
                    {
                        try
                        {
                            int sleepDurationMs = 30;
                            int totalSleepTimeMs = 0;
                            while (generator.State != ThumbnailGenerator.GeneratorState.Stopped)
                            {
                                Thread.Sleep(sleepDurationMs);
                                totalSleepTimeMs += sleepDurationMs;
                                if (sleepDurationMs > 1000)
                                    throw new Exception("ThumbnailGenerator error, taking over a second to cancel last generation?");
                            }

                            successfulGeneration = false;
                            generator.Generate(thumbnailWidth, secondStep, thumbnailDir, filepath, mediaScribeServer);
                            successfulGeneration = true;
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Thumbnail generator crashed: " + ex.ToString());
                            try
                            {
                                generator.Dispose();
                            }
                            catch { }
                            generator = new ThumbnailGenerator();
                        }
                    }
                    while (false == successfulGeneration);
                }
            });
        }
예제 #44
0
 //private void PipesMessageHandler(string message)
 //{
 //    try
 //    {
 //        if (Convert.ToInt32(message.Trim()) > 0)
 //        {
 //            stimcode = Convert.ToInt32(message.Trim());
 //            Debug.WriteLine("New stimcode: " + stimcode);
 //        }
 //    }
 //    catch (Exception ex)
 //    {
 //        Debug.WriteLine(ex.Message);
 //    }
 //}
 private void OnServerMessage(NamedPipeConnection<string,string> connection, string message)
 {
     Console.WriteLine("Server says: {0}", message);
 }
예제 #45
0
 private void OnServerMessage(NamedPipeConnection<string, string> connection, string message)
 {
     Console.WriteLine("Server says: {0}", message);
     int value;
     if (int.TryParse(message, out value))
     {
         if (value > 0)
             MainWindow.stimcode = value;
         else
             throw new ArgumentOutOfRangeException("Stimcode should only be positive");
     }
 }
예제 #46
0
 private void OnServerMessage(NamedPipeConnection<MyMessage, MyMessage> connection, MyMessage message)
 {
     Console.WriteLine("Server says: {0}", message);
 }
예제 #47
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NamedPipeServer" /> class.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="configuration">The configuration.</param>
        /// <exception cref="ServiceException">
        /// </exception>
        public NamedPipeServer(
            [NotNull] BaseService service,
            [NotNull] ServerConfig configuration)
        {
            if (service == null) throw new ArgumentNullException("service");
            if (configuration == null) throw new ArgumentNullException("configuration");
            if (configuration.MaximumConnections < 1)
                throw new ArgumentOutOfRangeException("configuration", CommonResources.NamedPipeServer_MaxConnections);

            Service = service;
            MaximumConnections = configuration.MaximumConnections;
            if (!string.IsNullOrWhiteSpace(configuration.Name))
                // ReSharper disable once AssignNullToNotNullAttribute
                Name = configuration.Name;
            else
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(Guid.NewGuid().ToString("D"))
                    .Append('_');
                Debug.Assert(service.ServiceName != null);
                foreach (char c in service.ServiceName)
                    builder.Append(char.IsLetterOrDigit(c) ? c : '_');
                builder.Append(Constants.NameSuffix);
                Name = builder.ToString();
            }

            // Create security context
            try
            {
                WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
                if (currentIdentity == null ||
                    currentIdentity.Owner == null)
                    throw new ServiceException(() => ServiceResources.Err_NamedPipeServer_CannotGetCurrentOwner);

                _pipeSecurity = new PipeSecurity();
                _pipeSecurity.AddAccessRule(
                    new PipeAccessRule(
                        configuration.Identity,
                        PipeAccessRights.ReadWrite,
                        AccessControlType.Allow));
                _pipeSecurity.AddAccessRule(
                    new PipeAccessRule(
                        currentIdentity.Owner,
                        PipeAccessRights.FullControl,
                        AccessControlType.Allow));
            }
            catch (Exception exception)
            {
                throw new ServiceException(exception, () => ServiceResources.Err_NamedPipeServer_Fatal_Error_Securing);
            }

            // Check no one has tried to create the pipe before us, combined with the GUID name this makes the most common
            // form of pipe attack (pre-registration) impossible.
            if (File.Exists(@"\\.\pipe\" + Name))
                throw new ServiceException(() => ServiceResources.Err_NamedPipeServer_PipeAlreadyExists);

            // Create a connection, before adding it to the list and starting.
            NamedPipeConnection connection = new NamedPipeConnection(this);
            _namedPipeConnections = new List<NamedPipeConnection>(MaximumConnections) { connection };
            connection.Start();
            _logger = new NamedPipeServerLogger(this);
            Log.AddLogger(_logger);

            _heartbeat = configuration.Heartbeat;
            if (_heartbeat < TimeSpan.Zero) return;

            _connectionCheckTimer = new Timer(CheckConnections);
            _connectionCheckTimer.Change(_heartbeat, Timeout.InfiniteTimeSpan);
        }
예제 #48
0
        private void OnDisconnected(NamedPipeConnection<string, string> connection)
        {
            _namedpipeServerConnected = false;

            //_namedpipeClient.Stop();
        }
예제 #49
0
 // 客户端连接上了NamedPipe
 private void OnClientConnected(NamedPipeConnection<string, string> connection)
 {
     connection.PushMessage(Constants.NamedPipe_Connect_Message);
     connection.PushMessage(Constants.NamedPipe_Command_USBCounting);
 }
예제 #50
0
        private void OnServerMessage(NamedPipeConnection<string, string> connection, string message)
        {
            if (!_namedpipeServerConnected)
            {
                _namedpipeServerConnected = true;
            }

            if (message.Equals("usbcounting"))
            {
                _namedpipeClient.PushMessage(string.Format("usbcounting {0}", _usbCount));
            }
        }
예제 #51
0
 // 客户端断开了NamedPipe
 private void OnClientDisconnected(NamedPipeConnection<string, string> connection)
 {
     LOG.Info(string.Format("client {0} disconnected.", connection.Name));
 }
예제 #52
0
 private void OnClientDisconnected(NamedPipeConnection<MyMessage, MyMessage> connection)
 {
     Console.WriteLine("Client {0} disconnected", connection.Id);
 }
예제 #53
0
        // 客户端发送的消息
        private void OnClientMessage(NamedPipeConnection<string, string> connection, string message)
        {
            LOG.Info("Message from service: " + message);

            // we only handle quit message
            if (message == Constants.NamedPipe_Command_Quit)
            {
                // quit app
                LOG.Info("client request to quit me.");
                SafeRemoveDevice();
            }
            else if (message.StartsWith(Constants.NamedPipe_Command_USBCounting + " "))
            {
                string cnt = message.Substring(Constants.NamedPipe_Command_USBCounting.Length + 1);

                LOG.Info("usb count=" + cnt);

                int v = 0;
                if (Int32.TryParse(cnt, out v))
                {
                    if (v > 0)
                    {
                        _usbCount = v;
                        _avalonFloatWindow.USBCount = v;

                        //bool postSucceed = User32.PostMessage(_avalonFloatWindow.Handle, 0x0400 + 100, 0, 0);
                        ShowFloatWindow(true);

                        LOG.Info("==ready to show home window");
                        //ShowHome(true);
                        //SafeControlUpdater.Invalidate(pictureBoxGraph);
                        this.notifyIcon1.Visible = true;

                        LOG.Info("==restart miner application");
                        RestartBfgMiner();
                    }
                    else
                    {
                        SafeRemoveDevice();
                    }
                }
            }
        }
예제 #54
0
        /// <summary>
        /// Starts a new listening connection, if there is capacity.
        /// </summary>
        private void Add()
        {
            lock (_namedPipeConnections)
            {
                // Sanity check, this will remove any connections that were terminated before they could tell us!
                // ReSharper disable once PossibleNullReferenceException
                _namedPipeConnections.RemoveAll(c => c.State == PipeState.Closed);

                if (_namedPipeConnections.Count >= MaximumConnections || _disposed) return;

                // Create a new connection.
                NamedPipeConnection connection = new NamedPipeConnection(this);
                _namedPipeConnections.Add(connection);
                // Note we never start the connection until we've added it to the list, to avoid a race condition where
                // it is removed before it is started.
                connection.Start();
            }
        }
예제 #55
0
 private void ServerOnClientMessage(NamedPipeConnection<byte[], byte[]> connection, byte[] message)
 {
     Logger.DebugFormat("Received {0} bytes from the client", message.Length);
     _actualData = message;
     _actualHash = Hash(message);
     _barrier.Set();
 }