Beispiel #1
0
        public CmdExeApi start()
        {
            try
            {
                PipeName.namePipeServer(ConsoleOut);         // setup namedpipe
                saveUsersWindow();
                this.sleep(250);
                // host process
                HostProcessStarted        = true;
                HostCmdExeProcess         = Processes.startProcess("cmd.exe", "", MinimizeHostWindow);
                HostCmdExeProcess.Exited += (sender, e) => HostProcessEnded = true;
                findHostProcessHandle();
                // child process
                // the ReadTimeout can be reset on next recompile
                // see http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true for details on cmd.exe redirection
                var CreateChildProcessWithRedirection = "\"{0}\" {1} > \\\\.\\pipe\\{2} 2>&1".format(ProcessToStart, Arguments, PipeName);

                restoreUsersWindow();

                hostCmd(CreateChildProcessWithRedirection);
                //ChildProcess = Processes.startProcess(ProcessToStart,ChildProcessAgumentsWithRedirection);

                //this.sleep(1000);
            }
            catch (Exception ex)
            {
                ex.log("in CmdExeApi.start");
            }
            return(this);
        }
Beispiel #2
0
        public static IDisposable BeginWritingMessages(this PipeName pipe, string processName, Action <Exception> onWriteError, params IObservable <IBinaryMessage>[] messages)
        {
            var ctSource    = new CancellationTokenSource();
            var queue       = new DispatcherQueue <IBinaryMessage>();
            var writeThread = new Thread(() =>
            {
                try
                {
                    using (var stream = Pipe.Connect(pipe).Result)
                        using (var writer = new BinaryWriter(stream))
                        {
                            queue.Dispatch(message => message.WriteTo(writer), ctSource.Token);
                        }
                }
                catch (Exception e)
                {
                    onWriteError(e);
                }
            })
            {
                Name         = "Write binary messages to " + processName,
                IsBackground = true,
            };

            writeThread.Start();

            return(Disposable.Combine(
                       Disposable.Create(ctSource.Cancel),
                       messages.Merge().Subscribe(queue.Enqueue)));
        }
Beispiel #3
0
        public void DataAndTypeAreReadWriteInvariant()
        {
            var pipe = PipeName.New();

            var outbox = new []
            {
                BinaryMessage.Compose("Elm1", writer => { }),
                BinaryMessage.Compose("Elm1", writer => { }),
                BinaryMessage.Compose("Elm2", writer => writer.Write(new byte[] { 13, 37 })),
                BinaryMessage.Compose("Elm3", writer => writer.Write(new byte[] { 19, 11 })),
                BinaryMessage.Compose("Elm4", writer => { })
            };

            pipe.BeginWritingMessages("Test", ex => Assert.Fail("Write failed: " + ex.Message), outbox.ToObservable());

            var inbox = pipe.ReadMessages("test").RefCount().ToEnumerable().Take(outbox.Length).ToArray();

            Assert.AreEqual(outbox.Length, inbox.Length);

            for (int i = 0; i < outbox.Length; i++)
            {
                Assert.AreEqual(outbox[i].Type, inbox[i].Type);
                CollectionAssert.AreEqual(outbox[i].DumpBytes(), inbox[i].DumpBytes());
            }
        }
Beispiel #4
0
 public static IConnectableObservable <IBinaryMessage> ReadMessages(this PipeName pipe, string processName)
 {
     return(Observable
            .Defer(() => Pipe.Host(pipe).ToObservable())
            .Select(p => p.ReadMessages(processName))
            .Concat()
            .Publish());
 }
Beispiel #5
0
        internal static string GetMSMQPath(this PipeName pipeName)
        {
            var machineNameEncoded = (String.IsNullOrEmpty(pipeName.MachineName))
                                            ? "."
                                            : pipeName.MachineName.ToLowerInvariant();

            return(machineNameEncoded + '\\' + pipeName.GetMSMQName());
        }
Beispiel #6
0
 internal static bool IsLocal(this PipeName pipeName)
 {
     return((String.IsNullOrEmpty(pipeName.MachineName) ||
             pipeName.MachineName == "." ||
             pipeName.MachineName.ToLower() == Environment.MachineName.ToLower())
                ? true
                : false);
 }
 public VisualStudioConnectionHandler(CodeLensDataPoint owner, int vspid)
 {
     this.owner = owner;
     stream     = new NamedPipeClientStream(
         serverName: ".",
         PipeName.Get(vspid),
         PipeDirection.InOut,
         PipeOptions.Asynchronous);
 }
