private void ensureOnlyOne() { var pipeName = $"{this.GetType().FullName}.{winServiceInstaller.ServiceName}"; try { var serverStream = createNewNamedPipedServerStream(pipeName); AsyncCallback ac = null; ac = ar => { showForm(); serverStream.Close(); serverStream = createNewNamedPipedServerStream(pipeName); serverStream.BeginWaitForConnection(ac, null); }; serverStream.BeginWaitForConnection(ac, null); } catch { try { var clientStream = new NamedPipeClientStream(pipeName); clientStream.Connect(); clientStream.Close(); } finally { this.DialogResult = DialogResult.Cancel; this.Close(); Environment.Exit(0); } } }
public static void Main(string[] args) { if (args.Length > 0) { if (args[0] == "spawnclient") { var pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); Console.WriteLine("Connecting to server...\n"); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); if (ss.ReadString() == "I am the one true server!") { ss.WriteString(Environment.CurrentDirectory + "\\testdata.txt"); Console.Write(ss.ReadString()); } else { Console.WriteLine("Server could not be verified."); } pipeClient.Close(); Thread.Sleep(4000); // Give the client process some time to display results before exiting. } } else { Console.WriteLine("\n*** Named pipe client stream with impersonation example ***\n"); StartClients(); } }
public override void evaluate() { try { if ((bool)pinInfo["trigger"].value.data && lastInput != pinInfo["trigger"].value.data) { myPipe = new NamedPipeClientStream(".", "lavalamp winamp control", PipeDirection.InOut, PipeOptions.None); myPipe.Connect(500); StreamWriter myWriter = new StreamWriter(myPipe); myWriter.AutoFlush = true; myWriter.Write(Cmd); myPipe.Close(); } lastInput = pinInfo["trigger"].value; } catch (ObjectDisposedException) { // todo - add option to ignore errors / errored state / etc MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?"); } catch (IOException) { // todo - add option to ignore errors / errored state / etc MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?"); } catch (System.TimeoutException) { MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?"); } }
public static bool SendCommandToCore(string machine, string command) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(machine, Kernel.MBCLIENT_MUTEX_ID, PipeDirection.Out, PipeOptions.None); StreamWriter sw = new StreamWriter(pipeClient); try { pipeClient.Connect(2000); } catch (TimeoutException) { Logger.ReportWarning("Unable to send command to core (may not be running)."); return false; } try { sw.AutoFlush = true; sw.WriteLine(command); pipeClient.Flush(); pipeClient.Close(); } catch (Exception e) { Logger.ReportException("Error sending commmand to core", e); return false; } return true; }
public void Connect(string pipeName, string serverName = ".", int timeout = 2000) { NamedPipeClientStream pipeStream = null; try { pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation); pipeStream.Connect(timeout); using (var stringStream = new StringStream(pipeStream)) { if (OnConnected != null) { OnConnected(stringStream); } } } catch (Exception exception) { if (OnErrorOcurred != null) { OnErrorOcurred(exception); } } finally { if (pipeStream != null && pipeStream.IsConnected) { pipeStream.Flush(); pipeStream.Close(); } } }
public void CheckUnenrolledHostShouldRemoved() { CredentialReceiver.instance.Init(); ServerListHelper.instance.Init(); DatabaseManager.CreateNewConnection(dbName); IXenConnection connection = DatabaseManager.ConnectionFor(dbName); Session _session = DatabaseManager.ConnectionFor(dbName).Session; DatabaseManager.ConnectionFor(dbName).LoadCache(_session); Dictionary<string, string> config = cleanStack(); connection.LoadCache(_session); int conSize = ServerListHelper.instance.GetServerList().Count; NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); string credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { connection.Hostname, connection.Username, connection.Password })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); List<ServerInfo> con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize + 1); //1. If XenServer has not enroll, lock will not been set. config = cleanStack(); config[HealthCheckSettings.STATUS] = "false"; Pool.set_health_check_config(_session, connection.Cache.Pools[0].opaque_ref, config); Assert.IsFalse(RequestUploadTask.Request(connection, _session)); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize); CredentialReceiver.instance.UnInit(); }
public void Close() { Console.WriteLine(string.Format("closing pipe server {0}...", PipeName)); m_closing = true; //emulate new client connected to resume listener thread using (NamedPipeClientStream fakeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.In)) { try { fakeClient.Connect(100); fakeClient.Close(); } catch { //server was stopped already } } if (m_listenerThread != null && m_listenerThread.IsAlive) { if (!m_listenerThread.Join(5000)) { m_listenerThread.Abort(); } } m_listenerThread = null; Console.WriteLine(string.Format("disconnecting clients from pipe {0}...", PipeName)); while (m_pipeStreams.Count > 0) { DisconnectClient(m_pipeStreams[0]); } Console.WriteLine(string.Format("Pipe server {0} stopped OK", PipeName)); }
private void client() { System.IO.Pipes.NamedPipeClientStream pipeClient = new System.IO.Pipes.NamedPipeClientStream(".", "testpipe", System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.None); if (pipeClient.IsConnected != true) { pipeClient.Connect(); } StreamReader sr = new StreamReader(pipeClient); StreamWriter sw = new StreamWriter(pipeClient); string temp; temp = sr.ReadLine(); if (temp == "Waiting") { try { sw.WriteLine("Test Message"); sw.Flush(); pipeClient.Close(); } catch (Exception ex) { throw ex; } } }
static void Main(string[] args) { string[] simpleNames = { "Yukari", "Maki", "Zunko", "Akane", "Aoi", "Koh" }; string[] simpleNamesA = { "yukari", "maki", "zunko", "akane", "aoi", "koh" }; //引数のチェック if (args.Length < 2) { string mergeName = ""; for (int i = 0; i < simpleNames.Length; i++) { mergeName = mergeName + simpleNames[i]; //ワード間に", "をつける if (i < simpleNames.Length - 1) mergeName = mergeName + ", "; } Console.WriteLine("引数を指定してください: VoiceroidTClient"+ mergeName +" [会話内容];[音量0.0-2.0];[話速0.5-4.0];[高さ0.5-2.0];[抑揚0.0-2.0]"); return; } //引数に設定されたボイスロイドの名前をチェック string selectedSimple = null; for (int i = 0; i < simpleNames.Length; i++) { if (args[0].CompareTo(simpleNames[i]) == 0 || args[0].CompareTo(simpleNamesA[i]) == 0) { selectedSimple = simpleNames[i]; } } if (selectedSimple == null) { string mergeName = ""; for (int i = 0; i < simpleNames.Length; i++) { mergeName = mergeName + simpleNames[i]; //ワード間に", "をつける if (i < simpleNames.Length - 1) mergeName = mergeName + ", "; } Console.WriteLine("第一引数に指定されたVOICEROIDの名前が正しくありません. 使用できる名前は次のとおりです: "+ mergeName); return; } //サーバーとの通信処理を開始 string message = args[1]; try { //サーバーのセッションを取得する using (NamedPipeClientStream client = new NamedPipeClientStream("voiceroid_talker" + selectedSimple)) { client.Connect(1000); //サーバにーメッセージを送信する byte[] buffer = UnicodeEncoding.Unicode.GetBytes(message); client.Write(buffer, 0, buffer.Length); byte[] response = new byte[4]; client.Read(response, 0, response.Length); client.Close(); } } catch (Exception e) { //サーバーに接続できない時、通信エラーが発生した場合 Console.WriteLine("VoiceroidTServerによるサーバー, [voiceroid_talker" + selectedSimple + "]が見つかりません."); } }
/// <summary> /// Checks the valid port. /// in future this could use lavalamp's methods to detect if a node is on a port /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> private void CheckVaildPort(object sender, EventArgs e) { try { bool success; if (cboPort.Text.Contains("pipe")) { int pipeNameIndex = cboPort.Text.LastIndexOf(@"\"); using (NamedPipeClientStream pipe = new NamedPipeClientStream(cboPort.Text.Substring(pipeNameIndex, (cboPort.Text.Length - pipeNameIndex)))) { pipe.Connect(50); success = pipe.IsConnected; pipe.Close(); } } else { using (SerialPort selectedPort = new SerialPort(cboPort.Text)) { selectedPort.Open(); success = selectedPort.IsOpen; selectedPort.Close(); } } if (success) { lblStatus.ForeColor = System.Drawing.Color.Green; lblStatus.Text = "Free"; } else { lblStatus.ForeColor = System.Drawing.Color.DarkRed; lblStatus.Text = "Cannot Open Port"; } } catch(Exception ex) { if (ex is AccessViolationException || ex is InvalidOperationException) { lblStatus.ForeColor = System.Drawing.Color.Orange; lblStatus.Text = "Already Open"; } else if (ex is ArgumentException) { lblStatus.ForeColor = System.Drawing.Color.Red; lblStatus.Text = "Invaild Port"; } else { lblStatus.ForeColor = System.Drawing.Color.DarkRed; lblStatus.Text = "Cannot Open Port"; } } }
// Use this for initialization void Start() { System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe"); clientStream.Connect (60); byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("Connected/n"); Debug.Log ("connected"); clientStream.Write (buffer, 0, buffer.Length); clientStream.Flush (); clientStream.Dispose (); clientStream.Close (); }
static void Main(string[] args) { string pipeString = "Hello hello hello!"; byte[] pipeBuffer = new byte[pipeString.Length * sizeof(char)]; System.Buffer.BlockCopy(pipeString.ToCharArray(), 0, pipeBuffer, 0, pipeString.Length); NamedPipeClientStream pipe = new NamedPipeClientStream(".", "MyServicePipe", PipeDirection.Out, PipeOptions.WriteThrough, System.Security.Principal.TokenImpersonationLevel.Impersonation); pipe.Connect(); pipe.Write(pipeBuffer, 0, pipeBuffer.Length); Thread.Sleep(10000); pipe.Close(); }
void SendToPipe() { byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("done"); System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe"); clientStream.Connect (System.TimeSpan.MaxValue.Seconds); clientStream.WaitForPipeDrain(); clientStream.Write (buffer, 0, buffer.Length); clientStream.Flush (); clientStream.Dispose(); clientStream.Close(); }
// Asynchronously create a new connection public async Task<Tuple<Int32, string>> ConnectAsync(string endpoint) { // Parse the endpoint. It should be formatted as // "\\server\pipe\name". string [] components = endpoint.Split(new char[] { '\\' }); if (components.Length != 5) { return Tuple.Create(-1, "invalid endpoint format"); } // Create the connection // NOTE: It is essential that the PipeOptions.Asynchronous option be // specified, or the ReadAsync and WriteAsync methods will block // (and I don't mean they'll call await and halt - I mean they'll // never return a Task object) var connection = new NamedPipeClientStream( components[2], components[4], PipeDirection.InOut, PipeOptions.Asynchronous ); // Try to connect asynchronously try { await connection.ConnectAsync(); } catch (Exception e) { return Tuple.Create(-1, e.Message); } // Store the connection Int32 connectionId = -1; lock (this) { // Compute the next connection id. Watch for overflow, because // we use -1 as the invalid identifier. if (_nextConnectionId < 0) { connection.Close(); return Tuple.Create(-1, "connection ids exhausted"); } connectionId = _nextConnectionId++; // Do the storage _connections[connectionId] = connection; } // All done return Tuple.Create(connectionId, ""); }
private static void Main(string[] args) { try { if (args.Length > 1) { var pipeGuid = args[0]; NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeGuid, PipeDirection.InOut); pipeClient.Connect(); var dlls = args.Skip(2).ToArray(); var nunit3ConsoleExePath = Encoding.UTF8.GetString(Convert.FromBase64String(args[1])); Write(pipeClient, Discover(dlls, pipeClient, nunit3ConsoleExePath)); pipeClient.WaitForPipeDrain(); pipeClient.Close(); } } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine(ex.Message); sb.AppendLine(ex.StackTrace); foreach (var arg in args) sb.AppendLine(arg); string fileName = DateTime.Now.ToString("YYYY-MM-DD hh:mm:ss"); Guid parsedGuid; if (args.Length > 0 && Guid.TryParse(args[0], out parsedGuid)) fileName = parsedGuid.ToString(); try { File.WriteAllText(fileName, sb.ToString()); } catch (Exception) { } Console.WriteLine(sb.ToString()); } }
public static void Write(string token) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "__MSDN__HELP__PIPE__", PipeDirection.Out); try { pipeClient.Connect(2000); StreamString ss = new StreamString(pipeClient); ss.WriteString(token); pipeClient.Close(); } catch(Exception) { } }
private void pipeWorker (object args) { try { string value = args.ToString(); _pipeStream = new NamedPipeClientStream( ".", _pipeName, PipeDirection.Out ); _pipeStream.Connect(); byte[] messageBytes = Encoding.UTF8.GetBytes( value ); _pipeStream.Write( messageBytes, 0, messageBytes.Length ); _pipeStream.WaitForPipeDrain(); _pipeStream.Close(); Thread.Sleep( 5000 ); _sendingFinished.Set(); } catch { } }
public static void ConnectToMasterPipeAndSendData(string data) { byte[] stringData = Encoding.UTF8.GetBytes(data); int stringLength = stringData.Length; byte[] array = new byte[sizeof(Int32) + stringLength]; using (MemoryStream stream = new MemoryStream(array)) { byte[] stringLengthData = BitConverter.GetBytes(stringLength); stream.Write(stringLengthData, 0, stringLengthData.Length); stream.Write(stringData, 0, stringData.Length); } NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "SpeditNamedPipeServer", PipeDirection.Out, PipeOptions.Asynchronous); pipeClient.Connect(5000); pipeClient.Write(array, 0, array.Length); pipeClient.Flush(); pipeClient.Close(); pipeClient.Dispose(); }
static void Main(string[] args) { try { if (args.Length > 1) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", args[0], PipeDirection.InOut); pipeClient.Connect(); Discover(args, pipeClient); pipeClient.WaitForPipeDrain(); pipeClient.Close(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void Main(string[] Args) { if (Args.Length > 0) { if (Args[0] == "spawnclient") { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); Console.WriteLine("Connecting to server...\n"); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); // Validate the server's signature string if (ss.ReadString() == "I am the one true server!") { // The client security token is sent with the first write. // Send the name of the file whose contents are returned // by the server. ss.WriteString(@"C:\Temp\textfile.txt"); // Print the file to the screen. Console.Write(ss.ReadString()); } else { Console.WriteLine("Server could not be verified."); } pipeClient.Close(); // Give the client process some time to display results before exiting. Thread.Sleep(4000); } } else { Console.WriteLine("\n*** Named pipe client stream with impersonation example ***\n"); StartClients(); } }
private static void client() { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "channell1", PipeDirection.InOut, PipeOptions.None); if (pipeClient.IsConnected != true) { pipeClient.Connect(); } StreamReader streamReader = new StreamReader(pipeClient); StreamWriter streamWriter = new StreamWriter(pipeClient); try { streamWriter.WriteLine("здорова"); streamWriter.Flush(); string len = streamReader.ReadLine(); Console.WriteLine("hength of string = " + len); pipeClient.Close(); } catch (Exception ex) { throw ex; } }
protected override void Run() { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); int retryCount = 120; do { try { pipeClient.Connect(0); } catch (System.TimeoutException exp) { throw exp; } catch { System.Threading.Thread.Sleep(1000); pipeClient = null; pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); } } while (!pipeClient.IsConnected && retryCount-- != 0); foreach (Host host in pool.Connection.Cache.Hosts) { if (host.IsMaster()) { string credential; if (callHomeSettings.Status == CallHomeStatus.Enabled) credential = ProtectCredential(host.address, username, password); else credential = ProtectCredential(host.address, string.Empty, string.Empty); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); break; } } pipeClient.Write(Encoding.UTF8.GetBytes(CallHomeSettings.HEALTH_CHECK_PIPE_END_MESSAGE), 0, CallHomeSettings.HEALTH_CHECK_PIPE_END_MESSAGE.Length); pipeClient.Close(); }
public static void RunProperMode(Command command) { if (command.ContainsCommandArg("/Uninstall")) { // Are we in uninstall-mode? UninstallHelper uninstallHelper = new UninstallHelper(); uninstallHelper.RunUninstall(); } else if (command.ContainsCommandArg("-silentinstall")) { Globals.InPortableMode = command["-portable"].ToBool(); Globals.IsSilentInstall = true; NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "www.pmuniverse.net-installer", PipeDirection.InOut, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Impersonation); pipeClient.Connect(); Pipes.StreamString clientStream = new Pipes.StreamString(pipeClient); Globals.SilentInstallCommunicationPipeStream = clientStream; Globals.SilentInstallCommunicationPipe = pipeClient; installWaitEvent = new ManualResetEvent(false); Installer installer = new Installer(command); installer.InstallComplete += new EventHandler(installer_InstallComplete); installer.Install(clientStream); installWaitEvent.WaitOne(); clientStream.WriteString("[InstallComplete]"); pipeClient.WaitForPipeDrain(); pipeClient.Close(); System.Environment.Exit(0); } else { // There are no special command line arguments, run the installer in install mode // Let's check if we elevated ourselves if (!Globals.CommandLine.ContainsCommandArg("/skipwelcome") || !VistaSecurity.IsAdmin()) { // Show the welcome page PageManager.ActivePage = new Pages.pgeWelcome(); } else { // Show the license page PageManager.ActivePage = new Pages.pgeLicense(); } } }
public static void LaunchWithUpload(string filename) { if (LaunchInt(filename)) { return; } try { NamedPipeClientStream client = new NamedPipeClientStream("foxScreenUploadPipe"); client.Connect(1); StreamWriter writer = new StreamWriter(client); writer.WriteLine(filename); writer.Close(); client.Close(); } catch(Exception e) { MessageBox.Show(e.ToString(), "foxScreen: ERROR"); } Stop(); }
public static void NotifYUser(Settings settings, SettingsPrinter printer, List<InkLevel> inkLevel) { string title = "Printer Ink is at low level"; string body = ""; //body += title + "\n\r\n\r"; body += "Printer Details:\n\r"; body += printer.Name + "\n\r"; foreach (var level in inkLevel) { if (level.Value <= printer.Level) { body += string.Format("{0} - {1:00%}\n\r", level.Name, level.Value); } } body += "\n\r\n\r*****"; try { var pipeClient = new NamedPipeClientStream("InkMonPipe"); pipeClient.Connect(3000); if (pipeClient.IsConnected) { var buf = Encoding.ASCII.GetBytes(body); pipeClient.Write(buf, 0, buf.Length); pipeClient.WaitForPipeDrain(); pipeClient.Close(); } } catch (Exception e) { Console.WriteLine(e); } }
public string LaunchRemoteProcess(string processFileName) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", RemoteDemoControlPipe.PIPE_NAME, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); string message = null; // Connecting to server... try { pipeClient.Connect(100); } catch (TimeoutException) { return "Failed to connect to demo launcher. Please make sure DemoLauncher is running on this machine."; } StreamString ss = new StreamString(pipeClient); // Validate the server's signature string if (ss.ReadString() == RemoteDemoControlPipe.PIPE_SIGNATURE) { // The client security token is sent with the first write. // Send the name of the file whose contents are returned // by the server. ss.WriteString(processFileName); message = ss.ReadString(); } else { message = "Demo launcher could not be verified. Please make sure the correct version of DemoLauncher is running on this machine."; } pipeClient.Close(); return message; }
static void PipeListener() { try { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "NowPlayingTunes", PipeDirection.InOut, PipeOptions.None); StreamString ss = new StreamString(pipeClient); pipeClient.Connect(); String rettext = ss.ReadString(); Console.WriteLine(rettext); pipeClient.Close(); pipeClient.Dispose(); } catch (Exception ex) { } if (DebugMode == false) { if (TimeoutThread.IsAlive == true) { TimeoutThread.Abort(); } } }
private void ReadPipeOutputNewLiveTV() { // investigate on using http://stackoverflow.com/questions/5718473/c-sharp-processstartinfo-start-reading-output-but-with-a-timeout byte[] bytes = new byte[16 * 1024];//16 * 1024 //http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/5966ab37-afec-4b96-8106-4de0fbc70040/ BeginTimeoutDetection(); BinaryWriter bw; bw = new BinaryWriter(new BufferedStream(ffMpegEncodeAndSegment.StandardInput.BaseStream)); while (true) { NamedPipeClientStream PipeClient = new NamedPipeClientStream(".", "liveVideoStreamPipe" + ID, PipeDirection.In, PipeOptions.Asynchronous); //((FFHLSRunner)caller).SendDebugMessage("ShellCmdRunner: pipeclient going to connect"); try { PipeClient.Connect(); { bw.Write(ReadFully(PipeClient, 0)); lock (lastReadStandardOutputLock) { lastReadStandardOutput = DateTime.Now; // Track the time out } } //http://stackoverflow.com/questions/895445/system-io-exception-pipe-is-broken PipeClient.Close(); } catch (Exception e) { ((FFHLSRunner)caller).SendDebugMessage(e.Message); } } bw.Close(); return; }
static void TestClient(object stateInfo) { Console.WriteLine("entering TestClient"); NamedPipeClientStream pipeClient1 = new NamedPipeClientStream(".", "openclmonitor_pipe", PipeDirection.InOut, PipeOptions.None); pipeClient1.Connect(5000); if (!pipeClient1.IsConnected) { Console.WriteLine("TestClient KO;Could not connect to pipe"); return; } StreamString ss = new StreamString(pipeClient1); MonitorMessage createMsgOUT = new MonitorMessage(OpCodes.CREATE, 0, 0, "DEVICETEST"); ss.WriteString(createMsgOUT.ToString()); MonitorMessage createMsgIN = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", createMsgIN.ToString()); pipeClient1.Close(); NamedPipeClientStream pipeClient2 = new NamedPipeClientStream(".", createMsgIN.Body[0], PipeDirection.InOut, PipeOptions.None); pipeClient2.Connect(5000); if (!pipeClient2.IsConnected) { Console.WriteLine("TestClient KO;Could not connect to queue pipe"); return; } ss = new StreamString(pipeClient2); MonitorMessage enumOUT = new MonitorMessage(OpCodes.ENUMERATE_COUNTERS, 0, 0, new string[] { "counterA", "counterB" }); ss.WriteString(enumOUT.ToString()); MonitorMessage enumIN = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", enumIN.ToString()); StringBuilder sb = new StringBuilder(); sb.Append("TestClient received enable counters: "); foreach (int cid in enumIN.BodyAsFloatArray) { sb.AppendFormat("{0}, ", cid); } Console.WriteLine(sb.ToString()); { MonitorMessage mOut = new MonitorMessage(OpCodes.PERF_INIT, 0, 0); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } { MonitorMessage mOut = new MonitorMessage(OpCodes.RELEASE, 0, 0); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } { MonitorMessage mOut = new MonitorMessage(OpCodes.GET_COUNTERS, 0, 0, new float[]{1.1f, 2.2f}); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } { MonitorMessage mOut = new MonitorMessage(OpCodes.END, 0, 0); ss.WriteString(mOut.ToString()); MonitorMessage mIn = MonitorMessage.ParseFromString(ss.ReadString()); Console.WriteLine("TestClient Received {0}", mIn.ToString()); } pipeClient2.Close(); Console.WriteLine("TestClient queue done"); }
/// <summary> /// Connect to our named-pipe server, send arguements and close current process /// </summary> /// <param name="args"></param> /// <param name="param"></param> private static void RunClient(string[] args, string param) { if (!isServerRunning) { MessageBox.Show("FTPbox must be running to use the context menus!", "FTPbox", MessageBoxButtons.OK, MessageBoxIcon.Information); RemoveFTPboxMenu(); Process.GetCurrentProcess().Kill(); } NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "FTPbox Server", PipeDirection.InOut, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Impersonation); Log.Write(l.Client, "Connecting client..."); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); if (ss.ReadString() == "ftpbox") { string p = CombineParameters(args, param); ss.WriteString(p); Log.Write(l.Client, ss.ReadString()); } else { Log.Write(l.Client, "Server couldnt be verified."); } pipeClient.Close(); Thread.Sleep(4000); Process.GetCurrentProcess().Kill(); }
/// <summary> /// Use the types in the System.IO.Pipes namespace to connect to the /// named pipe. This solution is recommended when you program against /// .NET Framework 3.5 or any newer releases of .NET Framework. /// </summary> public static void Run() { NamedPipeClientStream pipeClient = null; try { // Try to open the named pipe identified by the pipe name. pipeClient = new NamedPipeClientStream( Program.ServerName, // The server name Program.PipeName, // The unique pipe name PipeDirection.InOut, // The pipe is duplex PipeOptions.None // No additional parameters ); pipeClient.Connect(5000); Console.WriteLine("The named pipe ({0}) is connected.", Program.FullPipeName); // Set the read mode and the blocking mode of the named pipe. In // this sample, we set data to be read from the pipe as a stream // of messages. This allows a reading process to read varying- // length messages precisely as sent by the writing process. In // this mode, you should not use StreamWriter to write the pipe, // or use StreamReader to read the pipe. You can read more about // the difference from http://go.microsoft.com/?linkid=9721786. pipeClient.ReadMode = PipeTransmissionMode.Message; // // Send a request from client to server // string message = Program.RequestMessage; byte[] bRequest = Encoding.Unicode.GetBytes(message); int cbRequest = bRequest.Length; pipeClient.Write(bRequest, 0, cbRequest); Console.WriteLine("Send {0} bytes to server: \"{1}\"", cbRequest, message.TrimEnd('\0')); // // Receive a response from server. // do { byte[] bResponse = new byte[Program.BufferSize]; int cbResponse = bResponse.Length, cbRead; cbRead = pipeClient.Read(bResponse, 0, cbResponse); // Unicode-encode the received byte array and trim all the // '\0' characters at the end. message = Encoding.Unicode.GetString(bResponse).TrimEnd('\0'); Console.WriteLine("Receive {0} bytes from server: \"{1}\"", cbRead, message); } while (!pipeClient.IsMessageComplete); } catch (Exception ex) { Console.WriteLine("The client throws the error: {0}", ex.Message); } finally { // Close the pipe. if (pipeClient != null) { pipeClient.Close(); pipeClient = null; } } }