WaitForExit() public method

public WaitForExit ( int milliseconds ) : bool
milliseconds int
return bool
Exemplo n.º 1
12
        public String cmd(String cnd)
        {

            cnd = cnd.Trim();
            String output = " ";
            Console.WriteLine(cnd);

            if ((cnd.Substring(0, 3).ToLower() == "cd_") && (cnd.Length > 2))
            {

                if (System.IO.Directory.Exists(cnd.Substring(2).Trim()))
                    cpath = cnd.Substring(2).Trim();

            }
            else
            {
                cnd = cnd.Insert(0, "/B /c ");
                Process p = new Process();
                p.StartInfo.WorkingDirectory = cpath;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.Arguments = cnd;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();
                output = p.StandardOutput.ReadToEnd();  // output of cmd
                output = (output.Length == 0) ? " " : output;
                p.WaitForExit();

            }
            return output;
        } // end cmd 
Exemplo n.º 2
2
        void Button1Click(object sender, EventArgs e)
        {
            Process myProcess = new Process();

            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(@"C:\Users\IJMAIL\AppData\Roaming\Nox\bin\nox_adb.exe" );
            myProcessStartInfo.Arguments = "devices";
            myProcessStartInfo.UseShellExecute = false;
            myProcessStartInfo.RedirectStandardOutput = true;		// 데이터 받기
            myProcessStartInfo.RedirectStandardError = true;		// 오류내용 받기
            myProcessStartInfo.CreateNoWindow = true;				// 원도우창 띄우기(true 띄우지 않기, false 띄우기)
            myProcess.StartInfo = myProcessStartInfo;
            myProcess.Start();
            myProcess.WaitForExit();

            //string output = myProcess.StandardOutput.ReadToEnd();
            string output = myProcess.StandardOutput.ReadToEnd();
            string error = myProcess.StandardError.ReadToEnd();
            string[] aa = output.Split('\n');

            for(int i=1; i<aa.Length; i++) {
                listBox1.Items.Add(aa[i]);
            }

            //listBox1.Items.Add(aa.Length);

            //listBox1.Items.Add(aa[1]);

            //listBox1.Text = output;

            // 프로그램이 종료되면
            //System.Console.WriteLine( "ExitCode is " + myProcess.ExitCode );
            myProcess.WaitForExit();
            myProcess.Close();
        }
Exemplo n.º 3
1
 public static string Run(string path, string args, out string error)
 {
     try
     {
         using (Process process = new Process())
         {
             process.StartInfo.FileName = path;
             process.StartInfo.Arguments = args;
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.RedirectStandardError = true;
             process.Start();
             process.WaitForExit();
             error = process.StandardError.ReadToEnd();
             if (process.ExitCode != 0)
             {
                 return string.Empty;
             }
             return process.StandardOutput.ReadToEnd().Trim().Replace(@"\\", @"\");
         }
     }
     catch (Exception exception)
     {
         error = string.Format("Calling {0} caused an exception: {1}.", path, exception.Message);
         return string.Empty;
     }
 }
Exemplo n.º 4
1
        private MemoryStream GetThumbnailFromProcess(Process p, ref int width, ref int height)
        {
            Debug("Starting ffmpeg");
              using (var thumb = new MemoryStream()) {
            var pump = new StreamPump(p.StandardOutput.BaseStream, thumb, null, 4096);
            if (!p.WaitForExit(20000)) {
              p.Kill();
              throw new ArgumentException("ffmpeg timed out");
            }
            if (p.ExitCode != 0) {
              throw new ArgumentException("ffmpeg does not understand the stream");
            }
            Debug("Done ffmpeg");
            if (!pump.Wait(2000)) {
              throw new ArgumentException("stream reading timed out");
            }
            if (thumb.Length == 0) {
              throw new ArgumentException("ffmpeg did not produce a result");
            }

            using (var img = Image.FromStream(thumb)) {
              using (var scaled = ThumbnailMaker.ResizeImage(img, ref width, ref height)) {
            var rv = new MemoryStream();
            try {
              scaled.Save(rv, ImageFormat.Jpeg);
              return rv;
            }
            catch (Exception) {
              rv.Dispose();
              throw;
            }
              }
            }
              }
        }
Exemplo n.º 5
1
        /// <summary>
        /// Generate a keypair
        /// </summary>
        public static void generateKeypair()
        {
            // We need both, the Public and Private Key
            // Public Key to send to Gitlab
            // Private Key to connect to Gitlab later
            if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa.pub") &&
                File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa"))
            {
                return;
            }

            try {
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh");
            } catch (Exception) {}
            Process p = new Process();
            p.StartInfo.FileName = "ssh-keygen";
            p.StartInfo.Arguments = "-t rsa -f \"" + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\.ssh\\id_rsa\" -N \"\"";
            p.Start();
            Console.WriteLine();
            Console.WriteLine("Waiting for SSH Key to be generated ...");
            p.WaitForExit();
            while (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa.pub") &&
                   !File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa"))
            {
                Thread.Sleep(1000);
            }
            Console.WriteLine("SSH Key generated successfully!");
        }
Exemplo n.º 6
1
 public static void AddSimpleRectoSvn(string inputDir)
 {
     try {
         Process p = new Process();
         p.StartInfo.FileName = "svn";
         p.StartInfo.Arguments = "add -N " + inputDir + @"\*";
         p.StartInfo.UseShellExecute = false;
         p.StartInfo.RedirectStandardOutput = true;
         p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
         p.StartInfo.CreateNoWindow = false;
         p.Start();
         string output = p.StartInfo.Arguments + "\r\n";
         output = output + p.StandardOutput.ReadToEnd();
         p.WaitForExit();
         p = new Process();
         p.StartInfo.FileName = "svn";
         p.StartInfo.Arguments = "commit " + inputDir + "\\* -m\"addedFiles\"";
         p.StartInfo.UseShellExecute = false;
         p.StartInfo.RedirectStandardOutput = true;
         p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
         p.StartInfo.CreateNoWindow = false;
         p.Start();
         p.WaitForExit();
     } catch (Exception ex) {
         MessageBox.Show(ex.Message, "SVN checkout issue");
     }
 }
Exemplo n.º 7
1
        public static string AssembleFile(string ilFile, string outFile, bool debug)
        {
            if (!File.Exists(ilFile))
            {
                throw new FileNotFoundException("IL file \"" + ilFile + "\" not found.");
            }

            File.Delete(outFile);

            Process proc = new Process();
            proc.StartInfo.FileName = "\"" + GetIlasmPath() + "\"";
            proc.StartInfo.Arguments = "\"" + ilFile + "\" /out=\"" + outFile + "\" /dll" + (debug ? " /debug" : "");
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.UseShellExecute = false;
            proc.Start();
            string stdout = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            if (!File.Exists(outFile))
            {
                throw new Exception("File \"" + ilFile + "\" could not be assembled.");
            }
            return stdout;
        }
        public void ExecuteSync(string fileName, string arguments, string workingDirectory)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                throw new ArgumentException("fileName");

            var process = new Process {
                StartInfo = {
                    FileName = fileName,
                    Arguments = arguments,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    CreateNoWindow = true,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    WorkingDirectory = workingDirectory
                },
            };

            process.OutputDataReceived += Process_OutputDataReceived;
            process.ErrorDataReceived += Process_ErrorDataReceived;
            process.Exited += Process_Exited;

            try {
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit();
            } catch (Win32Exception) {
                throw new ExecuteFileNotFoundException(fileName);
            }
        }
Exemplo n.º 9
1
		private string RunProcess(string commandName, string arguments, bool useShell)
		{
			System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
			System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

			Process p = new Process();
			p.StartInfo.CreateNoWindow  = !useShell;
			p.StartInfo.UseShellExecute = useShell;
			p.StartInfo.Arguments = arguments;
			p.StartInfo.RedirectStandardOutput = !useShell;
			p.StartInfo.RedirectStandardError = !useShell;
			p.StartInfo.FileName = commandName;
			p.Start();
			if(!useShell)
			{
				string output = p.StandardOutput.ReadToEnd();
				string error = p.StandardError.ReadToEnd();
				p.WaitForExit();
				WriteToConsole(error);
				WriteToConsole(output);
				System.Windows.Forms.Cursor.Current =  oldCursor;
				return output;
			}
			return "";
		}
Exemplo n.º 10
1
        public void Pack_Works()
        {
            string pathToNuGet = MakeAbsolute(@".nuget\NuGet.exe");
            string pathToNuSpec = MakeAbsolute(@"src\app\SharpRaven\SharpRaven.nuspec");

            ProcessStartInfo start = new ProcessStartInfo(pathToNuGet)
            {
                Arguments = String.Format(
                        "Pack {0} -Version {1} -Properties Configuration=Release -Properties \"ReleaseNotes=Test\"",
                        pathToNuSpec,
                        typeof(IRavenClient).Assembly.GetName().Version),
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                WindowStyle = ProcessWindowStyle.Hidden,
            };

            using (var process = new Process())
            {
                process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
                process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
                process.StartInfo = start;
                Assert.That(process.Start(), Is.True, "The NuGet process couldn't start.");
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit(3000);
                Assert.That(process.ExitCode, Is.EqualTo(0), "The NuGet process exited with an unexpected code.");
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Execute some external program and return the results
        /// </summary>
        /// <param name="workingDirectory"></param>
        /// <param name="command"></param>
        /// <param name="arguments"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string Execute(string command, string arguments, int timeout = 30000, string workingDirectory = "")
        {
            if (workingDirectory.IsNullOrEmpty())
                workingDirectory = Directory.GetCurrentDirectory();

            Process p = new Process();
            p.StartInfo.FileName = command;
            p.StartInfo.Arguments = arguments;
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.ErrorDialog = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;

            p.Start();

            var output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            var error = p.StandardError.ReadToEnd();
            p.WaitForExit();

            if (p.ExitCode != 0)
                throw new ExternalProcessException("External processed exited with code: " + p.ExitCode +
                    " and message: " + error + "\n" + output);

            return output;
        }
Exemplo n.º 12
0
		private void Run(ReceivePack rp, string hook) {
			var processStartInfo = new ProcessStartInfo {
				FileName = hook, UseShellExecute = false,
				WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true,
				RedirectStandardOutput = true, RedirectStandardError = true,
				RedirectStandardInput = true,
				WorkingDirectory = FullPath
			};
			var appSettings = AppSettings.Current;
			using(var process = new Process { StartInfo = processStartInfo }) {
				if(!appSettings.RunHooksSilently) {
					process.OutputDataReceived += (d, r) => { if(!String.IsNullOrWhiteSpace(r.Data)) rp.sendMessage(r.Data); };
					process.ErrorDataReceived += (d, r) => { if(!String.IsNullOrWhiteSpace(r.Data)) rp.sendError(r.Data); };
				}
				process.Start();
				process.BeginOutputReadLine();
				process.BeginErrorReadLine();
				foreach(var command in rp.getAllCommands()) {
					process.StandardInput.WriteLine(command.getOldId().Name + " " + command.getNewId().Name + " " +
						command.getRefName());
				}
				process.StandardInput.Close();
				process.WaitForExit((int) appSettings.HookTimeout.TotalMilliseconds);
				process.WaitForExit();
				process.Close();
			}
		}
Exemplo n.º 13
0
        /// <summary>
        /// Preprocesses and runs Mike She
        /// Note that if the MzLauncher is used it uses the execution engine flags from the .she-file
        /// </summary>
        /// <param name="MsheFileName"></param>
        /// <param name="UseMZLauncher"></param>
        public static void PreprocessAndRun(string MsheFileName, bool UseMZLauncher)
        {
            Process Runner = new Process();

              string path;
              DHIRegistry key = new DHIRegistry(DHIProductAreas.COMMON_COMPONNETS, false);
              key.GetHomeDirectory(out path);

              if (UseMZLauncher)
              {
            Runner.StartInfo.FileName = Path.Combine(path,"Mzlaunch.exe");
            Runner.StartInfo.Arguments = Path.GetFullPath(MsheFileName) + " -exit";
              }

              else
              {
            Runner.StartInfo.FileName = Path.Combine(path,"Mshe_preprocessor.exe");
            Runner.StartInfo.Arguments = MsheFileName;
            Runner.Start();
            Runner.WaitForExit();
            Runner.StartInfo.FileName = Path.Combine(path,"Mshe_watermovement.exe");
              }
              Runner.Start();
              Runner.WaitForExit();
              Runner.Close();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Execute some external program and return the results
        /// </summary>
        /// <param name="workingDirectory"></param>
        /// <param name="command"></param>
        /// <param name="arguments"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string Execute(string command, string arguments, int timeout = 30000, string workingDirectory = "")
        {
            if (workingDirectory.IsNullOrEmpty())
                workingDirectory = Directory.GetCurrentDirectory();

            Process p = new Process();
            p.StartInfo.FileName = command;
            p.StartInfo.Arguments = arguments;
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.ErrorDialog = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;

            p.Start();

            var output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            var error = p.StandardError.ReadToEnd();
            p.WaitForExit();

            if (p.ExitCode != 0)
            {
                var message = string.Format("External process '{0}' exited with code: {1} and message: {2}\nProcess output:{3}",
                    command.And(arguments).Join(" "), p.ExitCode, error, output);
                throw new ExternalProcessException(message);
            }

            return output;
        }
Exemplo n.º 15
0
        private BuildRunResults runBuild(string buildExecutable, string arguments, string target, Func<bool> abortIfTrue)
        {
            if (_configuration.MSBuildAdditionalParameters.Length > 0)
                arguments += " " + _configuration.MSBuildAdditionalParameters;
            var timer = Stopwatch.StartNew();
            DebugLog.Debug.WriteInfo("Running build: {0} {1}", buildExecutable, arguments);
            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(buildExecutable, arguments);
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            string line;
            var buildResults = new BuildRunResults(target);
            var lines = new List<string>();
            while ((line = process.StandardOutput.ReadLine()) != null)
            {
                if (abortIfTrue.Invoke())
                {
                    process.Kill();
                    process.WaitForExit();
                    AutoTest.Core.DebugLog.Debug.WriteDebug("Aborting build run");
                    return new BuildRunResults(target);
                }
                lines.Add(line);
            }
            process.WaitForExit();
            timer.Stop();
            var parser = new MSBuildOutputParser(buildResults, lines.ToArray());
            parser.Parse();
            buildResults.SetTimeSpent(timer.Elapsed);
            return buildResults;
        }
Exemplo n.º 16
0
        public CmdResult Run(string[] Arguments)
        {
            if (Arguments == null)
                throw new ArgumentNullException("Arguments");

            if (Arguments.Length < 1)
                throw new ArgumentException("At least one argument is excpected as binary, that should be executed.", "Arguments");

            if (!File.Exists(Arguments[0]))
                throw new ArgumentException("The first argument does not point to a file that exists.", "Arguments");

            StringBuilder stdOut = new StringBuilder();
            StringBuilder stdErr = new StringBuilder();

            Process process = new Process();
            process.StartInfo = new ProcessStartInfo();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                stdOut.Append(e.Data + "\n");
            });
            process.StartInfo.RedirectStandardError = true;
            process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                stdErr.Append(e.Data + "\n");
            });

            process.StartInfo.FileName = Arguments[0];
            process.StartInfo.Arguments =
                String.Concat(
                    Arguments.Skip(1).Select(x => "\"" + x + "\" ")
                ).Trim()
            ;

            process.StartInfo.RedirectStandardInput = true;

            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();
            process.StandardInput.Close();

            if (TimeoutMS <= 0)
            {
                process.WaitForExit();
            }
            else
            {
                if (!process.WaitForExit(TimeoutMS))
                {
                    process.Kill();
                    throw new TimeoutException("The timeout of " + TimeoutMS + "ms has been reached for the execution.");
                }
            }

            return new CmdResult(stdOut.ToString(), stdErr.ToString(), process.ExitCode);
        }
Exemplo n.º 17
0
 static void Main(string[] args)
 {
     int nvar = int.Parse(ConfigurationSettings.AppSettings["NVars"]);
     Grads g = Grads.GetInstance();
     DirectoryInfo root = new DirectoryInfo(ConfigurationSettings.AppSettings["CtlDirectory"]);
     StreamWriter sw = new StreamWriter(ConfigurationSettings.AppSettings["DB2Filename"]);
     foreach (System.IO.FileInfo f in root.GetFiles())
     {
         if (!f.Extension.Equals(".ctl"))
             continue;
         try
         {
             g.Open(f.FullName, Grads.FileType.CTL);
         }
         catch (Exception e)
         {
             continue;
         }
         g.Lon.Start = 13.75;
         g.Lon.End = 14.7;
         g.Lat.Start = 40.5;
         g.Lat.End = 41;
         for (int t = 1; t < 25; t++)
         {
             Console.WriteLine("T: " + t);
             g.T.Value = t;
             for (int i = 0; i < nvar; i++)
             {
                 sw.Write(g.Amean(ConfigurationSettings.AppSettings["Var" + i]) + " ");
             }
             sw.WriteLine();
         }
     }
     sw.Close();
     Process p = new Process();
     p.StartInfo.FileName = ConfigurationSettings.AppSettings["AutoclassExe"];
     p.StartInfo.Arguments = "-search " + ConfigurationSettings.AppSettings["DB2Filename"] + " "
         + ConfigurationSettings.AppSettings["HD2Filename"] + " "
         + ConfigurationSettings.AppSettings["ModelFilename"] + " "
         + ConfigurationSettings.AppSettings["SParamsFilename"];
     p.Start();
     p.WaitForExit();
     Console.WriteLine(p.ExitCode);
     p.Start();
     p.WaitForExit();
     Console.WriteLine(p.ExitCode);
     p.Start();
     p.WaitForExit();
     Console.WriteLine(p.ExitCode);
     p = new Process();
     p.StartInfo.FileName = ConfigurationSettings.AppSettings["AutoclassExe"];
     p.StartInfo.Arguments = "-reports " + ConfigurationSettings.AppSettings["HD2Filename"].Replace(".hd2", ".results-bin") + " "
         + ConfigurationSettings.AppSettings["HD2Filename"].Replace(".hd2", ".search") + " "
         + ConfigurationSettings.AppSettings["RParamsFilename"];
     p.Start();
     p.WaitForExit();
     Console.WriteLine(p.ExitCode);
 }
