Ejemplo n.º 1
0
        void DisplayReceivedMessage(byte[] message)
        {
            ASCIIEncoding encoder = new ASCIIEncoding();
            string        str     = encoder.GetString(message, 0, message.Length);

            if (str == "close")
            {
                pipeClient.Disconnect();

                CreateNewPipeClient();
                pipeClient.Connect(tbPipeName.Text);
            }

            tbReceived.Text += str + "\r\n";
        }
Ejemplo n.º 2
0
        private void runPython()
        {
            PipeClient client;

            python = new PythonExecutor();

            if (!python.CanRun)
            {
                if (System.IO.File.Exists("Python35\\python.exe"))
                {
                    python = new PythonExecutor("Python35\\python.exe");
                }
                else if (MessageBox.Show("Unable to find python.\nDo you want to download an example interpreter from cheonghyun.com?", "IpcPythonCS", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                         == System.Windows.Forms.DialogResult.Yes)
                {
                    PythonDownloader down = new PythonDownloader();
                    down.DownloadAndUnzip();

                    python = new PythonExecutor(down.PythonInterpreter.FullName);
                }
                else
                {
                    MessageBox.Show("This application cannot run without Python.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            python.RunScript("main.py");

            client = new PipeClient();
            client.Connect("calculator");

            calculator = new PyCalculator(client);
        }
Ejemplo n.º 3
0
        protected void Run()
        {
            do
            {
                lock (Pipe)
                {
                    if (Pipe.Connected)
                    {
                        continue;
                    }
                    Connected = false;

                    if (!Pipe.Connect())
                    {
                        continue;
                    }
                    if (!SyncUser() || !SyncAll())
                    {
                        Pipe.Dispose();
                        continue;
                    }
                    Connected = true;
                }
            }while (!AsyncManager.StopEvent.WaitOne(500));
        }
Ejemplo n.º 4
0
 public override void ConnectToServer()
 {
     if (CanConnect)
     {
         CanConnect = false;
         _pipeClient.Connect("PipeNameXXX");
     }
 }
Ejemplo n.º 5
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(Constants.CHEF_NODE_PIPE_NAME, transport);

                        try
                        {
                            pipeClient.Connect(Constants.CHEF_NODE_CONNECT_TIMEOUT_MSECS);

                            SetNodeValueRequestBase request = CreateRequest();

                            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);
                            }

                            // 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;
                        }
                    }
                }
Ejemplo n.º 6
0
        private static string GetHwid()
        {
            PipeClient.ExceptionThrown += ByteGuardHelper.ThrowException;
            PipeClient.MessageReceived += MessageReceived;
            PipeClient.Connect();

            PipeClient.SendMessage("[GETID]");

            return(null);
        }
Ejemplo n.º 7
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            dmdBitmap.ChangeColor();
            pipeClient.Connect(tbPipeName.Text);

            if (pipeClient.Connected)
            {
                btnStart.Enabled = false;
            }

            Log("Connected to server.");
        }
Ejemplo n.º 8
0
        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();
        }
 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");
 }
Ejemplo n.º 10
0
    public PipeClient Connect(int TimeOut = 10000)
    {
        PipeClient clientPipe = new PipeClient(".", mPipeName);

        if (!clientPipe.Connect(TimeOut))
        {
            return(null);
        }

        clientPipes.Add(clientPipe);

        clientPipe.PipeClosed += (sndr, args) => {
            mDispatcher.Invoke(new Action(() => {
                clientPipes.Remove(clientPipe);
            }));
        };

        return(clientPipe);
    }
