static void Main() { ClearModifierKeys(); var args = Environment.GetCommandLineArgs(); var multi = args.Any(arg => arg == "-multi"); if ((multi) || (mutex.WaitOne(TimeSpan.Zero, true))) { var app = new App(); if (!multi) SetupPipeWait(app); app.Run(); if (!multi) mutex.ReleaseMutex(); return; } // Server already exists; connect and send command line var pipeClient = new NamedPipeClientStream(".", IPCName, PipeDirection.InOut); pipeClient.Connect(); var buf = Coder.StringToBytes(string.Join(" ", args.Skip(1).Select(arg => $"\"{arg.Replace(@"""", @"""""")}\"")), Coder.CodePage.UTF8); var size = BitConverter.GetBytes(buf.Length); pipeClient.Write(size, 0, size.Length); pipeClient.Write(buf, 0, buf.Length); }
/// <summary> /// Sends message to all remote listeners /// </summary> /// <param name="data">Message data</param> protected override void SendMessage(byte[] data) { foreach (var pipeConfiguration in _clientPipesConfiguration) { using (var namedPipeClient = new NamedPipeClientStream( pipeConfiguration.ServerName, pipeConfiguration.Name)) { try { _log.DebugFormat("Send message to {0}\\{1}", pipeConfiguration.ServerName, pipeConfiguration.Name); if (!ConnectToPipe(namedPipeClient)) { _log.WarnFormat("Couldn't connect to pipe {0}\\{1}", pipeConfiguration.ServerName, pipeConfiguration.Name); continue; } namedPipeClient.Write(data, 0, data.Length); } catch (IOException ex) { _log.Warn("Exception while sending a message", ex); } } } }
public static void ClientSendsByteServerReceives() { using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In)) { byte[] sent = new byte[] { 123 }; byte[] received = new byte[] { 0 }; Task t = Task.Run(() => { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out)) { client.Connect(); Assert.True(client.IsConnected); client.Write(sent, 0, 1); } }); server.WaitForConnection(); Assert.True(server.IsConnected); int bytesReceived = server.Read(received, 0, 1); Assert.Equal(1, bytesReceived); t.Wait(); Assert.Equal(sent[0], received[0]); } }
public static void SendBreakRequest() { using (NamedPipeClientStream client = new NamedPipeClientStream(PIPENAME)) { client.Connect(); client.Write(BREAK, 0, BREAK.Length); } }
private static void PipesWriter(string pipeName) { try { using (var pipeWriter = new NamedPipeClientStream("TheRocks", pipeName, PipeDirection.Out)) { pipeWriter.Connect(); WriteLine("writer connected"); bool completed = false; while (!completed) { string input = ReadLine(); if (input == "bye") completed = true; byte[] buffer = Encoding.UTF8.GetBytes(input); pipeWriter.Write(buffer, 0, buffer.Length); } } WriteLine("completed writing"); } catch (Exception ex) { WriteLine(ex.Message); } }
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(); }
static void Main() { try { using (var pipe = new NamedPipeClientStream(".", "sharp-express", PipeDirection.InOut)) { pipe.Connect(); var encoding = Encoding.UTF8; var sb = new StringBuilder(); sb.Append("GET / HTTP/1.1\r\n"); sb.Append("Header1: Hi!\r\n"); sb.Append("\r\n"); var bytes = encoding.GetBytes(sb.ToString()); pipe.Write(bytes, 0, bytes.Length); pipe.Flush(); var buf = new byte[64 * 1024]; var size = pipe.Read(buf, 0, buf.Length); var message = encoding.GetString(buf, 0, size); Console.WriteLine(message); } } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); }
static void Main() { try { using (var npcs = new NamedPipeClientStream("Stream Mosaic")) { try { npcs.Connect(500); var url = Environment.CommandLine.Substring(Environment.CommandLine.IndexOf(' ')).Trim(); var textBytes = Encoding.UTF8.GetBytes(url); npcs.Write(textBytes, 0, textBytes.Length); npcs.Flush(); var responseBytes = new byte[1]; npcs.Read(responseBytes, 0, 1); } catch (TimeoutException) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainWindow()); } } } catch (Exception exc) { MessageBox.Show(exc.ToString()); } }
protected override void WriteMessage(Byte[] message) { message = message ?? Empty; using (var pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.None)) { pipeStream.Connect(timeout); pipeStream.Write(message, 0, message.Length); } }
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 + "]が見つかりません."); } }
public static void SendPipeMessgae(String mes) { using (NamedPipeClientStream clientStream = new NamedPipeClientStream("zjlrcpipe")) { // connect to the pipe sever clientStream.Connect(); UTF8Encoding encoding = new UTF8Encoding(); Byte[] bytes = encoding.GetBytes(mes); clientStream.Write(bytes, 0, bytes.Length); } }
// 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(); }
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(); }
static void Main(string[] args) { Console.WriteLine("Opening pipe {0}", PIPE_NAME); NamedPipeClientStream pipeClient = new NamedPipeClientStream( ".", PIPE_NAME, PipeDirection.Out, PipeOptions.Asynchronous ); pipeClient.Connect(10000); Console.WriteLine("Writing message."); string messageText = "Hello World"; byte[] message = Encoding.UTF8.GetBytes(messageText); pipeClient.Write(message, 0, message.Length); string messageText2 = "This is a second message"; byte[] message2 = Encoding.UTF8.GetBytes(messageText2); pipeClient.Write(message2, 0, message2.Length); Console.WriteLine("Done."); }
public bool Send(string pipeName, string message) { bool bSuccess = true; using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { try { pipeStream.Connect(CONNECT_TIMEOUT); pipeStream.ReadMode = PipeTransmissionMode.Message; byte[] cData = Encoding.UTF8.GetBytes(message); pipeStream.Write(cData, 0, cData.Length); pipeStream.Flush(); } catch(Exception __errExcep) { if (logger.IsErrorEnabled) logger.ErrorFormat("{0}\r\n{1}", __errExcep.Message, __errExcep.StackTrace); bSuccess = false; } } return bSuccess; }
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(); }
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 { } }
private void SendCommand(int pid, string command) { var clientStream = new NamedPipeClientStream(".", this.PipeNameForPid(pid), PipeDirection.InOut, PipeOptions.Asynchronous); clientStream.Connect(500); clientStream.ReadMode = PipeTransmissionMode.Message; var commandBytes = Encoding.ASCII.GetBytes(command); byte[] buffer = new byte[256]; var responseBuilder = new StringBuilder(); clientStream.Write(commandBytes, 0, commandBytes.Length); int read = clientStream.Read(buffer, 0, buffer.Length); responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); while (!clientStream.IsMessageComplete) { read = clientStream.Read(buffer, 0, buffer.Length); responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); } this.ProcessResponse(responseBuilder.ToString()); }
private static void ChunkRequestSpeedTest(object data) { //initialize world SendCommandToEnviroGen(new byte[] { 1, 10, 10}); var getChunkCommand = new byte[] { 4, 0, 0 }; m_Watch.Start(); for (var i = 0; i < 1000; i++) { var pipe = new NamedPipeClientStream(".", m_OutputPipeName, PipeDirection.InOut); pipe.Connect(); pipe.Write(getChunkCommand, 0, getChunkCommand.Length); var input = new byte[32768 + 1]; pipe.Read(input, 0, input.Length); } m_Watch.Stop(); Console.WriteLine($"EnviroGen took {m_Watch.ElapsedMilliseconds}ms to serve 1000 chunks."); Console.WriteLine($"Average Time: {m_Watch.ElapsedMilliseconds / 1000f}ms"); m_Watch.Reset(); Console.ReadLine(); }
private void Init() { if (PipeExists(PIPENAME)) { using (NamedPipeClientStream client = new NamedPipeClientStream(PIPENAME)) { try { client.Connect(2000); client.Write(SHOW, 0, SHOW.Length); client.WaitForPipeDrain(); } catch { } } Environment.Exit(1); } using (NamedPipeServerStream server = new NamedPipeServerStream(PIPENAME)) { while (true) { server.WaitForConnection(); byte[] data = new byte[255]; int count = server.Read(data, 0, data.Length); string msg = Encoding.ASCII.GetString(data, 0, count).ToUpper(); if (msg.Equals("SHOW")) { main.Invoke(new MethodInvoker(delegate { main.Show(); main.WindowState = FormWindowState.Normal; })); } else if (msg.Equals("BREAK")) { break; } else if (msg.Equals("EXIT")) { Environment.Exit(0); } server.Disconnect(); } } }
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 bool Run() { if (IsFirstInstance) { try { pipeServer = new Thread(ServerMain); pipeServer.Start(); bool ShowMainForm = OnInitInstance(this); if (MainForm == null) return false; Application.ApplicationExit += OnExitInstance; MainForm.FormClosed += OnExitInstance; if (ShowMainForm) Application.Run(MainForm); else Application.Run(); return true; } finally { pipeServer.Abort(); } } else { try { NamedPipeClientStream client = new NamedPipeClientStream(".", instanceID, PipeDirection.Out); client.Connect(500); StringBuilder commandLineStr = new StringBuilder(CommandLine.Length * 64); foreach (string param in CommandLine) commandLineStr.Append(string.Format( CultureInfo.InvariantCulture, "{0}\0", param)); byte[] buffer = new byte[commandLineStr.Length]; int count = Encoding.UTF8.GetBytes(commandLineStr.ToString(), 0, commandLineStr.Length, buffer, 0); client.Write(buffer, 0, count); } catch (UnauthorizedAccessException) { MessageBox.Show(S._("Another instance of Eraser is already running but it is " + "running with higher privileges than this instance of Eraser.\n\n" + "Eraser will now exit."), S._("Eraser"), MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, S.IsRightToLeft(null) ? MessageBoxOptions.RtlReading : 0); } catch (TimeoutException) { } return false; } }
/// <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; } } }
public void Send(byte[] message) { using ( var pipeClientStream = new NamedPipeClientStream( ".", this.hookServerChannelName, PipeDirection.Out, PipeOptions.None)) { pipeClientStream.Connect(); pipeClientStream.Write(message, 0, message.Length); try { pipeClientStream.WaitForPipeDrain(); } catch { Debug.WriteLine("pipe bandaid!"); } } }
protected override void OnStartup(StartupEventArgs e) { if (e.Args == null) _exeArguments = new string[0]; else _exeArguments = e.Args; AppDomain.CurrentDomain.UnhandledException += UncaughtThreadException; DispatcherUnhandledException += UncaughtUiThreadException; using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) _pipeName = String.Format("DayZeroLauncher_{{{0}}}_Instance", identity.User); bool secondInstance = false; using (var pipeConn = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out)) { try { const int timeoutMs = 100; pipeConn.Connect(timeoutMs); pipeConn.ReadMode = PipeTransmissionMode.Message; string queryString = GetQueryParams(); if (!string.IsNullOrEmpty(queryString)) { byte[] bytesToWrite = Encoding.UTF8.GetBytes(queryString); pipeConn.Write(bytesToWrite, 0, bytesToWrite.Length); pipeConn.WaitForPipeDrain(); } secondInstance = true; pipeConn.Close(); } catch (TimeoutException) { } } if (secondInstance) //already sent message to pipe { Shutdown(); return; } //we are the only app, start the server StartPipeServer(); LocalMachineInfo.Current.Update(); base.OnStartup(e); }
private const char SEPARATOR = '\x202f'; // narrow non-breaking space. #endregion Fields #region Methods public static void CredentialReceiverTests() { CredentialReceiver.instance.Init(); ServerListHelper.instance.Init(); string HostName = "Host1"; string UserName = "******"; string Password = "******"; int conSize = ServerListHelper.instance.GetServerList().Count; try { //1. Empty credential NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); string credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); List<ServerInfo> con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize); //2. Send credential and check result pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName, UserName, Password })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize + 1); //3. Send credential twice and check result pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName, UserName, Password })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize + 1); //4. remove credential and check result pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize); //5. add long credential size pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); HostName = "Host01234546789012345467890123454678901234546789012345467890123454678901234546789012345467890123454678901234546789"; UserName = "******"; Password = "******"; credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName, UserName, Password })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize + 1); //6. remove long credential size pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize); //7. semd 2 credential pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); HostName = "host3"; credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName, UserName, Password })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); HostName = "host4"; credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName, UserName, Password })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize + 2); //8. remove 2 credential pipeClient = new NamedPipeClientStream(".", CallHomeSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); HostName = "host3"; credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); HostName = "host4"; credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { HostName })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize); } catch (Exception) { } CredentialReceiver.instance.UnInit(); }
public static IWebHost CreateWebHost(HttpsConnectionFilterOptions httpsOptions) { var webHostBuilder = new WebHostBuilder() .UseLoggerFactory(_loggerFactory) .UseConfiguration(Configuration) .UseKestrel(options => { if (httpsOptions != null) { options.UseHttps(httpsOptions); } //options.UseConnectionLogging(); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>(); var webHost = webHostBuilder.Build(); var serverAddresses = webHost.ServerFeatures.Get<IServerAddressesFeature>(); string pipeName = _startupOptions.WriteServerUrlsToPipe; if (pipeName != null) { NamedPipeClientStream pipe; try { pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out); pipe.Connect(10000); } catch (IOException ex) { _logger.LogCritical(0, ex, Resources.Critical_InvalidPipeHandle, pipeName); throw; } catch (TimeoutException ex) { _logger.LogCritical(0, ex, Resources.Critical_PipeConnectTimeOut, pipeName); throw; } var applicationLifetime = webHost.Services.GetService<IApplicationLifetime>(); applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => { using (pipe) { string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses); _logger.LogTrace(Resources.Trace_ServerUrlsToPipeBegin, pipeName, Environment.NewLine, serverUriStr); var serverUriData = Encoding.UTF8.GetBytes(serverUriStr); pipe.Write(serverUriData, 0, serverUriData.Length); pipe.Flush(); } _logger.LogTrace(Resources.Trace_ServerUrlsToPipeDone, pipeName); })); } return webHost; }
private void sendArgsToExistingInstance(string[] args) { var pipeClient = new NamedPipeClientStream(".", ipcNamedPipeGuid, PipeDirection.Out); // try to connect to the pipe server for the Timeout period try { var sb = new StringBuilder(); sb.AppendLine(args.Length.ToString()); foreach (string arg in args) sb.AppendLine(arg); byte[] buffer = Encoding.ASCII.GetBytes(sb.ToString()); pipeClient.Connect(Timeout); // can this ever happen? if it does, don't handle it like a timeout exception if (!pipeClient.IsConnected) throw new Exception("did not throw exception"); pipeClient.Write(buffer, 0, buffer.Length); } catch (Exception e) { if (!e.Message.ToLower().Contains("time")) throw; // no server was running; launch a new instance Launching(this, new SingleInstanceEventArgs(args)); } }