Exemplo n.º 18
0
        public static BinaryReader Decrypt(string fname, Encoding enc)
        {
            var process_decoder = new Process();
            string decoder_output = "";

            string fname_encoded = Path.Combine(RConfig.Instance.LineageDirectory, fname);
            string fname_decoded = Path.GetTempFileName();

            try
            {
                process_decoder.StartInfo.FileName = Path.Combine(GlobalUtilities.GetStartDirectory(false),
                                                                  "l2encdec\\l2encdec.exe");
                process_decoder.StartInfo.UseShellExecute = false;
                process_decoder.StartInfo.CreateNoWindow = true;
                process_decoder.StartInfo.RedirectStandardOutput = true;
                process_decoder.StartInfo.Arguments = String.Format("-s \"{0}\" \"{1}\"", fname_encoded, fname_decoded);
                process_decoder.Start();
                process_decoder.WaitForExit();

                if (process_decoder.ExitCode < 0)
                {
                    // lets try with -g switch
                    process_decoder.StartInfo.Arguments = String.Format("-g \"{0}\" \"{1}\"", fname_encoded,
                                                                        fname_decoded);
                    process_decoder.Start();
                    process_decoder.WaitForExit();

                    if (process_decoder.ExitCode < 0)
                    {
                        // guess this file is not encrypted
                        fname_decoded = fname_encoded;
                    }
                }

                try
                {
                    decoder_output = process_decoder.StandardOutput.ReadToEnd();
                }
                catch
                {
                    return null;
                }

                return new BinaryReader(File.OpenRead(fname_decoded), enc);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                    String.Format("Error decoding '{0}':\n\n{1}", fname_encoded, decoder_output), ex);
            }
            finally
            {
                process_decoder.Dispose();
            }

            return null;
        }
 public static ProcessExecutionResult RunProcess(string fileName, string arguments = null, int timeout = default(int))
 {
     var outputBuilder = new List<string>();
     var errorOutputBuilder = new List<string>();
     var startInfo = new ProcessStartInfo(fileName, arguments)
     {
         UseShellExecute = false,
         CreateNoWindow = true,
         WindowStyle = ProcessWindowStyle.Hidden,
         RedirectStandardError = true,
         RedirectStandardOutput = true,
     };
     using (var process = new Process
     {
         StartInfo = startInfo
     })
     {
         process.ErrorDataReceived += (sendingProcess, outLine) =>
         {
             if (!string.IsNullOrEmpty(outLine.Data))
             {
                 errorOutputBuilder.Add(outLine.Data);
             }
         };
         process.OutputDataReceived += (sendingProcess, outLine) =>
         {
             if (!string.IsNullOrEmpty(outLine.Data))
             {
                 outputBuilder.Add(outLine.Data);
             }
         };
         process.Start();
         process.BeginErrorReadLine();
         process.BeginOutputReadLine();
         if (timeout != default(int))
         {
             if (!process.WaitForExit(timeout))
             {
                 process.Kill();
                 throw new TimeoutException();
             }
         }
         else
         {
             process.WaitForExit();
         }
         var processExecutionResult = new ProcessExecutionResult
         {
             ExitCode = process.ExitCode,
             ErrorOutput = string.Join("\r\n", errorOutputBuilder),
             Output = string.Join("\r\n", outputBuilder),
         };
         return processExecutionResult;
     }
 }
Exemplo n.º 20
0
 void CloseApplication(Process process, bool force) {
     int num = force ? 1 : 0x2710;
     DateTime now = DateTime.Now;
     TimeSpan zero = TimeSpan.Zero;
     bool flag = false;
     IntPtr ptr = IntPtr.Zero;
     while (zero.TotalMilliseconds < num){
         Trace.WriteLine(DateTime.Now + "\tCall Process.Refresh() at WinApplicationAdapter.CloseApplication");
         process.Refresh();
         Trace.WriteLine(DateTime.Now + "\tCall Process.Refresh() success");
         Trace.WriteLine(DateTime.Now +"\tCall Process.MainWindowHandle at WinApplicationAdapter.CloseApplication");
         IntPtr mainWindowHandle = IntPtr.Zero;
         try{
             mainWindowHandle = process.MainWindowHandle;
         }
         catch (InvalidOperationException){
         }
         if ((mainWindowHandle != ptr) && (mainWindowHandle != IntPtr.Zero)){
             ptr = mainWindowHandle;
             try{
                 process.CloseMainWindow();
             }
             catch (Exception exception){
                 Logger.Instance.AddMessage(string.Format("Process{0}.CloseMainWindow return error:\n'{1}'",process.ProcessName, exception.Message));
             }
         }
         Trace.WriteLine(DateTime.Now + "\tCall Process.MainWindowHandle success");
         try{
             if (process.WaitForExit(Math.Min(0x3e8, num - ((int) zero.TotalMilliseconds)))){
                 flag = true;
                 break;
             }
         }
         catch (Exception exception2){
             Logger.Instance.AddMessage(string.Format("Process.WaitForExit return error:\n'{0}'",exception2.Message));
         }
         zero = DateTime.Now - now;
     }
     if (!flag){
         if (!force){
             Logger.Instance.AddMessage(string.Format("The process '{0}' was not closed in '{1}' millisecond after the Process.CloseMainWindow was invoked, trying to kill this process",process.ProcessName, num));
         }
         try{
             process.Kill();
         }
         catch (Exception exception3){
             Logger.Instance.AddMessage(string.Format("Process name: '{0}' is not killed.\nReason:\n'{1}'",process.ProcessName, exception3.Message));
         }
         if (!process.WaitForExit(0x2710)){
             throw new WarningException(
                 string.Format("Process name: '{0}' doesn't exited in 10 seconds after the Process.Kill was invoked",process.ProcessName));
         }
     }
 }
Exemplo n.º 21
0
        public TfsCommandResult Run()
        {
            if (string.IsNullOrWhiteSpace(this.programPath))
            {
                const string ErrorMessage = "Could not find the path to tf.exe";
                Debug.WriteLine(ErrorMessage);
                return new TfsCommandResult(ExitCodes.Fail, ErrorMessage);
            }

            ////var path = string.Format("\"{0}\"", this.programPath);
            var path = string.Format("\"{0}\"", this.programPath);
            var startInfo = new ProcessStartInfo(path);
            startInfo.Arguments = this.arguments;
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;

            if (this.workingDirectory != null)
            {
                startInfo.WorkingDirectory = this.workingDirectory;
            }

            var process = new Process() { StartInfo = startInfo, EnableRaisingEvents = true};
            try
            {
                process.Start();
                process.WaitForExit(1000 * 20);
                var hadToClose = false;
                if (!process.HasExited)
                {
                    hadToClose = true;
                    process.Kill();
                    process.WaitForExit();
                }

                var err = process.StandardError.ReadToEnd();
                var output = process.StandardOutput.ReadToEnd();
                if (hadToClose)
                {
                    err = err + Environment.NewLine + "[TFS command timed out]" + Environment.NewLine;
                }

                return new TfsCommandResult(process.ExitCode, err + output);
            }
            catch (Exception e)
            {
                // todo: really log this
                string message = string.Format("Error running TfsCommand in the shell. Command \"{0}\" arguments \"{1}\"", path, this.arguments);
                Debug.WriteLine(message, e);
                return new TfsCommandResult(ExitCodes.Fail, string.Empty);
            }
        }
Exemplo n.º 22
0
        internal static string RunProgram(string ipHost, string oid)
        {
            string exeName = "snmpget.exe";
            int timeoutSeconds = 0;

            string argsLine = String.Format(" -v1 -r 1 -t 0.025 -c public {0} {1}", ipHost, oid);
            StreamReader outputStream = StreamReader.Null;
            string strOutput = "";
            bool bSuccess = false;

            try
            {
                Process newProcess = new Process();
                newProcess.StartInfo.FileName = exeName;
                newProcess.StartInfo.Arguments = argsLine;
                newProcess.StartInfo.UseShellExecute = false;
                newProcess.StartInfo.CreateNoWindow = true;
                newProcess.StartInfo.RedirectStandardOutput = true;
                newProcess.Start();

                if (0 == timeoutSeconds)
                {
                    outputStream = newProcess.StandardOutput;
                    strOutput = outputStream.ReadToEnd();
                    newProcess.WaitForExit();
                }
                else
                {
                    bSuccess = newProcess.WaitForExit(timeoutSeconds * 1000);

                    if (bSuccess)
                    {
                        outputStream = newProcess.StandardOutput;
                        strOutput = outputStream.ReadToEnd();
                    }
                    else
                    {
                        strOutput = String.Format("Timed out at {0} seconds waiting for {1} to exit.", timeoutSeconds, exeName);
                    }
                }
            }
            catch (Exception e)
            {
                throw (new Exception(String.Format("An error occurred running {0}.", exeName), e));
            }
            finally
            {
                outputStream.Close();
            }

            return strOutput;
        }
Exemplo n.º 23
0
        internal static string Run(string exeName, string argsLine, int timeoutSeconds)
        {
            StreamReader outputStream = StreamReader.Null;
            string output = "";
            bool success = false;

            try
            {
                Process newProcess = new Process();
                newProcess.StartInfo.FileName = exeName;
                newProcess.StartInfo.Arguments = argsLine;
                newProcess.StartInfo.UseShellExecute = false;
                newProcess.StartInfo.CreateNoWindow = true;
                newProcess.StartInfo.RedirectStandardOutput = true;
                newProcess.Start();

                if (0 == timeoutSeconds)
                {
                    newProcess.WaitForExit();
                    success = true;
                }
                else
                {
                    success = newProcess.WaitForExit(timeoutSeconds * 1000);

                }
                if (success)
                {
                    outputStream = newProcess.StandardOutput;
                    output = outputStream.ReadToEnd();
                }
                else
                {
                    output = "Timed out at " + timeoutSeconds + " seconds waiting for " + exeName + " to exit.";
                }

            }
            catch (Exception e)
            {
                throw (new Exception("An error occurred running " + exeName + ".", e));
            }
            finally
            {
                outputStream.Close();
            }

            return "\t" + output;
        }
Exemplo n.º 24
0
        private static void RunMongo(string script)
        {
            var psi = new ProcessStartInfo("mongo", string.Format("--norc --eval \"{0}\" test", script))
                          {
                              UseShellExecute = false,
                              CreateNoWindow = true,
                              RedirectStandardOutput = true,
                              RedirectStandardError = true
                          };

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

            var stdOut = new StringBuilder();
            var stdErr = new StringBuilder();

            Action<StringBuilder, string> handleLine = (builder, line) =>
            {
                if (line == null)
                    return;
                builder.AppendLine(line);
            };

            process.OutputDataReceived += (obj, e) => handleLine(stdOut, e.Data);
            process.ErrorDataReceived += (obj, e) => handleLine(stdErr, e.Data);

            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();
            do
            {
                process.WaitForExit(100);
                process.Refresh();
            } while (!process.HasExited);

            process.WaitForExit();
            var infoOutput = stdOut.ToString();
            var errorOutput = stdErr.ToString();
            var exitCode = process.ExitCode;

            if (exitCode > 0)
            {
                throw new Exception(string.Format("Mongo exited with code {0}", exitCode));
            }
        }
Exemplo n.º 25
0
 public void run()
 {
     var executableName = "starbound_server" + (StarryboundServer.IsMono ? "" : ".exe");
     try
     {
         ProcessStartInfo startInfo = new ProcessStartInfo(executableName)
         {
             WindowStyle = ProcessWindowStyle.Hidden,
             UseShellExecute = false,
             RedirectStandardOutput = true,
             CreateNoWindow = true
         };
         process = Process.Start(startInfo);
         StarryboundServer.parentProcessId = process.Id;
         File.WriteAllText("starbound_server.pid", process.Id.ToString());
         process.OutputDataReceived += (sender, e) => parseOutput(e.Data);
         process.ErrorDataReceived += (sender, e) => logStarboundError("ErrorDataReceived from starbound_server.exe: " + e.Data);
         process.BeginOutputReadLine();
         process.WaitForExit();
         StarryboundServer.serverState = ServerState.Crashed;
     }
     catch (ThreadAbortException) { }
     catch (Exception e)
     {
         StarryboundServer.logException("Unable to start starbound_server.exe, is this file in the same directory? " + e.ToString());
         StarryboundServer.serverState = ServerState.Crashed;
     }
 }
