/// <summary> /// After registering at least ApplicationStarts, call this method to ensure this instance is the single instance. /// If this instance is the first (single) instance, the ApplicationStarts event will be triggered. /// If this instance is not the first (single) instance, the application will be terminated immediately. /// </summary> public void RunSingleInstance() { // get information from the mutex if we're the first/single instance. bool owned = false; mutex = new Mutex(false, "Global\\{" + id.ToString() + "}", out owned); if (owned) // we "own" the mutex, meaning we're the first instance { // inform the application to begin startup if (ApplicationStarts != null) { ApplicationStarts(this, new EventArgs()); } // prepare a named pipe to receive data from subsequent start attempts ListenNamedPipe(); } else // In this case, we're a subsequent instance. { // Connect to the named pipe, if able, to signal the original instance that subsequent startup has been attempted // This could be extended to send actual data to the original instance try { var np = new System.IO.Pipes.NamedPipeClientStream(".", id.ToString(), PipeDirection.Out); np.Connect(0); np.Dispose(); } catch { } // Regardless, shut down immediately Application.Current.Shutdown(); } }
// 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 (); }
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(); }
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 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 IEnumerable<string> SendCommand(string command, params string[] arguments) { if (!IsPowerShellExecutionHostRunning) throw new InvalidOperationException(); hostSemaphore.WaitOne(); try { var client = new NamedPipeClientStream(".", currentToken, PipeDirection.InOut); TextWriter w; TextReader r; try { client.Connect(CONNECTION_TIMEOUT); w = new StreamWriter(client, Encoding.UTF8, 4, true); r = new StreamReader(client, Encoding.UTF8, false, 4, true); } catch (TimeoutException) { yield break; } catch (IOException ioEx) { Debug.WriteLine(ioEx); yield break; } w.WriteLine(command); foreach (var arg in arguments) { w.WriteLine(arg); } w.Flush(); while (client.IsConnected) { var l = r.ReadLine(); if (l != null) { yield return l; } } r.Dispose(); client.Dispose(); } finally { hostSemaphore.Release(); } }
/// <summary> /// After registering at least ApplicationStarts, call this method to ensure this instance is the single instance. /// If this instance is the first (single) instance, the ApplicationStarts event will be triggered. /// If this instance is not the first (single) instance, the application will be terminated immediately. /// </summary> public void RunSingleInstance() { // get information from the mutex if we're the first/single instance. bool owned = false; mutex = new Mutex(false, "Global\\{" + id.ToString() + "}", out owned); if (owned) // we "own" the mutex, meaning we're the first instance { // inform the application to begin startup if (ApplicationStarts != null) ApplicationStarts(this, new EventArgs()); // prepare a named pipe to receive data from subsequent start attempts ListenNamedPipe(); } else // In this case, we're a subsequent instance. { // Connect to the named pipe, if able, to signal the original instance that subsequent startup has been attempted // This could be extended to send actual data to the original instance try { var np = new System.IO.Pipes.NamedPipeClientStream(".", id.ToString(), PipeDirection.Out); np.Connect(0); np.Dispose(); } catch { } // Regardless, shut down immediately Application.Current.Shutdown(); } }
static void Main(string[] args) { // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); using (var mutex = new Mutex(false, mutexId)) { // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 // mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(500, false); if (hasHandle == false) { if (args.Count() == 1) { if (args[0] == "update") { //TODO: send message to pipe NamedPipeClientStream pipe = new NamedPipeClientStream(".", "NXTLibTesterGUI_forceupdatepipe", PipeDirection.Out); StreamWriter sw = new StreamWriter(pipe); pipe.Connect(); sw.AutoFlush = true; sw.WriteLine("Force Update Now!"); pipe.WaitForPipeDrain(); pipe.Dispose(); } return; } MessageBox.Show("Application already running! Close the other instance and try again.", "Application Running", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } FindNXT.updatewaiting = false; if (args.Count() == 1) { if (args[0] == "update") { FindNXT.updatewaiting = true; } } // Perform your work here. Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FindNXT()); } finally { // edited by acidzombie24, added if statemnet if (hasHandle) mutex.ReleaseMutex(); } } }
void Client() { running = true; try { while (running) { pipe = new NamedPipeClientStream(settings.Host, settings.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous); eventPipe = new NamedPipeClientStream(settings.Host, settings.EventPipeName, PipeDirection.InOut, PipeOptions.Asynchronous); while (running) { try { pipe.Connect(2000); } catch { continue; } break; } if (!running) { if (pipe.IsConnected) pipe.Close(); break; } while (running) { try { eventPipe.Connect(2000); } catch { continue; } break; } if (!running) { if (eventPipe.IsConnected) eventPipe.Close(); break; } BinaryReader brPipe = new BinaryReader(pipe); BinaryWriter bwPipe = new BinaryWriter(pipe); bwEventPipe = new BinaryWriter(eventPipe); DriverConnected = true; try { while (running) { try { int command = brPipe.ReadInt32(); switch (command) { case 0: handler.ResetCard(true); Log("Reset"); if (cardInserted) { var ATR = handler.ATR; bwPipe.Write((Int32)ATR.Length); bwPipe.Write(ATR, 0, ATR.Length); bwPipe.Flush(); } else { bwPipe.Write((Int32)0); bwPipe.Flush(); } break; case 1: if (cardInserted) { var ATR = handler.ATR; bwPipe.Write((Int32)ATR.Length); bwPipe.Write(ATR, 0, ATR.Length); bwPipe.Flush(); } else { bwPipe.Write((Int32)0); bwPipe.Flush(); } //if (command == 0) // logMessage("Reset"); //else // logMessage("getATR"); break; case 2: int apduLen = brPipe.ReadInt32(); byte[] APDU = new byte[apduLen]; brPipe.Read(APDU, 0, apduLen); byte[] resp = handler.ProcessApdu(APDU); if (resp != null) { bwPipe.Write((Int32)resp.Length); bwPipe.Write(resp, 0, resp.Length); } else bwPipe.Write((Int32)0); bwPipe.Flush(); break; } } catch (Exception e) { if (!(e is EndOfStreamException) && !(e is ObjectDisposedException)) Log(e.ToString()); if (running) { break; } else { Log("Card Stop"); return; } } } } catch (Exception ex) { int p = 0; } finally { if (cardInserted) { cardInserted = false; if (CardInsert != null) CardInsert(false); } DriverConnected = false; if (pipe.IsConnected) pipe.Close(); if (eventPipe.IsConnected) eventPipe.Close(); pipe.Dispose(); eventPipe.Dispose(); } } } catch (Exception ex) { Log("Card Exception:" + ex.ToString()); } }
public void Run() { DateTime lastReport; outputDataProcessors = new Dictionary<string, List<OutputDataProcessor>>(); modelProperties = new Dictionary<string, Dictionary<string, string>>(); outputFiles = new Dictionary<string, Dictionary<string, string>>(); logger.Info("TaskRunner is initializing..."); pipeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut, PipeOptions.WriteThrough, TokenImpersonationLevel.Impersonation); pipeClient.Connect(); logger.Info("Pipe connected."); bool isReleased = false; try { using (BinaryReader br = new BinaryReader(pipeClient)) using (BinaryWriter bw = new BinaryWriter(pipeClient)) { /* handshake */ PipeUtil.WriteCommand(bw, new PipeCommand("Hello")); logger.Info("Pipe: Handshake signal sent."); PipeCommand helloCommand = PipeUtil.ReadCommand(br); if (helloCommand.Command != "Hello") throw new Exception("Handshake failed."); logger.Info("Pipe: Handshake signal received."); composition = new CompositionManager(); do { string modelId, assemblyPath; PipeCommand command = PipeUtil.ReadCommand(br); logger.Info("Pipe: Received command: " + command.Command); switch (command.Command) { case "AddModel": modelId = command.Parameters["modelId"]; string workingDirectory = command.Parameters["workingDirectory"]; assemblyPath = command.Parameters["assemblyPath"]; string linkableComponent = command.Parameters["linkableComponent"]; Model model = new Model(); model.Create(modelId, workingDirectory, assemblyPath, linkableComponent); composition.AddModel(model); logger.Info("Created model " + modelId + ": " + linkableComponent); break; case "AddDataProcessor": modelId = command.Parameters["modelId"]; assemblyPath = command.Parameters["assemblyPath"]; outputFiles[modelId] = SerializationUtil.Deserialize<Dictionary<string, string>>(command.Parameters["outputFiles"]); logger.Info("Adding data processor for model " + modelId + ": " + assemblyPath + "..."); foreach (KeyValuePair<string, string> entry in outputFiles[modelId]) { logger.Info("Output file " + entry.Key + ": " + entry.Value); } List<OutputDataProcessor> processors = getOutputDataProcessors(composition.GetModel(modelId), assemblyPath); if (!outputDataProcessors.ContainsKey(modelId)) outputDataProcessors[modelId] = new List<OutputDataProcessor>(); outputDataProcessors[modelId].AddRange(processors); foreach (OutputDataProcessor processor in processors) { logger.Info("Model " + modelId + " data processor: " + processor.GetType().FullName); } break; case "SetModelProperties": modelId = command.Parameters["modelId"]; foreach (KeyValuePair<string, string> entry in command.Parameters) { logger.Info("Model " + modelId + " Property: [Key=" + entry.Key + ", Value=" + entry.Value + "]"); } modelProperties[modelId] = command.Parameters; composition.GetModel(modelId).Init(modelProperties[modelId]); break; case "AddLink": string linkId = command.Parameters["linkId"]; string sourceModelId = command.Parameters["sourceModelId"]; string targetModelId = command.Parameters["targetModelId"]; string sourceQuantity = command.Parameters["sourceQuantity"]; string targetQuantity = command.Parameters["targetQuantity"]; string sourceElementSet = command.Parameters["sourceElementSet"]; string targetElementSet = command.Parameters["targetElementSet"]; logger.Info("Link " + linkId + " Property: [sourceModelId=" + sourceModelId + ", targetModelId=" + targetModelId + ", sourceQuantity=" + sourceQuantity + ", targetQuantity=" + targetQuantity + ", sourceElementSet=" + sourceElementSet + ", targetElementSet=" + targetElementSet + "]"); composition.AddLink(linkId, sourceModelId, targetModelId, sourceQuantity, targetQuantity, sourceElementSet, targetElementSet); break; case "SetSimulationProperties": DateTime triggerInvokeTime = DateTime.Parse(command.Parameters["triggerInvokeTime"]); bool parallelized = Boolean.Parse(command.Parameters["parallelized"]); progressReportInterval = Int32.Parse(command.Parameters["progressReportInterval"]); dataRecordBatchSize = Int32.Parse(command.Parameters["dataRecordBatchSize"]); composition.TriggerInvokeTime = triggerInvokeTime; composition.Parallelized = parallelized; break; case "RunSimulation": lastReport = DateTime.Now; modelProgress = new Dictionary<string, string>(); composition.CompositionModelProgressChangedHandler += new CompositionModelProgressChangedDelegate(delegate(object sender, string cmGuid, string progress) { lock (this) { modelProgress[cmGuid] = progress; if ((DateTime.Now - lastReport).TotalSeconds > progressReportInterval) { lastReport = DateTime.Now; PipeUtil.WriteCommand(bw, new PipeCommand("Progress", modelProgress)); } } }); RunSimulation(delegate(object sender, bool succeed) { logger.Info("Simulation finished, succeed=" + succeed); PipeUtil.WriteCommand(bw, new PipeCommand("Progress", modelProgress)); PipeUtil.WriteCommand(bw, new PipeCommand(succeed ? "Completed" : "Failed")); }); break; case "PostProcess": int channel = 0; foreach (KeyValuePair<string, List<OutputDataProcessor>> p in outputDataProcessors) { logger.Info("Post-processing model " + p.Key + "..."); foreach (OutputDataProcessor processor in p.Value) { logger.Info("Calling data processor " + processor.GetType().FullName + "..."); List<Stream> openedFs = new List<Stream>(); try { // set properties processor.SetProperties(modelProperties[p.Key]); // open data readers foreach (KeyValuePair<string, string> o in outputFiles[p.Key]) { if (!File.Exists(o.Value)) continue; Stream fs = new FileStream(o.Value, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); processor.SetDataReader(o.Key, fs); openedFs.Add(fs); logger.Info("Opened " + o.Value + " as " + o.Key + "."); } // transfer data Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters["ModelId"] = p.Key; parameters["ClassName"] = processor.GetType().FullName; parameters["Name"] = processor.GetName(); parameters["Channel"] = channel.ToString(); PipeUtil.WriteCommand(bw, new PipeCommand("DataSet", parameters)); List<string[]> buffer = new List<string[]>(); while (processor.HasNextRecord()) { buffer.Add(processor.GetNextRecord()); if (buffer.Count >= dataRecordBatchSize) flushDataRecord(bw, channel.ToString(), buffer); } if (buffer.Count > 0) flushDataRecord(bw, channel.ToString(), buffer); channel++; } finally { // clean up foreach (Stream fs in openedFs) { fs.Close(); fs.Dispose(); } } } } PipeUtil.WriteCommand(bw, new PipeCommand("PostProcessCompleted")); break; case "Halt": isReleased = true; return; } } while (true); } } catch (Exception e) { if (!isReleased) { logger.Crit("Exception occured during task lifetime: " + e.ToString()); } } finally { pipeClient.Close(); pipeClient.Dispose(); } }
private bool TryOpenInRunningApplication(string pipeName, string fileName) { try { using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { client.Connect(100); if (client.IsConnected) { if (fileName != null) { var bytes = Encoding.UTF8.GetBytes(fileName + "\0"); client.Write(bytes, 0, bytes.Length); client.Dispose(); } Environment.Exit(0); //Window.Dispatcher.InvokeAsync(() => Window.Close()); return true; } } } catch { } return false; }
// called by post build event static void Main(string[] args) { Console.WriteLine("enter Main"); //1> Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path 'X:\jsc.svn\examples\javascript\LINQ\test\auto\TestSelect\TestSelect\bin\DebugAsServerSignal'. //1> at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) //1> at System.Threading.EventWaitHandle..ctor(Boolean initialState, EventResetMode mode, String name) //1> at AutoRefreshTestingHost.Program.Main(String[] args) in x:\jsc.svn\examples\javascript\LINQ\test\AutoRefreshTesting\AutoRefreshTestingHost\Program.cs:line 283 var AsServerSignal = new EventWaitHandle( false, EventResetMode.AutoReset, Environment.CurrentDirectory.GetHashCode() + "AsServerSignal" ); // if its a trap then start a server var AsServer = AsServerSignal.WaitOne(1); Console.WriteLine(new { AsServer } + " continue?"); if (AsServer) { //IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle; IntPtr hWnd = GetConsoleWindow(); Console.WriteLine("time to create a server?" + new { hWnd }); // are we top most? #region WindowPos.xml new Thread( delegate () { Thread.Yield(); RECT rct0; RECT rct; #region MoveWindow if (File.Exists("WindowPos.xml")) { var WindowPos = XElement.Parse(File.ReadAllText("WindowPos.xml")); MoveWindow(hWnd, (int)WindowPos.Attribute("Left"), (int)WindowPos.Attribute("Top"), (int)WindowPos.Attribute("Right") - (int)WindowPos.Attribute("Left"), (int)WindowPos.Attribute("Bottom") - (int)WindowPos.Attribute("Top"), true ); } #endregion SetWindowPos(hWnd, new IntPtr(HWND_TOPMOST), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); while (GetWindowRect(new HandleRef(null, hWnd), out rct0)) while (GetWindowRect(new HandleRef(null, hWnd), out rct)) { //Console.Write("."); //Type.mem Thread.Sleep(100); if (rct0.GetHashCode() == rct.GetHashCode()) continue; File.WriteAllText( "WindowPos.xml", new XElement( "WindowPos", new XAttribute("Left", rct.Left), new XAttribute("Top", rct.Top), new XAttribute("Right", rct.Right), new XAttribute("Bottom", rct.Bottom) ).ToString() ); //Console.WriteLine(new { X, Y, Width, Height }); break; } } ) { IsBackground = true }.Start(); #endregion var pipeServer = new NamedPipeServerStream( Environment.CurrentDirectory.GetHashCode() + "foo", PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.WriteThrough); while (true) { //Console.WriteLine("awaiting for a new connection"); pipeServer.WaitForConnection(); //Console.WriteLine("client connected to server!"); var buffer = new byte[0xffff]; var c = pipeServer.Read(buffer, 0, buffer.Length); var xml = XElement.Parse( Encoding.UTF8.GetString(buffer, 0, c) ); var old = new { Console.ForegroundColor }; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(new { xml }); Console.ForegroundColor = old.ForegroundColor; // do something with incoming params? pipeServer.Disconnect(); // server inactive for a moment, update the state and reconnect to next client InternalMain( xml.Elements().Select(x => x.Value).ToArray() ); } } var wConnected = false; new Thread( delegate () { // allow 100 until we need to take action Thread.Sleep(100); if (wConnected) { // server already active! return; } AsServerSignal.Set(); // make us a new server // cmd.exe allows us to survive a process crash. Console.WriteLine("Process.Start cmd"); Process.Start("cmd.exe", "/K " + typeof(Program).Assembly.Location); } ) { IsBackground = true }.Start(); Console.WriteLine("connecting to the server..."); var w = new NamedPipeClientStream(".", Environment.CurrentDirectory.GetHashCode() + "foo", PipeDirection.Out, PipeOptions.WriteThrough); Thread.Yield(); w.Connect(); wConnected = true; Console.WriteLine("connecting to the server... done"); // http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.jmp(v=vs.110).aspx var bytes = Encoding.UTF8.GetBytes( new XElement("xml", from x in args select new XElement("arg", x) ).ToString() ); w.Write(bytes, 0, bytes.Length); w.Flush(); w.Dispose(); //Thread.Sleep(100); //Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read. //1> at System.Console.ReadKey(Boolean intercept) //1> at System.Console.ReadKey() //Debugger.Break(); //Console.ReadKey(); }