Ejemplo n.º 11
0
        private static void Main(string[] args)
        {
            SetupEventHandlers();
            PipeClient.Connect();

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

            string SeedStr =
                "2~2~1~0~0~24~25~0~False~2~False~5~0~0~HERO_04*-1*0*0*0*0*0*4*30*0*2*30*0*False*False*False*False*False*False*False*False*False*False*False*False*False*2*False~HERO_01*-1*2*0*0*0*0*36*30*0*2*32*0*False*False*False*False*False*False*False*False*False*False*False*False*False*2*False~CS2_101*-1*0*0*2*0*0*5*0*0*2*0*0*False*False*False*False*False*False*False*False*False*False*False*False*False*2*False~CS2_102*-1*0*0*2*0*0*37*0*0*2*0*0*False*False*False*False*True*False*False*False*False*False*False*False*False*2*False~EX1_080*0*0*1*1*0*0*9*2*0*1*2*0*False*False*False*False*False*False*False*False*False*False*False*False*False*1*False~0~GVG_061*0*0*0*3*0*0*24*0*0*0*0*0*False*False*False*False*False*False*True*False*False*False*False*False*False*0*False|AT_079*1*0*6*6*0*0*20*6*0*0*6*0*False*False*False*False*False*False*True*False*False*False*False*False*False*0*False|GVG_096*2*0*4*4*0*0*7*3*0*0*3*0*False*False*False*False*False*False*True*False*False*False*False*False*False*0*False|GAME_005*3*0*0*0*0*0*68*0*0*0*0*0*False*False*False*False*False*False*True*False*False*False*False*False*False*0*False|EX1_136*4*0*0*1*0*0*10*0*0*0*0*0*False*False*False*False*False*False*True*False*False*False*False*False*False*0*False|AT_073*5*0*0*1*0*0*32*0*0*0*0*0*False*False*False*False*False*False*True*False*False*False*False*False*False*0*False~0~0~0~0~0~False=False=False=False=False=False~0~0~0~False~GVG_096,GVG_096,GVG_059,CS2_092,CS2_092,EX1_383,FP1_002,GVG_110,AT_073,AT_073,EX1_379,EX1_080,EX1_080,FP1_030,EX1_136,FP1_012,EX1_130,EX1_130,NEW1_019,NEW1_019,FP1_020,FP1_020,GVG_058,GVG_058,GVG_061,GVG_061,AT_079,AT_079,CS2_093,CS2_097~";
            string ProfileStr = "Default";
            bool   AoESpells  = true;


            SendSeedRequest(SeedStr, ProfileStr, AoESpells);

            Console.ReadLine();

            PipeClient.Disconnect();
        }
Ejemplo n.º 12
0
        static void Main(string[] _)
        {
            var cancellation = new CancellationTokenSource();

            var pipeClient = new PipeClient(PipeConstants.PIPE_NAME, cancellation.Token);

            try
            {
                pipeClient.Connect();

                Console.WriteLine("Client OK");

                var requests = new List <string>()
                {
                    PipeConstants.READ_DATE_TIME,
                    PipeConstants.READ_COMPUTER_NAME,
                    PipeConstants.END_COMMUNICATION
                };

                foreach (var request in requests)
                {
                    pipeClient.SendMessage(new { Type = request });

                    var message = pipeClient.ReadMessage();

                    ValidateMessage(message);

                    var data = message.Value <string>("Data");

                    Console.WriteLine($"Server Response: {data}");
                }

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                pipeClient.Close();
            }
Ejemplo n.º 13
0
        public void TestPipeIO()
        {
            PipeClient client;
            Thread     thread;
            string     value;

            client = new PipeClient();

            thread = new Thread(() => OpenPipeServer("PipeTest"));
            thread.Start();

            client.Connect("PipeTest");

            client.Write("1");
            value = client.Read();

            Assert.AreEqual(1, Int32.Parse(value), "Pipe communication failed.");

            client.Close();
        }
Ejemplo n.º 14
0
        public void TestInitialize()
        {
            _mreSvrConnect = new ManualResetEventSlim();
            _mreCltConnect = new ManualResetEventSlim();

            _pipeServer = new PipeServer <SerializableClass>(nameof(SerializableTests));
            _pipeClient = new PipeClient <SerializableClass>(nameof(SerializableTests));

            _pipeServer.OnConnect += () => _mreSvrConnect.Set();
            _pipeClient.OnConnect += () => _mreCltConnect.Set();

            _pipeClient.Connect(TIMEOUT_MS);

            if (!_mreSvrConnect.Wait(TIMEOUT_MS))
            {
                Assert.Inconclusive($"Svr:{TIMEOUT_CONNECT}");
            }
            if (!_mreCltConnect.Wait(TIMEOUT_MS))
            {
                Assert.Inconclusive($"Clt:{TIMEOUT_CONNECT}");
            }
        }
Ejemplo n.º 15
0
        /// <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;
        }
Ejemplo n.º 16
0
        public void RunSelectiveSearch()
        {
            Predict        predict;
            PythonExecutor python = new PythonExecutor(@"C:\Users\kutiatore\AppData\Local\Programs\Python\Python35\python.exe");

            python.AddStandartOutputErrorFilters("Using TensorFlow backend.");
            python.AddStandartOutputErrorFilters("CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected");
            PipeClient client = new PipeClient();

            predict = new Predict(client);

            try
            {
                python.RunScript("main.py");

                client.Connect("openstsm");
                predict = new Predict(client);
                bool run = predict.LoadModel(@"E:\\Storage\\Python\\OpenSTSM\\ML\\models\\model.model");
                run = predict.ImageDimessionCorrections("E:\\Libraries\\Desktop\\Visa Docs\\test_selective_1.png");
                run = predict.RunSelectiveSearch(80, 1.0f);
                string results = predict.RunPrediction(5, 3, 5, 1, 8, 2, true);

                client.Close();
                python.Close();
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine("---------------------");
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
                System.Diagnostics.Debug.WriteLine("---------------------");
                if (client.isConnected())
                {
                    client.Close();
                }

                python.Close();
            }
        }