Exemplo n.º 26
0
        public static void openFeeddownload(string torrentclient, string folder, string link)
        {
            var sta = new Process();
            var downloadsafe = folder.Trim();
            Debug.Write(downloadsafe);
            //"add -p 'D:/Program Files (x86)/Deluge' 'D:/Development/python34/Anime checker/torrents/[HorribleSubs] Hibike! Euphonium - 13 [720p].mkv.torrent'"
            var call = $"\"add -p '{downloadsafe}' '{link.Replace("https", "http")}'\"";
            call = call.Replace(@"\\", "/");
            call = call.Replace(@"\", "/");
            sta.StartInfo.FileName = torrentclient;
            sta.StartInfo.Arguments = call;
            sta.StartInfo.RedirectStandardOutput = true;
            sta.StartInfo.RedirectStandardError = true;
            sta.EnableRaisingEvents = true;
            sta.StartInfo.CreateNoWindow = true;
            // see below for output handler
            sta.ErrorDataReceived += proc_DataReceived;
            sta.OutputDataReceived += proc_DataReceived;

            sta.StartInfo.UseShellExecute = false;
            sta.Start();

            sta.BeginErrorReadLine();
            sta.BeginOutputReadLine();
            sta.WaitForExit();
        }
Exemplo n.º 27
0
        static bool AddFirewallRule()
        {
            //accomplished via shelling out to netsh.exe with relevant arguments.
            Process proc = new Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.UseShellExecute = false; //the process should be created directly from this app.
            proc.StartInfo.RedirectStandardError = true; //allowed since we set UseShellExecute to false
            proc.StartInfo.FileName = "netsh.exe"; //would include the folder name if not in system path
            proc.StartInfo.Arguments = "advfirewall firewall add rule name=\"Banned IP Addresses\" dir=in action=block description=\"IPs detected from Security Event Log with more than 10 failed attempts a day\" enable=yes profile=any localip=any protocol=any interfacetype=any";
            proc.StartInfo.CreateNoWindow = true;
            string errstr = "";

            try
            {
                OutputMsg("Starting netsh.exe to add firewall rule");
                proc.Start();
                errstr = proc.StandardError.ReadToEnd();
                proc.WaitForExit();
            }
            catch (Exception e)
            {
                OutputMsg("Unable to add firewall rule. Error starting process for netsh.exe" , e.ToString());
                proc.Dispose();
                return false;
            }

            if (errstr != "")
            {
                OutputMsg("Suspicious output from netsh.exe:\n\t" + errstr +
                                "\n*** Check to verify that the update was processed correctly. ***");
             }

            proc.Dispose();
            return true;
        }
Exemplo n.º 28
0
        protected void InspectFile(string fileName)
        {
            if (!File.Exists(fileName))
                MessageBox.Show("File does not exist:\n" + fileName, "File does not exist", MessageBoxButton.OK, MessageBoxImage.Error);

            // Initialize the handle.exe process
            var tool = new Process();
            tool.StartInfo.FileName = @".\Assets\handle.exe";
            tool.StartInfo.Arguments = fileName;
            tool.StartInfo.UseShellExecute = false;
            tool.StartInfo.RedirectStandardOutput = true;

            // Ensure no console window appears
            tool.StartInfo.CreateNoWindow = true;
            tool.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            // Execute, and wait for results
            tool.Start();
            tool.WaitForExit();
            var fullOutputMessage = tool.StandardOutput.ReadToEnd();

            // Split the line endings and filter out the actual result
            var result = fullOutputMessage
                .Trim()         // Trim all line breaks and spaces
                .Split('\r')    // Split by hard returns
                .LastOrDefault()// Fetch the last argument
                .Trim();        // Again, trim all line breaks and spaces from the result

            //MessageBox.Show(result);
            HandleResultText.Text = result;
        }
Exemplo n.º 29
0
 //-------------------------------------------------------------------------------------------
 /// <summary>
 /// Works with the Windows and Linux versions of sox.
 /// </summary>
 /// <param name="fileName"></param>
 /// <returns>audio length in seconds </returns>
 public static decimal GetAudioLength(string filePath)
 {
     string soxpath = "sox";
        if (Common.Windows)
             soxpath = ConfigurationManager.AppSettings["sox_path"];
        string args = "\"" + filePath + "\" -n stat";
        Process command = new Process();
        command.StartInfo.FileName = soxpath;
        command.StartInfo.Arguments = args;
        command.StartInfo.RedirectStandardError = true;
        command.StartInfo.RedirectStandardInput = true;
        command.StartInfo.RedirectStandardOutput = true;
        command.StartInfo.UseShellExecute = false;
        command.StartInfo.ErrorDialog = false;
        bool started = command.Start();
        if (started)
        {
             command.WaitForExit(1000);
             string output = command.StandardOutput.ReadToEnd();
             string outputerror = command.StandardError.ReadToEnd();
             //Console.WriteLine("StandardOutput: " + output);
             //Console.WriteLine("StandardError: " + outputerror);
             output = outputerror;
             output = output.Substring(output.IndexOf("Length (seconds):") + 17);
             output = output.Substring(0, output.IndexOf("\n")).Trim();
             Console.Write("Detected audio length: " + output.ToString());
             decimal len = Decimal.Parse(output);
             Console.WriteLine(" - " + len.ToString());
             return len;
        }
        else
        {
             return 0;
        }
 }
Exemplo n.º 30
0
        public Boolean Start()
        {
            //FileInfo commandFile = new FileInfo(_commandFullPath);
            //if(commandFile.Exists == false) throw new FileNotFoundException();

            Boolean result = false;

            Process p = new Process();
            p.StartInfo.FileName = _command;
            if(_arugment.IsNullOrEmpty() == false) p.StartInfo.Arguments = _arugment;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;

            // These two optional flags ensure that no DOS window appears
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.Start();
            p.WaitForExit();
            ErrorMessage = p.StandardError.ReadToEnd();
            OutputMessage = p.StandardOutput.ReadToEnd();
            if(p.ExitCode == 0) result = true;
            p.Close();
            p.Dispose();

            return result;
        }
Exemplo n.º 31
0
        /// <summary>
        /// Releases all used resouces by the <see cref="FusionProcess"/> instance.
        /// </summary>
        public void Dispose()
        {
            isAutoRestartEnabled = false;

            if (process?.HasExited == false)
            {
                try
                {
                    process?.Kill();
                }
                catch (Exception ex) when(ex is Win32Exception || ex is InvalidOperationException)
                {
                }

                try
                {
                    process?.WaitForExit((int)defaultProcessTimeout.TotalMilliseconds);
                }
                catch (Exception ex) when(ex is Win32Exception || ex is SystemException)
                {
                }
            }

            CpuCounter?.Dispose();
            CpuCounter = null;

            MemoryCounter?.Dispose();
            MemoryCounter = null;

            process?.Dispose();
            process = null;
        }
Exemplo n.º 32
0
 private static void CloseDTE(DTE dte, Process process)
 {
     if (dte != null)
     {
         dte.Quit();
         process?.WaitForExit();
     }
     else
     {
         process?.Kill();
     }
 }
        // Need to be able to stub this method out for testing
        protected virtual void SafeInternalStop()
        {
            // Note: we're not checking IsRunning here as that check can fail if the
            // process wasn't started correctly.
            logger.WriteLine(Strings.Daemon_Stopping);

            SafeOperation(() =>
            {
                daemonClient = null;
                channel?.ShutdownAsync().Wait();
                channel = null;

                // Will throw an InvalidOperationException if the process isn't valid
                if (!process?.HasExited ?? false)
                {
                    process?.Kill();
                    process?.WaitForExit();
                }
                process = null;
            });

            logger.WriteLine(Strings.Daemon_Stopped);
        }
        void BuildImageTrackingAssets()
        {
            if (Directory.Exists(Application.streamingAssetsPath))
            {
                s_ShouldDeleteStreamingAssetsFolder = false;
            }
            else
            {
                // Delete the streaming assets folder at the end of the build pipeline
                // since it did not exist before we created it here.
                s_ShouldDeleteStreamingAssetsFolder = true;
                Directory.CreateDirectory(Application.streamingAssetsPath);
            }

            if (!Directory.Exists(ARCoreImageTrackingSubsystem.k_StreamingAssetsPath))
            {
                Directory.CreateDirectory(ARCoreImageTrackingSubsystem.k_StreamingAssetsPath);
            }

            try
            {
                string[] libGuids = AssetDatabase.FindAssets("t:xrReferenceImageLibrary");
                if (libGuids == null || libGuids.Length == 0)
                {
                    return;
                }

                // This is how much each library will contribute to the overall progress
                var          progressPerLibrary = 1f / libGuids.Length;
                const string progressBarText    = "Building ARCore Image Library";

                for (int libraryIndex = 0; libraryIndex < libGuids.Length; ++libraryIndex)
                {
                    var libGuid         = libGuids[libraryIndex];
                    var overallProgress = progressPerLibrary * libraryIndex;
                    var numSteps        = libGuids.Length + 1; // 1 per image plus arcoreimg
                    var libraryPath     = AssetDatabase.GUIDToAssetPath(libGuid);
                    var imageLib        = AssetDatabase.LoadAssetAtPath <XRReferenceImageLibrary>(libraryPath);

                    EditorUtility.DisplayProgressBar(progressBarText, imageLib.name, overallProgress);

                    var tempDirectory      = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
                    var inputImageListPath = Path.Combine(tempDirectory, Guid.NewGuid().ToString("N") + ".txt");

                    // prepare text file for arcoreimg to read from
                    try
                    {
                        Directory.CreateDirectory(tempDirectory);
                        using (var writer = new StreamWriter(inputImageListPath, false))
                        {
                            for (int i = 0; i < imageLib.count; i++)
                            {
                                var referenceImage     = imageLib[i];
                                var textureGuid        = referenceImage.textureGuid.ToString("N");
                                var assetPath          = AssetDatabase.GUIDToAssetPath(textureGuid);
                                var referenceImageName = referenceImage.guid.ToString("N");

                                EditorUtility.DisplayProgressBar(
                                    progressBarText,
                                    imageLib.name + ": " + assetPath,
                                    overallProgress + progressPerLibrary * i / numSteps);

                                var texture = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath);
                                if (texture == null)
                                {
                                    throw new BuildFailedException(string.Format(
                                                                       "ARCore Image Library Generation: Reference library at '{0}' is missing a texture at index {1}.",
                                                                       libraryPath, i));
                                }

                                var extension = Path.GetExtension(assetPath);
                                var entry     = new StringBuilder();

                                if (string.Equals(extension, ".jpg", StringComparison.Ordinal) ||
                                    string.Equals(extension, ".jpeg", StringComparison.Ordinal) ||
                                    string.Equals(extension, ".png", StringComparison.Ordinal))
                                {
                                    // If lowercase jpg or png, use image as is
                                    entry.Append($"{referenceImageName}|{assetPath}");
                                }
                                else if (string.Equals(extension, ".jpg", StringComparison.OrdinalIgnoreCase) ||
                                         string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase) ||
                                         string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase))
                                {
                                    // If jpg or png but NOT lowercase, then copy it to a temporary file that uses lowercase
                                    var pathWithLowercaseExtension = Path.Combine(tempDirectory, textureGuid + extension.ToLower());
                                    File.Copy(assetPath, pathWithLowercaseExtension);
                                    entry.Append($"{referenceImageName}|{pathWithLowercaseExtension}");
                                }
                                else
                                {
                                    var pngFilename = Path.Combine(tempDirectory, textureGuid + ".png");
                                    var bytes       = ImageConversion.EncodeToPNG(texture);
                                    if (bytes == null)
                                    {
                                        throw new BuildFailedException(string.Format(
                                                                           "ARCore Image Library Generation: Texture format for image '{0}' not supported. Inspect other error messages emitted during this build for more details.",
                                                                           texture.name));
                                    }

                                    File.WriteAllBytes(pngFilename, bytes);
                                    entry.Append($"{referenceImageName}|{pngFilename}");
                                }

                                if (referenceImage.specifySize)
                                {
                                    entry.Append($"|{referenceImage.width.ToString("G", CultureInfo.InvariantCulture)}");
                                }

                                writer.WriteLine(entry.ToString());
                            }
                        }
                    }
                    catch
                    {
                        Directory.Delete(tempDirectory, true);
                        throw;
                    }

                    // launch arcoreimg and wait for it to return so we can process the asset
                    try
                    {
                        EditorUtility.DisplayProgressBar(
                            progressBarText,
                            imageLib.name + ": Invoking arcoreimg",
                            overallProgress + progressPerLibrary * (numSteps - 1) / numSteps);

                        var packagePath = Path.GetFullPath("Packages/com.unity.xr.arcore");

                        string extension    = "";
                        string platformName = "Undefined";
    #if UNITY_EDITOR_WIN
                        platformName = "Windows";
                        extension    = ".exe";
    #elif UNITY_EDITOR_OSX
                        platformName = "MacOS";
                        extension    = "";
    #elif UNITY_EDITOR_LINUX
                        platformName = "Linux";
                        extension    = "";
    #endif
                        var arcoreimgPath = Path.Combine(packagePath, "Tools~", platformName, "arcoreimg" + extension);

    #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX
                        SetExecutablePermission(arcoreimgPath);
    #endif

                        var startInfo = new Diag.ProcessStartInfo();
                        startInfo.WindowStyle = Diag.ProcessWindowStyle.Hidden;
                        startInfo.FileName    = arcoreimgPath;

                        // This file must have the .imgdb extension (the tool adds it otherwise)
                        var outputDbPath = ARCoreImageTrackingSubsystem.GetPathForLibrary(imageLib);

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

                        startInfo.Arguments = string.Format(
                            "build-db --input_image_list_path={0} --output_db_path={1}",
                            $"\"{inputImageListPath}\"",
                            $"\"{outputDbPath}\"");

                        startInfo.UseShellExecute        = false;
                        startInfo.RedirectStandardOutput = true;
                        startInfo.RedirectStandardError  = true;
                        startInfo.CreateNoWindow         = true;

                        var process = new Diag.Process();
                        process.StartInfo           = startInfo;
                        process.EnableRaisingEvents = true;
                        var stdout = new StringBuilder();
                        var stderr = new StringBuilder();
                        process.OutputDataReceived += (sender, args) => stdout.Append(args.Data.ToString());
                        process.ErrorDataReceived  += (sender, args) => stderr.Append(args.Data.ToString());
                        process.Start();
                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();
                        process.WaitForExit();
                        process.CancelOutputRead();
                        process.CancelErrorRead();

                        if (!File.Exists(outputDbPath))
                        {
                            throw new BuildFailedException(string.Format(
                                                               "Failed to generate image database. Output from arcoreimg:\n\nstdout:\n{0}\n====\n\nstderr:\n{1}\n====",
                                                               stdout.ToString(),
                                                               stderr.ToString()));
                        }
                    }
                    catch
                    {
                        Debug.LogErrorFormat("Failed to generated ARCore reference image library '{0}'", imageLib.name);
                        throw;
                    }
                    finally
                    {
                        Directory.Delete(tempDirectory, true);
                    }
                }
            }
            catch
            {
                RemoveGeneratedStreamingAssets();
                throw;
            }
        }
Exemplo n.º 35
0
        protected void pdf_Click(object sender, System.EventArgs e)
        {
            Process p = new System.Diagnostics.Process();

            string   Nama        = "Laporan Master Tagihan";
            string   Link        = "";
            DateTime TglGenerate = DateTime.Now;
            string   FileName    = "";
            string   FileType    = "application/pdf";
            string   UserID      = Act.UserID;
            string   IP          = Act.IP;

            Db.Execute("EXEC spLapPDFDaftar"

                       + " '" + Nama + "'"
                       + ",'" + Link + "'"
                       + ",'" + TglGenerate + "'"
                       + ",'" + IP + "'"
                       + ",'" + UserID + "'"
                       + ",'" + FileName + "'"
                       + ",'" + FileType + "'"
                       + ",'" + Convert.ToDateTime(dari.Text) + "'"
                       + ",'" + Convert.ToDateTime(sampai.Text) + "'"
                       );

            //get nomor customer terbaru
            int NoAttachment = Db.SingleInteger(
                "SELECT TOP 1 AttachmentID FROM LapPDF ORDER BY AttachmentID DESC");

            string    strSql = "SELECT * FROM ISC064_FINANCEAR..LapPDF WHERE AttachmentID  = '" + NoAttachment + "'";
            DataTable rs     = Db.Rs(strSql);

            string nfilename = "LaporanMasterTagihan" + NoAttachment + ".pdf";

            //update filename
            Db.Execute("UPDATE ISC064_FINANCEAR..LapPDF SET FileName= '" + nfilename + "' WHERE AttachmentID = " + NoAttachment);


            //folder untuk menyimpan file pdf
            string save = Mi.PathFilePDFReport + "LaporanMasterTagihan" + rs.Rows[0]["AttachmentID"] + ".pdf";

            //parameter
            string Tipe = tipe.SelectedValue;

            string nStatusS = "";
            string nStatusA = "";
            string nStatusB = "";

            if (statusS.Checked == true)
            {
                nStatusS = statusS.Text;
            }
            else
            {
                nStatusS = "";
            }
            if (statusA.Checked == true)
            {
                nStatusA = statusA.Text;
            }
            else
            {
                nStatusA = "";
            }
            if (statusB.Checked == true)
            {
                nStatusB = statusB.Text;
            }
            else
            {
                nStatusB = "";
            }

            string JenisTgl = "";

            if (tglkontrak.Checked == true)
            {
                JenisTgl = "TglKontrak";
            }
            else if (tgljt.Checked == true)
            {
                JenisTgl = "TglJt";
            }

            string StatusKPA = "";

            if (includekpa.Checked)
            {
                StatusKPA = "includekpa";
            }
            else if (excludekpa.Checked)
            {
                StatusKPA = "excludekpa";
            }

            string nmtipe = string.Empty;

            try
            {
                foreach (ListItem item in tipe.Items)
                {
                    if (item.Selected == true)
                    {
                        nmtipe += item.Value.Replace(" ", "%") + "-";
                    }
                }
            }
            catch (Exception)
            {
            }

            string Project = "";

            if (project.SelectedIndex == 0)
            {
                Project = Act.ProjectListSql.Replace("'", "");
            }
            else
            {
                Project = project.SelectedValue;
            }

            //link untuk download pdf
            string link = Mi.PathAlamatWeb + "collection/LaporanPDF/PDFMasterTagihan.aspx?id=" + rs.Rows[0]["AttachmentID"]
                          + "&tipe=" + nmtipe
                          + "&status_a=" + nStatusA
                          + "&status_b=" + nStatusB
                          + "&status_s=" + nStatusS
                          + "&jenistgl=" + JenisTgl
                          + "&statuskpa=" + StatusKPA
                          + "&userid=" + UserID
                          + "&project=" + Project
                          + "&pers=" + pers.SelectedValue
            ;

            //update link
            Db.Execute("UPDATE ISC064_FINANCEAR..LapPDF SET Link= '" + link + "' WHERE AttachmentID = " + NoAttachment);

            //format page
            p.StartInfo.Arguments = "--orientation landscape --page-width 8.5in --page-height 11in --margin-left 0 --margin-right 0 --margin-top 0.25cm --margin-bottom 0 " + link + " " + save;

            //panggil aplikasi untuk mengconvert pdf
            p.StartInfo.FileName = Mi.PathWkhtmlPDFReport;
            p.Start();

            //60000 -> waktu jeda lama convert pdf
            p.WaitForExit(30000);

            string Src = Mi.PathFilePDFReport + nfilename;

            Mi.DownloadPDF(this, Src, (rs.Rows[0]["FileName"]).ToString(), rs.Rows[0]["FileType"].ToString());
        }
Exemplo n.º 36
0
        public string Call(Dictionary <string, string> environmentVariables = null, Action <StreamWriter> stdinWrite = null)
        {
            if (Shell)
            {
                return(Utils.CallProcessShell(Program, Args));
            }
            else
            {
                Logger.WriteLine($"{Program} {Args}");

                using (var p = new System.Diagnostics.Process())
                {
                    var sb    = new StringBuilder();
                    var sbAll = new StringBuilder();
                    p.StartInfo.Arguments       = Args;
                    p.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.FileName        = Program;

                    if (!p.StartInfo.UseShellExecute)
                    {
                        p.StartInfo.RedirectStandardOutput = true;
                        p.OutputDataReceived += (object sender, DataReceivedEventArgs e) => {
                            if (!Silent)
                            {
                                Console.WriteLine(e.Data);
                            }
                            sb.Append(e.Data);
                            sbAll.Append(e.Data + Environment.NewLine);
                        };
                        p.StartInfo.RedirectStandardError = true;
                        p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => {
                            if (!Silent)
                            {
                                Console.Error.WriteLine(e.Data);
                            }
                            sbAll.Append(e.Data + Environment.NewLine);
                        };
                    }
                    if (stdinWrite != null)
                    {
                        p.StartInfo.RedirectStandardInput = true;
                    }

                    if (environmentVariables != null)
                    {
                        foreach (var pair in environmentVariables)
                        {
                            if (p.StartInfo.EnvironmentVariables.ContainsKey(pair.Key))
                            {
                                p.StartInfo.EnvironmentVariables[pair.Key] = pair.Value;
                            }
                            else
                            {
                                p.StartInfo.EnvironmentVariables.Add(pair.Key, pair.Value);
                            }
                        }
                    }

                    p.Start();

                    if (stdinWrite != null)
                    {
                        stdinWrite(p.StandardInput);
                    }

                    if (!p.StartInfo.UseShellExecute)
                    {
                        p.BeginOutputReadLine();
                        p.BeginErrorReadLine();
                    }

                    p.WaitForExit();

                    if (p.ExitCode != 0)
                    {
                        Console.Error.WriteLine(sbAll.ToString());
                        Logger.WriteLineError($"Error: {Program} {Args}");
                        throw new InvalidOperationException($"Failed Process. ExitCode: {p.ExitCode}");
                    }
                    return(sb.ToString());
                }
            }
        }
