Exemple #1
0
        public void Listen(string PipeName)
        {
            try
            {
                // Set to class level var so we can re-use in the async callback method
                _pipeName = PipeName;
                // Create the new async pipe 
                NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                // Wait for a connection
                pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch (Exception oEX)
            {
                Debug.WriteLine(oEX.Message);
            }
        }
Exemple #2
0
        private void CreatePipeServer()
        {
            PipeSecurity ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule("Users",
                                                PipeAccessRights.CreateNewInstance | PipeAccessRights.ReadWrite,
                                                System.Security.AccessControl.AccessControlType.Allow));

            beaconServer = new NamedPipeServerStream("TransMockBeacon",
                                                     PipeDirection.InOut,
                                                     10,
                                                     PipeTransmissionMode.Message,
                                                     PipeOptions.Asynchronous,
                                                     8, 8, ps);

            connectResult = beaconServer.BeginWaitForConnection(cb => ClientConnected(cb), beaconServer);
        }
Exemple #3
0
 protected void BeginPushPipeListen()
 {
     if (!Running)
     {
         return;
     }
     lock (PushPipes)
     {
         if (ListeningPushPipe != null)
         {
             ListeningPushPipe.Dispose(); // Shouldn't happen too
         }
         // Note: PipeDirection.InOut ensures the client can set ReadMode, IDK why but it works this way
         ListeningPushPipe = new NamedPipeServerStream(Name + PipeConnection.PUSH_SUFFIX, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, BufferSize, CreateSecurity());
         ListeningPushPipe.BeginWaitForConnection(OnPushPipeConnect, null);
     }
 }
        private void PipeConnect(IAsyncResult iar)
        {
            if (!_IsRunning)
            {
                return;
            }

            _MainPipe.EndWaitForConnection(iar);

            _MainPipe.Write(_PipeData, 0, _PipeData.Length);

            _MainPipe.WaitForPipeDrain();
            _MainPipe.Disconnect();

            // neue Pipe erstellen, einmal geschlossen, wars das
            _MainPipe.BeginWaitForConnection(PipeConnect, null);
        }
        public void Listen(string PipeName)
        {
            try
            {
                _pipeName = PipeName;

                // Create the new async pipe
                NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                // Wait for a connection
                pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch (Exception oEX)
            {
                throw oEX;
            }
        }
Exemple #6
0
 public void Init()
 {
     lock (pipeServerLock)
     {
         if (pipeServer != null)
         {
             return;
         }
         var sid  = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
         var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,
                                       System.Security.AccessControl.AccessControlType.Allow);
         var sec = new PipeSecurity();
         sec.AddAccessRule(rule);
         pipeServer = new NamedPipeServerStream(HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0, sec);
         pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
     }
 }
Exemple #7
0
        public void Listen()
        {
            lock (_lck)
            {
                Log("Listen for client.");
                if (_mustShutdown)
                {
                    return;
                }

                _listener = new NamedPipeServerStream(PipeName,
                                                      PipeDirection.InOut,
                                                      NamedPipeServerStream.MaxAllowedServerInstances,
                                                      PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
                _listener.BeginWaitForConnection(OnConnect, null);
            }
        }
        public StudioServer()
        {
            try
            {
                pipeSecurity = new PipeSecurity();
                pipeSecurity.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));

                serverStream = NamedPipeServerStreamConstructors.New($@"\.\DSParamStudio\pipe\CommandQueue", PipeDirection.InOut, System.IO.Pipes.NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0, pipeSecurity);

                serverStream.BeginWaitForConnection(handleConnection, serverStream);

                new Thread(TestThread).Start();
            }
            catch
            {
            }
        }