Ejemplo n.º 17
0
        public void Start()
        {
            co.Connect();
            ci.Connect();
            Thread thread = new Thread(AAAA);

            thread.Start();
            Console.WriteLine("input command");
            while (true)
            {
                var strCmd = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(strCmd))
                {
                    continue;
                }
                if (strCmd == "exit")
                {
                    break;
                }
                var         c  = Encoding.UTF8.GetBytes(strCmd);
                List <byte> vs = new List <byte>();
                vs.AddRange(BitConverter.GetBytes(0x1122334455667788u));
                vs.AddRange(BitConverter.GetBytes(c.Length + 1));
                vs.Add(0);//type
                vs.AddRange(c);
                co.Write(vs.ToArray());
            }
            co.Write(new byte[] {
                0x88, 0x77, 0x66, 0x55,
                0x44, 0x33, 0x22, 0x11,
                0x01, 0x00, 0x00, 0x00,
                0x01
            });
            IsRun = false;
            co.Close();
            ;
        }
Ejemplo n.º 18
0
        public void TestInitialize()
        {
            _mreConnect.Reset();

            var ser = new CustomSerializerJson <SerializableClass>();

            _pipeClient = new PipeClient <SerializableClass>(PipeName)
            {
                OnConnect  = () => _mreConnect.Set(),
                Serializer = ser
            };

            _pipeServer = new PipeServer <SerializableClass>(PipeName)
            {
                Serializer = ser
            };

            _pipeClient.Connect(TIMEOUT_MS);

            if (!_mreConnect.Wait(TIMEOUT_MS))
            {
                Assert.Inconclusive(TIMEOUT_CONNECT);
            }
        }
Ejemplo n.º 19
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;
                        }
                    }
                }
Ejemplo n.º 20
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
                        {
                            GetNextActionRequest request = new GetNextActionRequest(LastActionExitCode, LastActionErrorMessage);

                            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);
                            }

                            // next action cannot be null.
                            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.");
                            }

                            // enhance next action with try-catch logic to set the $global:RS_LastErrorRecord variable
                            // in case of an exception thrown by a script. the try-catch block loses details of script
                            // execution if caught by an outer block instead of the inner block which threw it.
                            nextAction = NEXT_ACTION_PREFIX + nextAction + NEXT_ACTION_POSTFIX;

                            // automagically convert next action into an invocable script block.
                            //
                            // example of use:
                            //
                            //  while ($TRUE)
                            //  {
                            //      $Error.clear()
                            //      $nextAction = $NULL
                            //      $nextAction = get-NextAction $pipeName
                            //      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;
                        }
                    }
                }
Ejemplo n.º 21
0
 public RpcTransportOnPipe(string ipAddress, string strNamePipe, string userName, string password)
 {
     PC = new PipeClient(ipAddress, strNamePipe, PipeDirection.ReadWrite, userName, password);
     PC.Connect();
 }