Exemplo n.º 37
0
        protected void pdf_Click(object sender, System.EventArgs e)
        {
            Process p = new System.Diagnostics.Process();

            string   Nama        = "Laporan Master Agent";
            string   Link        = "";
            DateTime TglGenerate = DateTime.Now;
            string   FileName    = "";
            string   FileType    = "application/pdf";
            string   UserID      = Act.UserID;
            string   IP          = Act.IP;

            Db.Execute("EXEC spLapPDFDaftar"

                       + " '" + Nama + "'"
                       + ",'" + Link + "'"
                       + ",'" + TglGenerate + "'"
                       + ",'" + IP + "'"
                       + ",'" + UserID + "'"
                       + ",'" + FileName + "'"
                       + ",'" + FileType + "'"
                       + ",'" + null + "'"
                       + ",'" + null + "'"
                       //+ ",'" + Cf.Date(dari.Text) + "'"
                       //+ ",'" + Cf.Date(sampai.Text) + "'"
                       );

            //get nomor customer terbaru
            int NoAttachment = Db.SingleInteger(
                "SELECT TOP 1 AttachmentID FROM LapPDF ORDER BY AttachmentID DESC");

            string    strSql = "SELECT * FROM ISC064_MARKETINGJUAL..LapPDF WHERE AttachmentID  = '" + NoAttachment + "'";
            DataTable rs     = Db.Rs(strSql);

            string nfilename = "LapMasterAgent" + NoAttachment + ".pdf";

            //update filename
            Db.Execute("UPDATE ISC064_MARKETINGJUAL..LapPDF SET FileName= '" + nfilename + "' WHERE AttachmentID = " + NoAttachment);


            //folder untuk menyimpan file pdf
            string save = Mi.PathFilePDFReport + "LapMasterAgent" + rs.Rows[0]["AttachmentID"] + ".pdf";

            //declare parameter
            string Principal = principal.SelectedValue;

            string Input2 = "";

            if (input.SelectedIndex != 0)
            {
                string[] z = input.SelectedValue.Split(',');
                Input2 = z[0] + "-" + z[1];
            }
            else
            {
                Input2 = input.SelectedValue;
            }

            //declare parameter
            string Tipe  = tipe.SelectedValue;
            string Input = "";

            if (input.SelectedIndex != 0)
            {
                string[] z = input.SelectedValue.Split(',');
                Input = z[0] + "-" + z[1];
            }
            else
            {
                Input = input.SelectedValue;
            }

            string nStatusS = "";
            string nStatusA = "";
            string nStatusI = "";

            if (statusS.Checked == true)
            {
                nStatusS = statusS.Text;
            }
            else
            {
                nStatusS = "";
            }
            if (statusA.Checked == true)
            {
                nStatusA = statusA.Text;
            }
            else
            {
                nStatusA = "";
            }
            if (statusI.Checked == true)
            {
                nStatusI = statusI.Text;
            }
            else
            {
                nStatusI = "";
            }

            string Project = "";

            if (project.SelectedValue == "SEMUA")
            {
                Project = Act.ProjectListSql.Replace("'", "");
            }
            else
            {
                Project = project.SelectedValue;
            }

            string nm  = string.Empty;
            string nm2 = string.Empty;

            try
            {
                foreach (ListItem item in nama.Items)
                {
                    if (item.Selected == true)
                    {
                        nm += item.Value + '-';
                    }
                }
            }
            catch (Exception)
            {
            }
            //link untuk download pdf
            string link = Mi.PathAlamatWeb + "adminjual/LaporanPDF/PDFMasterAgent.aspx?id=" + rs.Rows[0]["AttachmentID"] + "&nama=" + nm + "&input=" + Input + "&status_s=" + nStatusS + "&status_i=" + nStatusI + "&status_a=" + nStatusA + "&principal=" + Principal + "&tipe=" + Tipe + "&project=" + Project + "";

            //update link
            Db.Execute("UPDATE ISC064_MARKETINGJUAL..LapPDF SET Link= '" + link + "' WHERE AttachmentID = " + NoAttachment);

            //format page
            p.StartInfo.Arguments = "--orientation landscape --page-width 8.5in --page-height 11in --margin-left 0 --margin-right 0 --margin-top 0.25cm --margin-bottom 0 " + link + " " + save;

            //panggil aplikasi untuk mengconvert pdf
            p.StartInfo.FileName = Mi.PathWkhtmlPDFReport;
            p.Start();

            //60000 -> waktu jeda lama convert pdf
            p.WaitForExit(30000);

            string Src = Mi.PathFilePDFReport + nfilename;

            Mi.DownloadPDF(this, Src, (rs.Rows[0]["FileName"]).ToString(), rs.Rows[0]["FileType"].ToString());
        }
Exemplo n.º 38
0
        private void PerformAction(string action, Project project, Cloud cloud, ProjectDirectories dir,
                                   Func <IVcapClient, DirectoryInfo, VcapClientResult> function)
        {
            var worker = new BackgroundWorker();

            Messenger.Default.Register <NotificationMessageAction <string> >(this,
                                                                             message =>
            {
                if (message.Notification.Equals(Messages.SetProgressData))
                {
                    message.Execute(action);
                }
            });

            var window     = new ProgressDialog();
            var dispatcher = window.Dispatcher;
            var helper     = new WindowInteropHelper(window);

            helper.Owner = (IntPtr)(dte.MainWindow.HWnd);
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += (s, args) =>
            {
                if (worker.CancellationPending)
                {
                    args.Cancel = true; return;
                }

                Messenger.Default.Send(new ProgressMessage(0, "Starting " + action));

                if (worker.CancellationPending)
                {
                    args.Cancel = true; return;
                }

                if (!Directory.Exists(dir.StagingPath))
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(10, "Creating Staging Path"))));
                    Directory.CreateDirectory(dir.StagingPath);
                }

                if (worker.CancellationPending)
                {
                    args.Cancel = true; return;
                }

                if (Directory.Exists(dir.DeployFromPath))
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(10, "Creating Precompiled Site Path"))));
                    Directory.Delete(dir.DeployFromPath, true);
                }

                if (worker.CancellationPending)
                {
                    args.Cancel = true; return;
                }

                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(30, "Preparing Compiler"))));

                VsWebSite.VSWebSite site = project.Object as VsWebSite.VSWebSite;
                if (site != null)
                {
                    site.PreCompileWeb(dir.DeployFromPath, true);
                }
                else
                {
                    string frameworkPath = (site == null) ? project.GetFrameworkPath() : String.Empty;

                    if (worker.CancellationPending)
                    {
                        args.Cancel = true; return;
                    }
                    string objDir = Path.Combine(dir.ProjectDirectory, "obj");
                    if (Directory.Exists(objDir))
                    {
                        Directory.Delete(objDir, true); // NB: this can cause precompile errors
                    }

                    var process = new System.Diagnostics.Process()
                    {
                        StartInfo = new ProcessStartInfo()
                        {
                            FileName               = Path.Combine(frameworkPath, "aspnet_compiler.exe"),
                            Arguments              = String.Format("-nologo -v / -p \"{0}\" -f -u -c \"{1}\"", dir.ProjectDirectory, dir.DeployFromPath),
                            CreateNoWindow         = true,
                            ErrorDialog            = false,
                            UseShellExecute        = false,
                            RedirectStandardOutput = true
                        }
                    };

                    if (worker.CancellationPending)
                    {
                        args.Cancel = true; return;
                    }
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(40, "Precompiling Site"))));
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    if (false == String.IsNullOrEmpty(output))
                    {
                        dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError("Asp Compile Error: " + output))));
                        return;
                    }
                }

                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(50, "Logging in to Cloud Foundry"))));

                if (worker.CancellationPending)
                {
                    args.Cancel = true; return;
                }

                var client = new VcapClient(cloud);
                VcapClientResult result = client.Login();
                if (result.Success == false)
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError("Failure: " + result.Message))));
                    return;
                }

                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(75, "Sending to " + cloud.Url))));
                if (worker.CancellationPending)
                {
                    args.Cancel = true; return;
                }

                result = function(client, new DirectoryInfo(dir.DeployFromPath));
                if (result.Success == false)
                {
                    dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressError("Failure: " + result.Message))));
                    return;
                }
                dispatcher.BeginInvoke((Action)(() => Messenger.Default.Send(new ProgressMessage(100, action + " complete."))));
            };

            worker.RunWorkerAsync();
            if (!window.ShowDialog().GetValueOrDefault())
            {
                worker.CancelAsync();
            }
        }
Exemplo n.º 39
0
        private void doIt(string script)
        {
            int desiredImageWidth  = this.TabControl.Size.Width - 5;
            int desiredImageHeight = this.TabControl.Size.Height - 5;

            string[] fullpath       = NodePath.Split(new char[] { '/' });
            string   nodeName       = fullpath[fullpath.Length - 1];
            string   imageFileName  = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + nodeName + ".png";
            string   scriptFileName = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + nodeName + ".R";

            List <string> OutputFileNames = new List <string>();

            UIUtility.OutputFileUtility.GetOutputFiles(Controller, Controller.Selection, OutputFileNames);

            // Build the R script from our XML value
            StringWriter newScript = new StringWriter();

            newScript.WriteLine("# Automatically generated - do not edit");
            newScript.WriteLine("width<- " + desiredImageWidth.ToString());
            newScript.WriteLine("height<- " + desiredImageHeight.ToString());
            newScript.WriteLine("imageFileName <- \"" + imageFileName.Replace("\\", "/") + "\"");
            newScript.Write("inputFiles <- c(");

            bool first = true;

            foreach (string outputfile in OutputFileNames)
            {
                if ((!(first)))
                {
                    newScript.Write(",");
                }
                newScript.Write("\"" + outputfile.Replace("\\", "/") + "\"");
                first = false;
            }
            newScript.WriteLine(")");
            newScript.Write(script);

            bool needsRerun = false;

            // See if the script has changed since its last run
            if ((File.Exists(scriptFileName)))
            {
                StreamReader sfp       = new StreamReader(scriptFileName, false);
                string       oldScript = sfp.ReadToEnd();
                needsRerun = !(string.Equals(oldScript, newScript.ToString()));
                sfp.Close();
            }
            else
            {
                needsRerun = true;
            }

            // See if the input files have changed
            if ((!(File.Exists(imageFileName))))
            {
                needsRerun = true;
            }
            else
            {
                // See if a simulation has been run that invalidates this image
                System.DateTime myDate = File.GetCreationTime(imageFileName);
                foreach (string outputfile in OutputFileNames)
                {
                    if ((File.Exists(outputfile) && (File.GetCreationTime(outputfile) > myDate)))
                    {
                        needsRerun = true;
                    }
                }
            }

            // See if the window size has changed
            if ((!(needsRerun) && File.Exists(imageFileName)))
            {
                Image diskImage = Image.FromFile(imageFileName);
                if (((desiredImageWidth != diskImage.Width) || (desiredImageHeight != diskImage.Height)))
                {
                    needsRerun = true;
                }
                diskImage.Dispose();
            }
            else
            {
                needsRerun = true;
            }

            bool canRun = true;

            if ((needsRerun))
            {
                foreach (string outputfile in OutputFileNames)
                {
                    if ((!(File.Exists(outputfile))))
                    {
                        canRun = false;
                    }
                }
            }

            if ((!(canRun)))
            {
                this.ConsoleBox.Text = "Output files are missing. Can't run R. Run APSIM first.";
            }
            else if ((needsRerun))
            {
                StreamWriter fp = new StreamWriter(scriptFileName, false);
                fp.Write(newScript.ToString());
                fp.Close();

                // scrub the old image so that we can be sure it's regenerated
                try {
                    File.Delete(imageFileName);
                } catch (System.IO.IOException) {
                } finally {
                }

                // try and run R with this script
                RegistryKey regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\R-core\\R", false);
                if (((regKey != null)))
                {
                    string rpath = (string)regKey.GetValue("InstallPath", "");

                    // Should test somehow for pre 2.12.x that doesnt have rscript installed
                    string rcmd = rpath + "\\bin\\Rscript.exe";
                    string args = "--slave --vanilla \"" + scriptFileName + "\"";

                    string consoleMsg = "Command:   " + rcmd + Environment.NewLine + Environment.NewLine;
                    consoleMsg          += "Arguments: " + args + Environment.NewLine + Environment.NewLine;
                    this.ConsoleBox.Text = consoleMsg;

                    System.Diagnostics.Process p = Utility.RunProcess(rcmd, args, Directory.GetCurrentDirectory());
                    p.WaitForExit();

                    consoleMsg          += "stdout: " + Environment.NewLine + p.StandardOutput.ReadToEnd() + Environment.NewLine + Environment.NewLine;
                    consoleMsg          += "stderr: " + Environment.NewLine + p.StandardError.ReadToEnd() + Environment.NewLine + Environment.NewLine;
                    consoleMsg          += "script: " + Environment.NewLine + newScript.ToString();
                    this.ConsoleBox.Text = consoleMsg;
                }
            }

            // update displayed image
            if ((File.Exists(imageFileName)))
            {
                FileStream newImageStream = new FileStream(imageFileName, FileMode.Open, FileAccess.Read);
                this.PictureBox.Image = Image.FromStream(newImageStream);
                newImageStream.Dispose();
            }
        }