Exemple #9
0
        private void StartServerPump()
        {
            if (!is_running)
            {
                return;
            }

            try
            {
                PipeSecurity ps = new PipeSecurity();
                ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));

                using (var npss = new NamedPipeServerStream(IPCCommon.PIPE_NAME, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 512, 512, ps))
                {
                    npss.BeginWaitForConnection(async_result =>
                    {
                        try
                        {
                            using (var npss_in_callback = (NamedPipeServerStream)async_result.AsyncState)
                            {
                                npss_in_callback.EndWaitForConnection(async_result);
                                npss_in_callback.WaitForPipeDrain();

                                StreamReader sr = new StreamReader(npss_in_callback);
                                var line        = sr.ReadLine();
                                IPCServerMessage?.Invoke(line);

                                npss_in_callback.Close();

                                // Listen for another client.  Note that this is NOT recursive as we are currently inside a lambda.
                                StartServerPump();
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.Error(ex, "Error while processing pipe connection. ({0})", IPCCommon.PIPE_NAME);
                        }
                    },
                                                npss);
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "Error while waiting for pipe connection. ({0})", IPCCommon.PIPE_NAME);
            }
        }
Exemple #10
0
        /// <summary>
        ///     Starts a new pipe server if one isn't already active.
        /// </summary>
        private void NamedPipeServerCreateServer()
        {
            if (_namedPipeServerStream != null)
            {
                // Already a pipe setup, just return
                return;
            }

            // Create a new pipe accessible by local authenticated users, disallow network
            //var sidAuthUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
            var sidNetworkService = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);
            var sidWorld          = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            var pipeSecurity = new PipeSecurity();

            // Deny network access to the pipe
            var accessRule = new PipeAccessRule(sidNetworkService, PipeAccessRights.ReadWrite, AccessControlType.Deny);

            pipeSecurity.AddAccessRule(accessRule);

            // Alow Everyone to read/write
            accessRule = new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow);
            pipeSecurity.AddAccessRule(accessRule);

            // This user is the owner (can create pipes)
            SecurityIdentifier sidOwner = WindowsIdentity.GetCurrent().Owner;

            if (sidOwner != null)
            {
                accessRule = new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow);
                pipeSecurity.AddAccessRule(accessRule);
            }

            // Create pipe and start the async connection wait
            _namedPipeServerStream = new NamedPipeServerStream(
                PipeName,
                PipeDirection.In,
                1,
                PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous,
                0,
                0,
                pipeSecurity);

            _namedPipeAsyncResult = _namedPipeServerStream.BeginWaitForConnection(NamedPipeServerConnectionCallback, _namedPipeServerStream);
        }
Exemple #11
0
        void IpcProcessConnection(IAsyncResult ar)
        {
            try
            {
                // connect and read command
                ipcServer.EndWaitForConnection(ar);
                int raw = ipcServer.ReadByte();
                if (raw >= 0)
                {
                    IpcCommands command = (IpcCommands)raw;
                    // commands interact with the main form and must therefore be processed in the UI thread
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        try
                        {
                            if (command == IpcCommands.ShowMainWindow)
                            {
                                this.MainWindow.ShowWindow();
                            }
                            else if (command == IpcCommands.Exit)
                            {
                                this.MainWindow.CloseWindow();
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("Error processing Ipc Message: " + ex.Message + " (" + ex.GetType().Name + ")", ex);
                        }
                    }));
                }
            }
            catch (Exception ex)
            {
                log.Error("Error processing Ipc Message: " + ex.Message + " (" + ex.GetType().Name + ")", ex);
            }

            try
            {
                ipcServer.Disconnect();
                ipcServer.BeginWaitForConnection(new AsyncCallback(IpcProcessConnection), null);
            }
            catch (Exception ex)
            {
                log.Error("Could not listen on Ipc Channel: " + ex.Message + " (" + ex.GetType().Name + ")", ex);
            }
        }
Exemple #12
0
        public HookProxy(Client cl)
        {
            string dllPath = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath.ToString(), "Hooker.dll");

            // string dllPath = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath.ToString(), "InjectBooter.dll");

            client = cl;

            string name = "InjectClient" + Convert.ToString(client.Process.Id);

            pipeRecv = new NamedPipeServerStream(name, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
            pipeRecv.BeginWaitForConnection(BeginWaitForConnection, pipeRecv);
            bool injected = Inject(dllPath);

            SetUpPipes();
            tibiaSock = new TibiaSock(cl);
        }
Exemple #13
0
 public ServerInstance(string serverName, bool writeThrough, int instance, int maxServerCount)
 {
     myMemoryStream  = new MemoryStream(buffSize);
     myReadPos       = 0;
     myThreadRunning = true;
     myInstance      = instance;
     myBuffer        = new byte[buffSize];
     myThread        = new Thread(new ThreadStart(ProcessServerStream));
     myThread.Start();
     myNamedPipeServerStream = new NamedPipeServerStream(
         serverName,
         PipeDirection.InOut,
         maxServerCount,
         PipeTransmissionMode.Byte,
         writeThrough ? PipeOptions.Asynchronous | PipeOptions.WriteThrough : PipeOptions.Asynchronous);
     myNamedPipeServerStream.BeginWaitForConnection(new AsyncCallback(OnConnect), null);
 }
Exemple #14
0
    private void waitForAdditionalInstances(string[] args)
    {
        var accumulatedArgs = new List <string>(args);

        while (true)
        {
            var signal = new ManualResetEvent(false);
            using (var pipeServer = new NamedPipeServerStream(ipcNamedPipeGuid, PipeDirection.In, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            {
                pipeServer.BeginWaitForConnection(x =>
                {
                    // if timed out, stop waiting for a connection
                    if (signal.WaitOne(0))
                    {
                        signal.Close();
                        return;
                    }

                    pipeServer.EndWaitForConnection(x);
                    signal.Set();
                }, null);

                // no client connected to the pipe within the Timeout period
                if (!signal.WaitOne(Timeout, true))
                {
                    signal.Set();
                    break;
                }

                using (var sr = new StreamReader(pipeServer))
                {
                    int length = Convert.ToInt32(sr.ReadLine());
                    for (int i = 0; i < length; ++i)
                    {
                        accumulatedArgs.Add(sr.ReadLine());
                    }
                }
            }

            // new args have been added to accumulatedArgs, continue loop to listen for another client
        }

        ipcMutex.Close();
        Launching(this, new SingleInstanceEventArgs(accumulatedArgs.ToArray()));
    }
Exemple #15
0
        private async void ConnectionCallback(IAsyncResult asyncResult)
        {
            try
            {
                using (var pipeServer = asyncResult.AsyncState as NamedPipeServerStream)        // get the pipeserver
                {
                    if (pipeServer != null)
                    {
                        pipeServer.EndWaitForConnection(asyncResult);       // finish connection

                        byte[] buffer = new byte[16 * 1024];
                        using (MemoryStream memoryStream = new MemoryStream())  // create mem stream to read in bytes from pipe stream
                        {
                            int read;
                            while ((read = await pipeServer.ReadAsync(buffer, 0, buffer.Length)) > 0) // read to the end of the stream
                            {
                                memoryStream.Write(buffer, 0, read);                                  // write the bytes to memory
                            }

                            var json     = GetString(memoryStream.ToArray());                                            // convert bytes to string
                            var msg      = Newtonsoft.Json.JsonConvert.DeserializeObject <KioskMessage <object> >(json); // deserialize to message with object payload - payload will be a json string when <object> is used as generic type
                            var assembly = typeof(KioskMessage <object>).Assembly;                                       // find the assembly where are payload types can be found
                            var dataType = assembly.GetType(msg.DataType);                                               // get the type of the payload
                            var payload  = Newtonsoft.Json.JsonConvert.DeserializeObject(msg.Data.ToString(), dataType); // deserialize the payload json to the correct type

                            switch (dataType.FullName)                                                                   // brittle switch statements based on type string - better way?
                            {
                            case "KinectPOC.Common.Messages.Demographics":
                                RaiseDemographicsEvent(payload as DemographicData);
                                break;
                            }
                        }

                        pipeServer.Close();
                    }
                }

                var newServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                newServer.BeginWaitForConnection(new AsyncCallback(ConnectionCallback), newServer);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #16
0
        public async Task <bool> StartAsync()
        {
            if (State != ServerState.Stopped)
            {
                return(false);
            }

            lock (_stateLock)
            {
                if (State != ServerState.Stopped)
                {
                    return(false);
                }

                State = ServerState.Starting;
            }

            if (_pipe != null)
            {
                await _pipe.DisposeAsync().ConfigureAwait(false);
            }

            try
            {
                _pipe = new NamedPipeServerStream(_configuration.PipeName, PipeDirection.InOut, 1,
                                                  PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
                _pipe.BeginWaitForConnection(OnConnectionReceived, null);

                lock (_stateLock)
                {
                    State = ServerState.Started;
                }

                return(true);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                lock (_stateLock)
                {
                    State = ServerState.Stopped;
                }
                return(false);
            }
        }
Exemple #17
0
        private void StartNewPipeServer()
        {
            if (_pipeServer != null)
            {
                throw new InvalidOperationException("Cannot start a new pipe server before destroying previous instance.");
            }

            if (_outstandingIO != 0)
            {
                throw new InvalidOperationException("Outstanding I/O is not zero.");
            }

            _nextPacketIndex = 0;

            _pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
            Interlocked.Increment(ref _outstandingIO);
            _pipeServer.BeginWaitForConnection(OnConnectionAsync, null);
        }
Exemple #18
0
        public void Listen(string pipeName)
        {
            try
            {
                this.pipeName = pipeName;

                NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipeName,
                                                                             PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);


                pipeServer.BeginWaitForConnection
                    (new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch (Exception exeptionon)
            {
                throw exeptionon;
            }
        }
Exemple #19
0
        private void IpcServerPipeCreate()
        {
            // Create message-mode pipe to simplify message transition
            // Assume all messages will be smaller than the pipe buffer sizes
            NamedPipeServerStream pipe = new NamedPipeServerStream(
                _pipeName,
                PipeDirection.InOut,
                -1,     // maximum instances
                PipeTransmissionMode.Message,
                PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                ServerInBufferSize,
                ServerOutBufferSize,
                _pipeSecurity
                );

            // Asynchronously accept a client connection
            pipe.BeginWaitForConnection(OnClientConnected, pipe);
        }
Exemple #20
0
        private static void _AsyncConnectionHandler(IAsyncResult result)
        {
            NamedPipeServerStream srv = result.AsyncState as NamedPipeServerStream;

            srv.EndWaitForConnection(result);

            BinaryFormatter bf = new BinaryFormatter();

            string[] inargs = bf.Deserialize(srv) as string[];

            AddFiles(inargs);

            srv.Close();

            srv = new NamedPipeServerStream(_AppName + "IPC", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            srv.BeginWaitForConnection(new AsyncCallback(_AsyncConnectionHandler), srv);
        }
Exemple #21
0
        private void StartNewPipeServer()
        {
            _pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 254, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

#if !NETSTANDARD1_6
            _pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, null);
#elif NETSTANDARD1_6
            Task.Run(async() =>
            {
                await _pipeServer.WaitForConnectionAsync();
                try
                {
                    WaitForConnectionCallBack(null);
                }
                catch (ObjectDisposedException) { }
            });
#endif
        }
Exemple #22
0
        private void IpcServerPipeCreate()
        {
            // Create message-mode pipe to simplify message transition
            // Assume all messages will be smaller than the pipe buffer sizes
            NamedPipeServerStream pipe = new NamedPipeServerStream(
                m_pipename,
                PipeDirection.InOut,
                -1,     // maximum instances
                PipeTransmissionMode.Message,
                PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                SERVER_IN_BUFFER_SIZE,
                SERVER_OUT_BUFFER_SIZE,
                m_ps
                );

            // Asynchronously accept a client connection
            AwaitingClientConnection = pipe.BeginWaitForConnection(OnClientConnected, pipe);
        }
Exemple #23
0
        static void PipeHandler(IAsyncResult res)
        {
            NamedPipeServerStream nps = res.AsyncState as NamedPipeServerStream;

            // End the current connection.
            nps.EndWaitForConnection(res);

            string data = Name + ":" + Port + "\r\n";

            nps.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
            nps.Flush();
            nps.WaitForPipeDrain();

            nps.Disconnect();

            // Start the new connection.
            nps.BeginWaitForConnection(PipeHandler, nps);
        }
        private void ClientConnected(IAsyncResult result)
        {
            NamedPipeServerStream asyncState = result.AsyncState as NamedPipeServerStream;

            asyncState.EndWaitForConnection(result);
            if (asyncState.IsConnected)
            {
                NamedPipeTransport item = new NamedPipeTransport(asyncState, PipeName);
                item.MessageReceived += new MessageEventHandler(OnMessageReceived);
                lock (mConnections)
                {
                    mConnections.Add(item);
                }
            }
            NamedPipeServerStream state = new NamedPipeServerStream(PipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            state.BeginWaitForConnection(new AsyncCallback(this.ClientConnected), state);
        }
Exemple #25
0
        public Boolean Start()
        {
            Trace("Start");

            _isStopping = false;

            try
            {
                this._pipeServer = new NamedPipeServerStream(this._pipeName, PipeDirection.InOut, 16, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                _pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, null);
                return(true);
            }
            catch (Exception ex)
            {
                Trace(ex, "BeginWaitForConnection");
                return(false);
            }
        }
Exemple #26
0
        private void RunSendingServer(string pipeName, IpcCommands command, Func <object> function)
        {
            _namedPipeServer = new NamedPipeServerStream(NamedPipe.GetUserPipeName(pipeName), PipeDirection.Out, 2, PipeTransmissionMode.Message,
                                                         PipeOptions.Asynchronous);

            AsyncCallback ac = null;

            ac = o =>
            {
                NamedPipeServerStream s = (NamedPipeServerStream)o.AsyncState;
                try
                {
                    if (disposedValue)
                    {
                        return;
                    }
                    s.EndWaitForConnection(o);
                    object data = function.Invoke();
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ms.WriteByte((byte)command);
                        if (data != null)
                        {
                            BinaryFormatter bf = new BinaryFormatter();
                            bf.Serialize(ms, data);
                        }
                        ms.Seek(0, SeekOrigin.Begin);

                        ms.CopyTo(s);
                        s.Flush();
                        s.WaitForPipeDrain();
                    }

                    s.Disconnect();
                    s.BeginWaitForConnection(ac, s);
                }
                catch (Exception)
                {
                    s.Dispose();
                    RunSendingServer(pipeName, command, function);
                }
            };
            _namedPipeServer.BeginWaitForConnection(ac, _namedPipeServer);
        }
Exemple #27
0
        /// <summary>
        /// Called whenever a new environment has been received.
        /// </summary>
        /// <param name="ar">The results of the aysnchronous operation.</param>
        /// <remarks>
        /// Byte Array to Structure code taken from @cite stackOverflowByte (http://stackoverflow.com/questions/3278827/how-to-convert-structure-to-byte-array-in-c)
        /// </remarks>
        private void EnvironmentReceived(IAsyncResult ar)
        {
            var environment = new StatusReport();
            var size        = Marshal.SizeOf(environment);

            if (disposed)
            {
                return;
            }

            pipeServer.EndWaitForConnection(ar);

            var bytes = new List <byte>();

            var buffer = new byte[size];

            pipeServer.Read(buffer, 0, size);

            bytes.AddRange(buffer);

            var array = bytes.ToArray();

            var ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(array, 0, ptr, size);

            lock (latestEnvironmentLocker)
            {
                var report = (StatusReport)Marshal.PtrToStructure(ptr, typeof(StatusReport));
                latestEnvironment  = report.Environment;
                CurrentVector      = report.FieldVector;
                fieldType          = report.FieldType;
                latestBallVelocity = report.BallVelocity;
            }

            if (!worker.IsBusy)
            {
                worker.RunWorkerAsync();
            }

            Marshal.FreeHGlobal(ptr);
            pipeServer.Disconnect();
            pipeServer.BeginWaitForConnection(EnvironmentReceived, null);
        }
        public MainWindow(string[] args)
        {
            InitializeComponent();

            SystemEvents.SessionEnding += SystemEvents_SessionEnding;

            _nzbDrive = new NZBDriveDLL.NZBDrive();

            _nzbDrive.LogLevel = NZBDriveDLL.LogLevelType.Info;

            this.Closing += MainWindow_Closing;

            _nzbDrive.EventLog += _nzbDrive_EventLog;

            _model             = new NZBDriveModel(_nzbDrive);
            this.DataContext   = _model;
            NZBDriveView.Model = _model;
            StatusBox.Status   = _model.Status;
            ToolBar.Model      = _model;

            _nzbDrive.ConnectionStateChanged += _nzbDrive_ConnectionStateChanged;
            _nzbDrive.NZBFileOpen            += _nzbDrive_NZBFileOpen;
            _nzbDrive.NZBFileClose           += _nzbDrive_NZBFileClose;
            _nzbDrive.FileAdded               += _nzbDrive_FileAdded;
            _nzbDrive.FileRemoved             += _nzbDrive_FileRemoved;
            _nzbDrive.FileInfo                += _nzbDrive_FileInfo;
            _nzbDrive.FileSegmentStateChanged += _nzbDrive_FileSegmentStateChanged;
            _nzbDrive.ConnectionInfo          += _nzbDrive_ConnectionInfo;
            _model.MountStatusHandle          += _model_MountStatus;

            NZBDriveSettings.Load(_model);

            _model.SettingsChanged += model_SettingsChanged;

            this.ContentRendered += MainWindow_ContentRendered;

            _pipe = new NamedPipeServerStream("NZBDriveApplicationPipe", PipeDirection.In,
                                              254, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            _pipeCallback = new AsyncCallback(PipedConnectionCallBack);
            _pipe.BeginWaitForConnection(_pipeCallback, this);

            _model.Mount(args);
        }
        private Process StartProcessWithRequest(AgentRequest request, string workingDirectory)
        {
            var agentPath = request.GetType().Assembly.Location;


            var startInfo = new ProcessStartInfo(agentPath)
            {
                WorkingDirectory       = workingDirectory,
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                CreateNoWindow         = true
            };

            using (var activationDirectory = new WorkingDirectory())
            {
                startInfo.EnvironmentVariables["COMPLUS_ApplicationMigrationRuntimeActivationConfigPath"] = activationDirectory.DirectoryInfo.FullName;
                if (_clrVersion == ClrVersion.Version4)
                {
                    var configPath = Path.Combine(activationDirectory.DirectoryInfo.FullName, string.Concat(Path.GetFileName(agentPath), ".activation_config"));
                    File.WriteAllText(configPath, ClrVersion4ActivationConfigContent);
                }

                var namedPipeName = string.Format("{0}.{1}", GetType().FullName, Guid.NewGuid());
                startInfo.Arguments = namedPipeName;
                using (var pipeServer = new NamedPipeServerStream(namedPipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
                {
                    var messagePipe = new MessagePipe(pipeServer);

                    var ar = pipeServer.BeginWaitForConnection(null, pipeServer);

                    var process = Process.Start(startInfo);

                    pipeServer.EndWaitForConnection(ar);

                    messagePipe.WriteMessage(request);

                    pipeServer.WaitForPipeDrain();

                    return(process);
                }
            }
        }
Exemple #30
0
        public void TestOneWay_XML()
        {
            PipeSecurity ps = new PipeSecurity();

            ps.AddAccessRule(
                new PipeAccessRule(
                    "USERS",
                    PipeAccessRights.CreateNewInstance | PipeAccessRights.ReadWrite,
                    System.Security.AccessControl.AccessControlType.Allow));

            // We first spin a pipe server to make sure that the send port will be able to connect
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(
                       "OneWaySend", PipeDirection.InOut, 1,
                       PipeTransmissionMode.Byte, PipeOptions.Asynchronous,
                       1024, 1024, ps))
            {
                string xml = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>";

                OutboundTestHelper testHelper = new OutboundTestHelper(pipeServer);

                pipeServer.BeginWaitForConnection(cb => testHelper.ClientConnected(cb), testHelper);
                //Here we spin the pipe client that will send the message to BizTalk
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost",
                                                                                    "OneWayReceive", PipeDirection.InOut, PipeOptions.Asynchronous))
                {
                    byte[] xmlBytes = Encoding.UTF8.GetBytes(xml);

                    pipeClient.Connect(10000);
                    pipeClient.Write(xmlBytes, 0, xmlBytes.Count());

                    pipeClient.WriteByte(0x00);//writing the EOF byte
                    pipeClient.Flush();

                    pipeClient.WaitForPipeDrain();
                }
                //Here we wait for the event to be signalled
                testHelper.syncEvent.WaitOne(60000);
                //The event was signalled, we get the message stirng from the outBuffer
                string receivedXml = Encoding.UTF8.GetString(testHelper.memStream.ToArray(), 0, (int)testHelper.memStream.Length);

                Assert.AreEqual(xml, receivedXml, "Contents of the received message is different");
            }
        }