Beispiel #8
0
        internal static bool GetExists(this PipeName pipeName)
        {
            if (pipeName.IsLocal())
            {
                string msmqPath = pipeName.GetMSMQPath();
                return(MessageQueue.Exists(msmqPath));
            }

            string myMSMQFormatName = pipeName.GetMSMQDirectName();

            MessageQueue[] queueList = MessageQueue.GetPrivateQueuesByMachine(pipeName.MachineName);
            return(queueList.Select(messageQueue => messageQueue.FormatName).Any(curMSMQFormatName => String.Compare(myMSMQFormatName, curMSMQFormatName, true) == 0));
        }
Beispiel #9
0
        internal static string GetMSMQName(this PipeName pipeName)
        {
            var typeName = pipeName.GetType().Name;

            Debug.Assert(typeName.EndsWith(TypeSuffix),
                         "PipeName subclass " + typeName + " does not end with mandatory suffix " + TypeSuffix);
            // TODO: Remove "PipeName" type suffix and lowercase the string.
            typeName = typeName.Substring(0, typeName.Length - TypeSuffix.Length).ToLowerInvariant();
            var msmqName = Privacy + '\\' + Badge + Delimiter + typeName;

            msmqName += Delimiter + pipeName.LongName;
            return(msmqName);
        }
        private static PipeName GetPipeName(string url)
        {
            IDictionary parts = null;

            if (!ParseUrl(url, out parts))
            {
                throw new ArgumentException("Invalid pipe address specified");
            }

            PipeName pipeName = new PipeName((string)parts["host"], (string)parts["pipe"]);

            return(pipeName);
        }
Beispiel #11
0
        public Stream CreateStream(string name)
        {
            var pipeName = new PipeName(GetProcessIdentifier() + name);

            try
            {
                return(new UnixSocketStream(pipeName, SocketUsage.Host));
            }
            catch (Exception)
            {
                UnixSocketStream.Unlink(pipeName);
            }

            return(new UnixSocketStream(pipeName, SocketUsage.Host));
        }
