private void newProcess(string file, string args)
 {
     //if process is already running or processes are queued
     if (consoleControl.IsProcessRunning || Processes.Count > 0)
     {
         //create new process struct
         Process qProcess = new Process();
         qProcess.File = file;
         qProcess.Args = args;
         //push process into queue
         Processes.Enqueue(qProcess);
         //wait until current process finishes
         while (consoleControl.IsProcessRunning) ;
         //pull next process from queue
         qProcess = Processes.Dequeue();
         //start next process
         consoleControl.StartProcess(qProcess.File, qProcess.Args);
     }
     else
     {
         //start new process
         consoleControl.StartProcess(file, args);
     }
     //update form title
     this.Text = "CIS Tronscript Toolbox - " + consoleControl.ProcessInterface.ProcessFileName;
 }
 private static string GetKeyHash(string alias, string keyStore, string password)
 {
     var proc = new Process();
     var arguments = @"""keytool -storepass {0} -keypass {1} -exportcert -alias {2} -keystore {3} | openssl sha1 -binary | openssl base64""";
     if (Application.platform == RuntimePlatform.WindowsEditor)
     {
         proc.StartInfo.FileName = "cmd";
         arguments = @"/C " + arguments;
     }
     else
     {
         proc.StartInfo.FileName = "bash";
         arguments = @"-c " + arguments;
     }
     proc.StartInfo.Arguments = string.Format(arguments, password, password, alias, keyStore);
     proc.StartInfo.UseShellExecute = false;
     proc.StartInfo.CreateNoWindow = true;
     proc.StartInfo.RedirectStandardOutput = true;
     proc.Start();
     var keyHash = new StringBuilder();
     while (!proc.HasExited)
     {
         keyHash.Append(proc.StandardOutput.ReadToEnd());
     }
     return keyHash.ToString();
 }
    public void ConvertFromUrl(string url, string file_out, HtmlToImageConverterOptions options)
    {
        string converter_path = HttpContext.Current.Server.MapPath ("~/bin/wkhtmltopdf/wkhtmltoimage.exe");

        string param_options = null;

        if (options != null)
        {
            StringBuilder sb_params = new StringBuilder();

            if (options.CropWidth > 0) sb_params.Append(" --crop-w ").Append(options.CropWidth);
            if (options.CropHeight > 0) sb_params.Append(" --crop-h ").Append(options.CropHeight);
            if (options.Quality > 0) sb_params.Append(" --quality ").Append(options.Quality);
            if (!string.IsNullOrEmpty(options.CookieName)) sb_params.Append(" --cookie ").Append(options.CookieName).Append(' ').Append(options.CookieValue);

            param_options = sb_params.ToString();
        }

        ProcessStartInfo psi = new ProcessStartInfo(converter_path, string.Format("{0} \"{1}\" \"{2}\"", param_options.Trim(), url, file_out));

        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;

        Process proc = new Process();
        proc.StartInfo = psi;
        proc.Start();

        proc.WaitForExit();
    }
Exemplo n.º 4
0
        public void Generate_Data()
        {
            if (_Type == QueueType.Process)
            {
                // use system data to make random processes
                System.Diagnostics.Process[] currentProcesses = System.Diagnostics.Process.GetProcesses();

                foreach (System.Diagnostics.Process p in currentProcesses)
                {
                    Process insert = new Process(Make_Start_Time(), Make_Burst_Time(), Make_Priority());
                    insert.ProcessID = p.ProcessName;
                    insert.Size = p.PeakPagedMemorySize64;
                    //insert.StartTime =
                    _ProcessList.Add(insert);
                }

                // now that all processes are in list, reorder againsts arival time
                _ProcessList = new Collection<Process>(_ProcessList.OrderBy(o => o.StartTime).ToList());
            }

            else if (_Type == QueueType.Memory_Paging)
            {
                // here we need generated information regarding blocks of data, so for random fun, lets use frequent things
                string localFolder = Environment.GetFolderPath(Environment.SpecialFolder.Recent);
                DirectoryInfo recentFolder = new DirectoryInfo(localFolder);
                _Files = recentFolder.GetFiles();
            }
        }
Exemplo n.º 5
0
	public static int Main(string[] args)
	{
		// Only run this test on Unix
		int pl = (int) Environment.OSVersion.Platform;
		if ((pl != 4) && (pl != 6) && (pl != 128)) {
			return 0;
		}

		// Try to invoke the helper assembly
		// Return 0 only if it is successful
		try
		{
			var name = "bug-17537-helper.exe";
			Console.WriteLine ("Launching subprocess: {0}", name);
			var p = new Process();
			p.StartInfo.FileName = Path.Combine (AppDomain.CurrentDomain.BaseDirectory + name);
			p.StartInfo.UseShellExecute = false;

			var result = p.Start();
			p.WaitForExit(1000);
			if (result) {
				Console.WriteLine ("Subprocess started successfully");
				return 0;
			} else {
				Console.WriteLine ("Subprocess failure");
				return 1;
			}
		}
		catch (Exception e)
		{
			Console.WriteLine ("Subprocess exception");
			Console.WriteLine (e.Message);
			return 1;
		}
	}
Exemplo n.º 6
0
    public static void BuildGame()
    {
        // Get filename.
        string path = EditorUtility.SaveFolderPanel("Choose Location of Built Game", "", "");

        // Get levels
        string map = "Assets/Scenes/zm_MAP_floatingCity_";
        string[] levels =
        {
            "Assets/Scenes/zm_SCENE_TitleScreen.unity",
            //map + "03.unity",
            //map + "04.unity",
            //map + "05.unity",
            //map + "06.unity",
            map + "07.unity",
        };

        // Build player.
        BuildPipeline.BuildPlayer(levels, path + "/BuiltGame.exe", BuildTarget.StandaloneWindows, BuildOptions.None);

        // Copy a file from the project folder to the build folder, alongside the built game.
        //FileUtil.CopyFileOrDirectory("Assets/WebPlayerTemplates/Readme.txt", path + "Readme.txt");

        // Run the game (Process class from System.Diagnostics).
        Process proc = new Process();
        proc.StartInfo.FileName = path + "BuiltGame.exe";
        proc.Start();
    }
        public static void OpenGitBash()
        {
            string projectDir = Application.dataPath + "/../";
            string gitDir = projectDir + ".git";
            #if !UNITY_EDITOR_WIN
            Debug.LogError("Only supported in Windows Editor");
            #else
            if (!Directory.Exists(gitDir)) {
                Debug.LogError("No git repo for this project");
                return;
            }
            string gitBash = null;
            if (File.Exists(GIT_BASH_64)) {
                gitBash = GIT_BASH_64;
            } else if (File.Exists(GIT_BASH_32)) {
                gitBash = GIT_BASH_32;
            } else {
                Debug.LogError("Couldn't find Git Bash");
                return;
            }

            Process foo = new Process {
                StartInfo = {
                FileName = gitBash,
                WorkingDirectory = projectDir
            }
            };
            foo.Start();
            #endif
        }
Exemplo n.º 8
0
    private static void onPostProcessBuildPlayer( BuildTarget target, string pathToBuiltProject )
    {
        if( target == BuildTarget.iOS )
        {
            // grab the path to the postProcessor.py file
            var scriptPath = Path.Combine( Application.dataPath, "Editor/Vungle/VunglePostProcessor.py" );

            // sanity check
            if( !File.Exists( scriptPath ) )
            {
                UnityEngine.Debug.LogError( "Vungle post builder could not find the VunglePostProcessor.py file. Did you accidentally delete it?" );
                return;
            }

            var pathToNativeCodeFiles = Path.Combine( Application.dataPath, "Editor/Vungle/VungleSDK" );

            var args = string.Format( "\"{0}\" \"{1}\" \"{2}\"", scriptPath, pathToBuiltProject, pathToNativeCodeFiles );
            var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "python2.6",
                    Arguments = args,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true
                }
            };

            proc.Start();
        }
    }
Exemplo n.º 9
0
    static void Main()
    {
        try
        {
            string[] words = { "start", "Start - Game", "end - GameStart" };
            string txtFile = @"..\..\textFile.txt";
            string outputFile = @"..\..\finish.txt";

            RandomizationFile(words, txtFile);
            ChangingWordInFile(txtFile, outputFile);

            Process openfile = new Process();
            openfile.StartInfo.FileName = txtFile;
            openfile.Start();

            openfile.StartInfo.FileName = outputFile;
            openfile.Start();
        }
        catch (FileNotFoundException FNFE)
        {
            Console.WriteLine(FNFE.Message);
        }
        catch (NullReferenceException NRE)
        {
            Console.WriteLine(NRE.Message);
        }
        catch (ArgumentNullException ANE)
        {
            Console.WriteLine(ANE.Message);
        }
        finally
        {
            Console.WriteLine("Good Bye");
        }
    }
