public void Start() { this.portMonitor = new PortMonitor(); IpcHandler ipcHandler = new IpcHandler(); ipcHandler.AddMonitorPort += new IpcHandler.AddMonitorPortEventHandler(portMonitor.AddPort); ipcHandler.DeleteMonitorPort += new IpcHandler.DeleteMonitorPortEventHandler(portMonitor.DeletePort); ipcHandler.OpenMonitorPort += new IpcHandler.OpenMonitorPortEventHandler(portMonitor.OpenPort); ipcHandler.CloseMonitorPort += new IpcHandler.CloseMonitorPortEventHandler(portMonitor.ClosePort); ipcHandler.StartDocMonitorPort += new IpcHandler.StartDocMonitorPortEventHandler(portMonitor.StartDoc); ipcHandler.EndDocMonitorPort += new IpcHandler.EndDocMonitorPortEventHandler(portMonitor.EndDoc); ipcHandler.WriteMonitorPort += new IpcHandler.WriteMonitorPortEventHandler(portMonitor.Write); this.pipeServer = new PipeServer(ipcHandler); //this.pipeServer.ClientConnected += new PipeServer.ClientConnectedEventHandler(this.ClientConnected); //this.pipeServer.ReadCompleted += new PipeServer.ReadCompletedEventHandler(this.ReadCompleted); //this.pipeServer.WriteCompleted += new PipeServer.WriteCompletedEventHandler(this.WriteCompleted); this.pipeServer.Start(); while (this.pipeServer.Step()) { // could do some other work here } // fixme: dispose pipeServer? }
/// <summary> /// Used as the start of the service /// </summary> public void Start() { if (!(bool)_memoryCache.Get(SERVICE_MEMORY)) { _memoryCache.Set(SERVICE_MEMORY, true); _loggerService.LogMessage(SERVICE_NAME, "Started", LogLevel.Info); } while ((bool)_memoryCache.Get(SERVICE_MEMORY)) { _loggerService.LogMessage(SERVICE_NAME, "Started", LogLevel.Info); _pipeClient.CreatePipe(); var incomingTask = _pipeClient.ReadString(); _loggerService.LogMessage(SERVICE_NAME, incomingTask, LogLevel.Info); _taskToProcess = new TaskModel(incomingTask); ProcessTask(); _pipeClient.WaitForDrain(); _pipeClient = new PipeClient(PIPE_NAME); _pipeServer = new PipeServer(); Thread.Sleep(1000); } }
public MainManager(IEventAggregator events, ILogger logger, LoopManager loopManager, DeviceManager deviceManager, EffectManager effectManager, ProfileManager profileManager) { _events = events; Logger = logger; LoopManager = loopManager; DeviceManager = deviceManager; EffectManager = effectManager; ProfileManager = profileManager; _processTimer = new Timer(1000); _processTimer.Elapsed += ScanProcesses; _processTimer.Start(); ProgramEnabled = false; Running = false; // TODO: Dependency inject utilities? KeyboardHook = new KeyboardHook(); // Create and start the web server GameStateWebServer = new GameStateWebServer(); GameStateWebServer.Start(); // Start the named pipe PipeServer = new PipeServer(); PipeServer.Start("artemis"); Logger.Info("Intialized MainManager"); }
private static async Task <PipeServer> StartPipeServerAsync() { var pipeServer = new PipeServer(RunnerConstants.PipeName); await pipeServer.WaitForConnectionAsync(); return(pipeServer); }
public static void Main() { ThreadPool.SetMaxThreads(2, 2); PipeServer server = new PipeServer("channell1"); server.Run(); }
public void PipeServer_SingleSessionInstance_DetectsRunningSessionInstance() { CreateSessionPipe(); Assert.IsTrue(PipeServer.SessionServerInstanceRunning(_pipeName), "No session pipe server found"); Assert.IsFalse(PipeServer.ServerInstanceRunning(_pipeName), "Found server pipe"); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); //create the notifyicon (it's a resource declared in NotifyIconResources.xaml Globals.NotifyIcon = (TaskbarIcon)FindResource("NotifyIcon"); Globals.NotifyIcon.TrayPopup = new TextBlock { Text = "No status available", Foreground = Brushes.LightSalmon, Background = Brushes.Black, FontSize = 14, }; if (SqlCe.GetAutoEnforceFlag()) { Dispatcher.Invoke(() => { Globals.NotifyIcon.IconSource = new BitmapImage(new Uri("pack://application:,,,/Icons/red.ico")); }); } _pipeServer = new PipeServer(); _pipeServer.Listen("01DB94E3-90F1-43F4-8DDA-8AEAF6C08A8E"); _pipeServer.PipeMessage += PipeServer_PipeMessage; }
public async Task Pipe_Client_Connect_ResponceServerIdTest() { const string ResponceServerId = "responceServerId"; var tcs = new TaskCompletionSource <bool>(); var id = string.Empty; var server = new PipeServer <string>(); var client = new PipeClient <string>(server.ServerId) { ResponceServerId = ResponceServerId }; server.ClientConnectedEvent += (sender, args) => { id = args.ClientId; tcs.SetResult(true); }; server.Start(); client.Start(); await tcs.Task; Assert.AreEqual(ResponceServerId, id, "Responce server id does not match the correct"); }
public void Start() { this.portMonitor = new PortMonitor(); IpcHandler ipcHandler = new IpcHandler(); ipcHandler.AddMonitorPort += new IpcHandler.AddMonitorPortEventHandler(portMonitor.AddPort); ipcHandler.DeleteMonitorPort += new IpcHandler.DeleteMonitorPortEventHandler(portMonitor.DeletePort); ipcHandler.OpenMonitorPort += new IpcHandler.OpenMonitorPortEventHandler(portMonitor.OpenPort); ipcHandler.CloseMonitorPort += new IpcHandler.CloseMonitorPortEventHandler(portMonitor.ClosePort); ipcHandler.StartDocMonitorPort += new IpcHandler.StartDocMonitorPortEventHandler(portMonitor.StartDoc); ipcHandler.EndDocMonitorPort += new IpcHandler.EndDocMonitorPortEventHandler(portMonitor.EndDoc); ipcHandler.WriteMonitorPort +=new IpcHandler.WriteMonitorPortEventHandler(portMonitor.Write); this.pipeServer = new PipeServer(ipcHandler); //this.pipeServer.ClientConnected += new PipeServer.ClientConnectedEventHandler(this.ClientConnected); //this.pipeServer.ReadCompleted += new PipeServer.ReadCompletedEventHandler(this.ReadCompleted); //this.pipeServer.WriteCompleted += new PipeServer.WriteCompletedEventHandler(this.WriteCompleted); this.pipeServer.Start(); while (this.pipeServer.Step()) { // could do some other work here } // fixme: dispose pipeServer? }
public async Task Pipe_Client_SendMessage_LongMessageTest() { const int BufferSize = 2048; var tcs = new TaskCompletionSource <string>(); var server = new PipeServer <string>(); var client = new PipeClient <string>(server.ServerId); server.MessageReceivedEvent += (sender, args) => { tcs.SetResult(args.Message); }; server.Start(); client.Start(); var longString = $"[{new string('*', 10 * 2048)}]"; Assert.IsTrue(Encoding.UTF8.GetByteCount(longString) > BufferSize, "Test string is smaller than needed buffer length"); var success = await client.SendMessageAsync(longString); Assert.IsTrue(success, "Send message failed"); var message = await tcs.Task; Assert.AreEqual(longString, message, "Messages are not equal"); }
public async Task Pipe_Client_SendMessage_MultiMessageTest() { const string FirstTestMessage = "Hi from first"; const string SecondTestMessage = "Hi from second"; var autoEvent = new AutoResetEvent(false); var message = string.Empty; var server = new PipeServer <string>(); var client = new PipeClient <string>(server.ServerId); server.MessageReceivedEvent += (sender, args) => { message = args.Message; autoEvent.Set(); }; server.Start(); client.Start(); var success = await client.SendMessageAsync(FirstTestMessage); Assert.IsTrue(success, "Send #1 message failed"); autoEvent.WaitOne(); Assert.AreEqual(FirstTestMessage, message, "#1 messages are not equal"); success = await client.SendMessageAsync(SecondTestMessage); Assert.IsTrue(success, "Send #2 message failed"); autoEvent.WaitOne(); Assert.AreEqual(SecondTestMessage, message, "#2 messages are not equal"); }
public async Task Pipe_Client_SendMessageTest() { const string Message = "Client's message"; var tcs = new TaskCompletionSource <string>(); var server = new PipeServer <string>(); var client = new PipeClient <string>(server.ServerId); server.MessageReceivedEvent += (sender, args) => { tcs.SetResult(args.Message); }; server.Start(); client.Start(); var success = await client.SendMessageAsync(Message); Assert.IsTrue(success, "Send message failed"); var message = await tcs.Task; Assert.AreEqual(Message, message, "Message are not equal"); }
public async Task Pipe_Client_DisconnectTest() { var tcs = new TaskCompletionSource <bool>(); var isDisconnected = false; var server = new PipeServer <string>(); var client = new PipeClient <string>(server.ServerId); server.ClientDisconnectedEvent += (sender, args) => { isDisconnected = true; tcs.SetResult(true); }; server.Start(); client.Start(); Assert.IsFalse(isDisconnected, "Client is disconected"); client.Stop(); client = null; await tcs.Task; Assert.IsTrue(isDisconnected, "Client is still connected"); }
public void Config(BeSafeConfig config, PipeServer pipeServer, bool stoppingService) { bool stateResult = (((config?.ComponentsState.ProcessWatcher == true) && (stoppingService == false)) ? _processWatcher.Start() : _processWatcher.Stop()); }
private void SendResponseOverNamedPipe(byte[] arrPayload) { // First, send the payload header that is being awaited for. PipeServer.Write(arrPayload, 0, GatewayPayloadConst.payloadHeaderSize); PipeServer.Flush(); PipeServer.WaitForPipeDrain(); // Named pipes can only send fixed block size data in a single go over the network. // Thus, we will chunk our payload accordingly and send it over. int iOffsetToWriteFrom = GatewayPayloadConst.payloadHeaderSize; int iRemainingLengthToWrite = arrPayload.Length - GatewayPayloadConst.payloadHeaderSize; if (iRemainingLengthToWrite > 0) { int iCurrentLengthToWrite = iRemainingLengthToWrite % GatewayPayloadConst.maxNamedPipePayloadSize; if (iCurrentLengthToWrite == 0) { iCurrentLengthToWrite = GatewayPayloadConst.maxNamedPipePayloadSize; } while (iRemainingLengthToWrite > 0) { // Send the payload and wait for it to be read by the receiver before sending any remaining chunks. PipeServer.Write(arrPayload, iOffsetToWriteFrom, iCurrentLengthToWrite); PipeServer.Flush(); PipeServer.WaitForPipeDrain(); iRemainingLengthToWrite -= iCurrentLengthToWrite; iOffsetToWriteFrom += iCurrentLengthToWrite; iCurrentLengthToWrite = GatewayPayloadConst.maxNamedPipePayloadSize; } } }
public MainManager(ILogger logger, LoopManager loopManager, DeviceManager deviceManager, ModuleManager moduleManager, PreviewManager previewManager, MigrationManager migrationManager, PipeServer pipeServer, GameStateWebServer gameStateWebServer) { _migrationManager = migrationManager; Logger = logger; LoopManager = loopManager; DeviceManager = deviceManager; ModuleManager = moduleManager; PreviewManager = previewManager; PipeServer = pipeServer; _processTimer = new Timer(1000); _processTimer.Elapsed += ScanProcesses; _processTimer.Start(); ProgramEnabled = false; // Create and start the web server GameStateWebServer = gameStateWebServer; GameStateWebServer.Start(); // Start the named pipe PipeServer.Start("artemis"); // Listen for power mode changes SystemEvents.PowerModeChanged += OnPowerChange; Logger.Info("Intialized MainManager"); Logger.Info($"Artemis version {Assembly.GetExecutingAssembly().GetName().Version} is ready!"); }
public MainForm(BaseSettings settings, Uploader uploader, PipeServer pipeServer, SingleInstance tasks, HotKeyService hotkeyService, SettingsService settingsService, IEnumerable <IImageUploader> uploaders, MusicPlayerService musicPlayerService, ShotrApiService shotrApiService) { _settings = settings; _uploader = uploader; _pipeServer = pipeServer; _tasks = tasks; _hotkeyService = hotkeyService; _settingsService = settingsService; _uploaders = uploaders; _musicPlayerService = musicPlayerService; _shotrApiService = shotrApiService; InitializeComponent(); Shown += MainFormShown; _pipeServer.PipeServerReceivedClient += _pipeserver_PipeServerReceivedClient; _pipeServer.StartServer(); _shotrIcon = Icon; }
public async Task SetUp() { Trace.WriteLine("Setting up test..."); _barrier.Reset(); _exceptions.Clear(); _server = new PipeServer <TestCollection>(PipeName); _client = new PipeClient <TestCollection>(PipeName); _expectedData = null; _expectedHash = 0; _actualData = null; _actualHash = 0; _server.MessageReceived += ServerOnMessageReceived; _server.ExceptionOccurred += (sender, args) => OnExceptionOccurred(args.Exception); _client.ExceptionOccurred += (sender, args) => OnExceptionOccurred(args.Exception); await _server.StartAsync(); await _client.ConnectAsync(); Trace.WriteLine("Client and server started"); Trace.WriteLine("---"); _startTime = DateTime.Now; }
static void ServerTest() { var loggerFactory = new LoggerFactory().AddConsole(LogLevel.Debug, true); var server = new PipeServer <string, int>("sample_pipe", s => s.Length, loggerFactory); Task.Run(() => { try { server.WhenAll().Wait(); } catch (AggregateException e) { Console.WriteLine(e.Message); } }); Console.WriteLine("Any key to cancel pipe server"); Console.ReadKey(); server.CancelAll(); Console.WriteLine("Any key to end application"); Console.ReadKey(); }
internal async Task <bool> SetupProtocol() { if (!HDTProtocol.Verify()) { var result = await this.ShowMessageAsync("Enable \"hdt\" protocol?", "The \"hdt\" protocol allows other processes and websites to directly communicate with HDT.", MessageDialogStyle.AffirmativeAndNegative); if (result == MessageDialogResult.Affirmative) { var procInfo = new ProcessStartInfo("HDTHelper.exe", "registerProtocol"); procInfo.Verb = "runas"; procInfo.UseShellExecute = true; var proc = Process.Start(procInfo); await Task.Run(() => proc.WaitForExit()); } } else { this.ShowMessage("Protocol already active", "The \"hdt\" protocol allows other processes and websites to directly communicate with HDT."); } if (HDTProtocol.Verify()) { PipeServer.StartAll(); return(true); } return(false); }
public static void StartListening(string pipeName, DelegateMessage eventHandler) { var server = new PipeServer(); server.PipeData += eventHandler; server.Listen(pipeName); }
public async Task Should_Record_Server_Calls_Post() { var pipeServer = new PipeServer <IClientCommunication, IServerCommunication>(new NullLoggerFactory()); var pipeName = Guid.NewGuid().ToString(); var mocked = new Mock <IServerCommunication>(); mocked.Setup(x => x.WriteTestResult(It.IsAny <SummarizedResult>())).Callback((SummarizedResult s) => { Assert.Equal(1, s.Vus); Assert.Equal(10, s.Iterations); Assert.Equal(10, s.HttpRequests); }); var snapshots = new List <InterprocessSnapshot>(); mocked.Setup(x => x.CollectStats(It.IsAny <InterprocessSnapshot[]>())).Callback((InterprocessSnapshot[] s) => { snapshots.AddRange(s); }); var task = Task.Run(async() => { await pipeServer.WaitForConnectionAsync(pipeName, () => mocked.Object, CancellationToken.None); }); var taskRun = Execute <StatsLoadTestPost>("--pipe", pipeName, "--out", "pipe"); await Task.WhenAll(task, taskRun); Assert.Contains(snapshots, x => x.Name == "http-socket-connection-duration"); Assert.Contains(snapshots, x => x.Name == "http-request-headers-duration"); Assert.Contains(snapshots, x => x.Name == "http-request-content-duration"); Assert.Contains(snapshots, x => x.Name == "http-response-headers-duration"); Assert.Contains(snapshots, x => x.Name == "http-response-content-duration"); Assert.Contains(snapshots, x => x.Name == "http-request-waiting-duration"); Assert.Contains(snapshots, x => x.Name == "http-request-duration"); Assert.Contains(snapshots, x => x.Name == "iteration-duration"); Assert.Contains(snapshots, x => x.Name == "http-requests-count"); Assert.Contains(snapshots, x => x.Name == "bytes-sent"); Assert.Contains(snapshots, x => x.Name == "bytes-received"); }
protected override void MessageReceivedHandler(object sender, PipeServer.MessageReceivedEventArgs e) { if (string.IsNullOrWhiteSpace(e.Message)) return; Received = e.Message.Equals(_desiredMessage, StringComparison.InvariantCulture); }
public MainManager(ILogger logger, LoopManager loopManager, DeviceManager deviceManager, EffectManager effectManager, ProfileManager profileManager, PipeServer pipeServer) { Logger = logger; LoopManager = loopManager; DeviceManager = deviceManager; EffectManager = effectManager; ProfileManager = profileManager; PipeServer = pipeServer; _processTimer = new Timer(1000); _processTimer.Elapsed += ScanProcesses; _processTimer.Start(); ProgramEnabled = false; Running = false; // Create and start the web server GameStateWebServer = new GameStateWebServer(logger); GameStateWebServer.Start(); // Start the named pipe PipeServer.Start("artemis"); // Start the update task var updateTask = new Task(Updater.UpdateApp); updateTask.Start(); Logger.Info("Intialized MainManager"); Logger.Info($"Artemis version {Assembly.GetExecutingAssembly().GetName().Version} is ready!"); }
public void Run() { var pipeName = "pipe"; _ = Task.Run(async() => { using var pipeServer = new PipeServer(pipeName); await pipeServer.WaitForConnectionAsync(); Console.WriteLine("Start sending..."); pipeServer.SendMessage(new LoadContextMessage("asd.dll")); Console.WriteLine("Done sending"); }); Task.Run(async() => { using var pipeClient = new PipeClient(pipeName); await pipeClient.ConnectAsync(); Console.WriteLine("Start receiving..."); var command = pipeClient.ReceiveMessage(); Console.WriteLine("Done receiving"); switch (command) { case LoadContextMessage loadCommand: Console.WriteLine(loadCommand.TargetAssemblyPath); break; } }).Wait(); }
public void client_receives_both_messages() { var pipe1 = Guid.NewGuid().ToString(); var pipe2 = Guid.NewGuid().ToString(); var pipe3 = Guid.NewGuid().ToString(); using (var server1 = new PipeServer(pipe1)) { using (var server2 = new PipeServer(pipe2)) { using (var junction = new PipeJunction(pipe3)) { junction.Combine(pipe1); junction.Combine(pipe2); server1.Send("Message from server 1"); server1.Send("Message from server 2"); var messages = new List <string>(); var client = new PipeClient(); new System.Threading.Thread(() => client.Listen(pipe3, (m) => messages.Add(m))).Start(); Timeout.AfterTwoSeconds().IfNot(() => messages.Count == 2); Assert.That(messages.Count, Is.EqualTo(2)); } } } }
private void OnLoaded(object sender, RoutedEventArgs e) { // loading position if (cfg.GetWindowPostition()) { var position = cfg.WindowPostition(); if (position.Top != 0 && position.Left != 0) { WindowStartupLocation = WindowStartupLocation.Manual; this.Top = position.Top; this.Left = position.Left; } } // loading switch settings swHander.IsEnabled = App.IsAdministrator(); swHander.IsChecked = FileAssociation.IsDefault(); swInstance.IsChecked = cfg.SingleInstance(); swWindow.IsChecked = cfg.GetWindowPostition(); // open apk passes arg not null if (!string.IsNullOrWhiteSpace(pathApk)) { txtPath.Text = pathApk; } // start pip server if in one single instance if (cfg.SingleInstance()) { var server = new PipeServer(App.PIPENAMESERVER); server.OnMessageReceived += OnMessageReceived; server.StartListening(); } }
public CredentialProviderProxy(ILog log) : base(nameof(CredentialProviderProxy), log) { _pipeServer = new PipeServer("hideezsafe3", log); _pipeServer.MessageReceivedEvent += PipeServer_MessageReceivedEvent; _pipeServer.ClientConnectedEvent += PipeServer_ClientConnectedEvent; }
public GtaVModel(DeviceManager deviceManager, LuaManager luaManager, PipeServer pipeServer) : base(deviceManager, luaManager) { _pipeServer = pipeServer; Settings = SettingsProvider.Load <GtaVSettings>(); DataModel = new GtaVDataModel(); ProcessNames.Add("GTA5"); }
public void PipeServerConstructor_createsAReadWritePipe() { var pipeServerStream = new NamedPipeServerStream("Agent Pipe", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); AgentRequestHandler agent = new AgentRequestHandler(); PipeServer serverObject = new PipeServer(pipeServerStream, agent); Assert.IsTrue(pipeServerStream.CanRead & pipeServerStream.CanWrite); }
public static void ManageComponentsState(BeSafeConfig configuration, PipeServer pipeServer, bool stoppingService) { ProcessRegulator.Instance().Config(configuration, pipeServer, stoppingService); ModuleRegulator.Instance().Config(configuration, pipeServer, stoppingService); DirectoryRegulator.Instance().Config(configuration, pipeServer, stoppingService); RegistryRegulator.Instance().Config(configuration, pipeServer, stoppingService); SecureVolumeRegulator.Instance().Config(configuration, pipeServer, stoppingService); }
private async void InitializeAsync() { await PipeServer.WaitForConnectionAsync(); Log.Debug("Daemon", $"Started device debugger server {{{Identifier}}}"); JsonWriter = new JsonTextWriter(new StreamWriter(PipeServer)); await JsonWriter.WriteStartArrayAsync(); }
public void StartPipeServer(Control OwnerHandle) { //Note: this function can only be called once. Explosions otherwise. owner = OwnerHandle; pipeServer = new PipeServer(); pipeServer.MessageReceived += pipeServer_MessageReceived; pipeServer.ClientDisconnected += pipeServer_ClientDisconnected; pipeServer.Start(UpdateHelperData.PipenameFromFilename(VersionTools.SelfLocation)); }
public void transfer(Dictionary<string, string> data) { PipeServer ps = new PipeServer(pipe_name, data); Thread thread = new Thread(new ThreadStart(ps.send)); thread.Start(); }
protected abstract void MessageReceivedHandler(object sender, PipeServer.MessageReceivedEventArgs e);
static void Main(string[] args) { // resolve persistent node path. string pipeName = null; string nextActionPath = null; if (4 == args.Length && args[0] == "-pn" && args[2] == "-na") { pipeName = args[1]; nextActionPath = args[3]; } else { Console.WriteLine("Usage: -pn <pipe name> -na <next action file path>"); Console.WriteLine(); Console.WriteLine("The <pipe name> is any legal file name which uniquely distinguishes the pipe server."); Console.WriteLine("The <next action file path> is a text file containing a list of actions to execute in PowerShell."); return; } FileStream fileStream = null; StreamReader streamReader = null; try { // read next action file linewise. fileStream = new FileStream(nextActionPath, FileMode.OpenOrCreate, FileAccess.Read); streamReader = new StreamReader(fileStream); // use JSON transport to unmarshal initial nodes. ITransport transport = new JsonTransport(); // create pipe server using JSON as transport. PipeServer pipeServer = new PipeServer(pipeName, transport); Console.WriteLine("Hit Ctrl+C to stop the server."); bool moreCommands = true; while (moreCommands) { try { Console.WriteLine("Waiting for client to connect..."); pipeServer.WaitForConnection(); GetNextActionRequest request = pipeServer.Receive<GetNextActionRequest>(); if (null == request) { break; } Console.WriteLine(String.Format("Received: {0}", request.ToString())); for (;;) { string nextLine = streamReader.ReadLine(); if (null == nextLine) { moreCommands = false; nextLine = "exit"; } if (nextLine.Trim().Length > 0) { GetNextActionResponse response = new GetNextActionResponse(nextLine); Console.WriteLine(String.Format("Responding: {0}", response.ToString())); pipeServer.Send(response); break; } } } catch (Exception e) { Console.WriteLine(e.Message); } finally { pipeServer.Close(); } } } catch (IOException e) { Console.WriteLine(e.Message); } finally { if (null != streamReader) { streamReader.Close(); streamReader = null; } if (null != fileStream) { fileStream.Close(); fileStream = null; } } }
/// <summary> /// Initiate the pipe that connects to all other FOG bus instances /// It MUST be assumed that this pipe is compromised /// Do NOT send security relevant data across it /// </summary> /// <returns></returns> private static void InitializePipe() { switch (_mode) { case Mode.Server: // Attempt to become the pipe server try { _server = new PipeServer("fog-bus"); _server.MessageReceived += pipe_RecieveMessage; _server.Start(); Log.Entry(LogName, "Became bus server"); } catch (Exception ex) { Log.Error(LogName, "Could not enter named pipe"); Log.Error(LogName, ex); } break; case Mode.Client: // If someone else is already a pipe server, try and become a pipe client try { _client = new PipeClient("fog-bus"); _client.MessageReceived += pipe_RecieveMessage; _client.Connect(); Log.Entry(LogName, "Became bus client"); } catch (Exception ex) { Log.Error(LogName, "Could not enter named pipe"); Log.Error(LogName, ex); } break; } _initialized = true; }
void pipeServer_MessageReceived(PipeServer.Server.Client client, string message) { //if (startstop == true) //{ //Console.WriteLine(message); this.Invoke(new PipeServer.Server.MessageReceivedHandler(DisplayMessageReceived), new object[] { client, message }); message = ""; //} }
void engagementpipe_MessageReceived(PipeServer.Server.Client client, string message) { this.Invoke(new PipeServer.Server.MessageReceivedHandler(DisplayMessageReceived2), new object[] { client, message }); message = ""; }
void DisplayMessageReceived2(PipeServer.Server.Client client, string message) { if (message.StartsWith("AP_OK")) //engagement module checkedListBox1.SetItemChecked(8, true); }
void DisplayMessageReceived(PipeServer.Server.Client client, string message) { if (message.StartsWith("Temp")) //q sensor data { //no more active } if (message.Substring(1,3)=="Dep") //kinect1 data { Console.WriteLine("Kinect: " + message); aTimer.Enabled = true; if (message.StartsWith("1")) { string[] parseMsg = message.Split(';'); Kinectdata = message; Kinectdata2 = ""; try { depth = Convert.ToDouble(parseMsg[0].Substring(parseMsg[0].IndexOf(':') + 1), ifp); Xp = Convert.ToDouble(parseMsg[1].Substring(parseMsg[1].IndexOf(':') + 1), ifp); Yp = Convert.ToDouble(parseMsg[2].Substring(parseMsg[2].IndexOf(':') + 1), ifp); Zp = Convert.ToDouble(parseMsg[3].Substring(parseMsg[3].IndexOf(':') + 1), ifp); RotH = Convert.ToDouble(parseMsg[4].Substring(parseMsg[4].IndexOf(':') + 1), ifp); RotV = Convert.ToDouble(parseMsg[5].Substring(parseMsg[5].IndexOf(':') + 1), ifp); } catch { depth = 0; Xp = 0; Yp = 0; Zp = 0; RotH = 0; RotV = 0; } DetectedPerson = true; try { AU4BrowLower = Convert.ToDouble(parseMsg[10].Substring(parseMsg[10].IndexOf(':') + 1), ifp); AU2BrowRaiser = Convert.ToDouble(parseMsg[11].Substring(parseMsg[11].IndexOf(':') + 1), ifp); } catch { AU4BrowLower = 0; AU2BrowRaiser = 0; } eyebrowControllerUsr1.SetBrowsValues(AU2BrowRaiser, AU4BrowLower); } else { Kinectdata2 = message; Kinectdata = ""; string[] parseMsg = message.Split(';'); try { depth = Convert.ToDouble(parseMsg[0].Substring(parseMsg[0].IndexOf(':') + 1), ifp); Xp2 = Convert.ToDouble(parseMsg[1].Substring(parseMsg[1].IndexOf(':') + 1), ifp); Yp2 = Convert.ToDouble(parseMsg[2].Substring(parseMsg[2].IndexOf(':') + 1), ifp); Zp2 = Convert.ToDouble(parseMsg[3].Substring(parseMsg[3].IndexOf(':') + 1), ifp); RotH2 = Convert.ToDouble(parseMsg[4].Substring(parseMsg[4].IndexOf(':') + 1), ifp); RotV2 = Convert.ToDouble(parseMsg[5].Substring(parseMsg[5].IndexOf(':') + 1), ifp); } catch { depth = 0; Xp2 = 0; Yp2 = 0; Zp2 = 0; RotH2 = 0; RotV2 = 0; } DetectedPerson2 = true; try { AU4BrowLower = Convert.ToDouble(parseMsg[10].Substring(parseMsg[10].IndexOf(':') + 1), ifp); AU2BrowRaiser = Convert.ToDouble(parseMsg[11].Substring(parseMsg[11].IndexOf(':') + 1), ifp); } catch { AU4BrowLower = 0; AU2BrowRaiser = 0; } eyebrowControllerUsr2.SetBrowsValues(AU2BrowRaiser, AU4BrowLower); } checkedListBox1.SetItemChecked(0, true); } if (message.StartsWith("Cam")) //camera data { if (message.Substring(3, 1) == "1") checkedListBox1.SetItemChecked(2, true); if (message.Substring(3, 1) == "2") checkedListBox1.SetItemChecked(3, true); if (message.Substring(3, 1) == "3") checkedListBox1.SetItemChecked(4, true); if (message.Substring(3, 1) == "4") checkedListBox1.SetItemChecked(5, true); if (message.Substring(3, 1) == "5") checkedListBox1.SetItemChecked(6, true); if (message.Substring(3, 1) == "6") checkedListBox1.SetItemChecked(7, true); } if (message.StartsWith("User")) //okao data { checkedListBox1.SetItemChecked(1, true); OKAOdata = message; string[] parseMsg1 = OKAOdata.Split(','); if (Convert.ToDouble(parseMsg1[1]) == 1) {//user 1 OKAOdata2 = ""; try { smile1 = Convert.ToInt16(parseMsg1[3]); confidence1 = Convert.ToInt16(parseMsg1[2]); fupdown1 = Convert.ToInt16(parseMsg1[11]); fleftright1 = Convert.ToInt16(parseMsg1[12]); o1Expression1= Convert.ToInt16(parseMsg1[4]); o1Expression2= Convert.ToInt16(parseMsg1[5]); o1Expression3= Convert.ToInt16(parseMsg1[6]); o1Expression4= Convert.ToInt16(parseMsg1[7]); o1Expression5= Convert.ToInt16(parseMsg1[8]); o1Expression6 = Convert.ToInt16(parseMsg1[9]); o1Expression7 = Convert.ToInt16(parseMsg1[10]); if(parseMsg1[13]=="screenL") GazeOut1=GazeDef.screenL; if(parseMsg1[13]=="screenR") GazeOut1=GazeDef.screenR; if(parseMsg1[13]=="else") GazeOut1=GazeDef.elsewhere; if(parseMsg1[13]=="robot") GazeOut1=GazeDef.Robot; if (parseMsg1[13] == "none") GazeOut1 = GazeDef.none; this.Invoke(new Action(() =>{ lblgaze.Text = GazeOut1.ToString(); lblHeadX.Text = parseMsg1[11]; lblHeadY.Text = parseMsg1[12]; } )); } catch { smile1 = 0; confidence1 = 0; fupdown1 = 0; fleftright1 = 0; fupdown1 = 0; fleftright1 = 0; GazeOut1=GazeDef.none; } } else {//user 2 OKAOdata2 = message; OKAOdata = ""; try { smile2 = Convert.ToInt16(parseMsg1[3]); confidence2 = Convert.ToInt16(parseMsg1[2]); fupdown2 = Convert.ToInt16(parseMsg1[11]); fleftright2 = Convert.ToInt16(parseMsg1[12]); o2Expression1 = Convert.ToInt16(parseMsg1[4]); o2Expression2 = Convert.ToInt16(parseMsg1[5]); o2Expression3 = Convert.ToInt16(parseMsg1[6]); o2Expression4 = Convert.ToInt16(parseMsg1[7]); o2Expression5 = Convert.ToInt16(parseMsg1[8]); o2Expression6 = Convert.ToInt16(parseMsg1[9]); o2Expression7 = Convert.ToInt16(parseMsg1[10]); if (parseMsg1[13] == "screenL") GazeOut2 = GazeDef.screenL; if (parseMsg1[13] == "screenR") GazeOut2 = GazeDef.screenR; if (parseMsg1[13] == "else") GazeOut2 = GazeDef.elsewhere; if (parseMsg1[13] == "robot") GazeOut2 = GazeDef.Robot; if (parseMsg1[13] == "none") GazeOut2 = GazeDef.none; this.Invoke(new Action(() => { lblgaze2.Text = GazeOut2.ToString(); lblHeadX2.Text = parseMsg1[11]; lblHeadY2.Text = parseMsg1[12]; } )); } catch { smile2 = 0; confidence2 = 0; fupdown2 = 0; fleftright2 = 0; GazeOut2 = GazeDef.none; } } } message = ""; }
static void Main(string[] args) { string inPipeHandle, outPipeHandle; if (PipeServer<WorkerProcessRequest, WorkerProcessResponse>.IsChildProcess(out inPipeHandle, out outPipeHandle)) { // Child process. WorkerProcess.Start(inPipeHandle, outPipeHandle); return; } // Server process. using (var pipeServer = new PipeServer<WorkerProcessRequest, WorkerProcessResponse>()) { var entries = JsonConvert.DeserializeObject<CompatTableEntry[]>(File.ReadAllText(@"..\..\Kangax\compat-table.json")); foreach (var testCase in entries) { try { testCase.Response = pipeServer.Send(new WorkerProcessRequest { Script = $"(function () {{ {testCase.script} }})();" }); if (testCase.Response.JsonResult == "true") testCase.Success = true; if (testCase.Success == false && Array.IndexOf( new string[] { "default function parameters", "for..of loops", "template literals", "typed arrays", "WeakMap", "Set", "WeakMap", "WeakSet", "Object static methods", @"function ""name"" property", "Array static methods", "Array.prototype methods", }, testCase.name) >= 0) { Console.WriteLine($"{testCase.name} -- {testCase.detail}, result: {testCase.Response.JsonResult ?? $"{testCase.Response.ErrorType}: {testCase.Response.ErrorMessage}"}"); } } catch (IOException) { Console.WriteLine("*** Worker process crashed ***"); } } Console.WriteLine(); Console.WriteLine(); foreach (var group in entries.GroupBy(e => e.group)) { Console.WriteLine($"**{group.Key}**|"); foreach (var test in group.GroupBy(e => e.name)) { int successCount = test.Count(t => t.Success); int totalCount = test.Count(); string status = ":x:"; if (successCount == 0) status = ":x:"; else if (successCount == totalCount) status = $":white_check_mark: {successCount}/{totalCount}"; else status = $"{successCount}/{totalCount}"; Console.WriteLine($" {test.Key.Replace("_", "\\_")}|{status}"); } } } //// Find the Test Suite Files directory. //var testSuiteFilesDir = FindTestSuiteFilesDir(); //if (testSuiteFilesDir == null) //{ // Console.WriteLine("Missing 'Test Suite Files' directory."); // Environment.Exit(-1); //} //var timer = System.Diagnostics.Stopwatch.StartNew(); //using (var testSuite = new TestSuite(testSuiteFilesDir)) //{ // //testSuite.RunInSandbox = true; // //testSuite.IncludedTests.Add("12.7-1"); // //testSuite.IncludedTests.Add("15.2.3.14-5-13"); // testSuite.TestFinished += OnTestFinished; // testSuite.Start(); // Console.WriteLine(); // Console.WriteLine("Finished in {0} minutes, {1} seconds!", (int)timer.Elapsed.TotalMinutes, timer.Elapsed.Seconds); // Console.WriteLine("Succeeded: {0} ({1:P1})", testSuite.SuccessfulTestCount, testSuite.SuccessfulPercentage); // Console.WriteLine("Failed: {0} ({1:P1})", testSuite.FailedTestCount, testSuite.FailedPercentage); // Console.WriteLine("Skipped: {0} ({1:P1})", testSuite.SkippedTestCount, testSuite.SkippedPercentage); // Console.WriteLine("Total: {0}", testSuite.ExecutedTestCount); //} }
public CaptureLogic(string pipeServerName, string dllName) { this.pipeServerName = pipeServerName; this.dllName = dllName; pipeServer = new PipeServer(pipeServerName); }
static void Main(string[] args) { // resolve persistent node path. string nodeFilePath = null; if (2 == args.Length && args[0] == "-nf") { nodeFilePath = args[1]; } else { Console.WriteLine("Usage: TestChefNodeCmdlet -nf <nodefile>"); Console.WriteLine(); Console.WriteLine("The nodefile is a JSON text file containing initial values and which receives any modified node values."); return; } // load initial node values, if any. string nodeFileText = ReadTextFile(nodeFilePath); // use JSON transport to unmarshal initial nodes. ITransport transport = new JsonTransport(); IDictionary nodeHash = new Hashtable(); if (nodeFileText.Length > 0) { nodeHash = (IDictionary)transport.NormalizeDeserializedObject(transport.ConvertStringToObject<object>(nodeFileText)); } // current and new resource hashes. IDictionary currentResourceHash = new Hashtable(); currentResourceHash.Add("name", "test name"); IDictionary newResourceHash = new Hashtable(currentResourceHash); // create pipe server using JSON as transport. PipeServer pipeServer = new PipeServer(Constants.CHEF_NODE_PIPE_NAME, transport); Console.WriteLine("Hit Ctrl+C to stop the server."); for (; ; ) { try { Console.WriteLine("Waiting for client to connect..."); pipeServer.WaitForConnection(); for (; ; ) { // use duck typing to determine type of request. IDictionary requestHash = (IDictionary)transport.NormalizeDeserializedObject(pipeServer.Receive<object>()); if (null == requestHash) { break; } bool validRequest = false; if (requestHash.Contains(Constants.JSON_COMMAND_KEY)) { if (requestHash.Contains(Constants.JSON_PATH_KEY) && requestHash.Contains(Constants.JSON_NODE_VALUE_KEY)) { if (requestHash[Constants.JSON_COMMAND_KEY].ToString() == "SetChefNodeRequest") { SetChefNodeRequest request = new SetChefNodeRequest((ICollection)requestHash[Constants.JSON_PATH_KEY], requestHash[Constants.JSON_NODE_VALUE_KEY]); Console.WriteLine(String.Format("Received: {0}", request.ToString())); InsertNodeHash(nodeHash, request.Path, transport.NormalizeDeserializedObject(request.NodeValue)); SetChefNodeResponse response = new SetChefNodeResponse(request.Path); Console.WriteLine(String.Format("Responding: {0}", response.ToString())); pipeServer.Send(response); // save change to node file. WriteTextFile(nodeFilePath, transport.ConvertObjectToString(nodeHash, true)); validRequest = true; } else if (requestHash[Constants.JSON_COMMAND_KEY].ToString() == "SetCurrentResourceRequest") { SetCurrentResourceRequest request = new SetCurrentResourceRequest((ICollection)requestHash[Constants.JSON_PATH_KEY], requestHash[Constants.JSON_NODE_VALUE_KEY]); Console.WriteLine(String.Format("Received: {0}", request.ToString())); InsertNodeHash(currentResourceHash, request.Path, transport.NormalizeDeserializedObject(request.NodeValue)); SetCurrentResourceResponse response = new SetCurrentResourceResponse(); Console.WriteLine(String.Format("Responding: {0}", response.ToString())); pipeServer.Send(response); validRequest = true; } else if (requestHash[Constants.JSON_COMMAND_KEY].ToString() == "SetNewResourceRequest") { SetNewResourceRequest request = new SetNewResourceRequest((ICollection)requestHash[Constants.JSON_PATH_KEY], requestHash[Constants.JSON_NODE_VALUE_KEY]); Console.WriteLine(String.Format("Received: {0}", request.ToString())); InsertNodeHash(newResourceHash, request.Path, transport.NormalizeDeserializedObject(request.NodeValue)); SetNewResourceResponse response = new SetNewResourceResponse(); Console.WriteLine(String.Format("Responding: {0}", response.ToString())); pipeServer.Send(response); validRequest = true; } } else if (requestHash.Contains(Constants.JSON_PATH_KEY)) { if (requestHash[Constants.JSON_COMMAND_KEY].ToString() == "GetChefNodeRequest") { GetChefNodeRequest request = new GetChefNodeRequest((ICollection)requestHash[Constants.JSON_PATH_KEY]); Console.WriteLine(String.Format("Received: {0}", request.ToString())); object nodeValue = QueryNodeHash(nodeHash, request.Path); GetChefNodeResponse response = new GetChefNodeResponse(request.Path, nodeValue); Console.WriteLine(String.Format("Responding: {0}", response.ToString())); pipeServer.Send(response); validRequest = true; } else if (requestHash[Constants.JSON_COMMAND_KEY].ToString() == "GetCurrentResourceRequest") { GetCurrentResourceRequest request = new GetCurrentResourceRequest((ICollection)requestHash[Constants.JSON_PATH_KEY]); Console.WriteLine(String.Format("Received: {0}", request.ToString())); object nodeValue = QueryNodeHash(currentResourceHash, request.Path); GetCurrentResourceResponse response = new GetCurrentResourceResponse(request.Path, nodeValue); Console.WriteLine(String.Format("Responding: {0}", response.ToString())); pipeServer.Send(response); validRequest = true; } else if (requestHash[Constants.JSON_COMMAND_KEY].ToString() == "GetNewResourceRequest") { GetNewResourceRequest request = new GetNewResourceRequest((ICollection)requestHash[Constants.JSON_PATH_KEY]); Console.WriteLine(String.Format("Received: {0}", request.ToString())); object nodeValue = QueryNodeHash(newResourceHash, request.Path); GetNewResourceResponse response = new GetNewResourceResponse(request.Path, nodeValue); Console.WriteLine(String.Format("Responding: {0}", response.ToString())); pipeServer.Send(response); validRequest = true; } } } if (false == validRequest) { // unknown request type; hang up and try again. break; } } } catch (Exception e) { Console.WriteLine(e.Message); } finally { pipeServer.Close(); } } }
public WaitHandler(PipeServer pipe, string desiredMessage) : base(pipe) { _desiredMessage = desiredMessage; }
protected AbstractHandler(PipeServer pipe) { pipe.MessageReceived += MessageReceivedHandler; }