Ejemplo n.º 1
2
    public static bool Execute(ProjectProperties properties, Log log)
    {
        Console.WriteLine("compiling");
        var processSettings = new ProcessStartInfo();
        processSettings.FileName = properties.CscPath;
        processSettings.Arguments = properties.FormatCscArguments();

        log.WriteLine("Executing {0}", processSettings.FileName);
        log.WriteLine("Csc Arguments: {0}", processSettings.Arguments);

        processSettings.CreateNoWindow = true;
        processSettings.RedirectStandardOutput = true;
        processSettings.UseShellExecute = false;

        Process cscProcess = null;
        try
        {
            cscProcess = Process.Start(processSettings);
        }
        catch (Win32Exception)
        {
            Console.WriteLine("ERROR: csc.exe needs to be on the path.");
            return false;
        }

        var output = cscProcess.StandardOutput.ReadToEnd();
        log.WriteLine(output);

        cscProcess.WaitForExit();

        if (output.Contains("error CS")) return false;
        return true;
    }
Ejemplo n.º 2
2
    static void ExecuteCommand(string command)
    {
        int exitCode;
        ProcessStartInfo processInfo;
        Process process;

        processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
        processInfo.CreateNoWindow = true;
        processInfo.UseShellExecute = false;
        // *** Redirect the output ***
        processInfo.RedirectStandardError = true;
        processInfo.RedirectStandardOutput = true;

        process = Process.Start(processInfo);
        process.WaitForExit();

        // *** Read the streams ***
        // Warning: This approach can lead to deadlocks, see Edit #2
        string output = process.StandardOutput.ReadToEnd();
        string error = process.StandardError.ReadToEnd();

        exitCode = process.ExitCode;

        Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
        Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
        Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
        process.Close();
    }
    public static int Execute(string fileName, string arguments,
      out string output)
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.UseShellExecute = false;
        psi.RedirectStandardError = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardInput = true;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.CreateNoWindow = true;
        psi.ErrorDialog = false;
        psi.FileName = fileName;
        psi.Arguments = arguments;

        using (Process process = Process.Start(psi))
        {
          process.StandardInput.Close();
          StreamReader sOut = process.StandardOutput;
          StreamReader sErr = process.StandardError;
          output = sOut.ReadToEnd() + sErr.ReadToEnd();
          sOut.Close();
          sErr.Close();
          process.WaitForExit();
          return process.ExitCode;
        }
    }
Ejemplo n.º 4
0
    static void Main()
    {
        for (;;)
        {
            var start = DateTime.Now;
            var info = new ProcessStartInfo("xbuild") {
                RedirectStandardError = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
            };
            var proc = Process.Start(info);
            proc.WaitForExit();
            if (proc.ExitCode != 0) {
                var allerrs = proc.StandardError
                .ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                .Concat(
                    proc.StandardOutput.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                )
                .Where(line => line.Contains("error"))
                .ToList();

                Process.Start("osascript", string.Format("-e 'display notification \"{0}\" with title \"Home CI\"'",
                    string.Join(" / ", allerrs.Select(line => line.Replace("\"", "\\\"").Replace("'", "`")))));
            }
            var wait = min_seconds - (int)(DateTime.Now - start).TotalSeconds;
            if (wait > 0)
                System.Threading.Thread.Sleep(wait * 1000);
        }
    }
    public static void Run(string name)
    {
        if (name.EndsWith("/")) name = name.Substring(0,name.Length-1);

        #if UNITY_STANDALONE_OSX || UNITY_EDITOR // Cut "|| UNITY_EDITOR" if you're using windows
        if (name.EndsWith(".app"))
        {
            name = name + "/Contents/MacOS/";
            string[] nn = Directory.GetFiles(name);
            name = nn[0];
        }

        ProcessStartInfo startInfo = new ProcessStartInfo( name);
        startInfo.UseShellExecute = false;
        startInfo.WorkingDirectory = CurrentDir();
        Process.Start(startInfo);

        #elif UNITY_STANDALONE_WIN // Paste "|| UNITY_EDITOR" if you're using windows

        ProcessStartInfo startInfo = new ProcessStartInfo( name);
        startInfo.UseShellExecute = true;
        startInfo.WorkingDirectory = CurrentDir();
        Process.Start(startInfo);

        #else
        Debug.LogError("Sorry, I can't open a file on this platform");
        #endif
        GUIUtility.ExitGUI();
    }
Ejemplo n.º 6
0
    public void Shot(string url, string caminhoDestino)
    {
        try
        {
            string arguments = url + " " + caminhoDestino;

            var startInfo = new ProcessStartInfo
            {
                Arguments = arguments,
                FileName = Util.Url.GetCaminhoFisico(Util.Sistema.AppSettings.UrlIECapt)
            };
            Process p = Process.Start(startInfo);

            //Process p = Process.Start(rootDir + "\\" + EXTRACTIMAGE_EXE, arguments);
            p.WaitForExit(TIMEOUT);
            if (!p.HasExited)
            {
                p.Kill();
                throw new Exception("Timed out while creating the thumbnail.");
            }
        }
        catch (Exception ex)
        {
            Trace.WriteLine(ex.ToString());
            throw ex;
        }
    }
Ejemplo n.º 7
0
    private void RTBackground_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            ProcessStartInfo RTStartInfo = new ProcessStartInfo();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT) { RTStartInfo = new ProcessStartInfo("\"" + MySettings.ProgramPath + "\"", e.Argument.ToString()); }
            else if (Environment.OSVersion.Platform == PlatformID.Unix) { RTStartInfo = new ProcessStartInfo("rawtherapee", e.Argument.ToString()); }
            else if (Environment.OSVersion.Platform == PlatformID.MacOSX) { RTStartInfo = new ProcessStartInfo("rawtherapee", e.Argument.ToString()); }
            else { e.Result = InfoType.InvalidOS; return; }

            RTStartInfo.UseShellExecute = false;
            RTStartInfo.CreateNoWindow = true;

            RT.StartInfo = RTStartInfo;
            RT.Start();
            lastTime = DateTime.Now.Ticks;
            RT.WaitForExit();

            e.Result = InfoType.OK;
        }
        catch (Exception ex)
        {
            ThreadException = ex;
            e.Result = InfoType.Error;
        }
    }
Ejemplo n.º 8
0
    public IList<MXServer> GetMXServers(string domainName)
    {
        string command = "nslookup -q=mx " + domainName;
        ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);

        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;

        procStartInfo.CreateNoWindow = true;

        Process proc = new Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        string result = proc.StandardOutput.ReadToEnd();

        if (!string.IsNullOrEmpty(result))
            result = result.Replace("\r\n", Environment.NewLine);

        IList<MXServer> list = new List<MXServer>();
        foreach (string line in result.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            if (line.Contains("MX preference =") && line.Contains("mail exchanger ="))
            {
                MXServer mxServer = new MXServer();
                mxServer.Preference = Int(GetStringBetween(line, "MX preference = ", ","));
                mxServer.MailExchanger = GetStringFrom(line, "mail exchanger = ");

                list.Add(mxServer);
            }
          }
        return list.OrderBy(m => m.Preference).ToList();
    }
Ejemplo n.º 9
0
    static bool CallProcess(string processName, string param)
    {
        ProcessStartInfo process = new ProcessStartInfo
        {
            CreateNoWindow = false,
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            FileName = processName,
            Arguments = param,
        };

        UnityEngine.Debug.Log(processName + " " + param);

        Process p = Process.Start(process);
        p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        string error = p.StandardError.ReadToEnd();
        if (!string.IsNullOrEmpty(error))
        {
            UnityEngine.Debug.LogError(processName + " " + param + "  ERROR! " + "\n" + error);

            string output = p.StandardOutput.ReadToEnd();
            if (!string.IsNullOrEmpty(output))
            {
                UnityEngine.Debug.Log(output);
            }
            return false;
        }
        return true;
    }
Ejemplo n.º 10
0
    //这里是关键函数了
    public string GetCustomerMac(string IP)
    {
        string dirResults = "";
        ProcessStartInfo psi = new ProcessStartInfo();
        Process proc = new Process();
        psi.FileName = "nbtstat";
        psi.RedirectStandardInput = false;
        psi.RedirectStandardOutput = true;
        psi.Arguments = "-a " + IP;
        psi.UseShellExecute = false;
        proc = Process.Start(psi);
        dirResults = proc.StandardOutput.ReadToEnd();
        proc.WaitForExit();

        //匹配mac地址
        Match m = Regex.Match(dirResults, "\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w\\w");

        //若匹配成功则返回mac,否则返回找不到主机信息
        if (m.ToString() != "")
        {
            return m.ToString();
        }
        else
        {
            return "找不到主机信息";
        }
    }
Ejemplo n.º 11
0
Archivo: test.cs Proyecto: mono/gert
	static int Main (string [] args)
	{
		string runtimeEngine = null;

		if (args.Length == 0)
			return 1;

		if (args.Length > 1 && args [1].Length > 0)
			runtimeEngine = args [1];

		if (args [0] == "nested")
			return 0;

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

		ProcessStartInfo pinfo = null;
		if (runtimeEngine != null) {
			pinfo = new ProcessStartInfo (runtimeEngine, "\"" + program + "\" nested");
		} else {
			pinfo = new ProcessStartInfo (program, "nested");
		}

		pinfo.UseShellExecute = false;
		pinfo.RedirectStandardInput = true;
		pinfo.RedirectStandardOutput = true;

		Process p = Process.Start (pinfo);
		if (p.StandardOutput.CurrentEncoding.BodyName != Console.OutputEncoding.BodyName) {
			return 2;
		}
		if (p.StandardInput.Encoding.BodyName != Console.InputEncoding.BodyName)
			return 3;
		return 0;
	}
Ejemplo n.º 12
0
    private void GetPrefKeysMac()
    {
        string homePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string pListPath = homePath +"/Library/Preferences/unity." + PlayerSettings.companyName + "." +
                           PlayerSettings.productName + ".plist";
        // Convert from binary plist to xml.
        Process p = new Process();
        ProcessStartInfo psi = new ProcessStartInfo("plutil", "-convert xml1 \"" + pListPath + "\"");
        p.StartInfo = psi;
        p.Start();
        p.WaitForExit();

        StreamReader sr = new StreamReader(pListPath);
        string pListData = sr.ReadToEnd();

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(pListData);

        XmlElement plist = xml["plist"];
        if (plist == null) return;
        XmlNode node = plist["dict"].FirstChild;
        while (node != null) {
            string name = node.InnerText;
            node = node.NextSibling;
            PlayerPrefStore pref = new PlayerPrefStore(name, node.Name, node.InnerText);
            node = node.NextSibling;
            playerPrefs.Add(pref);
        }

        //		// Convert plist back to binary
        Process.Start("plutil", " -convert binary1 \"" + pListPath + "\"");
    }
Ejemplo n.º 13
0
    private IEnumerator CaptureScreen(string path)
    {
        // Wait till the last possible moment before screen rendering to hide the UI
        yield return null;

        GameObject.Find("ScreenShotCanvas").GetComponent<Canvas>().enabled = false;

        path = "\"" + path + "\"";

        ProcessStartInfo startInfo = new ProcessStartInfo()
        {
            FileName = "screencapture",
            Arguments = path,
        };
        Process proc = new Process()
        {
            StartInfo = startInfo,
        };

        // Wait for screen rendering to complete
        yield return new WaitForEndOfFrame ();

        proc.Start();

        // wait for the process to end
        yield return new WaitForEndOfFrame ();
        yield return new WaitForEndOfFrame ();

        hasNewScreenShot = true;

        GameObject.Find("ScreenShotCanvas").GetComponent<Canvas>().enabled = true;
    }
Ejemplo n.º 14
0
    private static Process LaunchAdapter(int adaptee, int adapted)
    {
        var temp = Path.GetTempFileName() + ".ensimea.exe";
        File.Copy(@"%SCRIPTS_HOME%\ensimea.exe".Expand(), temp);

        var psi = new ProcessStartInfo();
        psi.FileName = temp;
        psi.Arguments = String.Format("{0} {1}", adaptee, adapted);
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        var p = new Process();
        p.StartInfo = psi;
        p.OutputDataReceived += (sender, args) => { if (args.Data != null) Console.WriteLine(args.Data); };
        p.ErrorDataReceived += (sender, args) => { if (args.Data != null) Console.WriteLine(args.Data); };

        if (p.Start()) {
          p.BeginOutputReadLine();
          p.BeginErrorReadLine();
          return p;
        } else {
          return null;
        }
    }
Ejemplo n.º 15
0
    public static string[] RunCommand( string cmd, string arguments )
    {
        ProcessStartInfo startInfo;
        Process p;
        StringBuilder result = new StringBuilder();

        startInfo = new ProcessStartInfo(cmd, arguments);
        startInfo.WorkingDirectory = Environment.CurrentDirectory;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.CreateNoWindow = true;
        startInfo.ErrorDialog = false;
        startInfo.RedirectStandardError = false;
        startInfo.RedirectStandardInput = false;
        startInfo.RedirectStandardOutput = true;
        startInfo.UseShellExecute = false;

        p = Process.Start(startInfo);

        using (StreamReader o = p.StandardOutput) {
            //while (!o.EndOfStream) {
            result.Append(o.ReadToEnd());
            //}
        }

        return result.ToString().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
    }
Ejemplo n.º 16
0
    public static void Main(string[] args)
    {
        if (args.Length < 4) {
            Console.WriteLine ("Usage : ./benchmarks-analyzer.exe mode mono1 mono2 benchmarker-folder");
            Console.WriteLine ("            mode    : majors for the two monos [s|c|cp]v[s|c|cp]");
            Console.WriteLine ("            mono2   : if mono2 is '-' then mono1 is used for both runs");
            return;
        }
        int arg = 0;

        string mode = args [arg++];
        string mono1 = args [arg++];
        string mono2 = args [arg++];
        string analyzer = "analyzer.exe";
        string benchmarker_folder = args [arg++];
        string benchmarks_folder = Path.Combine (benchmarker_folder, "benchmarks");
        string tests_folder = Path.Combine (benchmarker_folder, "tests");

        List<Benchmark> benchmark_list = Benchmark.LoadAllFrom (benchmarks_folder);

        foreach (Benchmark b in benchmark_list) {
            ProcessStartInfo info = new ProcessStartInfo {
                UseShellExecute = false,
            };

            info.FileName = analyzer;
            info.Arguments = mode + " " + mono1 + " " + mono2 + " " + Path.Combine (tests_folder, b.TestDirectory) + " " + string.Join (" ", b.CommandLine);

            Console.WriteLine ("{0}", b.Name);
            Process ps = Process.Start (info);
            ps.WaitForExit ();
        }
    }
Ejemplo n.º 17
0
    public static void Main(string[] args)
    {
        try
        {
            if (args.Length == 0 || args[0].ToLower() == "-?" || args[0].ToLower() == "/?")
            {
                Console.WriteLine(usage);
            }
            else
            {
                ProcessStartInfo psi = new ProcessStartInfo(args[0]);

                Console.Write(@"User Name [domain\user]: ");
                string[] userParts = Console.ReadLine().Split('\\');
                if (userParts.Length == 2)
                {
                    psi.Domain = userParts[0];
                    psi.UserName = userParts[1];
                }
                else
                    psi.UserName = userParts[0];

                psi.Password = ReadPassword();
                psi.UseShellExecute = false;
                for (int i = 1; i < args.Length; i++)
                    psi.Arguments += (i == 1 ? "\"" : " \"") + args[i] + "\"";

                Process.Start(psi);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    protected void btnScan_Click(object sender, EventArgs e)
    {
        try
        {
            string switches = " /inventory /startaddress:" + txt_range_from.Text + " /endaddress:" + txt_range_to.Text + " /computers:no /devices:yes /community:" + txt_community.Text;
            ProcessStartInfo info = new ProcessStartInfo(Server.MapPath("~/binaries/Admin.exe"), switches);
            Process pro = new Process();
            pro.StartInfo = info;
            pro.Start();
            pro.WaitForExit();
           // lbl_status.Text = "Scanning completed...";
            txt_community.Text = "";
            txt_range_from.Text = "";
            txt_range_to.Text = "";
            string myScript;
            myScript = "<script language=javascript>alert('Scanning completed successfully...');</script>";
            Page.RegisterClientScriptBlock("MyScript", myScript);
          //  return;

        }
        catch (Exception ex)
        {
            string myScript;
            myScript = "<script language=javascript>alert('Exception - '" + ex + "');</script>";
            Page.RegisterClientScriptBlock("MyScript", myScript);
            return;
        }
    }
Ejemplo n.º 19
0
    /// <summary>
    /// Restart the current process with administrator credentials
    /// </summary>
    internal static void RestartElevated()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        
        string arguments = "";
        string[] args = Environment.GetCommandLineArgs();
        for(int i = 1; i < args.Length; i++ )
            arguments +="\""+args[i]+"\" ";

        startInfo.Arguments = arguments.TrimEnd();
        startInfo.UseShellExecute = true;
        startInfo.WorkingDirectory = Environment.CurrentDirectory;
        startInfo.FileName = Application.ExecutablePath;
        startInfo.Verb = "runas";
        try
        {
            Process p = Process.Start(startInfo);
        }
        catch (System.ComponentModel.Win32Exception)
        {
            return; //If cancelled, do nothing
        }

        Application.Exit();
    }
    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();
    }
        private static void TestBaseHostWCFInit(TestContext testContext)
        {
            lock (lockObject)
            {
                if (TestBaseHostWCFHostProcess == null)
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.CreateNoWindow = false;
                    startInfo.UseShellExecute = false;
                    startInfo.FileName = Path.Combine(testContext.DeploymentDirectory, "$customNamespace$.WCF.ServicesHost.exe");
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    //startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

                    try
                    {
                        TestBaseHostWCFHostProcess = Process.Start(startInfo);

                        // Start the process with the info we specified.
                        // Call WaitForExit and then the using statement will close.
                        //using (Process exeProcess = Process.Start(startInfo))
                        //{
                        //exeProcess.WaitForExit();
                        //}
                    }
                    catch (Exception ex)
                    {
                        Assert.Inconclusive(ex.Message);
                    }
                }
            }
        }
 public static void RunPlistBuddyCommand(string workingDirectory, string arguments)
 {
     ProcessStartInfo proc = new ProcessStartInfo ("/usr/libexec/PlistBuddy", "Info.plist -c \"" + arguments + "\"");
     proc.WorkingDirectory = workingDirectory;
     proc.UseShellExecute = false;
     Process.Start(proc);
 }
Ejemplo n.º 23
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
        {

        }
    }
Ejemplo n.º 24
0
    public static int Main(string[] args)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("[EXE]", "[ARGUMENTS] " + GetArguments(args));
        startInfo.UseShellExecute = false;
        Process process;
        try
        {
            try
            {
                process = Process.Start(startInfo);
            }
            catch (Win32Exception ex)
            {
                if (ex.NativeErrorCode == Win32RequestedOperationRequiresElevation)
                {
                    // UAC handling requires ShellExecute
                    startInfo.UseShellExecute = true;
                    process = Process.Start(startInfo);
                }
                else throw;
            }

            process.WaitForExit();
        }
        catch (Win32Exception ex)
        {
            if (ex.NativeErrorCode == Win32Cancelled) return 100;
            else throw;
        }
        return process.ExitCode;
    }
    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));
    }
Ejemplo n.º 26
0
	static void LaunchEmulator ()
	{
		ProcessStartInfo startInfo = new ProcessStartInfo ()
		{
			WorkingDirectory = Application.dataPath,
			FileName = JavaBuildSettings.AndroidSDKPath + "/../../tools/emulator",
			Arguments = string.Format (
				"-avd {0}",
				"OUYA"
			),
			UseShellExecute = false,
			RedirectStandardError = true,
		};

		Process process = Process.Start (startInfo);
		process.Exited += new EventHandler (
			(object sender, EventArgs e) =>
			{
				if (!process.StandardError.EndOfStream)
				{
					Debug.LogError (
						"Android emulator error: " +
							process.StandardError.ReadToEnd ()
					);
				}
			}
		);
	}
Ejemplo n.º 27
0
 /// <summary>
 /// Executes a tortoiseSVN command.
 /// </summary>
 /// <param name="command">the command to execute. this command is one of the commands of the tortoiseproc.exe automation commands that you add after /command:. a list of them can be found in tortoiseSVN's help file in automating tortoiseSVN topic</param>
 /// <param name="path">the path that your command should be executed on. pass "" (i.e empty string) for pathing nothing</param>
 public static void SVNCommand(string command, string path)
 {
     string c = "/c tortoiseproc.exe /command:{0} /path:\"{1}\"";
     c = string.Format(c, command, path);
     ProcessStartInfo info = new ProcessStartInfo("cmd.exe", c);
     info.WindowStyle = ProcessWindowStyle.Hidden;
     Process.Start(info);
 }
Ejemplo n.º 28
0
 public static void Main( string[] args ){
     string arg = "";
     foreach( string s in args ){
         arg += "\"" + s + "\" ";
     }
     string exe = Environment.GetCommandLineArgs()[0];
     string exe_name = Path.GetFileNameWithoutExtension( exe );
     string path = Application.StartupPath;
     if( exe_name == "resampler" && args.Length >= 12 ){
         string outpath = args[1];
         string out_name = Path.GetFileNameWithoutExtension( outpath );
         string out_dir = Path.GetDirectoryName( outpath );
         string logname = Path.Combine( out_dir, out_name + ".log" );
         using( StreamWriter sw = new StreamWriter( logname ) ){
             const int PBTYPE = 5;
             int indx_q = args[11].IndexOf( "Q" );
             int count = 0;
             if( indx_q > 0 ){
                 string pit = args[11].Substring( 0, indx_q );
                 if( args[11].Length >= indx_q + 1 ){
                     string tempo = args[11].Substring( indx_q + 1 );
                     sw.WriteLine( "# " + tempo );
                 }
                 sw.WriteLine( (count * PBTYPE) + "\t" + pit );
                 count++;
             }
             for( int i = 12; i < args.Length; i++ ){
                 sw.WriteLine( (count * PBTYPE) + "\t" + args[i] );
                 count++;
             }
         }
     }
     using( StreamWriter sw = new StreamWriter( Path.Combine( path, exe_name + ".log" ), true ) ){
         sw.WriteLine( arg );
         Process p = null;
         try{
             p = new Process();
             ProcessStartInfo psi = new ProcessStartInfo();
             psi.FileName = Path.Combine( path, "_" + exe_name + ".exe" );
             psi.Arguments = arg;
             psi.CreateNoWindow = true;
             psi.UseShellExecute = false;
             psi.UseShellExecute = false;
             p.StartInfo = psi;
             p.Start();
             p.WaitForExit();
         }catch( Exception ex ){
             sw.WriteLine( "Resampler.Main(string[]); ex=" + ex );
         }finally{
             if( p != null ){
                 try{
                     p.Dispose();
                 }catch{
                 }
             }
         }
     }
 }
Ejemplo n.º 29
0
        public Result RunTests(IList<string> paths)
        {
            Result results = new Result();

            for (int i = 0; i < paths.Count; i += Environment.ProcessorCount)
            {
                List<Process> tasks = new List<Process>();

                for (int j = 0; j < Environment.ProcessorCount && i + j < paths.Count; j++)
                {
                    string file = Path.GetFileName(paths[i + j]);
                    string dir = Path.GetDirectoryName(paths[i + j]);
                    ProcessStartInfo psi = new ProcessStartInfo(cmd, file);
                    psi.UseShellExecute = false;
                    psi.RedirectStandardOutput = true;
                    psi.RedirectStandardError = true;
                    psi.WorkingDirectory = dir;
                    tasks.Add(Process.Start(psi));
                }

                foreach (Process process in tasks)
                {
                    process.WaitForExit();

                    if (process.ExitCode == 0)
                    {
                        Console.Write(".");
                        results.Pass++;
                    }
                    else
                    {
                        Console.Write("x");
                        results.Fail++;

                        log.WriteLine(process.StartInfo.Arguments);
                        log.WriteLine("  Out:");

                        string line;
                        while (null != (line = process.StandardOutput.ReadLine()))
                        {
                            log.Write("    ");
                            log.WriteLine(line);
                        }

                        log.WriteLine("  Error:");
                        while (null != (line = process.StandardError.ReadLine()))
                        {
                            log.Write("    ");
                            log.WriteLine(line);
                        }

                        log.Flush();
                    }
                }
            }

            return results;
        }
Ejemplo n.º 30
0
        public override int Run()
        {
            var rInstallPath = RInstallPath();

            if (!string.Equals(rInstallPath, "rscript", StringComparison.OrdinalIgnoreCase))
            {
                rInstallPath = Path.Combine(rInstallPath, @"bin\Rscript.exe");
                if (!(File.Exists(rInstallPath)))
                {
                    return(1);
                }
            }

            // create Achilles JSON root folder if not exists
            var jsonPath = GetSetting(PostprocessSettingName.AchillesJsonFolder);

            if (string.IsNullOrWhiteSpace(jsonPath))
            {
                jsonPath = Path.Combine(Environment.CurrentDirectory, @"achillesJson\" + Settings.Current.Building.LoadId);
            }

            jsonPath = Path.GetFullPath(new Uri(jsonPath).LocalPath)
                       .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            if (!(Directory.Exists(jsonPath)))
            {
                Directory.CreateDirectory(jsonPath);
            }
            jsonPath = jsonPath.Replace("\\", "/");

            var odbcConnection = new OdbcConnectionStringBuilder(Settings.Current.Building.DestinationConnectionString);
            var server         = odbcConnection["server"].ToString();
            var usr            = odbcConnection["uid"].ToString();
            var pass           = odbcConnection["pwd"].ToString();
            var schema         = Settings.Current.Building.DestinationSchemaName;
            var db             = odbcConnection["database"].ToString();
            var src            = Settings.Current.Building.Vendor.ToString();

            var loadId = Settings.Current.Building.LoadId;

            var hixConnection = new SqlConnectionStringBuilder(Settings.Current.HIXConnectionString);
            var hixServer     = hixConnection["Data Source"].ToString();
            var hixDb         = hixConnection["Initial Catalog"].ToString();
            var hixUser       = hixConnection["User Id"].ToString();
            var hixPass       = hixConnection["Password"].ToString();
            var hixPort       = "1433";

            var runCost = GetSetting(PostprocessSettingName.AchillesRunCostAnalysis);

            runCost = string.IsNullOrWhiteSpace(runCost) ? "TRUE" : runCost.Trim().ToUpper();


            var cdmV      = Settings.Current.Building.CDM == CDMVersions.v501 ? "5.0.1" : "5";
            var resSchema = GetSetting(PostprocessSettingName.ResultsSchema);

            if (string.IsNullOrWhiteSpace(resSchema))
            {
                resSchema = "cdm";
            }

            var scratchSchema = GetSetting(PostprocessSettingName.ScratchSchema);

            if (string.IsNullOrWhiteSpace(scratchSchema))
            {
                scratchSchema = "cdm";
            }

            var numThreads = GetSetting(PostprocessSettingName.AchillesNumThreads);

            if (string.IsNullOrWhiteSpace(numThreads))
            {
                numThreads = "1";
            }

            var achillesParams = new Dictionary <string, string>
            {
                { "rsCluster", server },
                { "rsUser", usr },
                { "rsPassword", pass },
                { "rsDbSchema", schema },
                { "rsDbName", db },
                { "sourceName", src },
                { "achillesJsonFolder", jsonPath },
                { "loadId", loadId.ToString() },
                //{"runCostAnalysis", runCost},
                //{"cdmVersion", cdmV},
                //{"numThreads", numThreads},
                //{"resultsSchema", resSchema},
                //{"scratchSchema", scratchSchema},
                { "hixServer", hixServer },
                { "hixUser", hixUser },
                { "hixPassword", hixPass },
                { "hixDb", hixDb },
                { "hixPort", hixPort }
            };

            var script = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, @"Postprocesses\Achilles\Achilles.R"));

            script = Regex.Replace(script, @"\{(.+?)\}", m => achillesParams[m.Groups[1].Value]);

            var scriptPath = Path.GetTempFileName();

            Logger.Write(null, LogMessageTypes.Info, script);
            File.WriteAllText(scriptPath, script);

            var processParameters = new ProcessStartInfo(rInstallPath)
            {
                Arguments              = string.Format("\"{0}\" --vanilla --slave", scriptPath),
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true
            };

            var r = new Process {
                StartInfo = processParameters
            };

            using (var outputWaitHandle = new AutoResetEvent(false))
                using (var errorWaitHandle = new AutoResetEvent(false))
                {
                    r.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            Logger.Write(null, LogMessageTypes.Info, e.Data);
                        }
                    };
                    r.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            LogMessageTypes msgType;
                            msgType = e.Data == "Execution halted" || e.Data.StartsWith("Error")
                     ? LogMessageTypes.Error
                     : LogMessageTypes.Warning;

                            Logger.Write(null, msgType, e.Data);
                        }
                    };

                    r.Start();
                    r.BeginOutputReadLine();
                    r.BeginErrorReadLine();

                    if (!r.WaitForExit(TIMEOUT) || !outputWaitHandle.WaitOne(TIMEOUT) || !errorWaitHandle.WaitOne(TIMEOUT))
                    {
                        throw new Exception("Achilles timed out.");
                    }

                    if (File.Exists(scriptPath))
                    {
                        File.Delete(scriptPath);
                    }

                    return(r.ExitCode);
                }
        }
        static bool CheckEnvironment(string s, UAPScript UAPScriptEnv, List <KeyValuePair <string, string> > parameters)
        {
            Host.WriteLine("Gathering system information...");
            long memory = 0;

            {
                //Run cmd to judge memory.
                {
                    switch (SystemEnvironment.currentSystem)
                    {
                    case SystemType.Windows:
                    {
                        ProcessStartInfo processStartInfo = new ProcessStartInfo("wmic MEMORYCHIP get Capacity");
                        processStartInfo.RedirectStandardOutput = true;
                        var    p    = Process.Start(processStartInfo);
                        var    outs = p.StandardOutput;
                        string line;
                        while ((line = outs.ReadLine()) != null)
                        {
                            int temp = 0;
                            int.TryParse(line, out temp);
                            memory += temp;
                        }
                        p.WaitForExit();
                        memory /= (1024 * 1024);
                    }
                    break;

                    case SystemType.Linux:
                    {
                        ProcessStartInfo processStartInfo = new ProcessStartInfo("cat /proc/meminfo");
                        processStartInfo.RedirectStandardOutput = true;
                        var    p    = Process.Start(processStartInfo);
                        var    outs = p.StandardOutput;
                        string line = outs.ReadLine();
                        line = line.Substring(line.IndexOf(":") + 1);
                        line = line.Substring(0, line.Length - 3);
                        line = line.Trim();
                        p.WaitForExit();
                        memory = (int.Parse(line)) / (1024 * 1024);
                    }
                    break;

                    case SystemType.MacOS:
                        break;

                    default:
                        break;
                    }
                    //MB now;
                }
            }
            foreach (var item in parameters)
            {
                switch (item.Key)
                {
                case "-SystemVersion":
                {
                    Version min = new Version(item.Value.Trim());
                    if (min.CompareTo(SystemEnvironment.SystemVersion) < 0)
                    {
                        Host.SetForeground(ConsoleColor.Red);
                        Host.WriteLine("Your OS is too old for this software.");
                        Host.SetForeground(ConsoleColor.White);
                        return(false);
                    }
                }
                break;

                case "-Memory":
                {
                    long minMem = long.Parse(item.Value);
                    if (memory < minMem)
                    {
                        Host.SetForeground(ConsoleColor.Red);
                        Host.WriteLine("Your PC's memory is too small for this software.");
                        Host.SetForeground(ConsoleColor.White);
                        return(false);
                    }
                }
                break;

                default:
                    break;
                }
            }
            return(true);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="tempRun"></param>
        /// <returns></returns>
        public int Execute(int Runas = 0, bool Default = false)
        {
            try
            {
                //如果是系统引用
                if (Manage.reSysRef.IsMatch(data.Path))
                {
                    //DO NOTHING
                }
                //如果是网址(URL正则有时也会匹配到程序全路径所以再加个文件存在性检测)
                else if (Manage.reURL.IsMatch(data.Path) && !System.IO.File.Exists(data.Path))
                {
                    //如果接管了浏览器
                    if (Manage.MOWeb.IsUsed)
                    {
                        Plugins.Run(Manage.MOWeb.MdlName, data.Path);
                    }
                }
                //文件或目录
                else
                {
                    //若文件不存在
                    if (FileOperation.IsFile(data.Path) == 1)
                    {
                        if (!System.IO.File.Exists(data.Path))
                        {
                            return(-1);
                        }
                    }
                    else
                    {
                        //若目录不存在
                        if (!System.IO.Directory.Exists(data.Path))
                        {
                            return(-1);
                        }
                        else
                        {
                            if (Manage.MOFolder.IsUsed)
                            {
                                //TODO:使用插件
                            }
                        }
                    }

                    //正常流程
                    //实例化
                    StartInfo = new ProcessStartInfo();

                    //填充信息
                    StartInfo.FileName         = data.Path;
                    StartInfo.Arguments        = data.Arguments;
                    StartInfo.WorkingDirectory = data.WorkingDirectory;

                    //确定是否使用管理员权限执行
                    if (Runas == 1 && Default)
                    {
                        data.RunAs = 1;
                    }
                    else if (RunAs == 1 && Default == false)
                    {
                        StartInfo.Verb = "runas";
                    }

                    //执行
                    Process.Start(StartInfo);

                    //清空主窗体上的检索框
                    Manage.WindowMain.ClearSearch();

                    //给出提示
                    Manage.TipPublic.ShowFixed(Manage.WindowMain, "Go!");
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(System.ComponentModel.Win32Exception))
                {
                    //DO NOTHING
                }
                else
                {
                    return(-2);
                }
            }
            return(0);
        }
Ejemplo n.º 33
0
 /// <summary>
 ///     Create a new <see cref="LanguageClient"/>.
 /// </summary>
 /// <param name="logger">
 ///     The logger to use.
 /// </param>
 /// <param name="serverStartInfo">
 ///     A <see cref="ProcessStartInfo"/> describing how to start the server process.
 /// </param>
 public LanguageClient(ILogger logger, ProcessStartInfo serverStartInfo)
     : this(logger, new StdioServerProcess(logger, serverStartInfo))
 {
 }
Ejemplo n.º 34
0
        public void CallExecutable()
        {
            if (!File.Exists(Executable))
            {
                return;
            }
            var commandLine = Executable;

            Trace.WriteLine("Running command: " + Executable + " " + Args);
            var psi = new ProcessStartInfo(commandLine)
            {
                UseShellExecute        = false,
                LoadUserProfile        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                WindowStyle            = ProcessWindowStyle.Hidden,
                CreateNoWindow         = true,
                Arguments = Args
            };

            if (RunInDir)
            {
                var path = Path.GetDirectoryName(Executable);
                if (path != null)
                {
                    psi.WorkingDirectory = path;
                }
            }
            Process = new Process {
                StartInfo = psi
            };
            try
            {
                Process.Start();
                Process.BeginOutputReadLine();
                Process.BeginErrorReadLine();
                Process.OutputDataReceived += Output;
                Process.ErrorDataReceived  += OutputError;
                _fromStart.Restart();
                Name = Process.ProcessName;

                // Watch process for not responding
                if (WaitForExit)
                {
                    Process.WaitForExit();
                    EndProcess();
                }
                else
                {
                    Process.Exited += ProcessExited;
                }
            }
            catch (Exception ex)
            {
                if (ErrorHandler != null)
                {
                    ErrorHandler(this, new ProcessMessageArgs(ex.Message, Process));
                }
                if (!ProcessUtils.ProcessRunning(Executable))
                {
                    if (ExitHandler != null)
                    {
                        ExitHandler(this, new ProcessStatusArgs(-1, Process));
                    }
                }
            }
        }
Ejemplo n.º 35
0
    public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuiltProject)
    {
        // Stop processing if targe is NOT iOS
        if (buildTarget != BuildTarget.iOS)
        {
            return;
        }

        // Initialize PbxProject
        var        projectPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj";
        PBXProject pbxProject  = new PBXProject();

        pbxProject.ReadFromFile(projectPath);
        string targetGuid = pbxProject.TargetGuidByName("Unity-iPhone");

        string config = pbxProject.BuildConfigByName(targetGuid, "Release");

        //adding build property
        // pbxProject.AddBuildProperty(targetGuid, "OTHER_LDFLAGS", "-all_load");

        //setting build property
        pbxProject.SetBuildProperty(targetGuid, "ENABLE_BITCODE", "NO");

        // pbxProject.AddBuildProperty(targetGuid, "SWIFT_VERSION", "4.0");
        pbxProject.SetBuildProperty(targetGuid, "SWIFT_VERSION", "4.0");

        pbxProject.SetBuildProperty(targetGuid, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Framewoks @loader_path/Frameworks");

//        //update build property
//        pbxProject.UpdateBuildProperty(targetGuid, "OTHER_LDFLAGS", new string[]{
//            "-ObjC",
//            "-lresolv",
//            "-weak_framework",
//            "CoreMotion"
//        });

        //adding REQUIRED framwrok
//        pbxProject.AddFrameworkToProject(targetGuid, "Security.framework", false);

        //adding OPTIONAL framework
        //pbxProject.AddFrameworkToProject(targetGuid, "SafariServices.framework", true);

        //setting compile flags
        // var guid = pbxProject.FindFileGuidByProjectPath("Classes/UI/Keyboard.mm");
        // var flags = pbxProject.GetCompileFlagsForFile(targetGuid, guid);
        // flags.Add("-fno-objc-arc");
        // pbxProject.SetCompileFlagsForFile(targetGuid, guid, flags);

        // Apply settings
        File.WriteAllText(projectPath, pbxProject.WriteToString());

        //editing Info.plist
        var plistPath = Path.Combine(pathToBuiltProject, "Info.plist");
        var plist     = new PlistDocument();

        plist.ReadFromFile(plistPath);

        // Add string setting
        // plist.root.SetString ("hogehogeId", "dummyid");

        plist.root.SetBoolean("NSAllowsArbitraryLoads", true);

        // // Add URL Scheme
        // var array = plist.root.CreateArray ("CFBundleURLTypes");
        // var urlDict = array.AddDict ();
        // urlDict.SetString ("CFBundleURLName", "");
        // var urlInnerArray = urlDict.CreateArray ("CFBundleURLSchemes");
        // urlInnerArray.AddString ("biligame");

        // Apply editing settings to Info.plist
        plist.WriteToFile(plistPath);

        ProcessStartInfo pi = new ProcessStartInfo(
            "open",
            pathToBuiltProject + "/Unity-iPhone.xcodeproj"
            );

        Process.Start(pi);
    }
Ejemplo n.º 36
0
        private IEnumerable <IEnumerable <Tuple <string, string> > > ExtractDataFromPdf(string file)
        {
            var arguments = string.Format(@"-R""{0}\{1}"" -F""{0}\{2}"" -O""{0}\{2}.csv""", RootDirectory, PdfConverterRules, file);
            int exitCode;

            var start = new ProcessStartInfo
            {
                Arguments       = arguments,
                FileName        = PdfConverterPath,
                WindowStyle     = ProcessWindowStyle.Hidden,
                CreateNoWindow  = true,
                UseShellExecute = false
            };

            // Run the external process & wait for it to finish
            using (var proc = Process.Start(start))
            {
                proc.WaitForExit(5000);
                exitCode = proc.ExitCode;
            }

            if (exitCode != 0)
            {
                return(null);
            }

            var list     = new List <List <Tuple <string, string> > >();
            var rawLines = System.IO.File.ReadAllLines(string.Format(@"{0}\{1}.csv", RootDirectory, file), Encoding.Default);

            var splitLines = rawLines.Select(line => line.Split(new[] { @""",""" }, StringSplitOptions.RemoveEmptyEntries)).ToArray();

            var currentLine = 0;
            var fetching    = false;
            var fetchFrom   = 0;
            var fetchAreas  = new List <Tuple <int, int> >();

            // Find areas to include
            while (currentLine < splitLines.Count())
            {
                var firstColumn = splitLines[currentLine][0].Trim();

                if (!fetching)
                {
                    if (Regex.IsMatch(firstColumn, @"(\d)+ STK"))
                    {
                        fetching  = true;
                        fetchFrom = currentLine;
                    }
                }
                else if (firstColumn == "\"Varekode" || firstColumn == "\"Nettovekt [kg]")
                {
                    fetching = false;
                    fetchAreas.Add(new Tuple <int, int>(fetchFrom, currentLine));
                }

                ++currentLine;
            }

            foreach (var area in fetchAreas)
            {
                var areaList  = new List <Tuple <string, string> >();
                var lastKey   = "";
                var lastValue = "";

                for (int i = area.Item1; i < area.Item2; ++i)
                {
                    var key   = splitLines[i][0].Replace("\"", "");
                    var value = splitLines[i][1].Replace("\"", "");

                    if (key.Any() && lastKey.Any())
                    {
                        areaList.Add(new Tuple <string, string>(lastKey, lastValue.StartsWith(": ") ? lastValue.Substring(2) : ""));
                        lastValue = "";
                    }

                    if (key.Any())
                    {
                        lastKey = key;
                    }

                    lastValue += value;
                }

                if (lastKey.Any())
                {
                    areaList.Add(new Tuple <string, string>(lastKey, lastValue.StartsWith(": ") ? lastValue.Substring(2) : ""));
                }

                var count = areaList[0].Item1;
                areaList[0] = new Tuple <string, string>(count.Substring(0, count.IndexOf("STK", StringComparison.Ordinal) + 3), areaList[0].Item2);

                list.Add(areaList);
            }

            return(list);
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Runs asynchronous process.
 /// </summary>
 /// <param name="processStartInfo">The <see cref="T:System.Diagnostics.ProcessStartInfo" /> that contains the information that is used to start the process, including the file name and any command-line arguments.</param>
 public static Task <ProcessResults> RunAsync(ProcessStartInfo processStartInfo)
 => RunAsync(processStartInfo, CancellationToken.None);
Ejemplo n.º 38
0
 /// <summary>
 /// Runs asynchronous process.
 /// </summary>
 /// <param name="processStartInfo">The <see cref="T:System.Diagnostics.ProcessStartInfo" /> that contains the information that is used to start the process, including the file name and any command-line arguments.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
 public static Task <ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
 => RunAsync(processStartInfo, new List <string>(), new List <string>(), cancellationToken);
Ejemplo n.º 39
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            switches = false;
            StringBuilder urlBuilder = new StringBuilder();
            urlBuilder.Append(@"http://www.turbo-keys.com/mousekeys.php?fbid=");
            urlBuilder.Append(textBox1.Text);
            urlBuilder.Append(@"&pin=");
            urlBuilder.Append(textBox2.Text);

            string url1 = urlBuilder.ToString();

            StringBuilder urlBuilder2 = new StringBuilder();
            urlBuilder2.Append(@"http://www.turbo-keys.com/mousekeys_check.php?fbid=");
            urlBuilder2.Append(textBox1.Text);
            urlBuilder2.Append(@"&pin=");
            urlBuilder2.Append(textBox2.Text);

            string url2 = urlBuilder2.ToString();

            HttpWebRequest WebRequestObject1 = (System.Net.HttpWebRequest)HttpWebRequest.Create(url1);

            WebRequestObject1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13";

            WebResponse Response1 = WebRequestObject1.GetResponse();
            Stream WebStream1 = Response1.GetResponseStream();
            StreamReader Reader1 = new StreamReader(WebStream1);
            string urlContent1 = Reader1.ReadToEnd();

            Reader1.Close();
            WebStream1.Close();
            Response1.Close();

            HttpWebRequest WebRequestObject2 = (System.Net.HttpWebRequest)HttpWebRequest.Create(url2);

            WebRequestObject2.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13";

            WebResponse Response2 = WebRequestObject2.GetResponse();
            Stream WebStream2 = Response2.GetResponseStream();
            StreamReader Reader2 = new StreamReader(WebStream2);
            string urlContent2 = Reader2.ReadToEnd();

            Reader2.Close();
            WebStream2.Close();
            Response2.Close();

            if (urlContent1 == "0")
            {
                DialogResult result = MessageBox.Show("Your Account Balance is Empty.\nGo to http://apps.facebook.com/turbokeys-points/ to recharge", "Empty Account", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    ProcessStartInfo sInfo = new ProcessStartInfo("http://apps.facebook.com/turbokeys-points");
                    Process.Start(sInfo);
                    Application.Exit();
                }
                else
                {
                    Application.Exit();
                }
            }
            else if (urlContent1 == "1")
            {
                DialogResult result = MessageBox.Show("There was a problem or mistake with your PIN or facebook ID. \nPlease update it at http://apps.facebook.com/turbokeys-points/", "ID or PIN Error", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    ProcessStartInfo sInfo = new ProcessStartInfo("http://apps.facebook.com/turbokeys-points");
                    Process.Start(sInfo);
                    Application.Exit();
                }
                else
                {
                    Application.Exit();
                }
            }
            else if (urlContent1 != null)
            {
                long content1Length = urlContent1.Length;
                long content2Length = urlContent2.Length;

                long balanceCode1 = Convert.ToInt64(urlContent1.Substring(6));
                long balanceCode2 = Convert.ToInt64(urlContent2.Substring(6));

                long random1 = Convert.ToInt64(urlContent1.Remove(6));
                long random2 = Convert.ToInt64(urlContent2.Remove(6));

                long fbid = Convert.ToInt64(textBox1.Text);
                long pin = Convert.ToInt64(textBox2.Text);

                long fbidpin = fbid * pin;

                long modfbidpin1 = fbidpin % random1;
                long modfbidpin2 = fbidpin % random2;

                long balance1 = balanceCode1 / modfbidpin1;

                if (balanceCode2 == modfbidpin2)
                {
                    if (balanceCode2 > 0)
                    {
                        if (checkBox1.Checked == true)
                        {
                            string inipath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Turbo-Keys\";
                            if (!File.Exists(inipath + "user_info.ini"))
                            {
                                System.IO.Directory.CreateDirectory(inipath);
                            }
                            string userInfoLocation = inipath + @"user_info.ini";

                            StreamWriter write = new StreamWriter(userInfoLocation);
                            write.Write("");
                            write.Flush();
                            write.Dispose();

                            IniParser parser = new IniParser(userInfoLocation);
                            parser.AddSetting("user_info", "facebook_id", textBox1.Text.ToString());
                            parser.AddSetting("user_info", "pin_number", textBox2.Text.ToString());

                            parser.SaveSettings();

                        }
                        switches = true;
                    }
                    this.Close();
                }
                else
                {
                    MessageBox.Show("There was an error contacting the server. Please try again later.");
                    Application.Exit();
                }
            }
            else
            {
                MessageBox.Show("There was an error contacting the server. Please try again later.");
                Application.Exit();
            }

        }
Ejemplo n.º 40
0
 public ProcessWrapper(ProcessStartInfo startInfo)
 {
     StartInfo = startInfo;
 }
Ejemplo n.º 41
0
 private void linkLabel1_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
 {
     ProcessStartInfo sInfo = new ProcessStartInfo("http://apps.facebook.com/turbokeys-points");
     Process.Start(sInfo);
 }
Ejemplo n.º 42
0
        public static async Task <ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
        {
            // force some settings in the start info so we can capture the output
            processStartInfo.UseShellExecute        = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError  = true;

            var tcs = new TaskCompletionSource <ProcessResults>();

            var standardOutput = new List <string>();
            var standardError  = new List <string>();

            var process = new Process {
                StartInfo           = processStartInfo,
                EnableRaisingEvents = true
            };

            var standardOutputResults = new TaskCompletionSource <string[]>();

            process.OutputDataReceived += (sender, args) => {
                if (args.Data != null)
                {
                    standardOutput.Add(args.Data);
                }
                else
                {
                    standardOutputResults.SetResult(standardOutput.ToArray());
                }
            };

            var standardErrorResults = new TaskCompletionSource <string[]>();

            process.ErrorDataReceived += (sender, args) => {
                if (args.Data != null)
                {
                    standardError.Add(args.Data);
                }
                else
                {
                    standardErrorResults.SetResult(standardError.ToArray());
                }
            };

            var processStartTime = new TaskCompletionSource <DateTime>();

            process.Exited += async(sender, args) => {
                // Since the Exited event can happen asynchronously to the output and error events,
                // we await the task results for stdout/stderr to ensure they both closed
                tcs.TrySetResult(new ProcessResults(process, await processStartTime.Task, await standardOutputResults.Task, await standardErrorResults.Task));
            };

            using (cancellationToken.Register(
                       () => {
                tcs.TrySetCanceled();
                try {
                    if (!process.HasExited)
                    {
                        process.Kill();
                    }
                } catch (InvalidOperationException) { }
            })) {
                cancellationToken.ThrowIfCancellationRequested();

                if (process.Start() == false)
                {
                    tcs.TrySetException(new InvalidOperationException("Failed to start process"));
                }
                processStartTime.SetResult(process.StartTime);

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

                return(await tcs.Task);
            }
        }
Ejemplo n.º 43
0
 public static IProcess Enqueue(ProcessStartInfo startInfo, Action <IProcess> preStart, Action <IProcess> postStart)
 {
     return(s_Instance.DoEnqueue(startInfo, preStart, postStart));
 }
Ejemplo n.º 44
0
        private void start_button_Click(object sender, EventArgs e)
        {
            string processName = "stitcher.exe";
            string arguments   = "-config fisheye.xml";

            if (stereo_checkBox.Checked)
            {
                arguments += " -tex \"" + input_left_L_textbox.Text + "\"";
                arguments += " -tex \"" + input_right_L_textbox.Text + "\"";
                arguments += " -tex \"" + input_top_L_textbox.Text + "\"";
                arguments += " -tex \"" + input_bottom_L_textbox.Text + "\"";

                arguments += " -tex \"" + input_left_R_textbox.Text + "\"";
                arguments += " -tex \"" + input_right_R_textbox.Text + "\"";
                arguments += " -tex \"" + input_top_R_textbox.Text + "\"";
                arguments += " -tex \"" + input_bottom_R_textbox.Text + "\"";

                arguments += " -leftPath \"" + left_output_path_textbox.Text + "\\" + FileNameTextBox.Text + "\"";
                arguments += " -rightPath \"" + right_output_path_textbox.Text + "\\" + FileNameTextBox.Text + "\"";
            }
            else
            {
                arguments += " -tex \"" + input_left_L_textbox.Text + "\"";
                arguments += " -tex \"" + input_right_L_textbox.Text + "\"";
                arguments += " -tex \"" + input_top_L_textbox.Text + "\"";
                arguments += " -tex \"" + input_bottom_L_textbox.Text + "\"";
                arguments += " -leftPath \"" + left_output_path_textbox.Text + "\\" + FileNameTextBox.Text + "\"";
            }

            arguments += " -start " + start_index_textBox.Text;
            arguments += " -seq " + input_startindex_textBox.Text + " " + input_stopindex_textBox.Text;
            arguments += " -rot " + left_transform_comboBox.Items[left_transform_comboBox.SelectedIndex].ToString();
            arguments += " " + right_transform_comboBox.Items[right_transform_comboBox.SelectedIndex].ToString();
            arguments += " " + top_transform_comboBox.Items[top_transform_comboBox.SelectedIndex].ToString();
            arguments += " " + bottom_transform_comboBox.Items[bottom_transform_comboBox.SelectedIndex].ToString();

            if (alpha_checkBox.Checked)
            {
                arguments += " -alpha 1";
            }
            else
            {
                arguments += " -alpha 0";
            }

            if (stereo_checkBox.Checked)
            {
                arguments += " -stereo 1";
            }
            else
            {
                arguments += " -stereo 0";
            }

            if (FXAACheckBox.Checked)
            {
                arguments += " -fxaa 1";
            }
            else
            {
                arguments += " -fxaa 0";
            }

            if (cubicCheckBox.Checked)
            {
                arguments += " -cubic 1";
            }
            else
            {
                arguments += " -cubic 0";
            }

            arguments += " -eyeSep " + eyeSeparation.ToString("0.000000", System.Globalization.CultureInfo.InvariantCulture);
            arguments += " -diameter " + domeDiameter.ToString("0.000000", System.Globalization.CultureInfo.InvariantCulture);
            arguments += " -msaa " + MSAA_ComboBox.Items[MSAA_ComboBox.SelectedIndex].ToString();

            string resolutionString = resolution_comboBox.Items[resolution_comboBox.SelectedIndex].ToString();

            arguments += " -res " + resolutionString.Substring(0, resolutionString.IndexOf("x"));

            string cubemapResString = cubemapComboBox.Items[cubemapComboBox.SelectedIndex].ToString();

            arguments += " -cubemap " + cubemapResString.Substring(0, cubemapResString.IndexOf("x"));

            arguments += " -format " + format_comboBox.Items[format_comboBox.SelectedIndex].ToString();
            arguments += " -compression " + compressionTrackBar.Value.ToString();

            //MessageBox.Show(arguments);

            ProcessStartInfo info = new ProcessStartInfo(processName, arguments);

            info.UseShellExecute  = false;
            info.WorkingDirectory = Directory.GetCurrentDirectory();

            try
            {
                Process.Start(info);
            }
            catch
            {
                MessageBox.Show("Couldn't find stitcher_msvc12_x64.exe!");
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        ///     Runs the redirected process and waits for it to return.
        /// </summary>
        /// <param name="workingDirectory">The directory to run the filename from.</param>
        /// <param name="command">The filename to run.</param>
        /// <param name="arguments">Parameters that will be passed to the command.</param>
        /// <returns>The exit code.</returns>
        public static int RunIn(string workingDirectory, string command, params string[] arguments)
        {
            var info = new ProcessStartInfo(command, string.Join(" ", arguments))
            {
                CreateNoWindow         = true,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                WorkingDirectory       = workingDirectory
            };

            using (var process = Process.Start(info))
            {
                if (process == null)
                {
                    throw new Exception(
                              $"Failed to run {info.FileName} {info.Arguments}\nIs the .NET Core SDK installed?");
                }

                process.EnableRaisingEvents = true;

                var processOutput = new StringBuilder();

                void OnReceived(object sender, DataReceivedEventArgs args)
                {
                    if (string.IsNullOrEmpty(args.Data))
                    {
                        return;
                    }

                    lock (processOutput)
                    {
                        processOutput.AppendLine(ProcessSpatialOutput(args.Data));
                    }
                }

                process.OutputDataReceived += OnReceived;
                process.ErrorDataReceived  += OnReceived;

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

                process.WaitForExit();

                // Ensure that the first line of the log is something useful in the Unity editor console.
                var trimmedOutput = processOutput.ToString().Trim();

                if (!string.IsNullOrEmpty(trimmedOutput))
                {
                    if (process.ExitCode == 0)
                    {
                        Debug.Log(trimmedOutput);
                    }
                    else
                    {
                        Debug.LogError(trimmedOutput);
                    }
                }

                return(process.ExitCode);
            }
        }
Ejemplo n.º 46
0
        protected override async Task DoAction()
        {
            Label = PlayingLabel;
            try
            {
                if (GameSettings.ScreenResolution == null)
                {
                    MessageBox.Show((Window)this.GetRootElement(), "Please select an available resolution.", "Information", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                    return;
                }

                String[] strArray     = GameSettings.ScreenResolution.Split('x');
                Int32    screenWidth  = Int32.Parse(strArray[0], CultureInfo.InvariantCulture);
                Int32    screenHeight = Int32.Parse(strArray[1], CultureInfo.InvariantCulture);

                String directoyPath = ".\\" + (GameSettings.IsX64 ? "x64" : "x86");

                String executablePath = directoyPath + "\\FF9.exe";
                if (GameSettings.IsDebugMode)
                {
                    String unityPath = directoyPath + "\\Unity.exe";

                    if (!File.Exists(unityPath))
                    {
                        File.Copy(executablePath, unityPath);
                        File.SetLastWriteTimeUtc(unityPath, File.GetLastWriteTimeUtc(executablePath));
                    }
                    else
                    {
                        FileInfo fi1 = new FileInfo(executablePath);
                        FileInfo fi2 = new FileInfo(unityPath);
                        if (fi1.Length != fi2.Length || fi1.LastWriteTimeUtc != fi2.LastWriteTimeUtc)
                        {
                            File.Copy(executablePath, unityPath, true);
                            File.SetLastWriteTimeUtc(unityPath, fi1.LastWriteTimeUtc);
                        }
                    }

                    executablePath = unityPath;

                    String ff9DataPath   = Path.GetFullPath(directoyPath + "\\FF9_Data");
                    String unityDataPath = Path.GetFullPath(directoyPath + "\\Unity_Data");

                    if (!Directory.Exists(unityDataPath))
                    {
                        JunctionPoint.Create(unityDataPath, ff9DataPath, true);
                    }
                }

                String arguments = $"-runbylauncher -single-instance -screen-width {screenWidth.ToString(CultureInfo.InvariantCulture)} -screen-height {screenHeight.ToString(CultureInfo.InvariantCulture)} -screen-fullscreen {(GameSettings.Windowed ? "0" : "1")}";
                await Task.Factory.StartNew(
                    () =>
                {
                    ProcessStartInfo gameStartInfo = new ProcessStartInfo(executablePath, arguments)
                    {
                        UseShellExecute = false
                    };
                    if (GameSettings.IsDebugMode)
                    {
                        gameStartInfo.EnvironmentVariables["UNITY_GIVE_CHANCE_TO_ATTACH_DEBUGGER"] = "1";
                    }

                    Process gameProcess = new Process {
                        StartInfo = gameStartInfo
                    };
                    gameProcess.Start();

                    if (GameSettings.IsDebugMode)
                    {
                        Process debuggerProcess = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.StartsWith("Memoria.Debugger"));
                        if (debuggerProcess == null)
                        {
                            String debuggerDirectory           = Path.Combine(Path.GetFullPath("Debugger"), (GameSettings.IsX64 ? "x64" : "x86"));
                            String debuggerPath                = Path.Combine(debuggerDirectory, "Memoria.Debugger.exe");
                            String debuggerArgs                = "10000"; // Timeout: 10 seconds
                            ProcessStartInfo debuggerStartInfo = new ProcessStartInfo(debuggerPath, debuggerArgs)
                            {
                                WorkingDirectory = debuggerDirectory
                            };
                            debuggerProcess = new Process {
                                StartInfo = debuggerStartInfo
                            };
                            debuggerProcess.Start();
                        }
                    }
                }
                    );

                Application.Current.Shutdown();
            }
            finally
            {
                Label = PlayLabel;
            }
        }
Ejemplo n.º 47
0
        private void Run(string path, BuilderState config)
        {
            if (!path.StartsWith("/"))
            {
                path = Path.Combine(Environment.CurrentDirectory, path);
            }

            if (!File.Exists(path))
            {
                UnityEngine.Debug.LogWarning("Shell script " + path + " doesn't exist");
                return;
            }

            string tool = "sh";

            using (var file = File.OpenText(path))
            {
                string line = file.ReadLine();
                if (line != null && line.StartsWith("#!"))
                {
                    tool = line.Substring(2);
                }
            }

            var psi = new ProcessStartInfo();

            psi.WorkingDirectory       = Environment.CurrentDirectory;
            psi.RedirectStandardOutput = true;
            psi.FileName = tool;

            psi.Arguments = MakeArgs(
                path,

                // 0
                Path.Combine(Environment.CurrentDirectory, config.buildPath),

                // 1
                // The type of player built:
                // "dashboard", "standaloneWin32", "standaloneOSXIntel", "standaloneOSXPPC", "standaloneOSXUniversal", "webplayer"
                GetPlayerTypeString(config.buildTarget),

                // 2
                // What optimizations are applied. At the moment either "" or "strip" when Strip debug symbols is selected.
                (config.buildOptions & BuildOptions.Development) != 0 ? "strip" : "",

                // 3
                // The name of the company set in the project settings
                PlayerSettings.companyName,

                // 4
                // The name of the product set in the project settings
                PlayerSettings.productName,

                // 5
                // The default screen width of the player.
                PlayerSettings.defaultScreenWidth.ToString(),

                // 6
                // The default screen height of the player
                PlayerSettings.defaultScreenHeight.ToString()
                );

            psi.EnvironmentVariables["BUILD_VERSION"]  = config.version;
            psi.EnvironmentVariables["BUILD_BUNDLEID"] = config.bundleIdentifier;
            psi.UseShellExecute = false;

            using (var p = Process.Start(psi))
            {
                string output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();

                if (!string.IsNullOrEmpty(output))
                {
                    config.Log(output);
                }
            }
        }
Ejemplo n.º 48
0
        private void CreateGameProcess()
        {
            // TODO: PUT ALL IN SEPARATE FUNCTIONS INSTEAD OF THIS DIHARREA THX
            var gameThread = new Thread(() =>
            {
                string loaderExe = "";
                string arguments = "";

                switch (_gameProfile.EmulatorType)
                {
                case EmulatorType.OpenParrot:
                    loaderExe = _gameProfile.Is64Bit ? "OpenParrotLoader64.exe" : "OpenParrotLoader.exe";
                    break;

                case EmulatorType.Lindbergh:
                    loaderExe = "BudgieLoader.exe";
                    break;

                case EmulatorType.TeknoParrot:
                default:
                    loaderExe = _gameProfile.Is64Bit ? "ParrotLoader64.exe" : "ParrotLoader.exe";
                    break;
                }

                var windowed   = _gameProfile.ConfigValues.Any(x => x.FieldName == "Windowed" && x.FieldValue == "1");
                var fullscreen = _gameProfile.ConfigValues.Any(x => x.FieldName == "Windowed" && x.FieldValue == "0");

                var extra = string.Empty;

                switch (_gameProfile.EmulationProfile)
                {
                case EmulationProfile.AfterBurnerClimax:
                    extra = fullscreen ? "-full " : string.Empty;
                    break;

                case EmulationProfile.TaitoTypeXBattleGear:
                    extra = fullscreen ? "_MTS_FULL_SCREEN_ " : string.Empty;
                    break;

                case EmulationProfile.NamcoMachStorm:
                    extra = fullscreen ? "-fullscreen " : string.Empty;
                    break;
                }

                if (_isTest)
                {
                    if (_testMenuIsExe)
                    {
                        arguments = $"\"{Path.Combine(Path.GetDirectoryName(_gameLocation), _testMenuExe)}\" {_testMenuString}";
                    }
                    else
                    {
                        arguments = $"\"{_gameLocation}\" {_testMenuString} {extra}";
                    }
                }
                else
                {
                    if (_gameProfile.EmulatorType == EmulatorType.Lindbergh)
                    {
                        if (_gameProfile.EmulationProfile == EmulationProfile.Vf5Lindbergh || _gameProfile.EmulationProfile == EmulationProfile.Vf5cLindbergh)
                        {
                            if (_gameProfile.ConfigValues.Any(x => x.FieldName == "VgaMode" && x.FieldValue == "1"))
                            {
                                extra += "-vga";
                            }
                            else
                            {
                                extra += "-wxga";
                            }
                        }
                    }

                    arguments = $"\"{_gameLocation}\" {extra}";
                }

                ProcessStartInfo info = new ProcessStartInfo(loaderExe, arguments);

                if (_gameProfile.EmulatorType == EmulatorType.Lindbergh)
                {
                    if (windowed)
                    {
                        info.EnvironmentVariables.Add("tp_windowed", "1");
                    }

                    if (_gameProfile.EmulationProfile == EmulationProfile.Vt3Lindbergh)
                    {
                        info.EnvironmentVariables.Add("tp_msysType", "2");
                    }

                    if (_gameProfile.EmulationProfile == EmulationProfile.Vf5Lindbergh)
                    {
                        info.EnvironmentVariables.Add("tp_msysType", "2");
                    }

                    if (_gameProfile.EmulationProfile == EmulationProfile.Vf5cLindbergh)
                    {
                        info.EnvironmentVariables.Add("tp_msysType", "2");
                    }

                    if (_gameProfile.EmulationProfile == EmulationProfile.SegaRtv)
                    {
                        info.EnvironmentVariables.Add("tp_msysType", "3");
                    }

                    if (_gameProfile.EmulationProfile == EmulationProfile.SegaJvsLetsGoJungle)
                    {
                        info.EnvironmentVariables.Add("tp_msysType", "3");
                    }

                    if (_gameProfile.EmulationProfile == EmulationProfile.SegaInitialDLindbergh ||
                        _gameProfile.EmulationProfile == EmulationProfile.Vf5Lindbergh ||
                        _gameProfile.EmulationProfile == EmulationProfile.Vf5cLindbergh ||
                        _gameProfile.EmulationProfile == EmulationProfile.SegaRtv ||
                        _gameProfile.EmulationProfile == EmulationProfile.SegaJvsLetsGoJungle)
                    {
                        info.EnvironmentVariables.Add("TEA_DIR", Path.GetDirectoryName(_gameLocation) + "\\");
                    }
                    else if (_gameProfile.EmulationProfile == EmulationProfile.Vt3Lindbergh)
                    {
                        info.EnvironmentVariables.Add("TEA_DIR",
                                                      Directory.GetParent(Path.GetDirectoryName(_gameLocation)) + "\\");
                    }

                    info.WorkingDirectory = Path.GetDirectoryName(_gameLocation);
                    info.UseShellExecute  = false;
                }
                else
                {
                    info.UseShellExecute = false;
                }

                info.WindowStyle = ProcessWindowStyle.Normal;

                if (InputCode.ButtonMode == EmulationProfile.NamcoMkdx)
                {
                    var AMCUS = Path.Combine(Path.GetDirectoryName(_gameLocation), "AMCUS");

                    //If these files exist, this isn't a "original version"
                    if (File.Exists(Path.Combine(AMCUS, "AMAuthd.exe")) && File.Exists(Path.Combine(AMCUS, "iauthdll.dll")))
                    {
                        // Write WritableConfig.ini
                        File.WriteAllText(
                            Path.Combine(Path.GetDirectoryName(_gameLocation), "AMCUS", "WritableConfig.ini"),
                            "[RuntimeConfig]\r\nmode=SERVER\r\nnetID=ABGN\r\nserialID=\r\n[MuchaChargeData]\r\ncamode-ch_token_consumed=0\r\ncamode-ch_token_charged=0\r\ncamode-ch_token_unit=0\r\ncamode-ch_token_lower=0\r\ncamode-ch_token_upper=0\r\ncamode-ch_token_month=0\r\n");

                        // Write AMConfig.ini
                        File.WriteAllText(Path.Combine(Path.GetDirectoryName(_gameLocation), "AMCUS", "AMConfig.ini"),
                                          "[AMUpdaterConfig] \r\n;; AMUpdater\r\namucfg-title=COCO\r\namucfg-lang=JP\r\namucfg-countdown=5\r\namucfg-h_resol=1360\r\namucfg-v_resol=768\r\namucfg-logfile=amupdater.log\r\namucfg-game_rev=1\r\n\r\n[AMAuthdConfig]\r\n;; AMAuthd\r\namdcfg-authType=ALL.NET\r\namdcfg-sleepTime=50\r\namdcfg-resoNameTimeout=180\r\namdcfg-writableConfig=WritableConfig.ini\r\namdcfg-showConsole=ENABLE\r\namdcfg-logfile=- ;\r\namdcfg-export_log=AmAuthdLog.zip ;\r\n\r\n[AllnetConfig] \r\n;; ALL.Net\r\nallcfg-gameID=SBZB\r\nallcfg-gameVer=1.10\r\n;allcfg-tenpoAddr=;\r\n;allcfg-authServerAddr=;\r\n\r\n[AllnetOptionRevalTime]\r\n;; ALL.Net\r\nallopt-reval_hour=7\r\nallopt-reval_minute=0\r\nallopt-reval_second=0\r\n\r\n[AllnetOptionTimeout]\r\n;; ALL.Net\r\nallopt-timeout_connect=60000  \r\nallopt-timeout_send=60000\r\nallopt-timeout_recv=60000\r\n\r\n[MuchaAppConfig]\r\n;; mucha_app\r\nappcfg-logfile=muchaapp.log;\r\nappcfg-loglevel=INFO ;\r\n\r\n[MuchaSysConfig]\r\n;; MUCHA\r\nsyscfg-daemon_exe=.\\MuchaBin\\muchacd.exe\r\nsyscfg-daemon_pidfile=muchacd.pid ;\r\nsyscfg-daemon_logfile=muchacd.log ;\r\nsyscfg-daemon_loglevel=INFO ;\r\nsyscfg-daemon_listen=tcp:0.0.0.0:8765\r\nsyscfg-client_connect=tcp:127.0.0.1:8765\r\n\r\n[MuchaCAConfig]\r\n;; MUCHA\r\ncacfg-game_cd=MK31 ;\r\ncacfg-game_ver=10.22\r\ncacfg-game_board_type=0\r\ncacfg-game_board_id=PCB\r\ncacfg-auth_server_url=https://127.0.0.1:443/mucha_front/\r\ncacfg-auth_server_sslverify=1\r\ncacfg-auth_server_sslcafile=.\\MuchaBin\\cakey_mk3.pem\r\ncacfg-auth_server_timeout=0\r\ncacfg-interval_ainfo_renew=1800\r\ncacfg-interval_ainfo_retry=60\r\ncacfg-auth_place_id=JPN0128C ;\r\n;cacfg-auth_store_router_ip=\r\n\r\n[MuchaDtConfig]\r\n;; MUCHA\r\ndtcfg-dl_product_id=0x4d4b3331\r\ndtcfg-dl_chunk_size=65536\r\ndtcfg-dl_image_path=chunk.img\r\ndtcfg-dl_image_size=0\r\ndtcfg-dl_image_type=FILE\r\ndtcfg-dl_image_crypt_key=0xfedcba9876543210\r\ndtcfg-dl_log_level=INFO ;\r\ndtcfg-dl_lan_crypt_key=0xfedcba9876543210\r\ndtcfg-dl_lan_broadcast_interval=1000\r\ndtcfg-dl_lan_udp_port=9026\r\ndtcfg-dl_lan_bandwidth_limit=0\r\ndtcfg-dl_lan_broadcast_address=0.0.0.0\r\ndtcfg-dl_wan_retry_limit=\r\ndtcfg-dl_wan_retry_interval=\r\ndtcfg-dl_wan_send_timeout=\r\ndtcfg-dl_wan_recv_timeout=\r\ndtcfg-dl_lan_retry_limit=\r\ndtcfg-dl_lan_retry_interval=\r\ndtcfg-dl_lan_send_timeout=\r\ndtcfg-dl_lan_recv_timeout=\r\n\r\n[MuchaDtModeConfig]\r\n;; MUCHA\r\ndtmode-io_dir=.\\ ;\r\ndtmode-io_file=MK3_JP_\r\ndtmode-io_conv=DECEXP\r\ndtmode-io_passphrase=ktinkynhgimbt\r\n");

                        // Register iauthd.dll
                        Register_Dlls(Path.Combine(Path.GetDirectoryName(_gameLocation), "AMCUS", "iauthdll.dll"));

                        // Start AMCUS
                        StartAmcus(loaderExe,
                                   $"\"{Path.Combine(Path.GetDirectoryName(_gameLocation), "AMCUS", "AMAuthd.exe")}\"");
                    }
                }

                if (InputCode.ButtonMode == EmulationProfile.SegaInitialD)
                {
                    var newCard = _gameProfile.ConfigValues.FirstOrDefault(x => x.FieldName == "EnableNewCardCode");
                    if (newCard == null || newCard.FieldValue == "0")
                    {
                        StartPicodaemon(loaderExe, $"\"{Path.Combine(Path.GetDirectoryName(_gameLocation), "picodaemon.exe")}");
                    }
                }

                var process = Process.Start(info);

                if (_parrotData.UseHaptic && _gameProfile.ForceFeedback)
                {
                    StartFfb();
                }

                while (!process.HasExited)
                {
                    if (_JvsOverride)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(this.DoCheckBoxesDude));
                    }

                    Thread.Sleep(500);
                }

                _gameRunning = false;
                TerminateThreads();

                Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(this.Close));
            });

            gameThread.Start();
        }
Ejemplo n.º 49
0
        private void ProcessUpdate(UpdaterConsoleOptions options)
        {
            var updateLocation = GetUpdateLocation();

            if (!(updateLocation.EndsWith("\\") || updateLocation.EndsWith("/")))
            {
                updateLocation += Path.DirectorySeparatorChar;
            }

            var pids = new int[] { };

            if (options.KillPids != null)
            {
                var pidsStr = options.KillPids.Split(',').Where(pid => !string.IsNullOrWhiteSpace(pid)).ToArray();
                pids = Array.ConvertAll(pidsStr, pid => int.Parse(pid));
            }

            var isWindows     = Environment.OSVersion.Platform == PlatformID.Win32NT;
            var trayRunning   = false;
            var trayProcesses = Process.GetProcessesByName("JackettTray");

            if (isWindows)
            {
                if (trayProcesses.Count() > 0)
                {
                    foreach (var proc in trayProcesses)
                    {
                        try
                        {
                            logger.Info("Killing tray process " + proc.Id);
                            proc.Kill();
                            trayRunning = true;
                        }
                        catch { }
                    }
                }

                // on unix we don't have to wait (we can overwrite files which are in use)
                // On unix we kill the PIDs after the update so e.g. systemd can automatically restart the process
                KillPids(pids);
            }
            logger.Info("Finding files in: " + updateLocation);
            var files = Directory.GetFiles(updateLocation, "*.*", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                var fileName = Path.GetFileName(file).ToLowerInvariant();

                if (fileName.EndsWith(".zip") ||
                    fileName.EndsWith(".tar") ||
                    fileName.EndsWith(".gz"))
                {
                    continue;
                }
                try
                {
                    logger.Info("Copying " + fileName);
                    var dest    = Path.Combine(options.Path, file.Substring(updateLocation.Length));
                    var destDir = Path.GetDirectoryName(dest);
                    if (!Directory.Exists(destDir))
                    {
                        logger.Info("Creating directory " + destDir);
                        Directory.CreateDirectory(destDir);
                    }
                    File.Copy(file, dest, true);
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // delete old dirs
            string[] oldDirs = new string[] { "Content/logos" };

            foreach (var oldDir in oldDirs)
            {
                try
                {
                    var deleteDir = Path.Combine(options.Path, oldDir);
                    if (Directory.Exists(deleteDir))
                    {
                        logger.Info("Deleting directory " + deleteDir);
                        Directory.Delete(deleteDir, true);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // delete old files
            string[] oldFiles = new string[] {
                "Content/css/jquery.dataTables.css",
                "Content/css/jquery.dataTables_themeroller.css",
                "Definitions/tspate.yml",
                "Definitions/freakstrackingsystem.yml",
                "Definitions/rarbg.yml",
                "Definitions/t411.yml",
                "Definitions/hdbc.yml", // renamed to hdbitscom
                "Definitions/maniatorrent.yml",
                "Definitions/nyaa.yml",
                "Definitions/nachtwerk.yml",
                "Definitions/leparadisdunet.yml",
                "Definitions/qctorrent.yml",
                "Definitions/dragonworld.yml",
                "Definitions/hdclub.yml",
                "Definitions/polishtracker.yml",
                "Definitions/zetorrents.yml",
                "Definitions/rapidetracker.yml",
                "Definitions/isohunt.yml",
                "Definitions/t411v2.yml",
                "Definitions/bithq.yml",
                "Definitions/blubits.yml",
                "Definitions/torrentproject.yml",
                "Definitions/torrentvault.yml",
                "Definitions/apollo.yml",       // migrated to C# gazelle base tracker
                "Definitions/secretcinema.yml", // migrated to C# gazelle base tracker
                "Definitions/utorrents.yml",    // same as SzeneFZ now
                "Definitions/ultrahdclub.yml",
                "Definitions/infinityt.yml",
                "Definitions/hachede-c.yml",
                "Definitions/hd4Free.yml",
                "Definitions/skytorrents.yml",
                "Definitions/gormogon.yml",
                "Definitions/czteam.yml",
                "Definitions/rockhardlossless.yml",
                "Definitions/oxtorrent.yml",
                "Definitions/tehconnection.yml",
                "Definitions/torrentwtf.yml",
                "Definitions/eotforum.yml",
                "Definitions/nexttorrent.yml",
                "appsettings.Development.json",
                "appsettings.json",
                "CurlSharp.dll",
                "CurlSharp.pdb",
                "Jackett.dll",
                "Jackett.dll.config",
                "Jackett.pdb",
                "Autofac.Integration.WebApi.dll",
                "Microsoft.Owin.dll",
                "Microsoft.Owin.FileSystems.dll",
                "Microsoft.Owin.Host.HttpListener.dll",
                "Microsoft.Owin.Hosting.dll",
                "Microsoft.Owin.StaticFiles.dll",
                "Owin.dll",
                "System.Web.Http.dll",
                "System.Web.Http.Owin.dll",
                "System.Web.Http.Tracing.dll",
            };

            foreach (var oldFile in oldFiles)
            {
                try
                {
                    var deleteFile = Path.Combine(options.Path, oldFile);
                    if (File.Exists(deleteFile))
                    {
                        logger.Info("Deleting file " + deleteFile);
                        File.Delete(deleteFile);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // kill pids after the update on UNIX
            if (!isWindows)
            {
                KillPids(pids);
            }

            if (options.NoRestart == false)
            {
                if (isWindows && (trayRunning || options.StartTray) && !string.Equals(options.Type, "WindowsService", StringComparison.OrdinalIgnoreCase))
                {
                    var startInfo = new ProcessStartInfo()
                    {
                        Arguments       = $"--UpdatedVersion \" {EnvironmentUtil.JackettVersion}\"",
                        FileName        = Path.Combine(options.Path, "JackettTray.exe"),
                        UseShellExecute = true
                    };

                    logger.Info("Starting Tray: " + startInfo.FileName + " " + startInfo.Arguments);
                    Process.Start(startInfo);

                    if (!windowsService.ServiceExists())
                    {
                        //User was running the tray icon, but not using the Windows service, starting Tray icon will start JackettConsole as well
                        return;
                    }
                }

                if (string.Equals(options.Type, "WindowsService", StringComparison.OrdinalIgnoreCase))
                {
                    logger.Info("Starting Windows service");

                    if (ServerUtil.IsUserAdministrator())
                    {
                        windowsService.Start();
                    }
                    else
                    {
                        try
                        {
                            var consolePath = Path.Combine(options.Path, "JackettConsole.exe");
                            processService.StartProcessAndLog(consolePath, "--Start", true);
                        }
                        catch
                        {
                            logger.Error("Failed to get admin rights to start the service.");
                        }
                    }
                }
                else
                {
                    var startInfo = new ProcessStartInfo()
                    {
                        Arguments       = options.Args,
                        FileName        = Path.Combine(options.Path, "JackettConsole.exe"),
                        UseShellExecute = true
                    };

                    if (isWindows)
                    {
                        //User didn't initiate the update from Windows service and wasn't running Jackett via the tray, must have started from the console
                        startInfo.Arguments      = $"/K {startInfo.FileName} {startInfo.Arguments}";
                        startInfo.FileName       = "cmd.exe";
                        startInfo.CreateNoWindow = false;
                        startInfo.WindowStyle    = ProcessWindowStyle.Normal;
                    }
                    else
                    {
                        startInfo.Arguments = startInfo.FileName + " " + startInfo.Arguments;
                        startInfo.FileName  = "mono";
                    }

                    logger.Info("Starting Jackett: " + startInfo.FileName + " " + startInfo.Arguments);
                    Process.Start(startInfo);
                }
            }
        }
Ejemplo n.º 50
0
        private static bool CheckUpdate(string[] args)
        {
            string currentPath = CUOEnviroment.ExecutablePath;

            string path      = string.Empty;
            string action    = string.Empty;
            int    processId = -1;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "--source" && i < args.Length - 1)
                {
                    path = args[i + 1];
                }
                else if (args[i] == "--action" && i < args.Length - 1)
                {
                    action = args[i + 1];
                }
                else if (args[i] == "--pid" && i < args.Length - 1)
                {
                    processId = int.Parse(args[i + 1]);
                }
            }

            if (action != string.Empty)
            {
                Console.WriteLine("[CheckUpdate] CURRENT PATH: {0}", currentPath);
                Console.WriteLine("[CheckUpdate] Args: \tpath={0}\taction={1}\tpid={2}", path, action, processId);
            }

            if (action == "update")
            {
                Log.Trace("ClassicUO Updating...");

                try
                {
                    Process processToBeKilled = Process.GetProcessById(processId);
                    processToBeKilled.Kill();
                    processToBeKilled.WaitForExit(5000);
                }
                catch
                {
                }

                //File.SetAttributes(Path.GetDirectoryName(path), FileAttributes.Normal);

                //foreach (string file in Directory.EnumerateFiles(currentPath, "*", SearchOption.AllDirectories))
                //{
                //    string sub = Path.Combine(file, file.Replace(currentPath, path));
                //    Console.WriteLine("COPIED {0} over {1}", file, sub);
                //    File.Copy(file, sub, true);
                //}

                DirectoryInfo dd = new DirectoryInfo(currentPath);
                dd.CopyAllTo(new DirectoryInfo(path));

                ProcessStartInfo processStartInfo = new ProcessStartInfo
                {
                    WorkingDirectory = path,
                    UseShellExecute  = false
                };

                if (CUOEnviroment.IsUnix)
                {
                    processStartInfo.FileName = "mono";

                    processStartInfo.Arguments = $"\"{Path.Combine(path, "ClassicUO.exe")}\" --source \"{currentPath}\" --pid {Process.GetCurrentProcess().Id} --action cleanup";
                }
                else
                {
                    processStartInfo.FileName = Path.Combine(path, "ClassicUO.exe");

                    processStartInfo.Arguments = $"--source \"{currentPath}\" --pid {Process.GetCurrentProcess().Id} --action cleanup";
                }

                Process.Start(processStartInfo);

                return(true);
            }

            if (action == "cleanup")
            {
                try
                {
                    Process.GetProcessById(processId);
                    Thread.Sleep(1000);

                    Process.GetProcessById(processId).Kill();
                }
                catch
                {
                }

                try
                {
                    Directory.Delete(path, true);
                }
                catch (Exception)
                {
                }

                Log.Trace("ClassicUO updated successfully!");
            }

            return(false);
        }
Ejemplo n.º 51
0
        private static bool CompileProtobufSystemPath(string protoFileSystemPath, string[] includePaths)
        {
            //Do not compile changes coming from UPM package.
            if (protoFileSystemPath.Contains("Packages/com.e7.protobuf-unity"))
            {
                return(false);
            }

            if (Path.GetExtension(protoFileSystemPath) == ".proto")
            {
                string outputPath = Path.GetDirectoryName(protoFileSystemPath);

                string options = " --csharp_out \"{0}\" ";
                if (ProtoPrefs.enabledGRPC)
                {
                    options += "--grpc_out \"{0}\"  --plugin=protoc-gen-grpc=" + ProtoPrefs.rawGRPCPath;
                }
                foreach (string s in includePaths)
                {
                    options += string.Format(" --proto_path \"{0}\" ", s);
                }

                //string combinedPath = string.Join(" ", optionFiles.Concat(new string[] { protoFileSystemPath }));

                string finalArguments = string.Format("\"{0}\"", protoFileSystemPath) + string.Format(options, outputPath);

                if (ProtoPrefs.logStandard)
                {
                    UnityEngine.Debug.Log("Protobuf Unity : Final arguments :\n" + finalArguments);
                }

                ProcessStartInfo startInfo = new ProcessStartInfo()
                {
                    FileName = ProtoPrefs.excPath, Arguments = finalArguments
                };

                Process proc = new Process()
                {
                    StartInfo = startInfo
                };
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError  = true;
                proc.Start();

                string output = proc.StandardOutput.ReadToEnd();
                string error  = proc.StandardError.ReadToEnd();
                proc.WaitForExit();

                if (ProtoPrefs.logStandard)
                {
                    if (output != "")
                    {
                        UnityEngine.Debug.Log("Protobuf Unity : " + output);
                    }
                    UnityEngine.Debug.Log("Protobuf Unity : Compiled " + Path.GetFileName(protoFileSystemPath));
                }

                if (ProtoPrefs.logError && error != "")
                {
                    UnityEngine.Debug.LogError("Protobuf Unity : " + error);
                }
                return(true);
            }
            return(false);
        }
    public static ShellRequest ProcessCommand(string cmd, string workDirectory, List <string> environmentVars = null)
    {
        ShellRequest req = new ShellRequest();

        ThreadPool.QueueUserWorkItem(delegate(object state)
        {
            Process p = null;
            try
            {
                ProcessStartInfo start = new ProcessStartInfo(shellApp);

#if UNITY_EDITOR_OSX
                string splitChar = ":";
                start.Arguments  = "-c";
#elif UNITY_EDITOR_WIN
                string splitChar = ";";
                start.Arguments  = "/c";
#endif

                if (environmentVars != null)
                {
                    foreach (string
                             var in environmentVars)
                    {
                        start.EnvironmentVariables["PATH"] += (splitChar +
                                                               var);
                    }
                }

                start.Arguments      += (" \"" + cmd + " \"");
                start.CreateNoWindow  = true;
                start.ErrorDialog     = true;
                start.UseShellExecute = false;
                //start.WorkingDirectory = workDirectory;

                if (start.UseShellExecute)
                {
                    start.RedirectStandardOutput = false;
                    start.RedirectStandardError  = false;
                    start.RedirectStandardInput  = false;
                }
                else
                {
                    start.RedirectStandardOutput = true;
                    start.RedirectStandardError  = true;
                    start.RedirectStandardInput  = true;
                    start.StandardOutputEncoding = UTF8Encoding.UTF8;
                    start.StandardErrorEncoding  = UTF8Encoding.UTF8;
                }

                p = Process.Start(start);
                p.ErrorDataReceived  += delegate(object sender, DataReceivedEventArgs e) { Debug.LogError(e.Data); };
                p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { Debug.LogError(e.Data); };
                p.Exited             += delegate(object sender, EventArgs e) { Debug.LogError(e.ToString()); };

                bool hasError = false;
                do
                {
                    string line = p.StandardOutput.ReadLine();
                    if (line == null)
                    {
                        break;
                    }

                    line = line.Replace("\\", "/");
                    _queue.Add(delegate() { req.Log(0, line); });
                } while (true);

                while (true)
                {
                    string error = p.StandardError.ReadLine();
                    if (string.IsNullOrEmpty(error))
                    {
                        break;
                    }

                    hasError = true;
                    _queue.Add(delegate() { req.Log(1, error); });
                }

                p.Close();
                if (hasError)
                {
                    _queue.Add(delegate() { req.Error(); });
                }
                else
                {
                    _queue.Add(delegate() { req.NotifyDone(); });
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                if (p != null)
                {
                    p.Close();
                }
            }
        });
        return(req);
    }
Ejemplo n.º 53
0
        public static ProcessStartInfo CreateProcessStartInfo(IServiceProvider provider, LaunchConfiguration config)
        {
            var psi = new ProcessStartInfo {
                FileName  = config.GetInterpreterPath(),
                Arguments = string.Join(" ", new[] {
                    config.InterpreterArguments,
                    config.ScriptName == null ? "" : ProcessOutput.QuoteSingleArgument(config.ScriptName),
                    config.ScriptArguments
                }.Where(s => !string.IsNullOrEmpty(s))),
                WorkingDirectory = config.WorkingDirectory,
                UseShellExecute  = false
            };

            if (string.IsNullOrEmpty(psi.FileName))
            {
                throw new FileNotFoundException(Strings.DebugLaunchInterpreterMissing);
            }
            if (!File.Exists(psi.FileName))
            {
                throw new FileNotFoundException(Strings.DebugLaunchInterpreterMissing_Path.FormatUI(psi.FileName));
            }
            if (string.IsNullOrEmpty(psi.WorkingDirectory))
            {
                psi.WorkingDirectory = PathUtils.GetParent(config.ScriptName);
            }
            if (string.IsNullOrEmpty(psi.WorkingDirectory))
            {
                throw new DirectoryNotFoundException(Strings.DebugLaunchWorkingDirectoryMissing);
            }
            if (!Directory.Exists(psi.WorkingDirectory))
            {
                throw new DirectoryNotFoundException(Strings.DebugLaunchWorkingDirectoryMissing_Path.FormatUI(psi.WorkingDirectory));
            }

            foreach (var kv in provider.GetPythonToolsService().GetFullEnvironment(config))
            {
                psi.Environment[kv.Key] = kv.Value;
            }

            var pyService = provider.GetPythonToolsService();
            // Pause if the user has requested it.
            string pauseCommand = null;

            if (config.GetLaunchOption(PythonConstants.NeverPauseOnExit).IsTrue())
            {
                // Do nothing
            }
            else if (pyService.DebuggerOptions.WaitOnAbnormalExit && pyService.DebuggerOptions.WaitOnNormalExit)
            {
                pauseCommand = "pause";
            }
            else if (pyService.DebuggerOptions.WaitOnAbnormalExit && !pyService.DebuggerOptions.WaitOnNormalExit)
            {
                pauseCommand = "if errorlevel 1 pause";
            }
            else if (pyService.DebuggerOptions.WaitOnNormalExit && !pyService.DebuggerOptions.WaitOnAbnormalExit)
            {
                pauseCommand = "if not errorlevel 1 pause";
            }

            if (!string.IsNullOrEmpty(pauseCommand))
            {
                psi.Arguments = string.Format("/c \"{0} {1}\" & {2}",
                                              ProcessOutput.QuoteSingleArgument(psi.FileName),
                                              psi.Arguments,
                                              pauseCommand
                                              );
                psi.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
            }

            return(psi);
        }
Ejemplo n.º 54
0
        }//btnSearch_Click

        //compare button action
        private void brnCompare_Click(object sender, EventArgs e)
        {
            Process          p     = new Process();
            ProcessStartInfo pinfo = new ProcessStartInfo();

            p.StartInfo           = pinfo;
            pinfo.FileName        = "CMD.exe";
            pinfo.WindowStyle     = ProcessWindowStyle.Hidden;
            pinfo.CreateNoWindow  = true;
            pinfo.UseShellExecute = false;

            pinfo.RedirectStandardInput  = true;
            pinfo.RedirectStandardError  = true;
            pinfo.RedirectStandardOutput = true;
            p.EnableRaisingEvents        = false;
            p.Start();


            int selectionStart  = tbxReleaseFileList.SelectionStart;
            int selectionLength = tbxReleaseFileList.SelectionLength;

            releaseFileListlines = releaseFileListlines == null ? tbxReleaseFileList.Lines : releaseFileListlines;
            backupFileListlines  = backupFileListlines == null ? tbxBackupFiles.Lines : backupFileListlines;

            int selectedLine          = 0;
            int currentReleaseFileCnt = 0;

            //total count include \r\n. it is 36 char bigger than text count.
            for (int i = 0; i < releaseFileListlines.Length; i++)
            {
                int preCnt = currentReleaseFileCnt;
                currentReleaseFileCnt = preCnt + releaseFileListlines[i].Length + 2;

                if (preCnt < selectionStart && selectionStart < currentReleaseFileCnt)
                {
                    selectedLine = i;
                }
            }

            string execUcl = "";

            if (string.IsNullOrEmpty(parser.CompareToolPath))
            {
                MessageBox.Show("(비교툴경로)가 설정되어있지 않습니다.");
                return;
            }

            if (releaseFileListlines[selectedLine].EndsWith(".java"))
            {
                string[] decompileFiles = decompileJava(backupFileListlines[selectedLine]);
                if (decompileFiles[0] == null || decompileFiles[1] == null)
                {
                    return;
                }
                try { execUcl = string.Format(@"""{0}"" ""{1}"" ""{2}""", parser.CompareToolPath, decompileFiles[0], decompileFiles[1]); }
                catch { execUcl = string.Format(@"ucl.exe"); }
            }
            else
            {
                try { execUcl = string.Format(@"""{0}"" ""{1}"" ""{2}""", parser.CompareToolPath, releaseFileListlines[selectedLine], backupFileListlines[selectedLine]); }
                catch { execUcl = string.Format(@"ucl.exe"); }
            }



            p.StandardInput.WriteLine(execUcl);
            p.StandardInput.Close();

            //  p.WaitForExit();
            p.Close();
            tbxReleaseFileList.Focus();
            tbxReleaseFileList.SelectionStart  = selectionStart;
            tbxReleaseFileList.SelectionLength = selectionLength;
        }//brnCompare_Click
Ejemplo n.º 55
0
        public void Setup()
        {
            Console.Write("Enter video framerate: ");
            var framerate = Console.ReadLine();

            Console.Write("Enter total frame count: ");
            var frames = int.Parse(Console.ReadLine());

            Console.Write("Enter output video file name (no extension): ");
            var name = Console.ReadLine().Trim();

            Console.Write("Enter resolution separated by a comma (480,480): ");
            var res = Console.ReadLine().Split(',').ToList().ConvertAll(resPart => int.Parse(resPart)).ToArray();

            Console.Write("Enter mandelbrot power range (x in f(z)=z^x + c) separated by a comma (1,10): ");
            var range = Console.ReadLine().Split(',').ToList().ConvertAll(rangePart => int.Parse(rangePart)).ToArray();
            var s     = Stopwatch.StartNew();

            Console.WriteLine("Generation is starting, please wait...");
            var done = 0;

            var items  = Enumerable.Range(0, frames).ToArray();
            var chunks = items
                         .Select((s2, i) => new { Value = s2, Index = i })
                         .GroupBy(x => x.Index / 10)
                         .Select(grp => grp.Select(x => x.Value).ToArray()).ToList();

            var threads = new List <Thread>();

            for (var t = 0; t < Environment.ProcessorCount - 1; t++)
            {
                var t2     = t;
                var thread = new Thread(() =>
                {
                    start:;
                    if (chunks.Count == 0)
                    {
                        goto exit;
                    }

                    var assignedChunk = chunks[0];
                    chunks.RemoveAt(0);
                    foreach (var a in assignedChunk)
                    {
                        var pow   = PMath.Map(a, 1, frames, range[0], range[1]);
                        var Image = new PSprite(res[0], res[1]);

                        var pixels = Image.Art.GetPixels();
                        for (var y = 0; y < Image.Height; y++)
                        {
                            for (var x = 0; x < Image.Width; x++)
                            {
                                var xTarget = 4f;
                                var yTarget = (xTarget / Image.Width) * Image.Height;

                                var x2 = (x / (Image.Width / (xTarget))) - (xTarget / 2);
                                var y2 = (y / (Image.Height / (yTarget))) - (yTarget / 2);

                                var c         = new Complex(x2, y2);
                                var z         = Complex.Zero;
                                var max       = -1f;
                                var maxWasHit = false;
                                for (var i = 0; i < maxDepth; i++)
                                {
                                    z = (Complex.Pow(z, pow)) + c;
                                    if ((z.Real * z.Real) + (z.Imaginary * z.Imaginary) > 16 && max == -1f)
                                    {
                                        max       = i;
                                        maxWasHit = true;
                                        break;
                                    }
                                }

                                var color = PColor.Black;

                                if (maxWasHit)
                                {
                                    var floorMax = (int)Math.Floor(max);
                                    var c1       = pallet[floorMax % pallet.Length];
                                    var c2       = pallet[(floorMax + 1) % pallet.Length];
                                    color        = PColor.Lerp(c1, c2, 0.5f);
                                }

                                var pos = ((y * Image.Width) + x) * 4;

                                pixels[pos]     = (byte)(color.R);
                                pixels[pos + 1] = (byte)(color.G);
                                pixels[pos + 2] = (byte)(color.B);
                                pixels[pos + 3] = 255;
                            }
                        }
                        Image.Art.SetPixels(pixels);
                        Image.Save(folder + a.ToString("000000") + ".png");
                        var percent           = (done / (float)frames);
                        var remaining         = (1f - percent) * 100;
                        var secondsPerPercent = s.Elapsed.TotalSeconds / (percent * 100f);
                        var minutesRemaining  = ((secondsPerPercent * remaining) / 60f);
                        var estimatedTime     = DateTime.Now.AddMinutes(done == 0 ? 0 : minutesRemaining);
                        Console.WriteLine("Progress: " + done + "/" + frames + "  " + (percent * 100f).ToString("0.00") +
                                          "%   Estimated completion time: " + estimatedTime);
                        done++;
                    }
                    goto start;
                    exit:;
                })
                {
                    Name     = "Mandelbrot: Core " + (t + 1),
                    Priority = ThreadPriority.AboveNormal,
                };
                threads.Add(thread);
                thread.Start();
            }
            ;

            var info = new ProcessStartInfo()
            {
                FileName         = "ffmpeg",
                Arguments        = string.Format(" -framerate {0} -i %06d.png -c:v libx264 -r {0} {1}.mp4", framerate, name),
                WorkingDirectory = folder,
            };

            var activeThreads = 1;

            do
            {
                Console.Title = "Active thread count: " + activeThreads;
                activeThreads = threads.Where(t => t.IsAlive).Count();
                Thread.Sleep(1000);
                Title(activeThreads);
            }while (activeThreads > 0);

            Console.Title = "Active thread count: 0";

            var p = Process.Start(info);

            p.WaitForExit();

            Console.WriteLine(@"Saved as " + folder + "out.mp4");
            Console.ReadLine();
            Close();
        }
Ejemplo n.º 56
0
    /// <summary>
    /// Runs the specified executable with the provided arguments and returns the process' exit code.
    /// </summary>
    /// <param name="output">Recieves the output of either std/err or std/out</param>
    /// <param name="input">Provides the line-by-line input that will be written to std/in, null for empty</param>
    /// <param name="exe">The executable to run, may be unqualified or contain environment variables</param>
    /// <param name="args">The list of unescaped arguments to provide to the executable</param>
    /// <returns>Returns process' exit code after the program exits</returns>
    /// <exception cref="System.IO.FileNotFoundException">Raised when the exe was not found</exception>
    /// <exception cref="System.ArgumentNullException">Raised when one of the arguments is null</exception>
    /// <exception cref="System.ArgumentOutOfRangeException">Raised if an argument contains '\0', '\r', or '\n'
    public static int Run(Action <string> output, TextReader input, string exe, params string[] args)
    {
        if (String.IsNullOrEmpty(exe))
        {
            throw new FileNotFoundException();
        }
        if (output == null)
        {
            throw new ArgumentNullException("output");
        }

        ProcessStartInfo psi = new ProcessStartInfo();

        psi.UseShellExecute        = false;
        psi.RedirectStandardError  = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardInput  = true;
        psi.WindowStyle            = ProcessWindowStyle.Hidden;
        psi.CreateNoWindow         = true;
        psi.ErrorDialog            = false;
        psi.WorkingDirectory       = WorkingFolder;
        psi.FileName  = FindExePath(exe);
        psi.Arguments = EscapeArguments(args);

        using (Process process = Process.Start(psi))
            using (ManualResetEvent mreOut = new ManualResetEvent(false),
                   mreErr = new ManualResetEvent(false))
            {
                process.OutputDataReceived += (o, e) =>
                {
                    if (e.Data == null)
                    {
                        mreOut.Set();
                    }
                    else
                    {
                        output(e.Data);
                    }
                };
                process.BeginOutputReadLine();
                process.ErrorDataReceived += (o, e) =>
                {
                    if (e.Data == null)
                    {
                        mreErr.Set();
                    }
                    else
                    {
                        output(e.Data);
                    }
                };
                process.BeginErrorReadLine();

                string line;
                while (input != null && null != (line = input.ReadLine()))
                {
                    process.StandardInput.WriteLine(line);
                }

                process.StandardInput.Close();
                process.WaitForExit();

                mreOut.WaitOne();
                mreErr.WaitOne();
                return(process.ExitCode);
            }
    }
Ejemplo n.º 57
0
        /// <summary>
        ///     The OAuth code receiver
        /// </summary>
        /// <param name="authorizeMode">which of the AuthorizeModes was used to call the method</param>
        /// <param name="codeReceiverSettings"></param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>Dictionary with values</returns>
        public async Task <IDictionary <string, string> > ReceiveCodeAsync(AuthorizeModes authorizeMode, ICodeReceiverSettings codeReceiverSettings,
                                                                           CancellationToken cancellationToken = default)
        {
            // Force OOB Uri, if nothing is set
            if (string.IsNullOrEmpty(codeReceiverSettings.RedirectUrl))
            {
                switch (authorizeMode)
                {
                case AuthorizeModes.OutOfBound:
                    codeReceiverSettings.RedirectUrl = "urn:ietf:wg:oauth:2.0:oob";
                    break;

                case AuthorizeModes.OutOfBoundAuto:
                    codeReceiverSettings.RedirectUrl = "urn:ietf:wg:oauth:2.0:oob:auto";
                    break;

                default:
                    throw new NotSupportedException($"Only {AuthorizeModes.OutOfBound} and {AuthorizeModes.OutOfBoundAuto} are supported modes for this receiver");
                }
            }

            var uriBuilder = new UriBuilder(codeReceiverSettings.AuthorizationUri)
            {
                Query = codeReceiverSettings.AuthorizationUri.QueryToKeyValuePairs()
                        .Select(x => new KeyValuePair <string, string>(x.Key, x.Value.FormatWith(codeReceiverSettings)))
                        .ToQueryString()
            };

            // Get the formatted FormattedAuthUrl
            var authorizationUrl = uriBuilder.Uri;

            Log.Debug().WriteLine("Opening a browser with: {0}", authorizationUrl.AbsoluteUri);
            // Open the url in the default browser
            var processStartInfo = new ProcessStartInfo(authorizationUrl.AbsoluteUri)
            {
                CreateNoWindow  = true,
                UseShellExecute = true
            };

            Process.Start(processStartInfo);

            Log.Debug().WriteLine("Waiting until a window gets a title with the state {0}", codeReceiverSettings.State);
            // Wait until a window get's a title which contains the state object
            var title = await WinEventHook.WindowTileChangeObservable()
                        .Select(info => InteropWindowFactory.CreateFor(info.Handle).Fill())
                        .Where(interopWindow => !string.IsNullOrEmpty(interopWindow?.Caption))
                        .Where(interopWindow => interopWindow.Caption.Contains(codeReceiverSettings.State))
                        // Skip temporary titles, where the redirect URL os briefly seen
                        .Where(interopWindow => interopWindow?.Caption.Contains(codeReceiverSettings.RedirectUrl) != true)
                        .Select(interopWindow => interopWindow.Caption)
                        .Take(1).ToTask(cancellationToken);

            Log.Debug().WriteLine("Got title {0}", title);
            if (string.IsNullOrEmpty(title))
            {
                return(new Dictionary <string, string>());
            }

            var match = QueryPartOfTitleRegEx.Match(title);

            if (!match.Success)
            {
                return(UriParseExtensions.QueryStringToDictionary(title));
            }

            var queryParameters = match.Groups["query"]?.Value;

            if (string.IsNullOrEmpty(queryParameters))
            {
                return(new Dictionary <string, string>());
            }
            Log.Debug().WriteLine("Query parameters: {0}", queryParameters);
            // Return result of the listening
            return(UriParseExtensions.QueryStringToDictionary(queryParameters));
        }
Ejemplo n.º 58
0
 public ProcessImpl(ProcessStartInfo startInfo, Action <IProcess> preStart, Action <IProcess> postStart)
 {
     this.startInfo = startInfo;
     m_PreStart     = preStart;
     m_PostStart    = postStart;
 }
Ejemplo n.º 59
0
        private void simpleButtonShowShareFlags_Click(object sender, EventArgs e)
        {
            if (!_isElevated)
            {
                ShowMessageBox("This feature is only available when running in elevated mode!");                 // ShareFlags in Handle.exe are only visible when runasadministrator
                return;
            }

            RowViewModel row = (RowViewModel)gridView1.GetFocusedRow();

            if (row == null)
            {
                ShowMessageBox("No focused row!");
                return;
            }
            if (row.ObjectTypeString != "File")
            {
                ShowMessageBox("Focused row is not of type'File'!");
                return;
            }

            const int        ERROR_CANCELLED = 1223;                                //The operation was canceled by the user.
            ProcessStartInfo info            = new ProcessStartInfo(@"Handle.exe"); // tool has to be in the same folder as this program

            info.RedirectStandardOutput = true;
            info.UseShellExecute        = false;      // 'UseShellExecute = true' does not work with redirect
            info.Arguments      = "-p " + row.PID;
            info.CreateNoWindow = true;
            //info.Verb = "runas"; needs UseShellExecute = true
            Process p = null;

            try
            {
                p = Process.Start(info);
            }
            catch (Win32Exception ex)
            {
                if (ex.NativeErrorCode == ERROR_CANCELLED)
                {
                    ShowMessageBox("Feature cannot run without admin privileges!");
                }
                else
                {
                    ShowMessageBox(ex.Message);
                }
            }
            Task <string> resultt = p.StandardOutput.ReadToEndAsync();

            p.WaitForExit();
            string es                = resultt.Result;
            var    lines             = es.Split(new[] { "\r\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string expectedLineStart = $"{row.Handle,5:X}: File  ";
            string foundLine         = lines.FirstOrDefault(item => item.StartsWith(expectedLineStart));

            if (foundLine == null)
            {
                ShowMessageBox("Handle not found!");
            }
            else
            {
                ShowMessageBox(foundLine);
            }
        }
Ejemplo n.º 60
-1
	static void Main ()
	{
		for (int i = 0; i < 1000; ++i) {
			ProcessStartInfo psi = new ProcessStartInfo () {
				FileName = "echo",
				Arguments = "hello 1>/dev/null",
			};

			Process p = Process.Start (psi);

			ManualResetEvent mre = new ManualResetEvent (false);

			Task t = Task.Run (() => {
				mre.Set ();
				if (!p.WaitForExit (1000))
					Environment.Exit (1);
			});

			if (!mre.WaitOne (1000))
				Environment.Exit (2);
			if (!p.WaitForExit (1000))
				Environment.Exit (3);

			if (!t.Wait (1000))
				Environment.Exit (4);
		}
	}