Exemplo n.º 40
0
        public override void Execute()
        {
            dte = GetService<DTE>(true);

            //set the directory where to place the output
            tempExportDir = Path.Combine(Path.GetTempPath(), "SPSFExport" + Guid.NewGuid().ToString());
            Directory.CreateDirectory(tempExportDir);
            tempFilename = EXPORTFILENAME;
            tempLogFilePath = Path.Combine(tempExportDir, "SPSFExport.log");

            _ExportSettings.ExportMethod = _ExportMethod;
            _ExportSettings.IncludeSecurity = _IncludeSecurity;
            _ExportSettings.IncludeVersions = _IncludeVersions;
            _ExportSettings.ExcludeDependencies = _ExcludeDependencies;

            //start bridge
            SharePointBrigdeHelper helper = new SharePointBrigdeHelper(dte);
            helper.ExportContent(_ExportSettings, tempExportDir, tempFilename, tempLogFilePath);

            if (_ExtractAfterExport)
            {
                //should they be extracted before
                string tempExtractFolder = tempExportDir; // Path.Combine(tempExportDir, "extracted");
                //Directory.CreateDirectory(tempExtractFolder);
                string fileToExtract = Path.Combine(tempExportDir, EXPORTFILENAME);

                // Launch the process and wait until it's done (with a 10 second timeout).
                string commandarguments = "\"" + fileToExtract + "\" \"" + tempExtractFolder + "\" -F:*";
                ProcessStartInfo startInfo = new ProcessStartInfo("expand ", commandarguments);
                startInfo.CreateNoWindow = true;
                startInfo.UseShellExecute = false;
                System.Diagnostics.Process snProcess = System.Diagnostics.Process.Start(startInfo);
                snProcess.WaitForExit(20000);

                //rename
                bool renameFilesAfterExport = true;
                if (renameFilesAfterExport)
                {
                    //get the manifest.xml
                    string manifestFilename = Path.Combine(tempExportDir, "Manifest.xml");
                    if (File.Exists(manifestFilename))
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(manifestFilename);

                        //get the contents of the elements node in the new xml
                        XmlNamespaceManager newnsmgr = new XmlNamespaceManager(doc.NameTable);
                        newnsmgr.AddNamespace("ns", "urn:deployment-manifest-schema");

                        //read all
                        XmlNodeList datFiles = doc.SelectNodes("/ns:SPObjects/ns:SPObject/ns:File", newnsmgr);
                        foreach (XmlNode datFile in datFiles)
                        {
                            //DispForm.aspx
                            if (datFile.Attributes["Name"] != null)
                            {
                                if (datFile.Attributes["FileValue"] != null)
                                {
                                    //is there a file with name 00000001.dat
                                    string datFilename = datFile.Attributes["FileValue"].Value;
                                    string datFilePath = Path.Combine(tempExportDir, datFilename);
                                    if (File.Exists(datFilePath))
                                    {
                                        //ok, lets change the name
                                        string newfilename = Path.GetFileNameWithoutExtension(datFilePath);
                                        string itemname = datFile.Attributes["Name"].Value;
                                        itemname = itemname.Replace(".", "_");
                                        itemname = itemname.Replace(" ", "_");
                                        newfilename = newfilename + SPSFConstants.NameSeparator + itemname + ".dat";

                                        string newfilePath = Path.Combine(tempExportDir, newfilename);
                                        //rename the file
                                        File.Move(datFilePath, newfilePath);

                                        //update the manifest.xml
                                        datFile.Attributes["FileValue"].Value = newfilename;
                                    }
                                }
                            }
                        }
                        doc.Save(manifestFilename);
                    }
                }

                //todo delete the cmp file
                if (File.Exists(fileToExtract))
                {
                    File.Delete(fileToExtract);
                }

                //create the ddf out of the contents (except the logfile);
                StringBuilder ddfcontent = new StringBuilder();
                ddfcontent.AppendLine(";*** Sample Source Code MakeCAB Directive file example");
                ddfcontent.AppendLine(";");
                ddfcontent.AppendLine(".OPTION EXPLICIT     ; Generate errors");
                ddfcontent.AppendLine(".Set CabinetNameTemplate=exportedData.cab");
                ddfcontent.AppendLine(".set DiskDirectoryTemplate=CDROM ; All cabinets go in a single directory");
                ddfcontent.AppendLine(".Set CompressionType=MSZIP;** All files are compressed in cabinet files");
                ddfcontent.AppendLine(".Set UniqueFiles=\"OFF\"");
                ddfcontent.AppendLine(".Set Cabinet=on");
                ddfcontent.AppendLine(".Set DiskDirectory1=.");
                ddfcontent.AppendLine(".Set CabinetFileCountThreshold=0");
                ddfcontent.AppendLine(".Set FolderFileCountThreshold=0");
                ddfcontent.AppendLine(".Set FolderSizeThreshold=0");
                ddfcontent.AppendLine(".Set MaxCabinetSize=0");
                ddfcontent.AppendLine(".Set MaxDiskFileCount=0");
                ddfcontent.AppendLine(".Set MaxDiskSize=0");

                foreach (string s in Directory.GetFiles(tempExportDir, "*.*", SearchOption.AllDirectories))
                {
                    if (!s.EndsWith(".log"))
                    {
                        FileInfo info = new FileInfo(s);
                        ddfcontent.AppendLine(info.Name);
                    }
                }

                ddfcontent.AppendLine("");
                ddfcontent.AppendLine(";*** The end");

                //write the ddf file
                string ddfFilename = Path.Combine(tempExportDir, "_exportedData.ddf");
                TextWriter writer = new StreamWriter(ddfFilename);
                writer.Write(ddfcontent.ToString());
                writer.Close();
            }

            //add all elements in temp folder to the folder exported objects in the project
            ProjectItem targetFolder = Helpers.GetProjectItemByName(TargetProject.ProjectItems, TargetFolder);
            if (targetFolder != null)
            {
                //is there already a folder named "ExportedData"
                ProjectItem exportedDataFolder = null;
                try
                {
                    exportedDataFolder = Helpers.GetProjectItemByName(targetFolder.ProjectItems, "ExportedData");
                }
                catch (Exception)
                {
                }
                if (exportedDataFolder == null)
                {
                    exportedDataFolder = targetFolder.ProjectItems.AddFolder("ExportedData", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                }

                //empty the exportedDataFolder
                foreach (ProjectItem subitem in exportedDataFolder.ProjectItems)
                {
                    subitem.Delete();
                }

                //add all files in temp folder to the project (except log file
                foreach (string s in Directory.GetFiles(tempExportDir, "*.*", SearchOption.AllDirectories))
                {
                    if (!s.EndsWith(".log"))
                    {
                        exportedDataFolder.ProjectItems.AddFromFileCopy(s);
                    }
                }

                //add log file to the parent folder
                if (File.Exists(tempLogFilePath))
                {
                    targetFolder.ProjectItems.AddFromFileCopy(tempLogFilePath);
                }
            }
        }