Ejemplo n.º 22
0
        public static void Main(string[] args)
        {
            App.args = args;

            mConsole = WinConsole.Initialize(TestArg("-console") || TestArg("-console-debug"));

            if (TestArg("-help") || TestArg("/?"))
            {
                ShowHelp();
                return;
            }
            else if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            Thread.CurrentThread.Name = "Main";

            Console.WriteLine("Starting...");

            AppLog Log = new AppLog();

            exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath);

            mVersion = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            if (fvi.FileBuildPart != 0)
            {
                mVersion += (char)('a' + (fvi.FileBuildPart - 1));
            }
            appPath  = Path.GetDirectoryName(exePath);
            mSession = Process.GetCurrentProcess().SessionId;

            Translate.Load();

            svc = new Service(mSvcName);

            if (TestArg("-engine"))
            {
                engine = new Engine();

                engine.Run();
                return;
            }
            else if (TestArg("-svc"))
            {
                if (TestArg("-install"))
                {
                    Console.WriteLine("Installing service...");
                    svc.Install(TestArg("-start"));
                    Console.WriteLine("... done");
                }
                else if (TestArg("-remove"))
                {
                    Console.WriteLine("Removing service...");
                    svc.Uninstall();
                    Console.WriteLine("... done");
                }
                else
                {
                    engine = new Engine();

                    ServiceBase.Run(svc);
                }
                return;
            }

            tweaks = new Tweaks();

            client = new PipeClient();

            if (!AdminFunc.IsDebugging())
            {
                Console.WriteLine("Trying to connect to Engine...");
                if (!client.Connect(1000))
                {
                    if (!AdminFunc.IsAdministrator())
                    {
                        Console.WriteLine("Trying to obtain Administrative proivilegs...");
                        if (AdminFunc.SkipUacRun(mName, App.args))
                        {
                            return;
                        }

                        Console.WriteLine("Trying to start with 'runas'...");
                        // Restart program and run as admin
                        var              exeName   = Process.GetCurrentProcess().MainModule.FileName;
                        string           arguments = "\"" + string.Join("\" \"", args) + "\"";
                        ProcessStartInfo startInfo = new ProcessStartInfo(exeName, arguments);
                        startInfo.UseShellExecute = true;
                        startInfo.Verb            = "runas";
                        try
                        {
                            Process.Start(startInfo);
                            return; // we restarted as admin
                        }
                        catch
                        {
                            MessageBox.Show(Translate.fmt("msg_admin_rights", mName), mName);
                            return; // no point in cintinuing without admin rights or an already running engine
                        }
                    }
                    else if (svc.IsInstalled())
                    {
                        Console.WriteLine("Trying to start service...");
                        if (svc.Startup())
                        {
                            Console.WriteLine("Trying to connect to service...");

                            if (client.Connect())
                            {
                                Console.WriteLine("Connected to service...");
                            }
                            else
                            {
                                Console.WriteLine("Failed to connect to service...");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Failed to start service...");
                        }
                    }
                }
            }

            // if we couldn't connect to the engine start it and connect
            if (!client.IsConnected() && AdminFunc.IsAdministrator())
            {
                Console.WriteLine("Starting Engine Thread...");

                engine = new Engine();

                engine.Start();

                Console.WriteLine("... engine started.");

                client.Connect();
            }

            // ToDo: use a more direct communication when running in one process

            itf = client;
            cb  = client;

            /*if (TestArg("-console-debug"))
             * {
             *  Console.WriteLine("Private WinTen reporting for duty, sir!");
             *  Console.WriteLine("");
             *
             *  for (bool running = true; running;)
             *  {
             *      String Line = Console.ReadLine();
             *      if (Line.Length == 0)
             *          continue;
             *
             *      String Command = TextHelpers.GetLeft(ref Line).ToLower();
             *
             *      if (Command == "quit" || Command == "exit")
             *          running = false;
             *
             *      if (Command == "test")
             *      {
             *      }
             *      else
             *      {
             *          Console.WriteLine("Unknown Command, sir!");
             *          continue;
             *      }
             *      Console.WriteLine("Yes, sir!");
             *  }
             *
             *  return;
             * }*/

            Console.WriteLine("Preparing GUI...");

            var app = new App();

            app.InitializeComponent();

            InitLicense();

            mTray         = new TrayIcon();
            mTray.Action += TrayAction;
            mTray.Visible = GetConfigInt("Startup", "Tray", 0) != 0;

            mMainWnd = new MainWindow();
            if (!App.TestArg("-autorun") || !mTray.Visible)
            {
                mMainWnd.Show();
            }

            app.Run();

            mTray.DestroyNotifyicon();

            client.Close();

            if (engine != null)
            {
                engine.Stop();
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// 启动升级客户端并连接
 /// </summary>
 /// <returns></returns>
 public static async Task <bool> StartUpgradeClientWithConnect()
 {
     return(await StartUpgradeClient() && await pipeClient.Connect(1000));
 }
Ejemplo n.º 24
0
 /// <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;
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Constructs a new PipeLogger
 /// </summary>
 /// <param name="serverName">The name of the server hosting the named pipe</param>
 /// <param name="pipeName">The name of the named pipe</param>
 /// <param name="addTimestamp">If true, the message will be prefixed with a timestamp</param>
 public PipeClientLogger(string serverName, string pipeName, bool addTimestamp = true) : base(pipeName, addTimestamp)
 {
     _client = new PipeClient();
     _client.Connect(serverName, pipeName, System.IO.Pipes.PipeDirection.InOut);
 }
Ejemplo n.º 26
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;
                        }
                    }
                }