// // Copyright 2015 Perforce Software Inc. // using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Windows.Threading; namespace Perforce.Helper { public class P4Listener : IDisposable { private BackgroundWorker _worker; private bool _runnable; public P4Listener() { _worker = new BackgroundWorker(); _worker.DoWork += new DoWorkEventHandler(this.DoWork); _worker.RunWorkerAsync(); } public void Start() { if (!_worker.IsBusy) { _worker.RunWorkerAsync(); } } public void Stop() { if (_worker.IsBusy) { _worker.CancelAsync(); _runnable = false; } } private void DoWork(object sender, DoWorkEventArgs e) { _runnable = true; while (_runnable) { //Create a named pipe using the current process ID of this application using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("PipeTo" + Process.GetCurrentProcess().Id.ToString())) { Log.Debug(string.Format("[Server] Pipe Created, the current process ID is {0}", Process.GetCurrentProcess().Id.ToString())); //wait for a connection from another process pipeStream.WaitForConnection(); Log.Debug("[Server] Pipe connection established"); using (StreamReader sr = new StreamReader(pipeStream)) { string url; //wait for message to arrive from the pipe, when message arrive print date/time and the message to the console. while ((url = sr.ReadLine()) != null) { if (url.StartsWith("p4://")) { GoToPath(url); } } } pipeStream.Close(); } } } private void GoToPath(string url) { App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UIHelper.GoToPath(url); })); } #region CLEANUP protected virtual void Dispose(bool disposing) { if (disposing) { // dispose managed resources if (_worker != null) { _worker.Dispose(); } } // free native resources } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }