コード例 #1
0
ファイル: Program.cs プロジェクト: otama-jaccy/Pipe
 static void client()
 {
     PipeClient pipe_client = new PipeClient(pipe_name);
     Console.WriteLine("StartClient");
     pipe_client.getMessage();
     Console.WriteLine("ENDClient");
 }
コード例 #2
0
ファイル: Form1.cs プロジェクト: kepazon/my_sumatrapdf
 void ClientDisconnected(PipeClient client)
 {
     clients.Remove(client);
     labelConnectionStatus.Text = String.Format("Connected {0} clients", clients.Count);
     int allocs = client.CurrAllocsMap.Count;
     ulong currAllocated = client.CurrAllocated;
     labelCurrAllocated.Text = String.Format("Currently allocated: {0} in {1} allocations", currAllocated, allocs);
 }
コード例 #3
0
        /// <summary>
        ///     Constructor for the Interrogator Service
        /// </summary>
        /// <param name="logger">
        ///     Requires an ILoggerService as the logger
        /// </param>
        /// <param name="memoryCache">
        ///     Requires an IMemoryCache for communicating with the memory
        /// </param>
        public InterrogatorService(ILoggerService logger,
                                   IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
            _logger      = logger;
            _pipeClient  = new PipeClient(PIPE_NAME);

            _memoryCache.Set(SERVICE_MEMORY, true);
        }
コード例 #4
0
ファイル: selector.cs プロジェクト: lisa3907/lotto.lion
        public Selector(ILogger <Selector> logger, IDbContextFactory <AppDbContext> contextFactory, WinnerSelector winnerSelector, WinnerReader winnerReader, PipeClient pipeClient)
        {
            _logger         = logger;
            _contextFactory = contextFactory;

            _winnerSelector = winnerSelector;
            _winnerReader   = winnerReader;
            _pipe_client    = pipeClient;
        }
コード例 #5
0
 /// <summary>
 /// Disposes the CustomLogger, releases resources and supresses the finalizer
 /// </summary>
 protected override void OnDispose()
 {
     base.OnDispose();
     if (_client != null)
     {
         _client.Dispose();
         _client = null;
     }
 }
コード例 #6
0
        static void Main(string[] args)
        {
            PipeClient client = new PipeClient();

            while (true)
            {
                Console.Write(":");
                client.WriteLine(Console.ReadLine());
            }
        }
コード例 #7
0
        /// <summary>
        /// Start the Pipe server that will listen for messages comming from the payment driver
        /// </summary>
        public void StartListening()
        {
            Log.Info(COMMUNICATOR_LOG, "Started communication server.");

            pipeServer = new PipeServer(CORE_PIPE_SERVER_NAME);

            pipeClient = new PipeClient();

            pipeServer.OnReceiveMessage += DoOnReceiveMessage;
        }
コード例 #8
0
        public bool EnviarInicioVersion(string Version, string APP)
        {
            PipeClient    pipeClient = new PipeClient();
            ServicioPago  servicio   = new ServicioPago();
            List <string> data       = new List <string>();
            var           cambiover  = false;

            if (APP == "APP_PAGO" && Version != Globals.VAppFPago)
            {
                Globals.VAppFPago = Version;
                cambiover         = true;
            }

            if (APP == "APP_EFE" && Version != Globals.VAppFEfe)
            {
                Globals.VAppFEfe = Version;
                cambiover        = true;
            }

            if (APP == "APP_TES" && Version != Globals.VAppFTes)
            {
                Globals.VAppFTes = Version;
                cambiover        = true;
            }

            if (APP == "SRVLOC2" && Version != Globals.VAppSV2)
            {
                Globals.VAppSV2 = Version;
                cambiover       = true;
            }
            if (APP == "APILOC")
            {
                cambiover = true;
            }
            if (cambiover == true)
            {
                data.Add("0");
                data.Add(Version);
                data.Add(APP);
                var resultado = false;
                pipeClient.Message = servicio.BuildMessage(ServicioPago.Comandos.APP_FRTINI, data);
                resultado          = pipeClient.SendMessage(ServicioPago.Comandos.APP_FRTINI);
                if (resultado == true)
                {
                    var datos = pipeClient.Resultado.Data[0].Split("~");
                    Globals.idmaquina     = datos[0];
                    Globals.nombremaquina = datos[1];
                }
                return(resultado);
            }
            else
            {
                return(true);
            }
        }
コード例 #9
0
        public static async Task DataTestAsync <T>(List <T> values, Func <T, string>?hashFunc = null, IFormatter?formatter = default, TimeSpan?timeout = default)
        {
            using var cancellationTokenSource = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(15));

            const string pipeName = "data_test_pipe";

            await using var server = new PipeServer <T>(pipeName, formatter ?? new BinaryFormatter());
            await using var client = new PipeClient <T>(pipeName, formatter: formatter ?? new BinaryFormatter());

            await DataTestAsync(server, client, values, hashFunc, cancellationTokenSource.Token);
        }
コード例 #10
0
        /// <summary>
        /// DoOnCheckForRemoteReplay method implementation (Server)
        /// </summary>
        private bool DoOnCheckForRemoteReplay(NamedPipeNotificationReplayRecord record)
        {
            if (_adfsservers.Count == 0)
            {
                BuildADFSServersList();
            }

            PipeClient pipe = new PipeClient(XORUtilities.XORKey, this.ADFSServers, true);

            return(pipe.DoCheckForRemoteReplay(record));
        }
コード例 #11
0
 public TcpService(ILoggerService loggerService,
                   IOptions <AppSettings> config,
                   IMemoryCache memoryCache)
 {
     _memoryCache   = memoryCache;
     _config        = config.Value;
     _loggerService = loggerService;
     _pipeClient    = new PipeClient();
     _pipeServer    = new PipeServer(PIPE_NAME);
     _memoryCache.Set(SERVICE_MEMORY, true);
 }
コード例 #12
0
        public LottoController(IOptions <JwtIssuerOptions> jwtOptions, AppDbContext dbContext, WinnerReader winnerReader, PrizeReader prizeReader, PipeClient pipeClient, dForcast forcast)
        {
            __usermgr    = new UserManager(jwtOptions.Value);
            __db_context = dbContext;

            __winner_reader = winnerReader;
            __prize_reader  = prizeReader;

            __pipe_client   = pipeClient;
            __prize_forcast = forcast;
        }
コード例 #13
0
        /// <summary>
        ///
        /// </summary>
        public IpcClientService(string pipeName)
        {
            pipeName = pipeName ?? throw new ArgumentNullException(nameof(pipeName));

            PipeClient = new PipeClient <string>(pipeName);
            PipeClient.MessageReceived   += PipeServer_OnMessageReceived;
            PipeClient.ExceptionOccurred += (_, args) => OnExceptionOccurred(args.Exception);
            PipeClient.Connected         += PipeServer_OnConnected;
            PipeClient.Disconnected      += PipeServer_OnDisconnected;

            AsyncDisposables.Add(PipeClient);
        }
コード例 #14
0
        void CreateNewPipeClient()
        {
            if (pipeClient != null)
            {
                pipeClient.MessageReceived    -= pipeClient_MessageReceived;
                pipeClient.ServerDisconnected -= pipeClient_ServerDisconnected;
            }

            pipeClient = new PipeClient();
            pipeClient.MessageReceived    += pipeClient_MessageReceived;
            pipeClient.ServerDisconnected += pipeClient_ServerDisconnected;
        }
コード例 #15
0
ファイル: Form1.cs プロジェクト: cnhans/sumatrapdf
 void ClientConnected(SafeFileHandle fileHandle)
 {
     PipeClient client = new PipeClient();
     client.FileHandle = fileHandle;
     client.Stream = new FileStream(fileHandle, FileAccess.ReadWrite, BUFFER_SIZE, true);
     client.NewMessage += pipeClient_NewMessage;
     client.ClientDisconnected += pipeClient_ClientDisconnected;
     clients.Add(client);
     labelConnectionStatus.Text = String.Format("Connected {0} clients", clients.Count);
     Thread readThread = new Thread(new ParameterizedThreadStart(ClientReadThread));
     readThread.Start(client);
 }
コード例 #16
0
 public static int SendCommand(int aKey, ...)
 {
     try
     {
         PipeClient.StartCommandSendClient(input, aKey);
     }
     catch (TimeoutException)
     {
         // returns error codes based on exceptions
     }
     return(0);
 }
