using System; using System.IO; using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; using Assinador.Model.Common; using Gestor.Application.Actions; using Newtonsoft.Json; namespace Gestor.Application.Helpers; public class PipeServer : IDisposable { private string _pipeName; private NamedPipeServerStream Pipe { get; set; } public bool CreateServer(string name) { _pipeName = name; return Create(); } private bool Create() { bool flag = true; try { new NamedPipeClientStream(".", _pipeName, PipeDirection.Out, PipeOptions.Asynchronous).Connect(1000); } catch (TimeoutException) { flag = false; } catch (Exception) { return false; } if (flag) { return true; } try { PipeSecurity pipeSecurity = new PipeSecurity(); SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); securityIdentifier.Translate(typeof(NTAccount)); pipeSecurity.SetAccessRule(new PipeAccessRule(securityIdentifier, PipeAccessRights.ReadWrite, AccessControlType.Allow)); Pipe = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, pipeSecurity); Pipe.BeginWaitForConnection(WaitForConnectionCallBack, Pipe); } catch (Exception) { return false; } return true; } private void WaitForConnectionCallBack(IAsyncResult iar) { try { NamedPipeServerStream namedPipeServerStream = (NamedPipeServerStream)iar.AsyncState; namedPipeServerStream.EndWaitForConnection(iar); using (StreamReader streamReader = new StreamReader(Pipe)) { string text = streamReader.ReadLine(); if (text != null && text.IndexOf("exit", StringComparison.InvariantCultureIgnoreCase) > -1) { Dispose(); } Handle(text); } namedPipeServerStream.Close(); namedPipeServerStream = null; Create(); } catch { } } public void Dispose() { Pipe.Dispose(); } private void Handle(string message) { if (message != null) { PipeMessageResult obj = JsonConvert.DeserializeObject(message); Gestor.Application.Actions.Actions.AcessarHoster?.Invoke(obj); } } }