Beispiel #12
0
        internal static uint Count(this PipeName pipeName)
        {
            MSMQExt.MQMGMTPROPS props = new MSMQExt.MQMGMTPROPS {
                cProp = 1
            };
            try
            {
                props.aPropID = Marshal.AllocHGlobal(sizeof(int));
                Marshal.WriteInt32(props.aPropID, (int)MSMQExt.MQMGMT_QUEUE_PROPERTIES.PROPID_MGMT_QUEUE_MESSAGE_COUNT);

                // Marshal.SizeOf(typeof(MSMQExt.MQPROPVARIANT))
                props.aPropVar = Marshal.AllocHGlobal(24);
                Marshal.StructureToPtr(new MSMQExt.MQPROPVARIANT {
                    vt = MSMQExt.VT_NULL
                }, props.aPropVar, false);

                props.aStatus = Marshal.AllocHGlobal(sizeof(int));
                Marshal.WriteInt32(props.aStatus, 0);

                string machineName = (pipeName.IsLocal()) ? null : pipeName.MachineName;
                string specialPath = "QUEUE=" + pipeName.GetMSMQDirectName();

                int result = MSMQExt.MQMgmtGetInfo(machineName, specialPath, ref props);
                if (result != 0 || Marshal.ReadInt32(props.aStatus) != 0)
                {
                    return(0);
                }

                MSMQExt.MQPROPVARIANT propVar = (MSMQExt.MQPROPVARIANT)Marshal.PtrToStructure(props.aPropVar, typeof(MSMQExt.MQPROPVARIANT));
                if (propVar.vt != MSMQExt.VT_UI4)
                {
                    return(0);
                }
                else
                {
                    return(propVar.Union1.ulVal);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(props.aPropID);
                Marshal.FreeHGlobal(props.aPropVar);
                Marshal.FreeHGlobal(props.aStatus);
            }
        }
Beispiel #13
0
        public static async Task AcceptCodeLensConnections()
        {
            try {
                while (true)
                {
                    var stream = new NamedPipeServerStream(
                        PipeName.Get(Process.GetCurrentProcess().Id),
                        PipeDirection.InOut,
                        NamedPipeServerStream.MaxAllowedServerInstances,
                        PipeTransmissionMode.Byte,
                        PipeOptions.Asynchronous);
                    await stream.WaitForConnectionAsync().Caf();

                    _ = HandleConnection(stream);
                }
            } catch (Exception ex) {
                LogVS(ex);
                throw;
            }
Beispiel #14
0
        private void Initialize(IDictionary properties, IServerChannelSinkProvider sinkProvider)
        {
            if (properties != null)
            {
                // read property values
                foreach (DictionaryEntry property in properties)
                {
                    switch ((string)property.Key)
                    {
                    case "name": _channelName = Convert.ToString(property.Value); break;

                    case "priority": _channelPriority = Convert.ToInt32(property.Value); break;

                    case "pipe": _pipe = Convert.ToString(property.Value); break;

                    case "securityDescriptor": _securityDescriptor = (property.Value as SecurityDescriptor); break;
                    }
                }
            }

            // setup pipe name
            _pipeName = new PipeName(@"\\.\pipe\" + _pipe);

            // create the chain of the sink providers that will process all messages
            _sinkProvider = ChannelHelper.ServerChannelCreateSinkProviderChain(sinkProvider);
            _channelData  = ChannelHelper.ServerChannelCreateDataStore(ChannelUri, _sinkProvider);

            // create transport sink
            IServerChannelSink nextSink = ChannelServices.CreateServerChannelSinkChain(_sinkProvider, this);

            _transportSink = new ServerTransportSink(nextSink);

            // create listener thread
            _transportListener           = new TransportListener(ChannelUri, typeof(PipeTransport));
            _listenerThread              = new Thread(new ThreadStart(ListenerStart));
            _listenerThread.IsBackground = true;

            _requestHandler = new ProcessRequestCallback(_transportSink.ProcessRequest);

            // start listening on the channel
            StartListening(null);
        }
Beispiel #15
0
 private string MakeConnectionString()
 {
     if (ConnectionType == ConnectionType.Embedded)
     {
         return(String.Format("type=embedded;storesDirectory={0}", DirectoryPath));
     }
     if (ConnectionType == ConnectionType.Http || ConnectionType == ConnectionType.Tcp)
     {
         var connString = new StringBuilder();
         connString.Append(ConnectionType == ConnectionType.Http
                               ? "type=http;endpoint=http://"
                               : "type=tcp;endpoint=net.tcp://");
         connString.Append(ServerName);
         if (!String.IsNullOrEmpty(ServerPort))
         {
             connString.Append(":");
             connString.Append(ServerPort);
         }
         if (!String.IsNullOrEmpty(ServerPath))
         {
             if (!ServerPath.StartsWith("/"))
             {
                 connString.Append("/");
             }
             connString.Append(ServerPath);
         }
         return(connString.ToString());
     }
     if (ConnectionType == ConnectionType.NamedPipe)
     {
         var connString = new StringBuilder();
         connString.Append("type=namedpipe;endpoint=net.pipe://");
         connString.Append(ServerName);
         if (!PipeName.StartsWith("/"))
         {
             connString.Append("/");
         }
         connString.Append(PipeName);
         return(connString.ToString());
     }
     throw new NotSupportedException(String.Format("Cannot generate connection string for connection type {0}", ConnectionType));
 }
Beispiel #16
0
        /// <summary>
        ///     Connects to the named pipe
        /// </summary>
        /// <returns>Whether connection was successful</returns>
        public bool Connect()
        {
            Client = new NamedPipeClientStream(PipeName.ToString());

            var tries = 0;

            while (Client.IsConnected == false)
            {
                if (tries == 20)
                {
                    break;              // Failed to connect
                }
                Client.Connect();
                tries += 1;

                Thread.Sleep(1000);
            }

            return(Client.IsConnected);
        }
Beispiel #17
0
        public static UnoHostProcess Spawn(AbsoluteFilePath assembly, IObservable <IBinaryMessage> messagesToUnoHost, AbsoluteFilePath userDataPath, IEnumerable <string> moreArgs)
        {
            if (Application == null)
            {
                throw new InvalidOperationException("UnoHostProcess.Application has not been initialized");
            }

            var args = new UnoHostArgs
            {
                AssemblyPath = assembly,
                OutputPipe   = PipeName.New(),
                InputPipe    = PipeName.New(),
                UserDataPath = userDataPath,
            };

            var disp = args.InputPipe.BeginWritingMessages("UnoHost", ex => Console.WriteLine("Designer failed to write message to UnoHost: " + ex), messagesToUnoHost);

            return(new UnoHostProcess
            {
                Messages = args.OutputPipe.ReadMessages("UnoHost"),
                Process = Observable.Start(() => Application.Start(args.Serialize().Concat(moreArgs))),
                Disposables = Disposable.Combine(disp)
            });
        }
Beispiel #18
0
 internal static string GetMSMQFormatName(this PipeName pipeName)
 {
     return(FormatNamePrefix + pipeName.GetMSMQDirectName());
 }
 internal MSMQPipe(PipeName pipeName)
 {
     this._pipeName = pipeName;
 }
Beispiel #20
0
 internal MSMQPipe(PipeName pipeName)
 {
     this._pipeName = pipeName;
 }
Beispiel #21
0
 public void SetUp()
 {
     _pipeName = new PipeName(Guid.NewGuid());
 }
Beispiel #22
0
 public DocumentAppHandler(IReport reporter, string applicationName, string[] args)
 {
     _reporter = reporter;
     _args     = args;
     _pipeName = new PipeName(applicationName);
 }