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;
                        }
                    }
                }
示例#2
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();
            }
        }
        public void Close()
        {
            if (client != null)
            {
                if (client.isConnected())
                {
                    client.Close();
                }
            }

            if (python != null)
            {
                python.OnPythonError -= Python_OnPythonError;
                python.Close();
            }
        }
示例#4
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();
            }
示例#5
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();
        }
示例#6
0
文件: Exec.cs 项目: tlsnns/NTLMClient
        private void AAAA()
        {
            while (IsRun)
            {
                try
                {
                    byte[] buff = ci.Read(12);
                    if (buff.Length != 12)
                    {
                        throw new Exception("Pipe Read Length Error");
                    }
                    ulong transportHeader = BitConverter.ToUInt64(buff, 0);
                    if (transportHeader != 0x1122334455667788u)
                    {
                        throw new Exception("Pipe Read TransportHeader Error");
                    }
                    uint transportLength = BitConverter.ToUInt32(buff, 8);

                    buff = ci.Read(transportLength);
                    if (buff.Length != transportLength)
                    {
                        throw new Exception("Pipe Read TransportLength Error");
                    }
                    var str = Encoding.UTF8.GetString(buff, 1, buff.Length - 1);
                    if (buff[0] == 1)
                    {
                        Console.Write(str);
                    }
                    else
                    {
                        Console.Write("Server failure:" + str);
                    }
                }
                catch { }
            }
            ci.Close();
        }
示例#7
0
文件: Exec.cs 项目: tlsnns/NTLMClient
        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();
            ;
        }
                // 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;
                        }
                    }
                }
                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;
                        }
                    }
                }
示例#10
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();
            }
        }
示例#11
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;
                        }
                    }
                }
示例#12
0
 void OnApplicationQuit()
 {
     PipeClient.Close();
 }
示例#13
0
 public override void Close()
 {
     PC.Close();
 }
示例#14
0
 public override void Disconnect()
 {
     _pipeClient.Close();
 }