コード例 #17
0
ファイル: Form1.cs プロジェクト: vilgaxbaha/pdf
        void ClientReadThread(object clientObj)
        {
            PipeClient client = (PipeClient)clientObj;
            FileStream stream = client.Stream;

            byte[] buf = new byte[BUFFER_SIZE];
            while (true)
            {
                int bytesRead = 0;
                int msgLen    = 0;
                try
                {
                    bytesRead = stream.Read(buf, 0, 2);
                    if (2 != bytesRead)
                    {
                        bytesRead = 0;
                        break;
                    }
                    msgLen = buf[0] + buf[1] * 256;
                    if (msgLen > BUFFER_SIZE)
                    {
                        bytesRead = 0;
                        break;
                    }
                    bytesRead = stream.Read(buf, 0, msgLen);
                    if (bytesRead != msgLen)
                    {
                        bytesRead = 0;
                        break;
                    }
                }
                catch
                {
                    //read error has occurred
                    break;
                }

                //client has disconnected
                if (bytesRead == 0)
                {
                    break;
                }

                byte[] msg = new byte[msgLen];
                Array.Copy(buf, msg, msgLen);
                client.NotifyNewMessage(msg);
            }

            stream.Close();
            client.FileHandle.Close();
            client.NotifyClientDisconnected();
        }
コード例 #18
0
 public void TearDown()
 {
     if (server != null)
     {
         server.Dispose();
         server = null;
     }
     if (client != null)
     {
         client.Dispose();
         client = null;
     }
 }
コード例 #19
0
ファイル: DLG_Login.cs プロジェクト: luckypal/Kiosk
 private void nKey_Click(object sender, EventArgs e)
 {
     Process[] processesByName = Process.GetProcessesByName("KVKeyboard");
     if (processesByName.Length >= 1)
     {
         PipeClient pipeClient = new PipeClient();
         pipeClient.Send("QUIT", "KVKeyboard");
     }
     else
     {
         Process.Start("KVKeyboard.exe", "es");
     }
 }
コード例 #20
0
 public static void InitializeNotifyIcon()
 {
     if (TaskVerifier.IsApplicationFirstInstance("SystemTrayAppMutexMetamorff"))
     {
         PipeServer pipeServer = new PipeServer();
         StartUpInternal();
     }
     else
     {
         PipeClient pipeClient = new PipeClient();
         Application.Exit();
     }
 }