Exemplo n.º 10
0
        public void GetId()
        {
            int id;
            foreach (var iteration in Benchmark.Iterations)
            {
                // Create several processes to test on
                Process[] processes = new Process[500];
                for (int i = 0; i < 500; i++)
                {
                    processes[i] = CreateProcess();
                    processes[i].Start();
                }

                // Begin Testing
                using (iteration.StartMeasurement())
                    for (int i = 0; i < 500; i++)
                        id = processes[i].Id;

                foreach (Process proc in processes)
                {
                    if (!proc.HasExited)
                        proc.Kill();
                    proc.WaitForExit();
                    proc.Dispose();
                }
            }
        }
        public void Initialize(Process process) {
            var connection = process.OutputConnection;
            var entity = process.OutputConnection.TflBatchEntity(process.Name);
            new ElasticSearchEntityDropper().Drop(connection, entity);

            process.Logger.Info( "Initialized TrAnSfOrMaLiZeR {0} connection.", process.OutputConnection.Name);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 编译指定目录下的文件
        /// </summary>
        /// <param name="root">源代码目录</param>
        /// <param name="outputDllName">编译输出的dll名称</param>
        /// <param name="references">编译时需要的引用程序集</param>
        public static void Compile(String root, String outputDllName, params String[] references)
        {
            var args = BuildCompileArgs(root, outputDllName, references);
            var cmd = Path.Combine(MonoLocation, "bin/mcs").ToConsistentPath();

            UnityEngine.Debug.Log(String.Format("{0} {1}", cmd, args));

#if UNITY_EDITOR_OSX
            var proc = new Process
            {
                StartInfo =
                {
                    FileName = cmd,
                    Arguments = args,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true
                }
            };
#else
            var proc = new Process
            {
                StartInfo =
                {
                    FileName = cmd,
                    Arguments = args,
                    UseShellExecute = true
                }
            };
#endif
            proc.Start();
            proc.WaitForExit();
            proc.Close();
        }
Exemplo n.º 13
0
        public void Kill()
        {
            const int inneriterations = 500;
            foreach (var iteration in Benchmark.Iterations)
            {
                // Create several processes to test on
                Process[] processes = new Process[inneriterations];
                for (int i = 0; i < inneriterations; i++)
                {
                    processes[i] = CreateProcessLong();
                    processes[i].Start();
                }

                // Begin Testing - Kill all of the processes
                using (iteration.StartMeasurement())
                    for (int i = 0; i < inneriterations; i++)
                        processes[i].Kill();

                // Cleanup the processes
                foreach (Process proc in processes)
                {
                    proc.WaitForExit();
                    proc.Dispose();
                }
            }
        }
Exemplo n.º 14
0
Arquivo: test.cs Projeto: mono/gert
	static bool RunProcess (string runtimeEngine, int numLines)
	{
		string stderr, stdout;
		sb = new StringBuilder ();

		string program = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"output.exe");

		Process proc = new Process ();
		if (!string.IsNullOrEmpty (runtimeEngine)) {
			proc.StartInfo.FileName = runtimeEngine;
			proc.StartInfo.Arguments = string.Format (CultureInfo.InvariantCulture,
				"\"{0}\" {1}", program, numLines);
		} else {
			proc.StartInfo.FileName = program;
			proc.StartInfo.Arguments = string.Format (CultureInfo.InvariantCulture,
				 "{0}", numLines);
		}
		proc.StartInfo.UseShellExecute = false;
		proc.StartInfo.RedirectStandardOutput = true;
		proc.StartInfo.RedirectStandardError = true;
		proc.OutputDataReceived += new DataReceivedEventHandler (OutputHandler);
		proc.Start ();

		proc.BeginOutputReadLine ();
		stderr = proc.StandardError.ReadToEnd ();
		proc.WaitForExit ();

		stdout = sb.ToString ();

		string expectedResult = "STDOUT => 1" + Environment.NewLine +
			"STDOUT => 2" + Environment.NewLine + "STDOUT => 3" +
			Environment.NewLine + "STDOUT => 4" + Environment.NewLine +
			" " + Environment.NewLine + "STDOUT => 6" + Environment.NewLine +
			"STDOUT => 7" + Environment.NewLine + "STDOUT => 8" +
			Environment.NewLine + "STDOUT => 9" + Environment.NewLine;
		if (stdout != expectedResult) {
			Console.WriteLine ("expected:");
			Console.WriteLine (expectedResult);
			Console.WriteLine ("was:");
			Console.WriteLine (stdout);
			return false;
		}

		expectedResult = "STDERR => 1" + Environment.NewLine +
			"STDERR => 2" + Environment.NewLine + "STDERR => 3" +
			Environment.NewLine + "STDERR => 4" + Environment.NewLine +
			" " + Environment.NewLine + "STDERR => 6" + Environment.NewLine +
			"STDERR => 7" + Environment.NewLine + "STDERR => 8" +
			Environment.NewLine + "STDERR => 9" + Environment.NewLine;
		if (stderr != expectedResult) {
			Console.WriteLine ("expected:");
			Console.WriteLine (expectedResult);
			Console.WriteLine ("was:");
			Console.WriteLine (stderr);
			return false;
		}

		return true;
	}
Exemplo n.º 15
0
    //使用winrar压缩文件
    public static void CompressFiles(string rarPath, ArrayList fileArray)
    {
        string rar;
        RegistryKey reg;
        object obj;
        string info;
        ProcessStartInfo startInfo;
        Process rarProcess;
        try
        {
            reg = Registry.ClassesRoot.OpenSubKey("Applications\\WinRAR.exe\\Shell\\Open\\Command");
            obj = reg.GetValue("");
            rar = obj.ToString();
            reg.Close();
            rar = rar.Substring(1, rar.Length - 7);
            info = " a -as -r -EP1 " + rarPath;
            foreach (string filepath in fileArray)
                info += " " + filepath;
            startInfo = new ProcessStartInfo();
            startInfo.FileName = rar;
            startInfo.Arguments = info;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            rarProcess = new Process();
            rarProcess.StartInfo = startInfo;
            rarProcess.Start();
        }
        catch
        {

        }
    }
Exemplo n.º 16
0
 protected void StartAndKillProcessWithDelay(Process p)
 {
     p.Start();
     Sleep();
     p.Kill();
     Assert.True(p.WaitForExit(WaitInMS));
 }
Exemplo n.º 17
0
 protected void StartSleepKillWait(Process p)
 {
     p.Start();
     Thread.Sleep(50);
     p.Kill();
     Assert.True(p.WaitForExit(WaitInMS));
 }
Exemplo n.º 18
0
    /// <summary>
    /// プロセスを実行
    /// </summary>
    public void StartProcess(ProcessData procData)
    {
        if(procData.use && !procData.IsRunning)
        {
            FileInfo fileInfo = new FileInfo(procData.exePath);
            if(fileInfo.Exists)
            {
                Process proc = new Process();
                proc.StartInfo.FileName = Path.GetFullPath(procData.exePath);

                //引数設定
                if(procData.argument != "")
                    proc.StartInfo.Arguments = procData.argument;

                //ウィンドウスタイル設定
                if(!ApplicationSetting.Instance.GetBool("IsDebug"))
                    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                try
                {
                    proc.Start();

                    processList.Add(proc);
                    procData.IsRunning = true;
                }
                catch(Exception e)
                {
                    UnityEngine.Debug.Log("ExternalProcess :: process start error - " + e.Message);
                }
            }
        }
    }
Exemplo n.º 19
0
 public object Apply(Context context, IList<object> arguments)
 {
     IFunction func = (IFunction)arguments[0];
     Process process = new Process();
     process.Start(func);
     return process;
 }
    public void ConvertFromUrl(string url, string file_out, HtmlToPdfConverterOptions options)
    {
        string converter_path = HttpContext.Current.Server.MapPath("~/bin/wkhtmltopdf/wkhtmltopdf.exe");

        string param_options = null;

        if (options != null)
        {
            StringBuilder sb_params = new StringBuilder();

            if (!string.IsNullOrEmpty(options.Orientation)) sb_params.Append(" --orientation ").Append(options.Orientation);
            if (options.PageWidth > 0) sb_params.Append(" --page-width ").Append(options.PageWidth);
            if (options.PageHeight > 0) sb_params.Append(" --page-height ").Append(options.PageHeight);
            if (!string.IsNullOrEmpty(options.PageSize)) sb_params.Append(" --page-size ").Append(options.PageSize);
            if (!string.IsNullOrEmpty(options.CookieName)) sb_params.Append(" --cookie ").Append(options.CookieName).Append(' ').Append(options.CookieValue);

            param_options = sb_params.ToString();
        }

        ProcessStartInfo psi = new ProcessStartInfo(converter_path, string.Format("{0} \"{1}\" \"{2}\"", param_options.Trim(), url, file_out));

        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;

        Process proc = new Process ();
        proc.StartInfo = psi;
        proc.Start();
        proc.WaitForExit();

        //!= 0) throw new Exception(string.Format("Could not generate {0}", file_out));
    }
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuildProject)
    {
        if (target == BuildTarget.tvOS) {
            UnityEngine.Debug.Log ("[SPIL] Starting custom post process build script." + pathToBuildProject);

            UnityEngine.Debug.Log ("[SPIL] Moving SpilTV.framework to the root of the project");
            MoveDirectory (pathToBuildProject + "/Frameworks/Plugins/tvOS/SpilTV.framework", pathToBuildProject + "/SpilTV.framework");

            bool exportDefaultEntitlements = EditorPrefs.GetBool ("exportDefaultEntitlements");
            bool useICloudContainer = EditorPrefs.GetBool ("useICloudContainer");
            bool useICloudKV = EditorPrefs.GetBool ("useICloudKV");
            bool usePushNotifications = EditorPrefs.GetBool ("usePushNotifications");

            String arguments = "Unity-iPhone " +
                                   exportDefaultEntitlements + " " +
                                   useICloudContainer + " " +
                                   useICloudKV + " " +
                                   usePushNotifications;

            UnityEngine.Debug.Log ("[SPIL] Executing: python " + pathToBuildProject + "/SpilTV.framework/setup.py " + arguments);
            Process setupProcess = new Process ();
            setupProcess.StartInfo.WorkingDirectory = pathToBuildProject;
            setupProcess.StartInfo.FileName = "python";
            setupProcess.StartInfo.Arguments = "SpilTV.framework/setup.py " + arguments;
            setupProcess.StartInfo.UseShellExecute = false;
            setupProcess.StartInfo.RedirectStandardOutput = true;
            setupProcess.Start ();
            setupProcess.WaitForExit ();

            UnityEngine.Debug.Log ("[SPIL] --> Setup.py output: " + setupProcess.StandardOutput.ReadToEnd ());

            UnityEngine.Debug.Log ("[SPIL] Custom post process build script finished executing!");
        }
    }
Exemplo n.º 22
0
    static void OnPostprocessAllAssets (string[] ia, string[] da, string[] ma, string[] mfap) {
        // skip if importing dll as already built
        if (Array.IndexOf(ia, "Assets/dll/scripts.dll") > -1) return;

        // setup the process
        var p = new Process();
        p.StartInfo.FileName = "/usr/bin/make";
        p.StartInfo.Arguments = "-C " + System.IO.Directory.GetCurrentDirectory() + "/Assets/Editor/";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;

        // assign events
        p.OutputDataReceived +=
            new DataReceivedEventHandler((o, e) => {
                if (e.Data != null) {
                    UnityEngine.Debug.Log(e.Data);
                }
            });
        p.ErrorDataReceived +=
            new DataReceivedEventHandler((o, e) => {
                if (e.Data != null) {
                    UnityEngine.Debug.LogError(e.Data);
                }
            });

        // start to process and output/error reading
        p.Start();
        p.BeginOutputReadLine();
        p.BeginErrorReadLine();
    }
Exemplo n.º 23
0
        public IndexInterleaveAbstract(Process processBase, Expression range)
        {
            Processes = new List<Process>();
            Processes.Add(processBase);

            RangeExpression = range;
        }
    public Magellan()
    {
        MsgDelegate = new MsgRecv(this.MsgRecvMethod);
        this.FormClosing += new FormClosingEventHandler(FormClosingMethod);

        ArrayList conf = ReadConfig();
        sph = new SerialPortHandler[conf.Count];
        for(int i = 0; i < conf.Count; i++){
            string port = ((string[])conf[i])[0];
            string module = ((string[])conf[i])[1];

            Type t = Type.GetType("SPH."+module+", SPH, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");

            sph[i] = (SerialPortHandler)Activator.CreateInstance(t, new Object[]{ port });
            sph[i].SetParent(this);
        }
        MonitorSerialPorts();

        browser_window = Process.Start("iexplore.exe",
                "http://localhost/");

        u = new UDPMsgBox(9450);
        u.SetParent(this);
        u.My_Thread.Start();
    }
    private static CommandExecResult RunCommand(String processName, String args)
    {
        Process p = new Process();
        string output = "";

        p.StartInfo.FileName = processName;
        p.StartInfo.WorkingDirectory = "..";
        p.StartInfo.Arguments = args;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        try
        {
            p.Start();

            output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            System.Environment.Exit(1);
        }

        CommandExecResult cmdResult;
        cmdResult.exitCode = p.ExitCode;
        cmdResult.stdOut = output;

        return cmdResult;
    }
Exemplo n.º 26
0
    static string CompileScript(string scriptFile)
    {
        string retval = "";
        StringBuilder sb = new StringBuilder();

        Process myProcess = new Process();
        myProcess.StartInfo.FileName = "cscs.exe";
        myProcess.StartInfo.Arguments = "/nl /ca \"" + scriptFile + "\"";
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.RedirectStandardOutput = true;
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.Start();

        string line = null;
        while (null != (line = myProcess.StandardOutput.ReadLine()))
        {
            sb.Append(line);
            sb.Append("\n");
        }
        myProcess.WaitForExit();

        retval = sb.ToString();

        string compiledFile = Path.ChangeExtension(scriptFile, ".csc");

        if (retval == "" && File.Exists(compiledFile))
            File.Delete(compiledFile);

        return retval;
    }
    static void Main()
    {
        try
        {
            string[] words = { "testAmigo", "middle - Game", "test" };
            string txtFile = @"..\..\textFile.txt";
            RandomizationFile(words, txtFile);
            DeletesText(txtFile);

            Process openfile = new Process();
            openfile.StartInfo.FileName = txtFile;
            openfile.Start();
        }
        catch (FileNotFoundException FNFE)
        {
            Console.WriteLine(FNFE.Message);
        }
        catch (NullReferenceException NRE)
        {
            Console.WriteLine(NRE.Message);
        }
        catch (ArgumentNullException ANE)
        {
            Console.WriteLine(ANE.Message);
        }
        catch (IOException IOE)
        {
            Console.WriteLine(IOE.Message);
        }
        finally
        {
            Console.WriteLine("Good Bye");
        }
    }
Exemplo n.º 28
0
 public void Sleepify(Process p, long duration)
 {
     p.timeToWake = DateTime.Now.AddMilliseconds(duration).Ticks;
     p.State = ProcessState.Sleeping;
     // Put them in makeshift queue, where last element = front of the queue
     timerWaiting.InsertSorted(p, (p1, p2) => (int)(p2.timeToWake - p1.timeToWake));
 }
Exemplo n.º 29
0
 public static void ExecuteMethod_ObtainLockRemoveFromContainerAndDeleteProcess(string processID, Process process, ProcessContainer ownerProcessContainer)
 {
     if (process == null)
     {
         if (ownerProcessContainer != null && ownerProcessContainer.ProcessIDs != null)
         {
             ownerProcessContainer.ProcessIDs.Remove(processID);
             ownerProcessContainer.StoreInformation();
         }
     }
     else
     {
         string lockEtag = process.ObtainLockOnObject();
         if (lockEtag == null)
             return;
         try
         {
             if (ownerProcessContainer != null)
             {
                 ownerProcessContainer.ProcessIDs.Remove(process.ID);
                 ownerProcessContainer.StoreInformation();
             }
             process.DeleteInformationObject();
         }
         finally
         {
             process.ReleaseLockOnObject(lockEtag);
         }
     }
 }