Exemplo n.º 41
0
        private async void DoOnSolutionReadyOrChange()
        {
            if (!File.Exists(_visualStudioWorkspace.CurrentSolution.FilePath))
            {
                LogWarn("Could not find solution.");
                return;
            }

            if (!WorkspaceHasBitConfigV1JsonFile())
            {
                LogWarn("Could not find BitConfigV1.json file.");
                return;
            }

            _outputPane.Clear();

            DefaultBitConfigProvider configProvider = new DefaultBitConfigProvider();

            BitConfig config;

            try
            {
                config = configProvider.GetConfiguration(_visualStudioWorkspace.CurrentSolution.FilePath);

                foreach (BitCodeGeneratorMapping mapping in config.BitCodeGeneratorConfigs.BitCodeGeneratorMappings)
                {
                    if (!_visualStudioWorkspace.CurrentSolution.Projects.Any(p => p.Name == mapping.DestinationProject.Name && p.Language == LanguageNames.CSharp))
                    {
                        LogWarn($"No project found named {mapping.DestinationProject.Name}");
                    }

                    foreach (BitTools.Core.Model.ProjectInfo proj in mapping.SourceProjects)
                    {
                        if (!_visualStudioWorkspace.CurrentSolution.Projects.Any(p => p.Name == proj.Name && p.Language == LanguageNames.CSharp))
                        {
                            LogWarn($"No project found named {proj.Name}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogException("Parse BitConfigV1.json failed.", ex);
                return;
            }

            try
            {
                InitHtmlElements(config);
            }
            catch (Exception ex)
            {
                LogException("Init html elements failed.", ex);
            }

            try
            {
                bitWorkspaceIsPrepared = thereWasAnErrorInLastBuild = lastActionWasClean = false;
                Log("Preparing bit workspace... This includes restoring nuget packages, building your solution and generating codes.");

                using (System.Diagnostics.Process dotnetBuildProcess = new System.Diagnostics.Process())
                {
                    dotnetBuildProcess.StartInfo.UseShellExecute        = false;
                    dotnetBuildProcess.StartInfo.RedirectStandardOutput = true;
                    dotnetBuildProcess.StartInfo.FileName         = @"dotnet";
                    dotnetBuildProcess.StartInfo.Arguments        = "build";
                    dotnetBuildProcess.StartInfo.CreateNoWindow   = true;
                    dotnetBuildProcess.StartInfo.WorkingDirectory = Directory.GetParent(_visualStudioWorkspace.CurrentSolution.FilePath).FullName;
                    dotnetBuildProcess.Start();
                    await dotnetBuildProcess.StandardOutput.ReadToEndAsync();

                    dotnetBuildProcess.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                LogException("Bit workspace preparation failed", ex);
            }
            finally
            {
                bitWorkspaceIsPrepared = true;
                await CallGenerateCodes();

                Log("Bit workspace gets prepared", activatePane: true);
            }
        }
        public async Task CancelOnProcessTermination_provides_CancellationToken_that_signals_termination_when_null_timeout_is_specified(int signo)
        {
            const string ChildProcessWaiting = "Waiting for the command to be cancelled";
            const int    CancelledExitCode   = 42;

            Func <string[], Task <int> > childProgram = (string[] args) =>
            {
                var command = new Command("the-command");

                command.SetHandler(async context =>
                {
                    var cancellationToken = context.GetCancellationToken();

                    try
                    {
                        context.Console.WriteLine(ChildProcessWaiting);
                        await Task.Delay(int.MaxValue, cancellationToken);
                        context.ExitCode = 1;
                    }
                    catch (OperationCanceledException)
                    {
                        // For Process.Exit handling the event must remain blocked as long as the
                        // command is executed.
                        // We are currently blocking that event because CancellationTokenSource.Cancel
                        // is called from the event handler.
                        // We'll do an async Yield now. This means the Cancel call will return
                        // and we're no longer actively blocking the event.
                        // The event handler is responsible to continue blocking until the command
                        // has finished executing. If it doesn't we won't get the CancelledExitCode.
                        await Task.Yield();

                        // Exit code gets set here - but then execution continues and is let run till code voluntarily returns
                        //  hence exit code gets overwritten below
                        context.ExitCode = 123;
                    }

                    // This is an example of bad pattern and reason why we need a timeout on termination processing
                    await Task.Delay(TimeSpan.FromMilliseconds(200));

                    context.ExitCode = CancelledExitCode;
                });

                return(new CommandLineBuilder(new RootCommand
                {
                    command
                })
                       // Unfortunately we cannot use test parameter here - RemoteExecutor currently doesn't capture the closure
                       .CancelOnProcessTermination(null)
                       .Build()
                       .InvokeAsync("the-command"));
            };

            using RemoteExecution program = RemoteExecutor.Execute(childProgram, psi: new ProcessStartInfo { RedirectStandardOutput = true });

            Process process = program.Process;

            // Wait for the child to be in the command handler.
            string childState = await process.StandardOutput.ReadLineAsync();

            childState.Should().Be(ChildProcessWaiting);

            // Request termination
            kill(process.Id, signo).Should().Be(0);

            // Verify the process terminates timely
            bool processExited = process.WaitForExit(10000);

            if (!processExited)
            {
                process.Kill();
                process.WaitForExit();
            }
            processExited.Should().Be(true);

            // Verify the process exit code
            process.ExitCode.Should().Be(CancelledExitCode);
        }
Exemplo n.º 43
0
        private void CommandExec(CommandModel cmd)
        {
            Trace.Call(cmd);

            if (cmd.DataArray.Length < 2)
            {
                NotEnoughParameters(cmd);
                return;
            }
            var parameter     = cmd.Parameter;
            var parameters    = cmd.Parameter.Split(' ');
            var messageOutput = false;
            var executeOutput = false;

            if (parameters.Length > 0)
            {
                var shift = false;
                switch (parameters[0])
                {
                case "-c":
                    executeOutput = true;
                    shift         = true;
                    break;

                case "-o":
                    messageOutput = true;
                    shift         = true;
                    break;
                }
                if (shift)
                {
                    parameters = parameters.Skip(1).ToArray();
                    parameter  = String.Join(" ", parameters);
                }
            }
            SysDiag.DataReceivedEventHandler handler = (sender, e) => {
                if (String.IsNullOrEmpty(e.Data))
                {
                    return;
                }
                // eat trailing newlines
                var output = e.Data.TrimEnd('\r', '\n');
                if (executeOutput || messageOutput)
                {
                    if (messageOutput && output.StartsWith(cmd.CommandCharacter))
                    {
                        // escape command character
                        output = String.Format("{0}{1}",
                                               cmd.CommandCharacter, output);
                    }
                    DoExecute(new CommandModel(cmd.FrontendManager,
                                               cmd.Chat,
                                               cmd.CommandCharacter, output));
                }
                else
                {
                    var msg = new MessageBuilder().AppendText(output).ToMessage();
                    AddMessageToFrontend(cmd, msg);
                }
            };

            string file;
            string args = null;

            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                file = "sh";
                args = String.Format("-c \"{0}\"",
                                     parameter.Replace("\"", @"\"""));
            }
            else
            {
                file = parameters[1];
                if (parameters.Length > 1)
                {
                    args = String.Join(" ", parameters.Skip(1).ToArray());
                }
            }
            var info = new SysDiag.ProcessStartInfo()
            {
                FileName               = file,
                Arguments              = args,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                UseShellExecute        = false
            };

            using (var process = new SysDiag.Process()) {
                process.StartInfo           = info;
                process.OutputDataReceived += handler;
                process.ErrorDataReceived  += handler;

                try {
                    process.Start();
                    process.StandardInput.Close();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    process.WaitForExit();
                } catch (Exception ex) {
#if LOG4NET
                    f_Logger.Error(ex);
#endif
                    var command = info.FileName;
                    if (!String.IsNullOrEmpty(info.Arguments))
                    {
                        command += " " + info.Arguments;
                    }
                    var msg = new MessageBuilder().
                              AppendErrorText("Executing '{0}' failed with: {1}",
                                              command, ex.Message).
                              ToMessage();
                    AddMessageToFrontend(cmd, msg);
                }
            }
        }
Exemplo n.º 44
0
        public static void RestoreBackup(string db_host, string db_name, string db_user, string filename)
        {
            string db_pass = SettingsMng.Instance.GetDBPassword();

            //Obtención de la ruta de pg_restore
            string path_pg_restore = Reg32GetPGBinPath() + Paths.PG_RESTORE;

            if (path_pg_restore == string.Empty)
            {
                return;
            }

            //Obtención de la ruta de pg_restore
            string path_pg_ctl = Application.StartupPath + Paths.PG_CTL;

            if (!File.Exists(path_pg_restore) || !File.Exists(path_pg_ctl))
            {
                throw new iQException(Errors.RESTORE_APP_NOT_FOUND);
            }

            //Creamos el fichero pgpass.conf para que no salte el prompt pidiendo password
            string pgpassPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            pgpassPath += Paths.PG_PASS;
            if (!Directory.Exists(Path.GetPathRoot(pgpassPath)))
            {
                Directory.CreateDirectory(Path.GetPathRoot(pgpassPath));
            }
            StreamWriter sw = File.CreateText(pgpassPath);

            sw.WriteLine(db_host + ":*:*:" + db_user + ":" + db_pass);
            sw.Close();

            string query =
                @"	SELECT DISTINCT client_addr 
					FROM pg_stat_activity 
					WHERE datname = '"                     + db_name + "';";

            System.Data.IDataReader reader = nHManager.Instance.SQLNativeSelect(query);

            string lista_ip   = string.Empty;
            long   interfaces = 0;

            while (reader.Read())
            {
                lista_ip += Environment.NewLine + reader["client_addr"].ToString();
                interfaces++;
            }

            DialogResult result = DialogResult.No;

            if (interfaces > 1)
            {
                result = MessageBox.Show(Resources.Messages.CLOSE_SESSIONS_1 +
                                         lista_ip + Environment.NewLine + Resources.Messages.CLOSE_SESSIONS_2,
                                         Resources.Messages.AVISO_CAPTION, MessageBoxButtons.YesNo);
            }

            if (result == DialogResult.No)
            {
                //cierra todas las conexiones abiertas con la base de datos
                query =
                    @"	SELECT pg_terminate_backend(procpid) 
						FROM pg_stat_activity WHERE datname = '"                         + db_name + "';";

                ExecuteSQL(db_host, db_name, db_user, query);
                //elimina la base de datos
                query = "DROP DATABASE \"" + db_name + "\";";
                ExecuteSQL(db_host, db_name, db_user, query);
                //vuelve a crear la base de datos
                query = "CREATE DATABASE \"" + db_name + "\";";
                ExecuteSQL(db_host, db_name, db_user, query);

                //Crea un nuevo proceso
                System.Diagnostics.Process p = new System.Diagnostics.Process();

                //Ejecución del pg_restore
                p.StartInfo.FileName  = path_pg_restore;
                p.StartInfo.Arguments = "--verbose " +
                                        "--host=" + db_host + " " +
                                        "-d \"" + db_name + "\" " +
                                        "-U " + db_user + " " +
                                        "\"" + filename + "\"";
                p.Start();
                p.WaitForExit();

                //Borramos el fichero pgpass.conf
                File.Delete(pgpassPath);
            }
        }
Exemplo n.º 45
0
        protected static void DoCreateBackup(string dbHost, string dbName, string dbUser, List <ISchemaInfo> schemas, string outputFile)
        {
            System.Diagnostics.Process process = null;

            try
            {
                //Obtención de la ruta de pg_dump
                string path_pg_dump = Reg32GetPGBinPath() + Paths.PG_DUMP;

                if (path_pg_dump == string.Empty)
                {
                    return;
                }

                if (!File.Exists(path_pg_dump))
                {
                    throw new iQException(Errors.BACKUP_APP_NOT_FOUND);
                }

                string msg = "Creating db credentials file " + outputFile;
                MyLogger.LogText(msg, "AppControllerBase::DoCreateBackup");
                Console.WriteLine(msg);

                string db_pass = SettingsMng.Instance.GetDBPassword();

                //Creamos el fichero pgpass.conf para que no salte el prompt pidiendo password
                string pgpassPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                pgpassPath += Paths.PG_PASS;
                if (!Directory.Exists(Path.GetPathRoot(pgpassPath)))
                {
                    Directory.CreateDirectory(Path.GetPathRoot(pgpassPath));
                }
                StreamWriter sw = File.CreateText(pgpassPath);
                sw.WriteLine(dbHost + ":*:*:" + dbUser + ":" + db_pass);
                sw.Close();

                if (!Directory.Exists(Path.GetDirectoryName(outputFile)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(outputFile));
                }

                //Crea un nuevo proceso
                process = new System.Diagnostics.Process();

                if (schemas == null)
                {
                    //Ejecución del pg_dump
                    process.StartInfo.FileName  = path_pg_dump;
                    process.StartInfo.Arguments =
                        string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8}"
                                      , new string[] {
                        "--format=c"
                        , "--ignore-version"
                        , "--oids"
                        , "--blobs"
                        , "--verbose"
                        , "--host=" + dbHost
                        , "-U " + dbUser
                        , @"--file=""" + string.Format(outputFile, "FULL") + @""""
                        , @"""" + dbName + @""""
                    }
                                      );
                    process.Start();
                    process.WaitForExit();
                }
                else
                {
                    //COMMON SCHEMA
                    try
                    {
                        //Ejecución del pg_dump
                        process.StartInfo.FileName  = path_pg_dump;
                        process.StartInfo.Arguments =
                            string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}"
                                          , new string[] {
                            "--format=c"
                            , "--ignore-version"
                            , "--oids"
                            , "--blobs"
                            , "--verbose"
                            , "--host=" + dbHost
                            , "-U " + dbUser
                            , @"--file=""" + string.Format(outputFile, AppContext.CommonSchema) + @""""
                            , "--schema=" + AppContext.CommonSchema
                            , @"""" + dbName + @""""
                        }
                                          );

                        process.Start();
                        process.WaitForExit();
                    }
                    catch (Exception ex)
                    {
                        MyLogger.LogException(ex, "AppControllerBase::DoCreateBackup");
                    }

                    //DETAILED SCHEMAS
                    foreach (ISchemaInfo schema in schemas)
                    {
                        try
                        {
                            //Ejecución del pg_dump
                            process.StartInfo.FileName  = path_pg_dump;
                            process.StartInfo.Arguments =
                                string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}"
                                              , new string[] {
                                "--format=c"
                                , "--ignore-version"
                                , "--oids"
                                , "--blobs"
                                , "--verbose"
                                , "--host=" + dbHost
                                , "-U " + dbUser
                                , @"--file=""" + string.Format(outputFile, schema.SchemaCode) + @""""
                                , "--schema=" + schema.SchemaCode
                                , @"""" + dbName + @""""
                            }
                                              );

                            process.Start();
                            process.WaitForExit();
                        }
                        catch (Exception ex)
                        {
                            MyLogger.LogException(ex, "AppControllerBase::DoCreateBackup");
                        }
                    }
                }

                //Borramos el fichero pgpass.conf
                File.Delete(pgpassPath);

                SettingsMng.Instance.SetBackupsLastDate(DateTime.Now);
                SettingsMng.Instance.SaveSettings();
            }
            catch (Exception ex)
            {
                MyLogger.LogException(ex, "AppControllerBase::DoCreateBackup");
                if (process != null)
                {
                    MyLogger.LogText("process.StartInfo.Arguments = " + process.StartInfo.Arguments);
                }
            }
        }
Exemplo n.º 46
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            Act.Pass();

            param.Visible  = false;
            report.Visible = true;
            int pdf   = Convert.ToInt16(Request.QueryString["pdf"]);
            int excel = Convert.ToInt16(Request.QueryString["Excel"]);

            if (excel == 1)
            {
                Report();
                //Rpt.ToExcel(this, report);

                rp.Controls.Add(report);
                rp.Controls.Add(list);
                rp.Controls.Add(rpt);
                Rpt.ToExcel(this, rp);
            }
            else if (pdf == 1)
            {
                Report();
                Process p = new System.Diagnostics.Process();

                string   Nama        = "Laporan Kartu Piutang";
                string   Link        = "";
                DateTime TglGenerate = DateTime.Now;
                string   FileName    = "";
                string   FileType    = "application/pdf";
                string   UserID      = Act.UserID;
                string   IP          = Act.IP;

                Db.Execute("EXEC spLapPDFDaftar"

                           + " '" + Nama + "'"
                           + ",'" + Link + "'"
                           + ",'" + TglGenerate + "'"
                           + ",'" + IP + "'"
                           + ",'" + UserID + "'"
                           + ",'" + FileName + "'"
                           + ",'" + FileType + "'"
                           + ",'" + null + "'"
                           + ",'" + null + "'"
                           );

                //get nomor customer terbaru
                int NoAttachment = Db.SingleInteger(
                    "SELECT TOP 1 AttachmentID FROM LapPDF ORDER BY AttachmentID DESC");

                string    strSql = "SELECT * FROM ISC064_FINANCEAR..LapPDF WHERE AttachmentID  = '" + NoAttachment + "'";
                DataTable rs     = Db.Rs(strSql);

                string nfilename = "KartuPiutang" + NoAttachment + ".pdf";

                //update filename
                Db.Execute("UPDATE ISC064_FINANCEAR..LapPDF SET FileName= '" + nfilename + "' WHERE AttachmentID = " + NoAttachment);


                //folder untuk menyimpan file pdf
                string save = Mi.PathFilePDFReport + "KartuPiutang" + rs.Rows[0]["AttachmentID"] + ".pdf";

                string NoKontrak = Convert.ToString(Request.QueryString["NoKontrak"]);

                //link untuk download pdf
                string link = Mi.PathAlamatWeb + "collection/LaporanPDF/PDFLaporanKartuPiutang.aspx?NoKontrak=" + NoKontrak + "&userid=" + Request.QueryString["userid"]
                ;

                //update link
                Db.Execute("UPDATE ISC064_FINANCEAR..LapPDF SET Link= '" + link + "' WHERE AttachmentID = " + NoAttachment);

                //format page
                p.StartInfo.Arguments = "--orientation landscape --page-width 8.5in --page-height 11in --margin-left 0 --margin-right 0 --margin-top 0.25cm --margin-bottom 0 " + link + " " + save;

                //panggil aplikasi untuk mengconvert pdf
                p.StartInfo.FileName = Mi.PathWkhtmlPDFReport;
                p.Start();

                //60000 -> waktu jeda lama convert pdf
                p.WaitForExit(30000);

                string Src = Mi.PathFilePDFReport + nfilename;
                Mi.DownloadPDF(this, Src, (rs.Rows[0]["FileName"]).ToString(), rs.Rows[0]["FileType"].ToString());
            }
            else
            {
                Report();
            }

            if (!Page.IsPostBack)
            {
                Js.Focus(this, scr);
                if (!Act.Sec("DownloadExcel"))
                {
                    xls.Enabled = false;
                }
            }
        }
        public void ProjectItemFinishedGenerating(ProjectItem
                                                  projectItem)
        {
            string projectDir = projectItem.ContainingProject.FullName;

            projectDir = projectDir.Substring(0, projectDir.LastIndexOf("\\"));
            string logFile = String.Format(@"{0}\{1}.log", projectDir, componentName);

            commandString = commandString.Replace("$ComponentName$", componentName);
            commandString = commandString.Replace("$ComponentDescription$", componentDescription);

            StringBuilder outputText = new StringBuilder();

            using (var proc = new System.Diagnostics.Process())
            {
                proc.StartInfo.WorkingDirectory = projectDir;
                proc.StartInfo.FileName         = @"cmd.exe";

                if (showWindow == "false")
                {
                    proc.StartInfo.Arguments              = string.Format(@" /c  {0}", commandString);
                    proc.StartInfo.RedirectStandardInput  = true;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError  = true;
                    proc.StartInfo.CreateNoWindow         = true;
                    proc.StartInfo.UseShellExecute        = false;
                    proc.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                    proc.Start();

                    proc.StandardInput.Flush();
                    proc.StandardInput.WriteLine("exit");
                    proc.StandardInput.Flush();

                    using (StreamReader reader = proc.StandardOutput)
                    {
                        string result = reader.ReadToEnd();
                        outputText.Append(result);
                    }

                    using (StreamReader reader = proc.StandardError)
                    {
                        string result = reader.ReadToEnd();
                        outputText.Append(result);
                    }
                }
                else
                {
                    proc.StartInfo.Arguments = string.Format(@" /k  {0}", commandString);
                    proc.Start();
                }

                proc.WaitForExit();

                using (StreamWriter sw = File.AppendText(logFile))
                {
                    sw.Write(outputText);
                }
            }

            string[] files = Directory.GetFiles(projectDir, "*.*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                if (!file.ToLower().Contains("node_modules") && !file.ToLower().Contains(@"\bin\") && !file.ToLower().Contains(@"\obj\") && !file.ToLower().Contains(@"\properties\"))
                {
                    try
                    {
                        projectItem.ContainingProject.ProjectItems.AddFromFile(file);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 48
0
        private static void Execute(string scriptpath, string eventname, string operationname, ref string remoteurl, ref string[] localpath, int timeout, bool requiredScript, IDictionary <string, string> options, string datafile)
        {
            try
            {
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(scriptpath);
                psi.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                psi.CreateNoWindow         = true;
                psi.UseShellExecute        = false;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError  = true;

                foreach (KeyValuePair <string, string> kv in options)
                {
                    psi.EnvironmentVariables["DUPLICATI__" + kv.Key.Replace('-', '_')] = kv.Value;
                }

                if (!options.ContainsKey("backup-name"))
                {
                    psi.EnvironmentVariables["DUPLICATI__backup_name"] = System.IO.Path.GetFileNameWithoutExtension(Duplicati.Library.Utility.Utility.getEntryAssembly().Location);
                }

                psi.EnvironmentVariables["DUPLICATI__EVENTNAME"]     = eventname;
                psi.EnvironmentVariables["DUPLICATI__OPERATIONNAME"] = operationname;
                psi.EnvironmentVariables["DUPLICATI__REMOTEURL"]     = remoteurl;
                if (localpath != null)
                {
                    psi.EnvironmentVariables["DUPLICATI__LOCALPATH"] = string.Join(System.IO.Path.PathSeparator.ToString(), localpath);
                }

                string stderr = null;
                string stdout = null;

                if (!string.IsNullOrEmpty(datafile))
                {
                    psi.EnvironmentVariables["DUPLICATI__RESULTFILE"] = datafile;
                }

                using (System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi))
                {
                    ConsoleDataHandler cs = new ConsoleDataHandler(p);

                    if (timeout <= 0)
                    {
                        p.WaitForExit();
                    }
                    else
                    {
                        p.WaitForExit(timeout);
                    }

                    if (requiredScript)
                    {
                        if (!p.HasExited)
                        {
                            throw new Duplicati.Library.Interface.UserInformationException(Strings.RunScript.ScriptTimeoutError(scriptpath));
                        }
                        else if (p.ExitCode != 0)
                        {
                            throw new Duplicati.Library.Interface.UserInformationException(Strings.RunScript.InvalidExitCodeError(scriptpath, p.ExitCode));
                        }
                    }

                    if (p.HasExited)
                    {
                        stderr = cs.StandardError;
                        stdout = cs.StandardOutput;
                        if (p.ExitCode != 0)
                        {
                            Logging.Log.WriteMessage(Strings.RunScript.InvalidExitCodeError(scriptpath, p.ExitCode), Duplicati.Library.Logging.LogMessageType.Warning);
                        }
                    }
                    else
                    {
                        Logging.Log.WriteMessage(Strings.RunScript.ScriptTimeoutError(scriptpath), Duplicati.Library.Logging.LogMessageType.Warning);
                    }
                }

                if (!string.IsNullOrEmpty(stderr))
                {
                    Logging.Log.WriteMessage(Strings.RunScript.StdErrorReport(scriptpath, stderr), Duplicati.Library.Logging.LogMessageType.Warning);
                }

                //We only allow setting parameters on startup
                if (eventname == "BEFORE" && stdout != null)
                {
                    foreach (string rawline in stdout.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        string line = rawline.Trim();
                        if (!line.StartsWith("--"))
                        {
                            continue; //Ingore anything that does not start with --
                        }
                        line = line.Substring(2);
                        int lix = line.IndexOf('=');
                        if (lix == 0) //Skip --= as that makes no sense
                        {
                            continue;
                        }

                        string key;
                        string value;

                        if (lix < 0)
                        {
                            key   = line.Trim();
                            value = "";
                        }
                        else
                        {
                            key   = line.Substring(0, lix).Trim();
                            value = line.Substring(lix + 1).Trim();

                            if (value.Length >= 2 && value.StartsWith("\"") && value.EndsWith("\""))
                            {
                                value = value.Substring(1, value.Length - 2);
                            }
                        }

                        if (string.Equals(key, "remoteurl", StringComparison.InvariantCultureIgnoreCase))
                        {
                            remoteurl = value;
                        }
                        else if (string.Equals(key, "localpath", StringComparison.InvariantCultureIgnoreCase))
                        {
                            localpath = value.Split(System.IO.Path.PathSeparator);
                        }
                        else if (
                            string.Equals(key, "eventname", StringComparison.InvariantCultureIgnoreCase) ||
                            string.Equals(key, "operationname", StringComparison.InvariantCultureIgnoreCase) ||
                            string.Equals(key, "main-action", StringComparison.InvariantCultureIgnoreCase) ||
                            key == ""
                            )
                        {
                            //Ignore
                        }
                        else
                        {
                            options[key] = value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Log.WriteMessage(Strings.RunScript.ScriptExecuteError(scriptpath, ex.Message), Duplicati.Library.Logging.LogMessageType.Warning, ex);
                if (requiredScript)
                {
                    throw;
                }
            }
        }
Exemplo n.º 49
0
 public void WaitForExit()
 {
     _process.WaitForExit();
 }
Exemplo n.º 50
0
        protected void pdf_Click(object sender, System.EventArgs e)
        {
            Process p = new System.Diagnostics.Process();

            string   Nama        = "Laporan PPJB";
            string   Link        = "";
            DateTime TglGenerate = DateTime.Now;
            string   FileName    = "";
            string   FileType    = "application/pdf";
            string   UserID      = Act.UserID;
            string   IP          = Act.IP;

            Db.Execute("EXEC spLapPDFDaftar"

                       + " '" + Nama + "'"
                       + ",'" + Link + "'"
                       + ",'" + TglGenerate + "'"
                       + ",'" + IP + "'"
                       + ",'" + UserID + "'"
                       + ",'" + FileName + "'"
                       + ",'" + FileType + "'"
                       + ",'" + Convert.ToDateTime(dari.Text) + "'"
                       + ",'" + Convert.ToDateTime(sampai.Text) + "'"
                       );

            //get nomor customer terbaru
            int NoAttachment = Db.SingleInteger(
                "SELECT TOP 1 AttachmentID FROM LapPDF ORDER BY AttachmentID DESC");

            string    strSql = "SELECT * FROM ISC064_MARKETINGJUAL..LapPDF WHERE AttachmentID  = '" + NoAttachment + "'";
            DataTable rs     = Db.Rs(strSql);

            string nfilename = "LapPPJB" + NoAttachment + ".pdf";

            //update filename
            Db.Execute("UPDATE ISC064_MARKETINGJUAL..LapPDF SET FileName= '" + nfilename + "' WHERE AttachmentID = " + NoAttachment);


            //folder untuk menyimpan file pdf
            string save = Mi.PathFilePDFReport + "LapPPJB" + rs.Rows[0]["AttachmentID"] + ".pdf";

            string Project = "";

            if (project.SelectedIndex == 0)
            {
                Project = Act.ProjectListSql.Replace("'", "");
            }
            else
            {
                Project = project.SelectedValue;
            }

            //link untuk download pdf
            string link = Mi.PathAlamatWeb + "legal/LaporanPDF/PDFLaporanPPJB.aspx?id=" + rs.Rows[0]["AttachmentID"] + "&project=" + Project + "&pers=" + pers.SelectedValue + "";

            //update link
            Db.Execute("UPDATE ISC064_MARKETINGJUAL..LapPDF SET Link= '" + link + "' WHERE AttachmentID = " + NoAttachment);

            //format page
            p.StartInfo.Arguments = "--orientation landscape --page-width 15in --page-height 20in --margin-left 0 --margin-right 0 --margin-top 0.25cm --margin-bottom 0 " + link + " " + save;

            //panggil aplikasi untuk mengconvert pdf
            p.StartInfo.FileName = Mi.PathWkhtmlPDFReport;
            p.Start();

            //60000 -> waktu jeda lama convert pdf
            p.WaitForExit(30000);

            string Src = Mi.PathFilePDFReport + nfilename;

            Mi.DownloadPDF(this, Src, (rs.Rows[0]["FileName"]).ToString(), rs.Rows[0]["FileType"].ToString());
        }
Exemplo n.º 51
0
        /**
         *  Execute it
         */
        public void Run()
        {
            log.Info(_cmd);
            try
            {
                _child = System.Diagnostics.Process.Start(_cmd);

                _outStream = _child.StandardInput;
                _inStream  = _child.StandardOutput;


                ////_errStream = _child.getErrorStream();
                _errStream = _child.StandardError;
                ////_inStream = _child.getOutputStream();
                ////_inStream = _child.Threads;
                ////
                if (CheckInterrupted())
                {
                    return;
                }
                //_outReader.Start(new ThreadStart(Run1));
                //_errReader.Start(new ThreadStart(Run2));
                //
                try
                {
                    if (CheckInterrupted())
                    {
                        return;
                    }
                    _errReader.Join();
                    if (CheckInterrupted())
                    {
                        return;
                    }
                    _outReader.Join();
                    if (CheckInterrupted())
                    {
                        return;
                    }
                    // _child.waitFor();
                    _child.WaitForExit();
                }
                catch (ThreadInterruptedException ie)
                {
                    log.Log(Level.INFO, "(ie) - " + ie);
                }

                try
                {
                    if (_child != null)
                    {
                        log.Fine("run - ExitValue=" + _child.ExitCode);//  .exitValue());
                    }
                }
                catch  { }
                log.Config("done");
            }
            catch (IOException ioe)
            {
                log.Log(Level.SEVERE, "(ioe)", ioe);
            }
        }   //  run
Exemplo n.º 52
0
        public void BeginScreenShot(object o)
        {
            if (!File.Exists(Properties.Settings.Default.FFMPEG_Path))
            {
                lock (lockobject)
                {
                    vieModel.ScreenShot_CurrentProgress_S++;
                }
                return;
            }
            ;

            List <object> list           = o as List <object>;
            string        cutoffTime     = list[0] as string;
            string        i              = list[1] as string;
            string        filePath       = list[2] as string;
            string        ScreenShotPath = list[3] as string;

            if (string.IsNullOrEmpty(cutoffTime))
            {
                lock (lockobject)
                {
                    vieModel.ScreenShot_CurrentProgress_S++;
                }
                return;
            }

            //try
            //{
            //    ct.ThrowIfCancellationRequested();

            //    if (Pause) { ShowStatus("暂停中……"); App.Current.Dispatcher.Invoke((Action)delegate { WaitingPanel.Visibility = Visibility.Collapsed; }); }

            //    while (Pause) { Task.Delay(500).Wait(); }
            //}
            //catch (OperationCanceledException ex)
            //{
            //    return;
            //}


            SemaphoreScreenShot.WaitOne();
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName               = "cmd.exe";
            p.StartInfo.UseShellExecute        = false; //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput  = true;  //接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
            p.StartInfo.RedirectStandardError  = true;  //重定向标准错误输出
            p.StartInfo.CreateNoWindow         = true;  //不显示程序窗口
            p.Start();                                  //启动程序

            string str = $"\"{Properties.Settings.Default.FFMPEG_Path}\" -y -threads 1 -ss {cutoffTime} -i \"{filePath}\" -f image2 -frames:v 1 \"{ScreenShotPath}\\ScreenShot-{i.PadLeft(2, '0')}.jpg\"";



            p.StandardInput.WriteLine(str + "&exit");
            p.StandardInput.AutoFlush = true;
            string output = p.StandardOutput.ReadToEnd();

            //App.Current.Dispatcher.Invoke((Action)delegate { cmdTextBox.AppendText(output + "\n"); });
            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
            SemaphoreScreenShot.Release();

            lock (lockobject)
            {
                vieModel.ScreenShot_CurrentProgress_S++;
            }
            ShowStatus(">", false);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Launches a program
        /// </summary>
        /// <param name="ProgramFile">Path to the program to run</param>
        /// <param name="Arguments">Command-line arguments</param>
        /// <param name="OnExit">Optional callback whent he program exits</param>
        /// <param name="OutputHandler">If supplied, std-out and std-error will be redirected to this function and no shell window will be created</param>
        /// <returns>The newly-created process, or null if it wasn't able to start.  Exceptions are swallowed, but a debug output string is emitted on errors</returns>
        public System.Diagnostics.Process LaunchProgram(string ProgramFile, string Arguments, EventHandler OnExit = null, DataReceivedEventHandler OutputHandler = null, bool bWaitForCompletion = false)
        {
            // Create the action's process.
            ProcessStartInfo ActionStartInfo = new ProcessStartInfo();

            ActionStartInfo.FileName  = ProgramFile;
            ActionStartInfo.Arguments = Arguments;

            if (OutputHandler != null)
            {
                ActionStartInfo.RedirectStandardInput  = true;
                ActionStartInfo.RedirectStandardOutput = true;
                ActionStartInfo.RedirectStandardError  = true;

                // True to use a DOS box to run the program in, otherwise false to run directly.  In order to redirect
                // output, UseShellExecute must be disabled
                ActionStartInfo.UseShellExecute = false;

                // Don't show the DOS box, since we're redirecting everything
                ActionStartInfo.CreateNoWindow = true;
            }


            Logging.WriteLine(String.Format("Executing: {0} {1}", ActionStartInfo.FileName, ActionStartInfo.Arguments));

            System.Diagnostics.Process ActionProcess;

            try
            {
                ActionProcess           = new System.Diagnostics.Process();
                ActionProcess.StartInfo = ActionStartInfo;

                if (OnExit != null)
                {
                    ActionProcess.EnableRaisingEvents = true;
                    ActionProcess.Exited += OnExit;
                }

                if (ActionStartInfo.RedirectStandardOutput)
                {
                    ActionProcess.EnableRaisingEvents = true;
                    ActionProcess.OutputDataReceived += OutputHandler;
                    ActionProcess.ErrorDataReceived  += OutputHandler;
                }

                // Launch the program
                ActionProcess.Start();

                if (ActionStartInfo.RedirectStandardOutput)
                {
                    ActionProcess.BeginOutputReadLine();
                    ActionProcess.BeginErrorReadLine();
                }

                if (bWaitForCompletion)
                {
                    while ((ActionProcess != null) && (!ActionProcess.HasExited))
                    {
                        ActionProcess.WaitForExit(50);
                    }
                }
            }
            catch (Exception Ex)
            {
                // Couldn't launch program
                Logging.WriteLine("Couldn't launch program: " + ActionStartInfo.FileName);
                Logging.WriteLine("Exception: " + Ex.Message);
                ActionProcess = null;
            }

            return(ActionProcess);
        }
Exemplo n.º 54
0
        //     https://blogs.msdn.microsoft.com/krimakey/2008/04/18/click-once-forced-updates-in-vsto-ii-a-fuller-solution/
        public string InstallUpdateSyncWithInfo()
        {
            // https://msdn.microsoft.com/en-us/library/ms404263.aspx
            UpdateCheckInfo info = null;

            //if (!ApplicationDeployment.IsNetworkDeployed)
            //    return "La version actuelle n'est pas déployé en réseau ou est une version de développement.";

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                //TEST SASHA
                // downloadFileFTPForUpdate();
                //FIN TEST

                Assembly addinAssembly = Assembly.GetExecutingAssembly();

                string CachePath = addinAssembly.CodeBase.Substring(0, addinAssembly.CodeBase.Length -
                                                                    System.IO.Path.GetFileName(addinAssembly.CodeBase).Length);

                ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;

                // https://blogs.msdn.microsoft.com/krimakey/2008/04/10/click-once-forced-updates-in-vsto-some-things-we-dont-recommend-using-that-you-might-consider-anyway/
                ApplicationIdentity appId = new ApplicationIdentity(ad.UpdatedApplicationFullName);

                PermissionSet unrestrictedPerms = new PermissionSet(PermissionState.Unrestricted);

                ApplicationTrust appTrust = new ApplicationTrust(appId)
                {
                    DefaultGrantSet           = new PolicyStatement(unrestrictedPerms),
                    IsApplicationTrustedToRun = true,
                    Persist = true
                };

                ApplicationSecurityManager.UserApplicationTrusts.Add(appTrust);

retry:
                try {
                    info = ad.CheckForDetailedUpdate();
                } catch (DeploymentDownloadException dde) {
                    // À CE STADE, ON A TÉLÉCHARGÉ LE FICHIER .VSTO // SI UNE MISE À JOUR EST DISPONIBLE, L'ERREUR EST ATTRAPÉ ICI.

                    //MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message); //MessageBox.Show("La nouvelle version de l'application ne peut être télécharger en ce moment. \n\nVeuillez vérifier votre connection, ou réessayer plus tard. Erreur: " + dde.Message);

                    //return "La nouvelle version de l'application ne peut être télécharger en ce moment. \n\nVeuillez vérifier votre connection, ou réessayer plus tard. Erreur: " + dde.Message;
                    DialogResult result = MessageBox.Show("Bienvenu dans l'application " + ThisAddIn.NameOfAddin + "! Une nouvelle version de l'application est disponible et doit être téléchargé. La durée du téléchargement est d'une quinzaine (15) de secondes. \n\nSouhaitez-vous la télécharger maintenant?", ThisAddIn.NameOfAddin + " - Mise à jour disponible", MessageBoxButtons.YesNo);

                    if (result == DialogResult.Yes)
                    {
                        try {
                            if (downloadFTPfolderForUpdate())
                            {
                                goto retry;
                            }
                            else
                            {
                                return("La nouvelle version de l'application ne peut être télécharger en ce moment. \n\nVeuillez vérifier votre connection, ou réessayer plus tard. Erreur: " + dde.Message);
                            }
                        } catch (Exception e) {
                            return("La nouvelle version de l'application ne peut être télécharger en ce moment. \n\nVeuillez vérifier votre connection, ou réessayer plus tard. Erreur: " + dde.Message + "\n\n" + e.Message);
                        }
                    }
                    else
                    {
                        return("Vous avez choisi de ne pas télécharger la mise à jour qui est disponible en ce moment. \n\nVeuillez réeesayer plus tard, ou communiquez avec le support pour plus d'informations.");
                    }
                } catch (InvalidDeploymentException ide) {
                    //MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
                    //MessageBox.Show("Impossible de vérifier pour une nouvelle version de l'application. Le déploiement ClickOnce de l'application est corrompue. Veuillez redéployez l'application et réessayer. Erreur: " + ide.Message);
                    return("Impossible de vérifier pour une nouvelle version de l'application. Le déploiement ClickOnce de l'application est corrompue. Veuillez redéployez l'application et réessayer. Erreur: " + ide.Message);
                } catch (InvalidOperationException ioe) {
                    //MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
                    //MessageBox.Show("Cet application ne peut être mise à jour. Ce n'est vraisemblablement pas une application ClickOnce. Erreur: " + ioe.Message);
                    return("Cet application ne peut être mise à jour. Ce n'est vraisemblablement pas une application ClickOnce. Erreur: " + ioe.Message);
                }

                if (!info.UpdateAvailable)
                {
                    return("La version actuelle (" + (DateTime.Now.Year % 100).ToString() + "." + ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString() + ") est à jour.");
                }

                if (info.UpdateAvailable)
                {
                    Boolean doUpdate = true;

                    //  string test = CurrentDep.UpdatedVersion.ToString();

                    if (!info.IsUpdateRequired)
                    {
                        //DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel);
                        DialogResult dr = MessageBox.Show("La mise à jour de l'application est téléchargé et disponible. Souhaitez-vous l'exécuter maintenant?", ThisAddIn.NameOfAddin + " - Mise à jour disponible", MessageBoxButtons.OKCancel);
                        if (!(DialogResult.OK == dr))
                        {
                            doUpdate = false;
                            return("Mise à jour annulée."); //
                        }
                    }
                    else
                    {
                        // Display a message that the app MUST reboot. Display the minimum required version.
                        MessageBox.Show("This application has detected a mandatory update from your current " +
                                        "version to version " + info.MinimumRequiredVersion.ToString() +
                                        ". The application will now install the update and restart.",
                                        "Update Available", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }

                    if (doUpdate)
                    {
                        try {
                            // ad.Update(); // Enlèvement SB
                            Uri DocPath       = new Uri(Globals.ThisAddIn.Application.Path + "\\" + Globals.ThisAddIn.Application.Name);     //test sb
                            Uri InstallerPath = new Uri("C:\\Program Files\\Common Files\\microsoft shared\\VSTO\\10.0\\VSTOINSTALLER.exe"); //test sb
                                                                                                                                             // Uri RestarterPath = new Uri(CachePath + "WordRestarter.exe"); //enlève sb
                            Uri Updatelocation = new Uri(ad.UpdateLocation.ToString());

                            //Call VSTOInstaller Explicitely in "Silent Mode"
                            Process VstoInstallerProc = new System.Diagnostics.Process();
                            VstoInstallerProc.StartInfo.Arguments = " /S /I " + Updatelocation.AbsoluteUri;
                            VstoInstallerProc.StartInfo.FileName  = InstallerPath.AbsoluteUri;
                            VstoInstallerProc.Start();

                            VstoInstallerProc.WaitForExit();
                            if (VstoInstallerProc.ExitCode == 0)
                            {
                                string updatedVersDL = (DateTime.Now.Year % 100).ToString() + "." + ad.UpdatedVersion.ToString();
                                MessageBox.Show("La mise à jour de l'application à la version " + updatedVersDL + " a été réussi et sera effective au prochain redémarrage de l'application. Veuillez redémarrer l'application maintenant.", "Mise à jour - Version " + updatedVersDL);
                                return(updatedVersDL);
                            }
                            else
                            {
                                //  MessageBox.Show("Échec de mise à jour: Exit Code (" + VstoInstallerProc.ExitCode.ToString() + ")");
                                return("Échec de mise à jour: Exit Code (" + VstoInstallerProc.ExitCode.ToString() + ")");
                            }


                            //Call VSTOInstaller Explicitely in "Silent Mode"
                            // Process RestarterProc = new System.Diagnostics.Process();
                            // RestarterProc.StartInfo.Arguments = DocPath.AbsoluteUri;
                            // RestarterProc.StartInfo.FileName = RestarterPath.AbsoluteUri;
                            //  RestarterProc.Start();


                            //MessageBox.Show("The application has been upgraded, and will now restart.");
                            //MessageBox.Show("La mise à jour de l'application a été réussi et sera effective au prochain redémarrage.");

                            //Application.Restart(); MODIF SB ENLÈVEMENT !
                        } catch (DeploymentDownloadException dde) {
                            //MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
                            // MessageBox.Show("Échec d'installation de la plus récente mise à jour. \n\nVeuillez vérifier votre connection, ou réessayer plus tard. Erreur: " + dde);
                            return("Échec d'installation de la plus récente mise à jour. \n\nVeuillez vérifier votre connection, ou réessayer plus tard. Erreur: " + dde);
                        }
                    }
                }
            }
            return("");
        }
Exemplo n.º 55
0
        public bool Execute()
        {
            bool errors = false;

            if (string.IsNullOrWhiteSpace(MapBasicExe) || !File.Exists(MapBasicExe))
            {
                Console.Error.WriteLine("MapBasicExe not specified or not found. Path='{0}'", MapBasicExe);
                return(false);
            }

            var startInfo = new System.Diagnostics.ProcessStartInfo
            {
                CreateNoWindow  = true,
                UseShellExecute = false,
                FileName        = MapBasicExe,
                //WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                Arguments        = MapBasicArguments,
                WorkingDirectory = Path.GetDirectoryName(OutputFolder) ?? throw new InvalidOperationException()
            };

            if (!string.IsNullOrEmpty(ProjectFile))
            {
                // we have a project file, then only compile mbs from it, not from folder
                SourceFiles.Clear();
                // load project file and add modules to list of files to be built
                // check for existence of .mb file
                var projectIni = new IniFile(ProjectFile);
                if (!VerifyMbp(projectIni))
                {
                    return(false);
                }
                // get application=mbxname
                foreach (var val in projectIni["Link"]["Module"].Value)
                {
                    var mb = Path.Combine(OutputFolder, val);
                    mb = Path.ChangeExtension(mb, ".mb");
                    if (File.Exists(mb))
                    {
                        SourceFiles.Add(mb);
                    }
                }
            }
            foreach (var item in SourceFiles)
            {
                if (item == null)
                {
                    continue;
                }
                startInfo.Arguments += " -d " + item;
            }

            if (!string.IsNullOrWhiteSpace(ProjectFile))
            {
                startInfo.Arguments += " -l " + ProjectFile;
            }
            try
            {
                // Start the process with the info we specified.
                // Call WaitForExit and then the using statement will close.
                using (System.Diagnostics.Process exeProcess = System.Diagnostics.Process.Start(startInfo))
                {
                    exeProcess?.WaitForExit();
                }


                errors = ProcessErrors(OutputFolder);
            }
            catch (Exception)
            {
                //TODO: write an error to stderr
                errors = true;
            }
            return(!errors);
        }

        // returns true if errors
        bool ProcessErrors(string folder)
        {
            // Put all err file names in current directory.
            string[] errFiles = Directory.GetFiles(folder, @"*.err");
            bool     errors   = false;

            foreach (var errFile in errFiles)
            {
                using (StreamReader r = new StreamReader(errFile))
                {
                    string errLine;
                    while ((errLine = r.ReadLine()) != null)
                    {
                        // sample error:  (prospy.mb:72) Found: [End ] while searching for [End Program], [End MapInfo], or [End function].
                        if (!errLine.StartsWith("("))
                        {
                            errLine = $"({Path.GetFileNameWithoutExtension(errFile)}.mbp:1)" + errLine;
                        }
                        Console.Error.WriteLine(errLine);
                        errors = true;
                    }
                }
            }
            return(errors);
        }
    }
Exemplo n.º 56
0
        //one of the test methods for debugging, running against
        //sqlcmd - due to bug in S2K5, where we hang wen executing
        //this method causes hang as well
        bool ExecStmt2(string cmdText)
        {
            OutputWindow ow = _app.ToolWindows.OutputWindow;

            ow.Parent.Activate();
            try {
                owp = ow.OutputWindowPanes.Item("Debug");
            }

            catch {
                owp = ow.OutputWindowPanes.Add("Debug");
            }

            try {
                _app.StatusBar.Text = "Debug started";
                ow.Parent.Activate();
                owp.Activate();
                string buildPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
                buildPath = Path.Combine(buildPath, "MSBUILD.exe");

                owp.OutputString("Debug Started\n");
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                string sqlFile = "";

                //sqlcmd -d test2 -Q "select dbo.MyAdder99



                sqlFile = Path.Combine(ProjectPath, "sql.proj");
                //string paramString = string.Format("\"{0}\" /t:ExecDebug /p:CmdText=\"{1}\"", sqlFile, cmdText);
                //p.StartInfo = new ProcessStartInfo("cmd.exe", "/k " + buildPath + " \"" + sqlFile + "\" /t:ExecDebug /p:CmdText=\"" + cmdText + "\"");
                p.StartInfo = new ProcessStartInfo("sqlcmd.exe", "-d test2 -Q \"" + cmdText + "\"");

                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.CreateNoWindow         = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
                p.Start();

                p.BeginOutputReadLine();
                //owp.OutputString(p.StandardOutput.ReadToEnd());
                p.WaitForExit();

                owp.Activate();
                string statusMsg = "succeeded";
                if (p.ExitCode != 0)
                {
                    statusMsg = "failed";
                }

                _app.StatusBar.Text = string.Format("Debug {0}", statusMsg);
                ow.Parent.Activate();
                //ow.Parent.AutoHides = true;
                return(true);
            }

            catch (Exception e) {
                _app.StatusBar.Text = "Debug failed";

                string msg = string.Format("An unexpected exception occured.\n\nThe exception is: {0}", e.Message);
                owp.OutputString(msg);
                return(false);
            }

            finally {
            }
        }
Exemplo n.º 57
0
        /// <summary>
        /// </summary>
        /// <param name = "command">OsCommand to be executed</param>
        /// <param name = "wait">wait property</param>
        /// <param name = "show">show property</param>
        /// <param name = "errMsg">hold error message string, if command execution fails.</param>
        /// <param name = "exitCode">exit code returned by process</param>
        /// <returns>this returns errcode, if command fails to execute. </returns>
        public static int InvokeOS(String command, bool wait, CallOsShow show, ref String errMsg, ref int exitCode)
        {
            String[] commands = null;
            int      retcode  = -1;

            if (command == null)
            {
                command = "";
            }

            if (command.Length > 0)
            {
                commands = SeparateParams(command);
            }

            if (commands != null && commands.Length > 0)
            {
                try
                {
                    var processInfo = new ProcessStartInfo(commands[0], commands[1]);
#if !PocketPC
                    switch (show)
                    {
                    case CallOsShow.Hide:
                        processInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        break;

                    case CallOsShow.Normal:
                        processInfo.WindowStyle = ProcessWindowStyle.Normal;
                        break;

                    case CallOsShow.Maximize:
                        processInfo.WindowStyle = ProcessWindowStyle.Maximized;
                        break;

                    case CallOsShow.Minimize:
                        processInfo.WindowStyle = ProcessWindowStyle.Minimized;
                        break;
                    }
#endif
                    System.Diagnostics.Process process = System.Diagnostics.Process.Start(processInfo);
                    retcode = 0;

                    if (wait)
                    {
                        process.WaitForExit();
                        if (process.HasExited)
                        {
                            exitCode = process.ExitCode;
                        }
                    }
                }
                catch (Win32Exception e)
                {
                    retcode = e.NativeErrorCode; // Return the error code returned if process start fails.
                    if (e.NativeErrorCode == (int)Win32ErrorCode.ERROR_ACCESS_DENIED)
                    {
                        errMsg = "Permission Denied";
                    }
                    else if (e.NativeErrorCode == (int)Win32ErrorCode.ERROR_FILE_NOT_FOUND)
                    {
                        errMsg = "File not found: " + commands[0];
                    }
                    else
                    {
                        errMsg = e.Message;
                    }
                }
                catch (Exception)
                {
                    errMsg  = "Loading error: " + commands[0];
                    retcode = -1; // Return -1 in case of any other exception.
                }
            }

            return(retcode);
        }
Exemplo n.º 58
0
        private void ConvertSFD()
        {
            Process pProcess;
            string  strOutput;

            if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, "system")))
            {
                WriteLog("Could not locate the system folder.");
                MessageBox.Show("Unable to locate SADX system folder at: " + Path.Combine(Environment.CurrentDirectory, "system") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: system folder not found", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }
            // Convert all SA* SFDs to MPG
            if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA1.SFD")))
            {
                pProcess = new System.Diagnostics.Process();
                pProcess.StartInfo.FileName               = "sfd2mpg.exe";
                pProcess.StartInfo.Arguments              = "-c \"..\\lame --silent\" sa1.sfd sa2.sfd sa3.sfd sa4.sfd sa5.sfd sa6.sfd sa7.sfd sa8.sfd";
                pProcess.StartInfo.UseShellExecute        = false;
                pProcess.StartInfo.RedirectStandardOutput = true;
                pProcess.StartInfo.WorkingDirectory       = Path.Combine(Environment.CurrentDirectory, "system");
                pProcess.StartInfo.CreateNoWindow         = true;
                pProcess.Start();
                strOutput = pProcess.StandardOutput.ReadToEnd();
                WriteLog(strOutput);
                pProcess.WaitForExit();
                bool mpgcheck = false;
                progressBar1.Value += 40;
                // Convert SA* MPGs using FFMPEG
                for (int u = 1; u < 9; u++)
                {
                    progressBar1.Value += 20;
                    WriteLog("Converting SA" + u.ToString() + ".MPG...");
                    pProcess.StartInfo.FileName              = "ffmpeg.exe";
                    pProcess.StartInfo.Arguments             = "-y -hide_banner -loglevel error -f mpeg -r 29.97 -i sa" + u.ToString() + ".mpg -vcodec mpeg1video -s 640x480 -aspect 4/3 -acodec mp2 -b:v 3000000 SA" + u.ToString() + ".MPEG";
                    pProcess.StartInfo.UseShellExecute       = false;
                    pProcess.StartInfo.RedirectStandardError = true;
                    pProcess.StartInfo.WorkingDirectory      = Path.Combine(Environment.CurrentDirectory, "system");
                    pProcess.StartInfo.CreateNoWindow        = true;
                    pProcess.Start();
                    strOutput = pProcess.StandardError.ReadToEnd();
                    WriteLog(strOutput);
                    pProcess.WaitForExit();
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPEG")))
                    {
                        if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPG")))
                        {
                            File.Replace(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPEG"), Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPG"), Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + "_bk.MPEG"));
                        }
                        File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + "_bk.MPEG"));
                        if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".SFD")))
                        {
                            File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".SFD"));
                        }
                    }
                    else
                    {
                        WriteLog("Error converting file SA" + u.ToString() + ".MPG.");
                    }
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "tmp.mp2")))
                    {
                        File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "tmp.mp2"));
                    }
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "tmp.wav")))
                    {
                        File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "tmp.wav"));
                    }
                }
                for (int o = 1; o < 9; o++)
                {
                    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + o.ToString() + ".MPG")))
                    {
                        mpgcheck = true;
                    }
                }
                if (mpgcheck)
                {
                    MessageBox.Show("sfd2mpg failed to convert some or all SADX videos to 2004 format. Verify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }
            }
            else
            {
                WriteLog("SA* SFD files not found, skipping conversion.");
                bool mpgcheck = false;
                for (int o = 1; o < 9; o++)
                {
                    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + o.ToString() + ".MPG")))
                    {
                        mpgcheck = true;
                    }
                }
                if (mpgcheck)
                {
                    MessageBox.Show("sfd2mpg failed to convert some or all SADX videos to 2004 format. Verify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }
                else
                {
                    WriteLog("SA* MPG files already exist.");
                }
            }
            // Convert US intro using FFMPEG
            if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG")))
            {
                if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, "DLC")))
                {
                    WriteLog("Could not locate the DLC folder.");
                    MessageBox.Show("Could not locate the DLC folder at " + Path.Combine(Environment.CurrentDirectory, "DLC") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    return;
                }
                else
                {
                    pProcess = new System.Diagnostics.Process();
                    WriteLog("Converting RE-US.MPG...");
                    pProcess.StartInfo.FileName              = "ffmpeg.exe";
                    pProcess.StartInfo.Arguments             = "-y -hide_banner -loglevel error -f mpeg -r 29.97 -i re-us2.sfd -vcodec mpeg1video -aspect 4/3 -acodec mp2 -b:v 5800000 RE-US.MPG";
                    pProcess.StartInfo.UseShellExecute       = false;
                    pProcess.StartInfo.RedirectStandardError = true;
                    pProcess.StartInfo.WorkingDirectory      = Path.Combine(Environment.CurrentDirectory, "DLC");
                    pProcess.StartInfo.CreateNoWindow        = true;
                    pProcess.Start();
                    strOutput = pProcess.StandardError.ReadToEnd();
                    WriteLog(strOutput);
                    pProcess.WaitForExit();
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-US.MPG")))
                    {
                        File.Move(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-US.MPG"), Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG"));
                    }
                    else
                    {
                        WriteLog("Error converting RE-US.MPG.");
                    }
                    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG")))
                    {
                        MessageBox.Show("Intro file conversion failed: " + Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    }
                }
            }
            else
            {
                WriteLog("File RE-US.MPG already exists.");
            }
            // Convert JP intro using FFMPEG
            if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG")))
            {
                pProcess = new System.Diagnostics.Process();
                WriteLog("Converting RE-JP.MPG");
                pProcess.StartInfo.FileName              = "ffmpeg.exe";
                pProcess.StartInfo.Arguments             = "-y -hide_banner -loglevel error -f mpeg -r 29.97 -i re-jp2.sfd -vcodec mpeg1video -aspect 4/3 -acodec mp2 -b:v 5800000 RE-JP.MPG";
                pProcess.StartInfo.UseShellExecute       = false;
                pProcess.StartInfo.RedirectStandardError = true;
                pProcess.StartInfo.WorkingDirectory      = Path.Combine(Environment.CurrentDirectory, "DLC");
                pProcess.StartInfo.CreateNoWindow        = true;
                pProcess.Start();
                strOutput = pProcess.StandardError.ReadToEnd();
                WriteLog(strOutput);
                pProcess.WaitForExit();
                if (File.Exists(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-JP.MPG")))
                {
                    File.Move(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-JP.MPG"), Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG"));
                }
                else
                {
                    WriteLog("Error converting RE-JP.MPG.");
                }
                if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG")))
                {
                    MessageBox.Show("Intro file conversion failed: " + Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }
            }
            else
            {
                WriteLog("File RE-JP.MPG already exists.");
            }
        }
        public static bool ExecuteSolutionPackager(SolutionPackagerCommand command)
        {
            OutputLogger.WriteToOutputWindow($"{Resource.Message_Begin} {command.Action}: {command.SolutionName}", MessageType.Info);

            int    timeout          = 60000;
            string workingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            if (string.IsNullOrEmpty(workingDirectory))
            {
                OutputLogger.WriteToOutputWindow(Resource.ErrorMessage_CouldNotSetWorkingDirectory, MessageType.Error);
                return(false);
            }

            using (System.Diagnostics.Process process = new System.Diagnostics.Process())
            {
                var processStartInfo = CreateProcessStartInfo(command);
                process.StartInfo = processStartInfo;
                process.StartInfo.WorkingDirectory = workingDirectory;

                StringBuilder output            = new StringBuilder();
                StringBuilder errorDataReceived = new StringBuilder();

                using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                {
                    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                    {
                        process.OutputDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                outputWaitHandle.Set();
                            }
                            else
                            {
                                output.AppendLine(e.Data);
                            }
                        };
                        process.ErrorDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                errorWaitHandle.Set();
                            }
                            else
                            {
                                errorDataReceived.AppendLine(e.Data);
                            }
                        };

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

                        string message;
                        if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout))
                        {
                            if (process.ExitCode == 0)
                            {
                                OutputLogger.WriteToOutputWindow($"{Resource.Message_End} {command.Action}: {command.SolutionName}", MessageType.Info);
                                return(true);
                            }

                            message = $"{Resource.Message_ErrorExecutingSolutionPackager}: {command.Action}: {command.SolutionName}";
                        }
                        else
                        {
                            message = $"{Resource.Message_TimoutExecutingSolutionPackager}: {command.Action}: {command.SolutionName}";
                        }

                        ExceptionHandler.LogProcessError(Logger, message, errorDataReceived.ToString());
                        MessageBox.Show(message);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 60
0
        private void OnProjectContextMenuInvokeHandler(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (!(sender is MenuCommand menuCommand) || _dte2.SelectedItems.Count != 1)
            {
                return;
            }

            var selectedProject     = _dte2.SelectedItems.Item(1).Project;
            var selectedProjectItem = _dte2.SelectedItems.Item(1).ProjectItem;

            if (selectedProject == null)
            {
                selectedProject = selectedProjectItem.ContainingProject;
            }

            if (selectedProject == null)
            {
                return;
            }

            var selectedProjectName = selectedProject.Name;

            // Locate LanguageService Version
            // https://github.com/dotnet/roslyn/blob/master/docs/wiki/NuGet-packages.md

            var componentModel = (IComponentModel)GetService(typeof(SComponentModel));

            Assumes.Present(componentModel);
            var workspace = componentModel.GetService <VisualStudioWorkspace>();
            var projects  = workspace.CurrentSolution.Projects;

            // Code Refactoring In Project
            if (menuCommand.CommandID.ID == PkgCmdIDList.cmdidVstFileEncoding)
            {
                projects = projects.Where(p => p.Name.Equals(selectedProjectName));
            }
            else if (menuCommand.CommandID.ID == PkgCmdIDList.cmdidVstFileEncodingAll)
            {
            }
            else
            {
                return;
            }

            var affectedFilesCount = 0;
            var commands           = new List <string>();

            var dialogWindow = new ToolWindows.ReplaceDialog();

            dialogWindow.ShowModal();

            if (!dialogWindow.DialogResult.GetValueOrDefault())
            {
                return;
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var refactoringOptions = dialogWindow.ViewModel;

            projects = projects.Where(p => p.SupportsCompilation);

            var logContext = string.Empty;

            try
            {
                var allDocuments = projects.Select(project => project.Documents.ToList()).DimensionReduction().ToList();


                if (refactoringOptions.AdjustNamespaces)
                {
                    SynchronizeNamespaces(allDocuments, workspace.CurrentSolution);
                }


                var encoding = Encoding.GetEncoding(refactoringOptions.FileEncoding);

                // 修复文件编码
                for (var documentIndex = 0; documentIndex < allDocuments.Count; documentIndex++)
                {
                    var document = allDocuments[documentIndex];
                    logContext = document.FilePath;
                    var fileExtension  = Path.GetExtension(document.FilePath);
                    var fileExtensions = new string[] { ".cs", ".vb" };
                    if (!document.FilePath.EndsWith(".cshtml.g.cs") && fileExtensions.Contains(fileExtension) && File.Exists(document.FilePath))
                    {
                        var fileName    = Path.GetFileName(document.FilePath);
                        var text        = document.GetTextAsync().ConfigureAwait(false).GetAwaiter().GetResult().ToString();
                        var newFilePath = Path.ChangeExtension(document.FilePath, $"{fileExtension}cp");

                        File.Delete(document.FilePath);

                        if (File.Exists(document.FilePath))
                        {
                            OutputGeneralPane($"File Delete failed: {document.FilePath}");
                        }

                        using (var sw = new StreamWriter(newFilePath, false, encoding))
                        {
                            sw.AutoFlush = true;
                            sw.Write(text);
                            sw.Flush();
                        }
                        if (!File.Exists(newFilePath))
                        {
                            OutputGeneralPane($"File Generate failed: {newFilePath}");
                        }

                        commands.Add($@"rename ""{newFilePath}"" ""{fileName}"" ");
                    }
                }
            }
            catch (Exception ex)
            {
                OutputGeneralPane($"File Fixe failed with Exception: {logContext}");
                OutputGeneralPane(ex.ToString());
            }


            using (var process = new System.Diagnostics.Process())
            {
                process.StartInfo = new ProcessStartInfo()
                {
                    FileName              = "cmd.exe",
                    Arguments             = "",
                    UseShellExecute       = false,
                    CreateNoWindow        = true,
                    RedirectStandardInput = true,
                    // when RedirectStandardOutput set true, it will block RedirectStandardInput
                    RedirectStandardOutput = false,
                    RedirectStandardError  = false,
                };

                //process.StartInfo = new ProcessStartInfo()
                //{
                //    FileName = "sh",
                //    Arguments = "-c \"systemctl --version && dotnet --info\"",
                //    UseShellExecute = false,
                //    CreateNoWindow = true,
                //    RedirectStandardInput = true,
                //    // when RedirectStandardOutput set true, it will block RedirectStandardInput
                //    RedirectStandardOutput = false,
                //    RedirectStandardError = false,
                //};

                process.Start();
                process.StandardInput.AutoFlush = true;

                foreach (var commandText in commands)
                {
                    process.StandardInput.WriteLine(commandText);
                    process.StandardInput.Flush();

                    affectedFilesCount++;
                }

                process.StandardInput.WriteLine("exit");

                if (!process.WaitForExit(10000))
                {
                    process.Kill();
                }
            }

            stopwatch.Stop();

            // Show a message box to prove we were here
            VsShellUtilities.ShowMessageBox(
                this,
                $"Process Sucess.\n {affectedFilesCount} Files affected! Time:{stopwatch.ElapsedMilliseconds} ms",
                "",
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
        }