コード例 #21
0
ファイル: Form1.cs プロジェクト: vilgaxbaha/pdf
        void DecodeFreeDataMsg(PipeClient client, byte[] msg)
        {
            UInt32 addr = BitConverter.ToUInt32(msg, 2);
            UInt32 size;

            if (!client.CurrAllocsMap.TryGetValue(addr, out size))
            {
                return;
            }
            client.CurrAllocated -= size;
            client.CurrAllocsMap.Remove(addr);
            UpdateCurrAllocated(client.CurrAllocated);
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: zanzo420/sb-debugger
        private static void Main(string[] args)
        {
            bool ENEMY    = false; // isFriend is the bool, so enemy must be false.
            bool JUSTICAR = true;

            MakeCardNames();
            SetupEventHandlers();
            PipeClient.Connect();

            // make a empty board from base seed;
            Board _board = Board.FromSeed("10~5~37~0~0~20~19~2~True~7~True~8~EX1_536*0*0*3*3*0*2*37*2*0*0*2*0*False*False*False*False*False*False*False*False*False*False*False*False*False*0*False~0~HERO_06*0*0*0*0*0*30*37*30*0*0*30*0*False*False*False*False*False*False*False*False*False*False*False*False*False*0*False~HERO_06*0*0*0*0*0*30*37*30*0*0*30*0*False*False*False*False*False*False*False*False*False*False*False*False*False*0*False~CS2_017*0*0*0*2*0*0*37*0*0*0*0*0*False*False*False*False*False*False*False*False*False*False*False*False*False*0*False~AT_132_DRUID*0*0*0*2*0*0*37*0*0*0*0*0*False*False*False*False*False*False*False*False*False*False*False*False*False*0*False~0~0~0~0~0~0~0~0~True=True=False~0~0~0~False~AT_029,EX1_011,CS2_233,EX1_124,EX1_581,EX1_131,EX1_162,GVG_023,GVG_006,GVG_103,EX1_129,EX1_556,EX1_412,EX1_134,AT_100,GVG_091,AT_114,GVG_078,CS2_179,EX1_023,EX1_043,BRM_008,AT_090,AT_028,CS2_155,CS2_222,AT_103~");

            // Board _board = new Board();
            _board.IsOwnTurn = true; // can't sim if it's not your turn


            // define constants, modify as see fit
            _board.EnemyClass       = Card.CClass.HUNTER;
            _board.FriendClass      = Card.CClass.DRUID;
            _board.ManaAvailable    = 10;
            _board.SecretEnemy      = true;
            _board.SecretEnemyCount = 2; // TODO for profiles: if it's 5 secrects on a pally we kinda know what they are.


            SetUpHero(ref _board, _board.FriendClass);
            SetUpHero(ref _board, _board.EnemyClass, ENEMY, JUSTICAR);
            _board.HeroFriend.CurrentHealth = 30;
            _board.HeroFriend.CurrentArmor  = 0;
            _board.HeroEnemy.CurrentHealth  = 30;
            _board.HeroEnemy.CurrentArmor   = 0;
            SetUpSeed(ref _board);


            Card test = Card.Create(CardTemplate.StringToCard("CS2_179"), true, GlobalCounter);

            Console.WriteLine(test.Template.Name);


            Console.WriteLine("Pipe connected : " + PipeClient.IsConnected());

            string SeedStr     = _board.ToSeed();
            string ProfileStr  = "Default"; // NOTE: make sure your profiles don't have weird characters in their names
            bool   AutoConcede = false;


            SendSeedRequest(SeedStr, ProfileStr, AutoConcede);

            Console.ReadLine();

            PipeClient.Disconnect();
        }
コード例 #23
0
ファイル: Form1.cs プロジェクト: vilgaxbaha/pdf
        void ClientConnected(SafeFileHandle fileHandle)
        {
            PipeClient client = new PipeClient();

            client.FileHandle          = fileHandle;
            client.Stream              = new FileStream(fileHandle, FileAccess.ReadWrite, BUFFER_SIZE, true);
            client.NewMessage         += pipeClient_NewMessage;
            client.ClientDisconnected += pipeClient_ClientDisconnected;
            clients.Add(client);
            labelConnectionStatus.Text = String.Format("Connected {0} clients", clients.Count);
            Thread readThread = new Thread(new ParameterizedThreadStart(ClientReadThread));

            readThread.Start(client);
        }
コード例 #24
0
 private void Init()
 {
     isFirstLoad = true;
     Predictions = null;
     python      = !string.IsNullOrEmpty(pythonPath) ? new PythonExecutor(pythonPath) : new PythonExecutor();
     python.AddStandartOutputErrorFilters("Using TensorFlow backend.");
     python.AddStandartOutputErrorFilters("CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected");
     client  = new PipeClient();
     predict = new Predict(client);
     python.OnPythonError += Python_OnPythonError;
     TinfoBox.Start(initText, title);
     python.RunScript("main.py");
     client.Connect("openstsm");
 }
コード例 #25
0
ファイル: SpecialStart.cs プロジェクト: zaieda/TemPOS
        private static void SendMessgage(string message)
        {
            PipeClient pipeClient = new PipeClient("TaskManagerAccessService", ".");

            try
            {
                pipeClient.SendMessage(message);
            }
            catch (Exception ex)
            {
                WriteConsole("[Exception]: " + ex.Message +
                             Environment.NewLine + ex.StackTrace + Environment.NewLine);
            }
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: frankfg94/Bolter
        static void  IPCAdminBridgeTest()
        {
            var server = new PipeClient();
            // TODO relative paths
            var bridgePath   = @"C:\Users\franc\source\repos\Bolter\BridgeProcess\bin\Debug\netcoreapp3.1\BridgeProcess.exe";
            var adminAppPath = @"C:\Users\franc\source\repos\Bolter\Bolter\Resources\BolterAdminApp.exe";

            server.ConnectToBridge(adminAppPath, bridgePath);
            Console.WriteLine("Connected");
            server.SendMessage("unblock");
            server.SendMessage("ooo");
            Thread.Sleep(2000);
            server.Stop();
        }
コード例 #27
0
 /// <summary>
 ///     Processes the task by creating a client pipe to the core
 /// </summary>
 /// <param name="task">Requires a <see cref="string" /></param>
 private string ProcessTask(string task)
 {
     if (!IsValidJson(task))
     {
         return("");
     }
     _loggerService.LogMessage(SERVICE_NAME, "Processing Task",
                               LogLevel.Debug);
     _pipeClient = new PipeClient();
     _pipeClient.CreatePipe();
     _pipeClient.WriteString(task);
     _pipeClient.WaitForDrain();
     return(_pipeClient.ReadString());
 }
コード例 #28
0
        public void TearDown()
        {
            if (_client != null)
            {
                _client.Stop();
                _client = null;
            }

            if (_server != null)
            {
                _server.Stop();
                _server = null;
            }
        }
コード例 #29
0
        public void the_client_receives_it()
        {
            var pipeName = Guid.NewGuid().ToString();
            var client   = new PipeClient();

            using (var server = new PipeServer(pipeName))
            {
                string receivedMessage = null;
                new System.Threading.Thread(() => client.Listen(pipeName, (m) => receivedMessage = m)).Start();
                server.Send("message sent by server");
                Timeout.AfterTwoSeconds().IfNot(() => receivedMessage != null);
                Assert.That(receivedMessage, Is.EqualTo("message sent by server"));
            }
        }
コード例 #30
0
        /// <summary>
        /// Constructor
        /// </summary>
        public CoreCommunicator()
        {
            Log.Info(COMMUNICATOR_LOG, "Started communication server.");

            try
            {
                pipeServer = new PipeServer(PAY_APPLICATION_PIPE_SERVER_NAME);
                pipeClient = new PipeClient();
                pipeServer.OnReceiveMessage += DoOnReceiveMessage;
            }
            catch (Exception ex)
            {
                Log.Info(COMMUNICATOR_LOG, string.Format("Failed to start CoreCommunicator.\r\n{0}", ex.ToString()));
            }
        }
コード例 #31
0
        public void T04_SendMessageFromServer_Ok()
        {
            // Arrange
            string pipeName        = "T04pipe";
            var    server          = new PipeServer(pipeName: pipeName);
            var    client          = new PipeClient(pipeName: pipeName);
            string expectedMessage = "Hallo ich bin der Server";

            // Act
            server.SendMessage(expectedMessage);
            string actualMessage = client.ReceiceMessage();

            // Assert
            Assert.AreEqual(expectedMessage, actualMessage);
        }
コード例 #32
0
ファイル: Form1.cs プロジェクト: vilgaxbaha/pdf
        void DecodeMessage(PipeClient client, byte[] msg)
        {
            MsgId msgId = (MsgId)BitConverter.ToUInt16(msg, 0);

            switch (msgId)
            {
            case MsgId.AllocData:
                DecodeAllocDataMsg(client, msg);
                break;

            case MsgId.FreeData:
                DecodeFreeDataMsg(client, msg);
                break;
            }
        }
コード例 #33
0
        public void PipeServer_WhenPreparingShutdown_MessagesAreRejected()
        {
            CreateSessionPipe();
            const string message = "test";

            _pipeServer.Start();

            var pipeClient = new PipeClient(_pipeName);

            _pipeServer.PrepareShutdown();

            var success = pipeClient.SendMessage(message);

            Assert.IsFalse(success);
        }
コード例 #34
0
ファイル: Form1.cs プロジェクト: cnhans/sumatrapdf
 void DecodeMessage(PipeClient client, byte[] msg)
 {
     MsgId msgId = (MsgId)BitConverter.ToUInt16(msg, 0);
     switch (msgId)
     {
         case MsgId.AllocData:
             DecodeAllocDataMsg(client, msg);
             break;
         case MsgId.FreeData:
             DecodeFreeDataMsg(client, msg);
             break;
     }
 }
コード例 #35
0
                // Summary:
                //  implements required cmdlet processing method.
                protected override void ProcessRecord()
                {
                    // iterate attempting to connect, send and receive to Chef node server.
                    for (int tryIndex = 0; tryIndex < Constants.MAX_CLIENT_RETRIES; ++tryIndex)
                    {
                        ITransport transport = new JsonTransport();
                        PipeClient pipeClient = new PipeClient(Constants.CHEF_NODE_PIPE_NAME, transport);

                        try
                        {
                            GetNodeValueRequestBase request = CreateRequest();

                            pipeClient.Connect(Constants.CHEF_NODE_CONNECT_TIMEOUT_MSECS);

                            IDictionary responseHash = (IDictionary)transport.NormalizeDeserializedObject(pipeClient.SendReceive<object>(request));

                            if (null == responseHash)
                            {
                                if (tryIndex + 1 < Constants.MAX_CLIENT_RETRIES)
                                {
                                    // delay retry a few ticks to yield time in case server is busy.
                                    Thread.Sleep(Constants.SLEEP_BETWEEN_CLIENT_RETRIES_MSECS);
                                    continue;
                                }
                                else
                                {
                                    string message = String.Format("Failed to get expected response after {0} retries.", Constants.MAX_CLIENT_RETRIES);

                                    throw CreateException(message);
                                }
                            }
                            if (ChefNodeCmdletExceptionBase.HasError(responseHash))
                            {
                                throw CreateException(responseHash);
                            }

                            // can't write a null object to pipeline, so write nothing in the null case.
                            object nodeValue = responseHash.Contains(Constants.JSON_NODE_VALUE_KEY) ? responseHash[Constants.JSON_NODE_VALUE_KEY] : null;

                            if (null != nodeValue)
                            {
                                WriteObject(nodeValue, nodeValue is ICollection);
                            }

                            // done.
                            break;
                        }
                        catch (TimeoutException e)
                        {
                            ThrowTerminatingError(new ErrorRecord(e, "Connection timed out", ErrorCategory.OperationTimeout, pipeClient));
                        }
                        catch (ChefNodeCmdletExceptionBase e)
                        {
                            ThrowTerminatingError(new ErrorRecord(e, "ChefNodeCmdlet exception", ErrorCategory.InvalidResult, pipeClient));
                        }
                        catch (Exception e)
                        {
                            ThrowTerminatingError(new ErrorRecord(e, "Unexpected exception", ErrorCategory.NotSpecified, pipeClient));
                        }
                        finally
                        {
                            pipeClient.Close();
                            pipeClient = null;
                        }
                    }
                }
コード例 #36
0
ファイル: Bus.cs プロジェクト: uw-it-cte/fog-client
 /// <summary>
 /// Initiate the pipe that connects to all other FOG bus instances
 /// It MUST be assumed that this pipe is compromised
 /// Do NOT send security relevant data across it
 /// </summary>
 /// <returns></returns>
 private static void InitializePipe()
 {
     switch (_mode)
     {
         case Mode.Server:
             // Attempt to become the pipe server
             try
             {
                 _server = new PipeServer("fog-bus");
                 _server.MessageReceived += pipe_RecieveMessage;
                 _server.Start();
                 Log.Entry(LogName, "Became bus server");
             }
             catch (Exception ex)
             {
                 Log.Error(LogName, "Could not enter named pipe");
                 Log.Error(LogName, ex);
             }
             break;
         case Mode.Client:
             // If someone else is already a pipe server, try and become a pipe client
             try
             {
                 _client = new PipeClient("fog-bus");
                 _client.MessageReceived += pipe_RecieveMessage;
                 _client.Connect();
                 Log.Entry(LogName, "Became bus client");
             }
             catch (Exception ex)
             {
                 Log.Error(LogName, "Could not enter named pipe");
                 Log.Error(LogName, ex);
             }
             break;
     }
     _initialized = true;
 }
コード例 #37
0
ファイル: Form1.cs プロジェクト: cnhans/sumatrapdf
 void pipeClient_ClientDisconnected(PipeClient client)
 {
     this.Invoke(
         new ClientDisconnectedHandler(ClientDisconnected),
         new object[] { client });
 }
コード例 #38
0
ファイル: Form1.cs プロジェクト: cnhans/sumatrapdf
 void NewMessage(PipeClient client, byte[] msg)
 {
     messagesCount += 1;
     messagesSize += msg.Length;
     DecodeMessage(client, msg);
     UpdateMessagesCount();
 }
コード例 #39
0
ファイル: Form1.cs プロジェクト: cnhans/sumatrapdf
 void DecodeFreeDataMsg(PipeClient client, byte[] msg)
 {
     UInt32 addr = BitConverter.ToUInt32(msg, 2);
     UInt32 size;
     if (!client.CurrAllocsMap.TryGetValue(addr, out size))
         return;
     client.CurrAllocated -= size;
     client.CurrAllocsMap.Remove(addr);
     UpdateCurrAllocated(client.CurrAllocated);
 }
コード例 #40
0
ファイル: Form1.cs プロジェクト: cnhans/sumatrapdf
 void DecodeAllocDataMsg(PipeClient client, byte[] msg)
 {
     UInt32 size = BitConverter.ToUInt32(msg, 2);
     UInt32 addr = BitConverter.ToUInt32(msg, 2 + 4);
     client.CurrAllocated += size;
     client.CurrAllocsMap[addr] = size;
     UpdateCurrAllocated(client.CurrAllocated);
 }
コード例 #41
0
ファイル: Form1.cs プロジェクト: cnhans/sumatrapdf
 void pipeClient_NewMessage(PipeClient client, byte[] msg)
 {
     this.Invoke(new NewMessageHandler(NewMessage), new object[] { client, msg });
 }
コード例 #42
0
                protected override void ProcessRecord()
                {
                    // iterate attempting to connect, send and receive to Chef node server.
                    for (int tryIndex = 0; tryIndex < Constants.MAX_CLIENT_RETRIES; ++tryIndex)
                    {
                        ITransport transport = new JsonTransport();
                        PipeClient pipeClient = new PipeClient(PipeName, transport);

                        try
                        {
                            // FIX: query the current value of $LastExitCode from powershell host.
                            int lastExitCode = 0;
                            GetNextActionRequest request = new GetNextActionRequest(lastExitCode);

                            pipeClient.Connect(Constants.NEXT_ACTION_CONNECT_TIMEOUT_MSECS);

                            IDictionary responseHash = (IDictionary)transport.NormalizeDeserializedObject(pipeClient.SendReceive<object>(request));

                            if (null == responseHash)
                            {
                                if (tryIndex + 1 < Constants.MAX_CLIENT_RETRIES)
                                {
                                    // delay retry a few ticks to yield time in case server is busy.
                                    Thread.Sleep(Constants.SLEEP_BETWEEN_CLIENT_RETRIES_MSECS);
                                    continue;
                                }
                                else
                                {
                                    string message = String.Format("Failed to get expected response after {0} retries.", Constants.MAX_CLIENT_RETRIES);
                                    throw new GetNextActionException(message);
                                }
                            }
                            if (ChefNodeCmdletExceptionBase.HasError(responseHash))
                            {
                                throw new GetNextActionException(responseHash);
                            }

                            // can't write a null object to pipeline, so write nothing in the null case.
                            string nextAction = responseHash.Contains(Constants.JSON_NEXT_ACTION_KEY) ? responseHash[Constants.JSON_NEXT_ACTION_KEY].ToString() : null;

                            if (null == nextAction)
                            {
                                throw new GetNextActionException("Received null for next action; expecting an exit command when finished.");
                            }

                            // automagically convert next action into an invocable script block.
                            //
                            // example of use:
                            //
                            //  while ($TRUE)
                            //  {
                            //      $Error.clear()
                            //      $nextAction = $NULL
                            //      $nextAction = get-NextAction
                            //      if ($Error.Count -eq 0)
                            //      {
                            //          write-output $nextAction
                            //          Invoke-Command -scriptblock $nextAction
                            //          sleep 1
                            //      }
                            //      else
                            //      {
                            //          break
                            //      }
                            //  }
                            ScriptBlock scriptBlock = ScriptBlock.Create(nextAction);

                            WriteObject(scriptBlock);

                            // done.
                            break;
                        }
                        catch (TimeoutException e)
                        {
                            ThrowTerminatingError(new ErrorRecord(e, "Connection timed out", ErrorCategory.OperationTimeout, pipeClient));
                        }
                        catch (GetNextActionException e)
                        {
                            ThrowTerminatingError(new ErrorRecord(e, "get-NextAction exception", ErrorCategory.InvalidResult, pipeClient));
                        }
                        catch (Exception e)
                        {
                            ThrowTerminatingError(new ErrorRecord(e, "Unexpected exception", ErrorCategory.NotSpecified, pipeClient));
                        }
                        finally
                        {
                            pipeClient.Close();
                            pipeClient = null;
                        }
                    }
                }