Exemplo n.º 30
0
 private void menuItemCreateProcess_Click(object sender, EventArgs e)
 {
     OpenFileDialog ofDlg = new OpenFileDialog();
     ofDlg.Filter = "可执行文件|*.exe";
     if (ofDlg.ShowDialog() == DialogResult.OK)
     {
         Process newProcess = new Process();
         try
         {
             newProcess.StartInfo.UseShellExecute = false;
             newProcess.StartInfo.FileName = ofDlg.FileName;
             newProcess.StartInfo.CreateNoWindow = true;
             newProcess.Start();
             if (newProcess != null)
             {
                 newProcess.EnableRaisingEvents = true;
                 newProcess.Exited += new EventHandler(OnProcessExited);
                 newProcess.WaitForExit();
             }
             ListAllProcesss();
         }
         catch (ArgumentException ex)
         {
             MessageBox.Show(ex.Message, "参数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Exemplo n.º 31
0
        private static byte[] GetSystemData()
        {
            MemoryStream ms = new MemoryStream();

            byte[] pb;

            pb = MemUtil.Int32ToBytes(Environment.TickCount);
            MemUtil.Write(ms, pb);

            pb = MemUtil.Int64ToBytes(DateTime.UtcNow.ToBinary());
            MemUtil.Write(ms, pb);

#if !KeePassLibSD
            // In try-catch for systems without GUI;
            // https://sourceforge.net/p/keepass/discussion/329221/thread/20335b73/
            try
            {
                Point pt = Cursor.Position;
                pb = MemUtil.Int32ToBytes(pt.X);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int32ToBytes(pt.Y);
                MemUtil.Write(ms, pb);
            }
            catch (Exception) { }
#endif

            pb = MemUtil.UInt32ToBytes((uint)NativeLib.GetPlatformID());
            MemUtil.Write(ms, pb);

            try
            {
#if KeePassUAP
                string strOS = EnvironmentExt.OSVersion.VersionString;
#else
                string strOS = Environment.OSVersion.VersionString;
#endif
                AddStrHash(ms, strOS);

                pb = MemUtil.Int32ToBytes(Environment.ProcessorCount);
                MemUtil.Write(ms, pb);

#if !KeePassUAP
                AddStrHash(ms, Environment.CommandLine);

                pb = MemUtil.Int64ToBytes(Environment.WorkingSet);
                MemUtil.Write(ms, pb);
#endif
            }
            catch (Exception) { Debug.Assert(false); }

            try
            {
                foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
                {
                    AddStrHash(ms, (de.Key as string));
                    AddStrHash(ms, (de.Value as string));
                }
            }
            catch (Exception) { Debug.Assert(false); }

#if KeePassUAP
            pb = DiagnosticsExt.GetProcessEntropy();
            MemUtil.Write(ms, pb);
#elif !KeePassLibSD
            Process p = null;
            try
            {
                p = Process.GetCurrentProcess();

                pb = MemUtil.Int64ToBytes(p.Handle.ToInt64());
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int32ToBytes(p.HandleCount);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int32ToBytes(p.Id);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.NonpagedSystemMemorySize64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.PagedMemorySize64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.PagedSystemMemorySize64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.PeakPagedMemorySize64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.PeakVirtualMemorySize64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.PeakWorkingSet64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.PrivateMemorySize64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.StartTime.ToBinary());
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.VirtualMemorySize64);
                MemUtil.Write(ms, pb);
                pb = MemUtil.Int64ToBytes(p.WorkingSet64);
                MemUtil.Write(ms, pb);

                // Not supported in Mono 1.2.6:
                // pb = MemUtil.UInt32ToBytes((uint)p.SessionId);
                // MemUtil.Write(ms, pb);
            }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }
            finally
            {
                try { if (p != null)
                      {
                          p.Dispose();
                      }
                }
                catch (Exception) { Debug.Assert(false); }
            }
#endif

            try
            {
                CultureInfo ci = CultureInfo.CurrentCulture;
                if (ci != null)
                {
                    pb = MemUtil.Int32ToBytes(ci.GetHashCode());
                    MemUtil.Write(ms, pb);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
            catch (Exception) { Debug.Assert(false); }

            pb = Guid.NewGuid().ToByteArray();
            MemUtil.Write(ms, pb);

            byte[] pbAll = ms.ToArray();
            ms.Close();
            return(pbAll);
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((4 + 2 >= 42))
            {
                {}
            }
            else if (!(4 + 2 >= 42))
            {
                StringBuilder text = new StringBuilder(tainted_2);
                text.Replace("&", "&amp;");
                text.Replace("'", "&apos;");
                text.Replace(@"""", "&quot;");
                text.Replace("<", "&lt;");
                text.Replace(">", "&gt;");
                tainted_3 = text.ToString();
            }
            else
            {
                {}
            }

            //flaw

            string query = "SELECT * FROM Articles WHERE id=" + tainted_3;


            SQLiteConnection dbConnection = null;

            try{
                dbConnection = new SQLiteConnection("data source=C:\\data");
                SQLiteCommand    command = new SQLiteCommand(query, dbConnection);
                SQLiteDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            }catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 33
0
        public virtual bool?ShowDialog(IntPtr owner, bool throwOnError = false)
        {
            var dialog = (IFileOpenDialog) new FileOpenDialog();

            if (!string.IsNullOrEmpty(InputPath))
            {
                if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out var item), throwOnError) != 0)
                {
                    return(null);
                }
                dialog.SetFolder(item);
            }
            var options = FOS.FOS_PICKFOLDERS;

            options = (FOS)SetOptions((int)options);
            dialog.SetOptions(options);
            if (Title != null)
            {
                dialog.SetTitle(Title);
            }
            if (OkButtonLabel != null)
            {
                dialog.SetOkButtonLabel(OkButtonLabel);
            }
            if (FileNameLabel != null)
            {
                dialog.SetFileName(FileNameLabel);
            }
            if (owner == IntPtr.Zero)
            {
                owner = Process.GetCurrentProcess().MainWindowHandle;
                if (owner == IntPtr.Zero)
                {
                    owner = GetDesktopWindow();
                }
            }
            var hr = dialog.Show(owner);

            if (hr == ERROR_CANCELLED)
            {
                return(null);
            }
            if (CheckHr(hr, throwOnError) != 0)
            {
                return(null);
            }
            if (CheckHr(dialog.GetResult(out var result), throwOnError) != 0)
            {
                return(null);
            }
            if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var path), throwOnError) != 0)
            {
                return(null);
            }
            ResultPath = path;
            if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out path), false) == 0)
            {
                ResultName = path;
            }
            return(true);
        }
Exemplo n.º 34
0
 private void BTN_OPEN_HISTORY_FOLDER_Click(object sender, EventArgs e)
 {
     Process.Start(m_fm.param_path.i07_PATH_HIST_MEASURE);
 }
Exemplo n.º 35
0
        public override void OnActivated(string invokedArgs, NotificationUserInput userInput, string appUserModelId)
        {
            var dict = new Dictionary<string, string>();
            var splitArgs = invokedArgs.Split("&");
            foreach (var arg in splitArgs)
            {
                if (arg.Contains("="))
                {
                    var split = arg.Split("=");
                    dict.Add(split[0], split[1]);
                }
            }

            if (dict.ContainsKey("action"))
            {

                switch (dict["action"])
                {
                    case "viewUrl":
                        if (dict.ContainsKey("url"))
                        {
                            dict["url"].OpenUrl();
                        }

                        break;
                    case "viewUpdate":
                        var subscribe = bool.Parse(dict["subscribeAlphaBeta"]);
                        var updateForm = new UpdateForm(dict["changes"], subscribe, dict["installerUrl"], dict["version"]);
                        updateForm.ShowDialog();
                        break;
                    case "openDirectory":
                        var directory = dict["path"];
                        var process = new Process
                        {
                            StartInfo = new ProcessStartInfo
                            {
                                FileName = "explorer.exe",
                                Arguments = $"/select, \"{directory}\"",
                                UseShellExecute = true
                            }
                        };
                        process.Start();
                        process.Dispose();
                        break;
                    case "snoozeUpdate":
                        if (userInput.ContainsKey("snooze"))
                        {
                            var value = userInput["snooze"];
                            // Transform key to datetime.
                            var timeToSnooze = value switch
                            {
                                "6h" => TimeSpan.FromHours(6),
                                "12h" => TimeSpan.FromHours(12),
                                "1d" => TimeSpan.FromDays(1),
                                "3d" => TimeSpan.FromDays(3),
                                "1w" => TimeSpan.FromDays(7),
                                _ => TimeSpan.FromDays(1)
                            };

                            Updater.TimeToCheck = (int)timeToSnooze.TotalMilliseconds;
                            Updater.CheckForUpdates();
                        }

                        break;
                    case "uploadVideo":
                        var videoPath = dict["path"];
                        var uploader = Program.ServiceProvider.GetService<Uploader>();
                        if (uploader is { })
                        {
                            uploader.AddToQueue(new FileShell(videoPath));
                        }

                        break;
 private void moreinfoLiveEncodingProfilelink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     // Send the URL to the operating system.
     Process.Start(e.Link.LinkData as string);
 }
Exemplo n.º 37
0
 private void NewRewriteRuleDialogHelpButtonClicked(object sender, CancelEventArgs e)
 {
     Process.Start("http://go.microsoft.com/fwlink/?LinkID=130421&amp;clcid=0x409");
 }
Exemplo n.º 38
0
        public ShellViewModel(
            IAppCommands appCommander,
            IWindowManagerEx windowManager,
            EndpointExplorerViewModel endpointExplorer,
            MessageListViewModel messages,
            Func<ServiceControlConnectionViewModel> serviceControlConnection,
            Func<LicenseRegistrationViewModel> licenceRegistration,
            StatusBarManager statusBarManager,
            IEventAggregator eventAggregator,
            AppLicenseManager licenseManager,
            MessageFlowViewModel messageFlow,
            SagaWindowViewModel sagaWindow,
            MessageBodyViewModel messageBodyViewer,
            MessageHeadersViewModel messageHeadersViewer,
            SequenceDiagramViewModel sequenceDiagramViewer,
            ISettingsProvider settingsProvider,
            MessagePropertiesViewModel messageProperties,
            LogWindowViewModel logWindow,
            CommandLineArgParser comandLineArgParser)
        {
            this.appCommander = appCommander;
            this.windowManager = windowManager;
            this.eventAggregator = eventAggregator;
            this.licenseManager = licenseManager;
            this.settingsProvider = settingsProvider;
            this.comandLineArgParser = comandLineArgParser;
            this.serviceControlConnection = serviceControlConnection;
            this.licenceRegistration = licenceRegistration;
            MessageProperties = messageProperties;
            MessageFlow = messageFlow;
            SagaWindow = sagaWindow;
            StatusBarManager = statusBarManager;
            EndpointExplorer = endpointExplorer;
            MessageHeaders = messageHeadersViewer;
            MessageBody = messageBodyViewer;
            SequenceDiagram = sequenceDiagramViewer;
            Messages = messages;
            LogWindow = logWindow;

            Items.Add(endpointExplorer);
            Items.Add(messages);
            Items.Add(messageHeadersViewer);
            Items.Add(messageBodyViewer);
            Items.Add(messageFlow);

            InitializeAutoRefreshTimer();
            InitializeIdleTimer();

            ShutDownCommand = this.CreateCommand(() => this.appCommander.ShutdownImmediately());
            AboutCommand = this.CreateCommand(() => this.windowManager.ShowDialog<AboutViewModel>());
            HelpCommand = this.CreateCommand(() => Process.Start(@"http://docs.particular.net/serviceinsight"));
            ConnectToServiceControlCommand = this.CreateCommand(ConnectToServiceControl, vm => vm.CanConnectToServiceControl);

            RefreshAllCommand = this.CreateCommand(RefreshAll);

            RegisterCommand = this.CreateCommand(() =>
            {
                this.windowManager.ShowDialog<LicenseRegistrationViewModel>();
                DisplayRegistrationStatus();
            });

            ResetLayoutCommand = this.CreateCommand(() => View.OnResetLayout(settingsProvider));

            OptionsCommand = this.CreateCommand(() => windowManager.ShowDialog<OptionsViewModel>());
        }
Exemplo n.º 39
0
		private void btnFork_Click(object sender, EventArgs e)
		{
			Process.Start(Application.ExecutablePath);
		}
Exemplo n.º 40
0
 public static Architecture GetArchitecture(this Process process)
 => NativeMethods.IsProcess64BitWithoutException(process ?? throw new ArgumentNullException(nameof(process)))
Exemplo n.º 41
0
    public static Task<MemoryStream> decodeAudio(string file, int format)
    {
        string dec = string.Empty;
        string args = string.Empty;
        string tempFilename = "temp.wav";
        if (DLNAPlayer.Properties.Settings.Default.UseFFMPEG)
        {
            dec = "ffmpeg.exe";
            if (DLNAPlayer.Properties.Settings.Default.DecodeToFLAC)
            {
                tempFilename = "temp.flac";
                args = "-i \"" + file + "\" " + tempFilename + " -y";
            }
            else
            {
                args = "-i \"" + file + "\" " + tempFilename + " -y";
            }
        }
        else
            switch (format)
            {
                case 1:
                    dec = "opusdec.exe";
                    args = "--rate 48000 --no-dither --float \"" + file + "\" " + tempFilename;
                    break;
                case 2:
                    dec = "flac.exe";
                    args = "-d \"" + file + "\" -o " + tempFilename;
                    break;
                case 3:
                    dec = "ffmpeg.exe";
                    args = "-i \"" + file + "\" " + tempFilename + " -y";
                    break;
            }
        ProcessStartInfo decProcessInfo = new ProcessStartInfo()
        {
            FileName = dec,
            Arguments = args,
            CreateNoWindow = true,
            RedirectStandardOutput = false,
            UseShellExecute = false
        };
        Process.Start(decProcessInfo).WaitForExit();
        MemoryStream decodedWav = new MemoryStream();
        bool decoded = false;
        while (!decoded)
        {
            try
            {
                FileStream temp = new FileStream(tempFilename, FileMode.Open);
                temp.CopyTo(decodedWav);
                temp.Close();
                decoded = true;
            }
            catch
            {
                decoded = false;
            }
        }

        File.Delete(tempFilename);
        return Task.FromResult<MemoryStream>(decodedWav);
    }
Exemplo n.º 42
0
 private void mnuReportBug_Click(object sender, EventArgs e)
 {
     Process.Start("https://www.mesen.ca/snes/ReportBug.php");
 }
Exemplo n.º 43
0
        public static void Run()
        {
            // Create the consumer session
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = "ZGIXM2M1Y2RIZJGYNGY1Y2EWZGYZMW",
                ConsumerSecret              = "RZRCMBRPK57EAG6GRO4GPLYDH9REPX",
                SignatureMethod             = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true,
                UserAgent = string.Format("Xero.API.ScreenCast v1.0 (Public App Testing)")
            };

            OAuthSession consumerSession = new OAuthSession(
                consumerContext,
                Settings.Default.RequestTokenURI,
                Settings.Default.AuthoriseURI,
                Settings.Default.AccessTokenURI);

            // 1. Get a request token
            IToken requestToken = consumerSession.GetRequestToken();

            Console.WriteLine("Request Token Key: {0}", requestToken.Token);
            Console.WriteLine("Request Token Secret: {0}", requestToken.TokenSecret);


            // 2. Get the user to log into Xero using the request token in the querystring
            //string authorisationUrl = Settings.Default.AuthoriseURI.AbsoluteUri + "?oauth_token=" + HttpUtility.UrlEncode(requestTokenKey);
            string authorisationUrl = consumerSession.GetUserAuthorizationUrlForToken(requestToken);

            Process.Start(authorisationUrl);

            // 3. Get the use to enter the authorisation code from Xero (4-7 digit number)
            Console.WriteLine("Please input the code you were given in Xero:");
            var verificationCode = Console.ReadLine();

            if (string.IsNullOrEmpty(verificationCode))
            {
                Console.WriteLine("You didn't type a verification code!");
                return;
            }

            verificationCode = verificationCode.Trim();


            // 4. Use the request token and verification code to get an access token
            IToken accessToken;

            try
            {
                accessToken = consumerSession.ExchangeRequestTokenForAccessToken(requestToken, verificationCode);
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }

            Console.WriteLine("Access Token Key: {0}", accessToken.Token);
            Console.WriteLine("Access Token Secret: {0}", accessToken.TokenSecret);


            // 5. Make a call to api.xero.com to check that we can use the access token.
            IConsumerRequest getOrganisationRequest = consumerSession
                                                      .Request()
                                                      .ForMethod("GET")
                                                      .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Organisation"))
                                                      .SignWithToken(accessToken);

            string getOrganisationResponse = getOrganisationRequest.ToString();

            if (getOrganisationResponse != string.Empty)
            {
                var    organisationXml  = XElement.Parse(getOrganisationResponse);
                string organisationName = organisationXml.XPathSelectElement("//Organisation/Name").Value;
                Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisationName));
            }


            // 6. Make a PUT call to the API - add a dummy contact
            Console.WriteLine("Please enter the name of a new contact to add to Xero");
            string contactName = Console.ReadLine();

            if (string.IsNullOrEmpty(contactName))
            {
                return;
            }

            string putContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name></Contact></Contacts>", contactName);
            string putContactResponse;

            IConsumerRequest putContactRequest = consumerSession
                                                 .Request()
                                                 .ForMethod("PUT")
                                                 .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                                                 .WithFormParameters(new { xml = putContactRequestBody })
                                                 .SignWithToken(accessToken);

            try
            {
                putContactResponse = putContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (putContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(putContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string contactId = responseElement.XPathSelectElement("/Contacts/Contact[1]/ContactID").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contactName, contactId));
                }
            }


            // 7. Try to update the contact that's just been created, but this time use a POST method
            string postContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name><EmailAddress>{1}@nowhere.com</EmailAddress></Contact></Contacts>", contactName, contactName.ToLower().Replace(" ", "."));
            string postContactResponse;

            IConsumerRequest postContactRequest = consumerSession
                                                  .Request()
                                                  .ForMethod("POST")
                                                  .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                                                  .WithFormParameters(new { xml = postContactRequestBody })
                                                  .SignWithToken(accessToken);

            try
            {
                postContactResponse = postContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (postContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(postContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string emailAddress = responseElement.XPathSelectElement("/Contacts/Contact[1]/EmailAddress").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contactName, emailAddress));
                }
            }
        }
Exemplo n.º 44
0
        private static string GetParentProcessName()
        {
            var parentProcess = ParentProcessUtils.GetParentProcess(Process.GetCurrentProcess());

            return(parentProcess == null ? string.Empty : parentProcess.ProcessName);
        }
Exemplo n.º 45
0
        /// <summary>
        /// OVPN changes it status.
        /// Show or hide elements.
        /// </summary>
        /// <param name="sender">ignored</param>
        /// <param name="e">the new state</param>
        /// <seealso cref="stateChanged"/>
        void State_StateChanged(object sender, StateChangedEventArgs e)
        {
            try
            {
                if (m_parent.InvokeRequired)
                {
                    m_parent.BeginInvoke(
                        new EventHandler <StateChangedEventArgs>(
                            State_StateChanged), sender, e);
                    return;
                }
            }
            catch (ObjectDisposedException)
            {
                return;
            }

            switch (e.NewState.ConnectionState)
            {
            case VPNConnectionState.Initializing:
                m_menu_disconnect.Visible = true;
                m_menu_connect.Visible    = false;
                m_menu.Image = Properties.Resources.STATE_Initializing;
                break;

            case VPNConnectionState.Running:

                m_menu_disconnect.Visible = true;
                m_menu_connect.Visible    = false;
                m_menu.Image = Properties.Resources.STATE_Running;

                // show assigned ip if possible
                string text = ProgramVPN.res.GetString("STATE_Connected");
                if (m_vpn.IP != null)
                {
                    text += Environment.NewLine +
                            "IP: " + m_vpn.IP;
                }

                //m_parent.ShowPopup(Name, text);
                break;

            case VPNConnectionState.Stopped:
                m_menu_disconnect.Visible = false;
                m_menu_connect.Visible    = true;
                m_menu.Image = Properties.Resources.STATE_Stopped;
                break;

            case VPNConnectionState.Stopping:
                m_menu_disconnect.Visible = false;
                m_menu_connect.Visible    = false;
                m_menu.Image = Properties.Resources.STATE_Stopping;
                break;

            case VPNConnectionState.Error:
            default:
                m_menu_disconnect.Visible = false;
                m_menu_connect.Visible    = true;
                m_menu.Image = Properties.Resources.STATE_Error;

                if (m_vpn.LogFile != null)
                {
                    if (RTLMessageBox.Show(m_status,
                                           ProgramVPN.res.GetString("BOX_VPN_Error"),
                                           MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button2,
                                           MessageBoxIcon.Error) == DialogResult.Yes)
                    {
                        ProcessStartInfo pi = new ProcessStartInfo();
                        pi.Arguments       = "\"" + m_vpn.LogFile + "\"";
                        pi.ErrorDialog     = true;
                        pi.FileName        = "notepad.exe";
                        pi.UseShellExecute = true;


                        Process.Start(pi);
                    }
                }
                else
                {
                    RTLMessageBox.Show(m_status,
                                       ProgramVPN.res.GetString("BOX_VPNS_Error"),
                                       MessageBoxButtons.OK, MessageBoxDefaultButton.Button2,
                                       MessageBoxIcon.Error);
                }
                break;
            }

            //m_parent.SetTrayIconAndPopupText();
        }
Exemplo n.º 46
0
        /// <summary>
        ///     设置绕行规则
        /// </summary>
        /// <returns>是否设置成功</returns>
        private void SetupRouteTable()
        {
            Global.MainForm.StatusText(i18N.Translate("SetupBypass"));

            Logging.Info("绕行 → 全局绕过 IP");
            _directIPs.AddRange(Global.Settings.BypassIPs.Select(IPNetwork.Parse));

            Logging.Info("绕行 → 服务器 IP");
            if (!IPAddress.IsLoopback(_serverAddresses))
            {
                _directIPs.Add(IPNetwork.Parse(_serverAddresses.ToString(), 32));
            }

            Logging.Info("绕行 → 局域网 IP");
            _directIPs.AddRange(_bypassLanIPs.Select(IPNetwork.Parse));

            switch (_savedMode.Type)
            {
            case 1:
                // 代理规则
                Logging.Info("代理 → 规则 IP");
                _proxyIPs.AddRange(_savedMode.FullRule.Select(IPNetwork.Parse));

                //处理 NAT 类型检测,由于协议的原因,无法仅通过域名确定需要代理的 IP,自己记录解析了返回的 IP,仅支持默认检测服务器
                if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
                {
                    try
                    {
                        Logging.Info("代理 → STUN 服务器 IP");
                        _proxyIPs.AddRange(new[]
                        {
                            Dns.GetHostAddresses(Global.Settings.STUN_Server)[0],
                            Dns.GetHostAddresses("stunresponse.coldthunder11.com")[0]
                        }.Select(ip => IPNetwork.Parse(ip.ToString(), 32)));
                    }
                    catch
                    {
                        Logging.Info("NAT 类型测试域名解析失败,将不会被添加到代理列表");
                    }
                }

                if (Global.Settings.TUNTAP.ProxyDNS)
                {
                    Logging.Info("代理 → 自定义 DNS");
                    if (Global.Settings.TUNTAP.UseCustomDNS)
                    {
                        _proxyIPs.AddRange(Global.Settings.TUNTAP.DNS.Select(ip => IPNetwork.Parse(ip, 32)));
                    }
                    else
                    {
                        _proxyIPs.AddRange(new[] { "1.1.1.1", "8.8.8.8", "9.9.9.9", "185.222.222.222" }.Select(ip => IPNetwork.Parse(ip, 32)));
                    }
                }

                break;

            case 2:
                // 绕过规则

                // 将 TUN/TAP 网卡权重放到最高
                Process.Start(new ProcessStartInfo
                {
                    FileName        = "netsh",
                    Arguments       = $"interface ip set interface {Global.TUNTAP.Index} metric=0",
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = true,
                    CreateNoWindow  = true
                }
                              );

                Logging.Info("绕行 → 规则 IP");
                _directIPs.AddRange(_savedMode.FullRule.Select(IPNetwork.Parse));

                Logging.Info("代理 → 全局");

                if (!RouteAction(Action.Create, IPNetwork.Parse("0.0.0.0", 0), RouteType.TUNTAP))
                {
                    State = State.Stopped;
                    return;
                }

                break;
            }

            Logging.Info("设置路由规则");
            RouteAction(Action.Create, _directIPs, RouteType.Outbound);
            RouteAction(Action.Create, _proxyIPs, RouteType.TUNTAP);
        }
Exemplo n.º 47
0
        public async Task <IState> Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            await CleanupOldFiles();

            var autoUpdate = session.LogicSettings.AutoUpdate;
            var isLatest   = IsLatest();

            if (isLatest || !autoUpdate)
            {
                if (isLatest)
                {
                    session.EventDispatcher.Send(new UpdateEvent
                    {
                        Message =
                            session.Translation.GetTranslation(TranslationString.GotUpToDateVersion, Assembly.GetEntryAssembly().GetName().Version.ToString(3))
                    });
                    return(new LoginState());
                }
                session.EventDispatcher.Send(new UpdateEvent
                {
                    Message = session.Translation.GetTranslation(TranslationString.AutoUpdaterDisabled, LatestRelease)
                });

                return(new LoginState());
            }
            else
            {
                Logger.Write("New update detected, would you like to update? Y/N", LogLevel.Update);

                bool boolBreak = false;
                while (!boolBreak)
                {
                    string strInput = Console.ReadLine().ToLower();

                    switch (strInput)
                    {
                    case "y":
                        boolBreak = true;
                        break;

                    case "n":
                        Logger.Write("Update Skipped", LogLevel.Update);
                        return(new LoginState());

                    default:
                        Logger.Write(session.Translation.GetTranslation(TranslationString.PromptError, "Y", "N"), LogLevel.Error);
                        continue;
                    }
                }
            }

            session.EventDispatcher.Send(new UpdateEvent
            {
                Message = session.Translation.GetTranslation(TranslationString.DownloadingUpdate)
            });
            var remoteReleaseUrl =
                $"https://github.com/NecronomiconCoding/NecroBot/releases/download/v{RemoteVersion}/";
            const string zipName          = "Release.zip";
            var          downloadLink     = remoteReleaseUrl + zipName;
            var          baseDir          = Directory.GetCurrentDirectory();
            var          downloadFilePath = Path.Combine(baseDir, zipName);
            var          tempPath         = Path.Combine(baseDir, "tmp");
            var          extractedDir     = Path.Combine(tempPath, "Release");
            var          destinationDir   = baseDir + Path.DirectorySeparatorChar;

            Console.WriteLine(downloadLink);

            if (!DownloadFile(downloadLink, downloadFilePath))
            {
                return(new LoginState());
            }

            session.EventDispatcher.Send(new UpdateEvent
            {
                Message = session.Translation.GetTranslation(TranslationString.FinishedDownloadingRelease)
            });

            if (!UnpackFile(downloadFilePath, tempPath))
            {
                return(new LoginState());
            }

            session.EventDispatcher.Send(new UpdateEvent
            {
                Message = session.Translation.GetTranslation(TranslationString.FinishedUnpackingFiles)
            });

            if (!MoveAllFiles(extractedDir, destinationDir))
            {
                return(new LoginState());
            }

            session.EventDispatcher.Send(new UpdateEvent
            {
                Message = session.Translation.GetTranslation(TranslationString.UpdateFinished)
            });

            if (TransferConfig(baseDir, session))
            {
                Utils.ErrorHandler.ThrowFatalError(session.Translation.GetTranslation(TranslationString.FinishedTransferringConfig), 5, LogLevel.Update);
            }

            Process.Start(Assembly.GetEntryAssembly().Location);
            Environment.Exit(-1);
            return(null);
        }
Exemplo n.º 48
0
        public static void MakeReport()
        {
            var teams = File.ReadLines("teams.csv")
                        .Skip(1)
                        .Select(z => z.Split(';'))
                        .Select(z => new { name = z[0], id = int.Parse(z[1]), team = z[2] })
                        .ToList();

            var extract = Json.Read <List <TournamentParticipantExtraction> >("extract.json")
                          .ToDictionary(z => z.Participant.Id, z => z);
            var verify = Json.Read <List <TournamentVerificationResult> >("verify.json")
                         .ToDictionary(z => z.Participant.Id, z => z);

            var results = File.ReadLines("results.json").Select(JsonConvert.DeserializeObject <TournamentGameResult>)
                          .GroupBy(z => z.Task.Participants[0].Id)
                          .ToDictionary(z => z.Key, z => z);

            var report = new List <UserReport>();

            foreach (var e in teams)
            {
                var r = new UserReport();
                r.Name   = e.name;
                r.Team   = e.team;
                r.TeamId = e.id;

                if (extract.ContainsKey(e.id))
                {
                    r.Extraction = extract[e.id].Status;
                }
                if (verify.ContainsKey(e.id))
                {
                    r.Verification = verify[e.id].Status;
                }
                if (results.ContainsKey(e.id))
                {
                    r.Results = results[e.id]
                                .Select(z => z.Result.ScoresByPlayer["Left"].Where(x => x.Key == "Main").Select(x => x.Value).First())
                                .ToArray();
                    r.Average = r.Results.Average();
                }
                report.Add(r);
            }

            using (var wr = new StreamWriter("report.html"))
            {
                wr.WriteLine("<!DOCTYPE html>\n<meta charset=\"UTF-8\">\n<html><body><table>");
                wr.WriteLine("<tr><th>ФИО</th><th>Команда</th><th>ИД команды</th><th>Формат</th><th>Прозвон</th><th>Игра 1</th><th>Игра 2</th><th>Игра 3</th><th>Среднее</th><tr>");
                foreach (var e in report.OrderByDescending(z => z.Average).ThenBy(z => !z.Extraction.HasValue).ThenBy(z => z.TeamId))
                {
                    wr.WriteLine($"<tr><td>{e.Name}</td><td>{e.Team}</td><td>{e.TeamId}</td><td>{e.Extraction}</td><td>{e.Verification}</td>");
                    for (int i = 0; i < 3; i++)
                    {
                        wr.WriteLine("<td>");
                        if (e.Results != null && e.Results.Length > i)
                        {
                            wr.WriteLine(e.Results[i]);
                        }
                        wr.WriteLine("</td>");
                    }
                    wr.WriteLine($"<td>{e.Average.ToString("0.00")}</td></tr>");
                }
                wr.WriteLine("</table></body></html>");
            }
            Process.Start("report.html");
        }
Exemplo n.º 49
0
        private void buttonEditFlow_Click(object sender, EventArgs e)
        {
            string flowFilePath = textBoxFlowFile.Text;

            Process.Start(flowFilePath);
        }
Exemplo n.º 50
0
 public static void Cleanup()
 {
     if (false)
         foreach (var process in Process.GetProcessesByName(ADB_EXEC.Replace(".exe", "")))
             process.Kill();
 }
Exemplo n.º 51
0
        public void ViewFile(FileEntry entry, PackageFileEntry be = null)
        {
            try
            {
                Console.WriteLine(entry.BundleEntries.Count);
                if (entry.BundleEntries.Count == 0)
                {
                    return;
                }

                string          typ      = Definitions.TypeFromExtension(entry._extension.ToString());
                FormatConverter exporter = null;

                if (ScriptActions.Converters.ContainsKey(typ))
                {
                    //  if(ScriptActions.Converters[typ].Count > 1)
                    // {
                    SaveOptionsDialog dlg    = new SaveOptionsDialog(typ);
                    DialogResult      dlgres = dlg.ShowModal();

                    if (dlgres == DialogResult.Cancel)
                    {
                        return;
                    }

                    exporter = dlg.SelectedExporter;
                    //  }
                }

                //Thread thread = new Thread(() =>
                //{
                TempFile temp = this.GetTempFile(entry, be, exporter);
                //{
                GC.Collect();
                ProcessStartInfo pi = new ProcessStartInfo(temp.Path);

                pi.UseShellExecute = true;
                if (General.IsLinux)
                {
                    pi.Arguments = temp.Path;
                    pi.FileName  = "xdg-open";
                }
                else
                {
                    pi.FileName = temp.Path;
                }

                Process proc = Process.Start(pi);
                //temp.RunProcess = proc;
                if (!this.TempFiles.ContainsKey(entry))
                {
                    this.TempFiles.Add(entry, temp);
                }

                /*if (proc == null)//seconds -> milliseconds
                 *  Thread.Sleep(20 * 1000);
                 * proc?.WaitForExit();
                 * while((!(proc?.HasExited ?? true)))
                 * { }
                 *
                 * if (General.IsLinux && (proc?.ExitCode == 3 || proc?.ExitCode == 4))
                 *  Console.WriteLine("No default file association for filetype {0}", Path.GetExtension(temp.Path));
                 *
                 * while (!this.IsFileAvailable(temp.Path))
                 * {
                 *  Console.WriteLine("Waiting on file");
                 * }
                 * }
                 * this.TempFiles.Remove(entry);*/
                //});
                //thread.IsBackground = true;
                //thread.Start();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                Console.WriteLine(exc.StackTrace);
            }
        }
Exemplo n.º 52
0
 private static string GetUptime()
 => (DateTime.Now - Process.GetCurrentProcess().StartTime).ToString(@"dd\.hh\:mm\:ss");
Exemplo n.º 53
0
        /// <summary>
        /// Performs the playback of actions in this module.
        /// </summary>
        /// <remarks>You should not call this method directly, instead pass the module
        /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method
        /// that will in turn invoke this method.</remarks>
        void ITestModule.Run()
        {
            if (!Global.SwitchUploadOnly)
            {
                Mouse.DefaultMoveTime        = 300;
                Keyboard.DefaultKeyPressTime = 100;
                Delay.SpeedFactor            = 1.0;

                Global.PhoneNumbertype = "";                 // all types


                // Create the needed classes
                RanorexRepository  repo             = new RanorexRepository();
                fnGetEndTime       GetEndTime       = new fnGetEndTime();
                fnGetStartTime     GetStartTime     = new fnGetStartTime();
                fnPlayWavFile      PlayWavFile      = new fnPlayWavFile();
                fnWriteToLogFile   WriteToLogFile   = new fnWriteToLogFile();
                fnDumpStats        DumpStats        = new fnDumpStats();
                fnWriteToErrorFile WriteToErrorFile = new fnWriteToErrorFile();
                SpeechSynthesizer  Speech           = new SpeechSynthesizer();

                Global.LogFileIndentLevel++;
                Global.LogText = "IN fnDoScenarios";
                WriteToLogFile.Run();

                Global.CurrentIteration = 1;

                if (Global.TimeToStartExecution != "")
                {
                    Global.LogText = "Waiting for start time - IN fnDoScenarios: " + Global.TimeToStartExecution;
                    WriteToLogFile.Run();
                    Report.Log(ReportLevel.Info, "fnDoScenarios", "Waiting for start time: " + Global.TimeToStartExecution, new RecordItemIndex(0));

                    bool TimeToStart = false;
                    while (!TimeToStart)
                    {
                        System.DateTime DateTimeNow = System.DateTime.Now;
                        int             TimeUp      = System.DateTime.Compare(DateTimeNow, Convert.ToDateTime(Global.TimeToStartExecution));
                        if (TimeUp > 0)
                        {
                            TimeToStart = true;
                        }
                    }
                }

                Global.LoopingDone = false;
                while (!Global.LoopingDone)
                {
                    try
                    {
                        DoScenarioLooping();
                    }
                    catch (Exception e)
                    {
                        string sayString = "";
                        if (e.ToString().IndexOf("Thread was being aborted.") == -1)
                        {
                            sayString = e.ToString().Substring(0, 28);
                            Global.TempErrorString = "Ranorex Crashed Message: " + e.Message;
                            WriteToErrorFile.Run();
                            Global.WavFilePath = "RanorexCrashed.wav";
                            PlayWavFile.Run();

                            if (e.ToString().Contains("MemoryException"))
                            {
                                // Write out Tasklist to file in C:\PAL\Reports String.Empty
                                string TimeStampPart = System.DateTime.Now.ToString();
                                TimeStampPart = Regex.Replace(TimeStampPart, @"[/]", "-");
                                TimeStampPart = Regex.Replace(TimeStampPart, @"[:]", "-");
                                TimeStampPart = Regex.Replace(TimeStampPart, @"[ ]", "_");
                                TimeStampPart = "(" + TimeStampPart + ")";
                                string CsvFilename = "Tasklist_(" + Global.RegisterName + ")_" + TimeStampPart;

                                var proc = new Process
                                {
                                    StartInfo = new ProcessStartInfo
                                    {
                                        FileName               = Global.Register1DriveLetter + @":\PAL\Reports\GetTaskList.bat",
                                        Arguments              = CsvFilename,
                                        UseShellExecute        = false,
                                        RedirectStandardOutput = true,
                                        CreateNoWindow         = true,
                                        WorkingDirectory       = Global.Register1DriveLetter + @":\PAL\Reports\"
                                    }
                                };

                                proc.Start();
                            }
                            ;

                            //Report.Snapshot("/form[@controlname='frmWebBrowserHost']");

                            if (Global.DoRegisterSoundAlerts)
                            {
                                Speech.Speak(sayString);
                            }
                            Global.WavFilePath = "Error.wav";
                            PlayWavFile.Run(); PlayWavFile.Run(); PlayWavFile.Run(); PlayWavFile.Run();

                            string ErrorMessage;
                            ErrorMessage   = e.ToString();
                            Global.LogText = @ErrorMessage;
                            WriteToLogFile.Run();

                            MessageBox.Show(e.ToString(), "Ranorex has crashed");

                            fnTearDown Teardown = new fnTearDown();
                            Report.Log(ReportLevel.Info, "Main", "Starting Teardown", new RecordItemIndex(0));
                            TestModuleRunner.Run(Teardown);
                            Report.Log(ReportLevel.Info, "Main", "Teardown Finished", new RecordItemIndex(0));

                            Environment.Exit(0);
                        }
                    }
                }

                Global.LogText = "OUT fnDoScenarios";
                WriteToLogFile.Run();
                Global.LogFileIndentLevel--;
            }
        }
Exemplo n.º 54
0
 private void labelDocumentation_Click(object sender, EventArgs e)
 {
     Process.Start("IExplore.exe", "https://tagui.readthedocs.io/en/latest/index.html");
 }
Exemplo n.º 55
0
 public Task KillTreeAsync(Process process, ILog log, bool?diagnostics = true) => KillTreeAsync(process.Id, log, diagnostics);
Exemplo n.º 56
0
        public bool ConfigureDcmtk(bool install, Profile profile, string currentProfile)
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            profile.version++;

            //determine platform
            var platform = Environment.OSVersion.Platform;

            Console.WriteLine($"OSVersion is {Environment.OSVersion}");
            Console.WriteLine($"{RuntimeInformation.OSDescription}");
            Console.WriteLine($"Processor:{System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture} OS Arch:{System.Runtime.InteropServices.RuntimeInformation.OSArchitecture}");
            Console.WriteLine($"{System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}");
            Console.WriteLine($"Current Profile is {currentProfile}");


            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Console.WriteLine($"Platform is Linux");
                if (install)
                {
                    Console.WriteLine("Linux: dcmtk-3.6.3-linux-x86_64.tar.bz2 will be uncompressed ../LITE/tools/dcmtk/dcmtk-3.6.3-linux-x86_64");

                    //tar -xjvf tools/dcmtk/dcmtk-3.6.3-linux-x86_64.tar.bz2
                    var proc = new Process();
                    ProcessStartInfo procinfo = new ProcessStartInfo
                    {
                        WindowStyle            = ProcessWindowStyle.Hidden,
                        CreateNoWindow         = true,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true,
                        Verb = "runas",

                        //Directory.CreateDirectory("tools/dcmtk/dcmtk-3.6.3-linux-x86_64");
                        Arguments = $"-xjvf tools/dcmtk/dcmtk-3.6.3-linux-x86_64.tar.bz2 -C tools/dcmtk",
                        FileName  = "tar"
                    };
                    proc.StartInfo = procinfo;


                    proc.Start();
                    proc.OutputDataReceived += (object sendingProcess,
                                                DataReceivedEventArgs outLine) =>
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(outLine.Data))
                            {
                                Console.WriteLine($"{outLine.Data}");
                            }
                        }

                        catch (Exception e)
                        {
                            _logger.Log(LogLevel.Information, $"{e.Message}{e.StackTrace}");
                        }
                    };
                    proc.ErrorDataReceived += (object sendingProcess, DataReceivedEventArgs outLine) =>
                    {
                        try
                        {
                            if (!String.IsNullOrEmpty(outLine.Data))
                            {
                                Console.WriteLine($"{outLine.Data}");
                            }
                        }

                        catch (Exception e)
                        {
                            _logger.Log(LogLevel.Information, $"{e.Message}{e.StackTrace}");
                        }
                    };
                    proc.EnableRaisingEvents = true;
                    proc.Exited += (object sender, EventArgs e) =>
                    {
                        Process p = (Process)sender;
                        if (p.ExitCode != 0)
                        {
                            Console.WriteLine($"{((Process)sender).StartInfo.FileName} Proc ExitCode:{proc.ExitCode}");
                        }
                        ;
                    };

                    while (!proc.HasExited)
                    {
                        Console.WriteLine($"{procinfo.FileName} is running...");
                        Task.Delay(1000, _taskManager.cts.Token).Wait();
                    }

                    if (proc.ExitCode != 0)
                    {
                        Console.WriteLine($"Not updating dcmtkLibPath due to extraction error.");
                        return(false);
                    }
                    else
                    {
                        Console.WriteLine($"Updating dcmtkLibPath.");
                        profile.dcmtkLibPath = "tools/dcmtk/dcmtk-3.6.3-linux-x86_64";
                        //profile.Save(currentProfile);
                        _fileProfileWriter.Save(profile, currentProfile);
                    }
                }

                else
                {
                    if (profile.dcmtkLibPath != null)
                    {
                        Console.WriteLine($"Clearing dcmtkLibPath.");
                        Directory.Delete(profile.dcmtkLibPath, true);
                        profile.dcmtkLibPath = null;
                        //profile.Save(currentProfile);
                        _profileWriter.SaveProfile(profile).Wait();
                    }
                }
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Console.WriteLine($"Platform is OSX");
                if (install)
                {
                    Console.WriteLine("Mac: dcmtk-3.6.3-macosx-x86_64.tar.bz2 will be uncompressed to tools/dcmtk/dcmtk-3.6.3-macosx-x86_64");

                    //tar -xjvf tools/dcmtk/dcmtk-3.6.3-macosx-x86_64.tar.bz2
                    var proc = new Process();
                    ProcessStartInfo procinfo = new ProcessStartInfo
                    {
                        WindowStyle            = ProcessWindowStyle.Hidden,
                        CreateNoWindow         = true,
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true,

                        Verb = "runas",

                        //Directory.CreateDirectory("tools/dcmtk/dcmtk-3.6.3-macosx-x86_64");
                        Arguments = $"-xjvf tools/dcmtk/dcmtk-3.6.3-macosx-x86_64.tar.bz2 -C tools/dcmtk",
                        FileName  = "tar"
                    };

                    proc.StartInfo           = procinfo;
                    proc.OutputDataReceived += (object sendingProcess, DataReceivedEventArgs outLine) =>
                    {
                        try
                        {
                            if (!String.IsNullOrEmpty(outLine.Data))
                            {
                                Console.WriteLine($"{outLine.Data}");
                            }
                        }

                        catch (Exception e)
                        {
                            _logger.Log(LogLevel.Information, $"{e.Message}{e.StackTrace}");
                        }
                    };
                    proc.ErrorDataReceived += (object sendingProcess, DataReceivedEventArgs outLine) =>
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(outLine.Data))
                            {
                                Console.WriteLine($"{outLine.Data}");
                            }
                        }

                        catch (Exception e)
                        {
                            _logger.Log(LogLevel.Information, $"{e.Message}{e.StackTrace}");
                        }
                    };
                    proc.EnableRaisingEvents = true;
                    proc.Exited += (object sender, EventArgs e) =>
                    {
                        Process p = (Process)sender;
                        if (p.ExitCode != 0)
                        {
                            Console.WriteLine($"{((Process)sender).StartInfo.FileName} Proc ExitCode:{proc.ExitCode}");
                        }
                        ;
                    };

                    proc.Start();
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();

                    while (!proc.HasExited)
                    {
                        Console.WriteLine($"{procinfo.FileName} is running...");
                        Task.Delay(1000, _taskManager.cts.Token).Wait();
                    }

                    if (proc.ExitCode != 0)
                    {
                        return(false);
                    }
                    else
                    {
                        profile.dcmtkLibPath = "tools/dcmtk/dcmtk-3.6.3-maxosx-x86_64";
                        //profile.Save(currentProfile);
                        _fileProfileWriter.Save(profile, currentProfile);
                    }
                }
                else
                {
                    if (profile.dcmtkLibPath != null)
                    {
                        Console.WriteLine($"Clearing dcmtkLibPath.");
                        Directory.Delete(profile.dcmtkLibPath, true);
                        profile.dcmtkLibPath = null;
                        //profile.Save(currentProfile);
                        _fileProfileWriter.Save(profile, currentProfile);
                    }
                }
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Console.WriteLine($"Platform is Windows");
                Console.WriteLine($"Windows: dcmtk-3.6.3-win64-dynamic.zip will be uncompressed to ../LITE/tools/dcmtk/dcmtk-3.6.3-win64-dynamic");

                if (install)
                {
                    ZipFile.ExtractToDirectory("tools/dcmtk/dcmtk-3.6.3-win64-dynamic.zip", "tools/dcmtk");
                    profile.dcmtkLibPath = "tools" + Path.DirectorySeparatorChar + Constants.Dirs.dcmtk + Path.DirectorySeparatorChar + "dcmtk-3.6.3-win64-dynamic";
                    //profile.Save(currentProfile);
                    _fileProfileWriter.Save(profile, currentProfile);
                }
                else
                {
                    if (profile.dcmtkLibPath != null)
                    {
                        Console.WriteLine($"Clearing dcmtkLibPath.");
                        Directory.Delete(profile.dcmtkLibPath, true);
                        profile.dcmtkLibPath = null;
                        //profile.Save(currentProfile);
                        _fileProfileWriter.Save(profile, currentProfile);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 57
0
 public void StartTime()
 {
     GC.Collect();
     GC.WaitForPendingFinalizers();
     startTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
 }
Exemplo n.º 58
0
        protected static async Task KillTreeAsync(
            int pid,
            ILog log,
            Action <int, int> kill,
            Func <ILog, int, IList <int> > getChildProcessIds,
            bool?diagnostics = true)
        {
            log.WriteLine($"Killing process tree of {pid}...");

            var pids = getChildProcessIds(log, pid);

            log.WriteLine($"Pids to kill: {string.Join(", ", pids.Select((v) => v.ToString()).ToArray())}");

            if (diagnostics == true)
            {
                foreach (var pidToDiagnose in pids)
                {
                    log.WriteLine($"Running lldb diagnostics for pid {pidToDiagnose}");

                    var template = Path.GetTempFileName();
                    try
                    {
                        var commands = new StringBuilder();
                        using (var dbg = new Process())
                        {
                            commands.AppendLine($"process attach --pid {pidToDiagnose}");
                            commands.AppendLine("thread list");
                            commands.AppendLine("thread backtrace all");
                            commands.AppendLine("detach");
                            commands.AppendLine("quit");

                            dbg.StartInfo.FileName  = "lldb";
                            dbg.StartInfo.Arguments = StringUtils.FormatArguments("--source", template);

                            File.WriteAllText(template, commands.ToString());

                            log.WriteLine($"Printing backtrace for pid={pidToDiagnose}");
                            await RunAsyncInternal(
                                process : dbg,
                                log : new NullLog(),
                                stdout : log,
                                stderr : log,
                                kill,
                                getChildProcessIds,
                                timeout : TimeSpan.FromSeconds(20),
                                diagnostics : false);
                        }
                    }
                    catch (Win32Exception e) when(e.NativeErrorCode == 2)
                    {
                        log.WriteLine("lldb was not found, skipping diagnosis..");
                    }
                    catch (Exception e)
                    {
                        log.WriteLine("Failed to diagnose the process using lldb:" + Environment.NewLine + e);
                    }
                    finally
                    {
                        try
                        {
                            File.Delete(template);
                        }
                        catch
                        {
                            // Don't care
                        }
                    }
                }
            }

            // Send SIGABRT since that produces a crash report
            // lldb may fail to attach to system processes, but crash reports will still be produced with potentially helpful stack traces.
            for (int i = 0; i < pids.Count; i++)
            {
                kill(pids[i], 6);
            }

            // send kill -9 anyway as a last resort
            for (int i = 0; i < pids.Count; i++)
            {
                kill(pids[i], 9);
            }
        }
Exemplo n.º 59
0
 public void StopTime()
 {
     duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startTime);
 }
Exemplo n.º 60
0
        protected static async Task <ProcessExecutionResult> RunAsyncInternal(
            Process process,
            ILog log,
            ILog stdout,
            ILog stderr,
            Action <int, int> kill,
            Func <ILog, int, IList <int> > getChildProcessIds,
            TimeSpan?timeout = null,
            Dictionary <string, string>?environmentVariables = null,
            CancellationToken?cancellationToken = null,
            bool?diagnostics = null)
        {
            var stdoutCompletion = new TaskCompletionSource <bool>();
            var stderrCompletion = new TaskCompletionSource <bool>();
            var result           = new ProcessExecutionResult();

            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.RedirectStandardOutput = true;
            // Make cute emojiis show up as cute emojiis in the output instead of ugly text symbols!
            process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            process.StartInfo.StandardErrorEncoding  = Encoding.UTF8;
            process.StartInfo.UseShellExecute        = false;

            if (environmentVariables != null)
            {
                foreach (var kvp in environmentVariables)
                {
                    if (kvp.Value == null)
                    {
                        process.StartInfo.EnvironmentVariables.Remove(kvp.Key);
                    }
                    else
                    {
                        process.StartInfo.EnvironmentVariables[kvp.Key] = kvp.Value;
                    }
                }
            }

            process.OutputDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    lock (stdout)
                    {
                        stdout.WriteLine(e.Data);
                        stdout.Flush();
                    }
                }
                else
                {
                    stdoutCompletion.TrySetResult(true);
                }
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    lock (stderr)
                    {
                        stderr.WriteLine(e.Data);
                        stderr.Flush();
                    }
                }
                else
                {
                    stderrCompletion.TrySetResult(true);
                }
            };

            var sb = new StringBuilder();

            if (process.StartInfo.EnvironmentVariables != null)
            {
                var currentEnvironment = Environment.GetEnvironmentVariables().Cast <DictionaryEntry>().ToDictionary(v => v.Key.ToString(), v => v.Value?.ToString(), StringComparer.Ordinal);
                var processEnvironment = process.StartInfo.EnvironmentVariables.Cast <DictionaryEntry>().ToDictionary(v => v.Key.ToString(), v => v.Value?.ToString(), StringComparer.Ordinal);
                var allKeys            = currentEnvironment.Keys.Union(processEnvironment.Keys).Distinct();
                foreach (var key in allKeys)
                {
                    if (key == null)
                    {
                        continue;
                    }

                    string?a = null, b = null;
                    currentEnvironment?.TryGetValue(key, out a);
                    processEnvironment?.TryGetValue(key, out b);
                    if (a != b)
                    {
                        sb.Append($"{key}={StringUtils.Quote(b)} ");
                    }
                }
            }

            sb.Append($"{StringUtils.Quote(process.StartInfo.FileName)} {process.StartInfo.Arguments}");
            log.WriteLine(sb.ToString());

            process.Start();
            var pid = process.Id;

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            cancellationToken?.Register(() =>
            {
                var hasExited = false;
                try
                {
                    hasExited = process.HasExited;
                }
                catch
                {
                    // Process.HasExited can sometimes throw exceptions, so
                    // just ignore those and to be safe treat it as the
                    // process didn't exit (the safe option being to not leave
                    // processes behind).
                }

                if (!hasExited)
                {
                    stderr.WriteLine($"Killing process {pid} as it was cancelled");
                    kill(pid, 9);
                }
            });

            if (timeout.HasValue)
            {
                if (!await WaitForExitAsync(process, timeout.Value))
                {
                    log.WriteLine($"Process {pid} didn't exit within {timeout} and will be killed");

                    await KillTreeAsync(pid, log, kill, getChildProcessIds, diagnostics ?? true);

                    result.TimedOut = true;

                    lock (stderr)
                    {
                        log.WriteLine($"{pid} Execution timed out after {timeout.Value.TotalSeconds} seconds and the process was killed.");
                    }
                }
            }
            else
            {
                await WaitForExitAsync(process);
            }

            if (process.HasExited)
            {
                // make sure redirected output events are finished
                process.WaitForExit();
            }

            Task.WaitAll(new Task[] { stderrCompletion.Task, stdoutCompletion.Task }, TimeSpan.FromSeconds(1));

            try
            {
                result.ExitCode = process.ExitCode;
                log.WriteLine($"Process {Path.GetFileName(process.StartInfo.FileName)} exited with {result.ExitCode}");
            }
            catch (Exception e)
            {
                result.ExitCode = 12345678;
                log.WriteLine($"Failed to get ExitCode: {e}");
            }

            return(result);
        }