//-------------------------------------------------------------------//
        //add
        public void CopyFolder(DirectoryInfo source, DirectoryInfo target)
        {
            try
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = "cmd.exe";
                if (!(Directory.Exists(target.FullName)))
                {
                    startInfo.Arguments = "/C md " + target.FullName;
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();

                }
                string cmd = "/c xcopy ";
                startInfo.Arguments = cmd + source.FullName + " " + target.FullName + " /e /y";
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();
            }
            catch (Exception e)
            {
                string[] temp = e.ToString().Split('\'');
                string ex = temp[0] + "\n" + temp[1];
                temp = ex.Split(new string[] { ": " }, StringSplitOptions.None);
                MessageBox.Show("" + temp[1]);
            }
        }
Exemple #2
0
        protected void SaveAndConvert(Datamodel.Datamodel dm, string encoding, int version)
        {
            dm.Save(DmxSavePath, encoding, version);

            var dmxconvert = new System.Diagnostics.Process();
            dmxconvert.StartInfo = new System.Diagnostics.ProcessStartInfo()
            {
                FileName = System.IO.Path.Combine(Properties.Resources.ValveSourceBinaries, "dmxconvert.exe"),
                Arguments = String.Format("-i \"{0}\" -o \"{1}\" -oe {2}", DmxSavePath, DmxConvertPath, encoding),
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
            };

            Console.WriteLine(String.Join(" ", dmxconvert.StartInfo.FileName, dmxconvert.StartInfo.Arguments));
            Assert.IsTrue(File.Exists(dmxconvert.StartInfo.FileName), String.Format("Could not find dmxconvert at {0}", dmxconvert.StartInfo.FileName));
            
            Console.WriteLine();
            
            dmxconvert.Start();
            var err = dmxconvert.StandardOutput.ReadToEnd();
            err += dmxconvert.StandardError.ReadToEnd();
            dmxconvert.WaitForExit();

            Console.WriteLine(err);

            if (dmxconvert.ExitCode != 0)
                throw new AssertFailedException(err);

        }
Exemple #3
0
        public static void Extract(string Archive, string Output)
        {
            string cmd = null, arg = null;
            System.Diagnostics.Process P = new System.Diagnostics.Process();

            if (OS.IsWindows)
            {
                cmd = "cmd.exe";
                arg = String.Format("/c .\\unpack.exe x -y -o\"{0}\" \"{1}\"", Output, Archive);
            }
            else
            {
                cmd = "bash";
                arg = String.Format("-c \"./unpack x \\\"{1}\\\" -so | tar xf - -C \\\"{0}\\\" && echo ONE ADDONS UPDATED!\"", Output, Archive);
            }

            P.StartInfo.FileName = cmd;
            P.StartInfo.Arguments = arg;
            P.StartInfo.WorkingDirectory = Globals.AppInfo.CurrentFolder;
            P.StartInfo.UseShellExecute = false;
            P.StartInfo.CreateNoWindow = true;

            P.Start();
            P.WaitForExit();
            P.Close();
        }
Exemple #4
0
 /// <summary>
 /// 文件加解密
 /// </summary>
 /// <param name="oFileName">原文件地址</param>
 /// <param name="EncodeOrDecode">加密或解密参数,如:-d、-f</param>
 /// <param name="Password">密码</param>
 /// <returns></returns>
 public static bool FileCrypt(string oFileName, string EncodeOrDecode, string Password)
 {
     string jpfile = HttpContext.Current.Server.MapPath("~/Bin/tools/jpfile.exe");
     if ((!System.IO.File.Exists(jpfile)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(oFileName))))
     {
         return false;
     }
     oFileName = HttpContext.Current.Server.MapPath(oFileName);
     string Command = EncodeOrDecode + " \"" + oFileName + "\" \"" + Password + "\"";
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = jpfile;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/");
     p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序 启动 线程
     //p.StartInfo.RedirectStandardInput = true;
     //p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中(这个一定要注意,jpfile的所有输出信息,都为错误输出流,用 StandardOutput是捕获不到任何消息的...
     p.StartInfo.CreateNoWindow = false;//不创建进程窗口
     p.Start();//启动线程
     p.BeginErrorReadLine();//开始异步读取
     p.WaitForExit();//等待完成
     //p.StandardError.ReadToEnd();//开始同步读取
     p.Close();//关闭进程
     p.Dispose();//释放资源
     return true;
 }
Exemple #5
0
        public string RunCommand(string fileName, string arguments, string workingDirectory)
        {
            Console.WriteLine("Executing command: {0}" , fileName);
            var pProcess = new System.Diagnostics.Process
                {
                    StartInfo =
                        {
                            FileName = fileName,
                            Arguments = arguments,
                            UseShellExecute = false,
                            RedirectStandardOutput = true,
                            WorkingDirectory = workingDirectory
                        }
                };

            pProcess.Start();

            var strOutput = pProcess.StandardOutput.ReadToEnd();

            pProcess.WaitForExit();

            Console.WriteLine(strOutput);

            if (pProcess.ExitCode > 0)
            {
                Console.WriteLine("Executing command {0} failed with exit code {1}", fileName, pProcess.ExitCode);
                throw new ConsoleException(pProcess.ExitCode);
            }

            return strOutput;
        }
Exemple #6
0
 /// <summary>
 /// 使用cmd环境执行命令,同步执行一句传入命令
 /// </summary>
 /// http://www.cnblogs.com/wucg/archive/2012/03/16/2399980.html
 /// <param name="workDir"></param>
 /// <param name="cmdStr"></param>
 public static void callCmdSync(string workDir, string cmdStr)
 {
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.EnableRaisingEvents = false;
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.CreateNoWindow = false;//true
     p.StartInfo.RedirectStandardInput = true;
     p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.FileName = "cmd.exe"; //fileName;
     p.StartInfo.WorkingDirectory = workDir;//@"E:\";
     //p.StartInfo.Arguments = args;//传入bat的参数
     p.StartInfo.LoadUserProfile = false;
     p.Start();
     //输出到命令行
     p.StandardInput.WriteLine(cmdStr);
     p.StandardInput.WriteLine("exit");
     //捕获不到类似 dirxxx的错误信息
     //string ret = p.StandardOutput.ReadToEnd(); //获取返回值
     //LogOutput.logConsoleNow(ret);
     /* 按行获取返回值 */
     string line = p.StandardOutput.ReadLine();//每次读取一行
     while (!p.StandardOutput.EndOfStream) {
         if (line != string.Empty) {
             LogOutput.logConsoleNow(line + " ");
         }
         line = p.StandardOutput.ReadLine();
     }
     p.WaitForExit();
     p.Close();
     LogOutput.logConsoleNow("--cmd over--");
 }
        public void ExecuteTask(IDuplicityTask task)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo = SetupEnv(task);
            p.Start();
            p.WaitForExit();

            string errorstream = p.StandardError.ReadToEnd();
            string outstream = p.StandardOutput.ReadToEnd();

            string logentry = "";
            if (!string.IsNullOrEmpty(errorstream))
            {
                string tmp = errorstream.Replace("gpg: CAST5 encrypted data", "").Replace("gpg: encrypted with 1 passphrase", "").Trim();

                if (tmp.Length > 0)
                    logentry += "** Error stream: \r\n" + errorstream + "\r\n**\r\n";
            }
            logentry += outstream;

            task.RaiseTaskCompleted(logentry);

            if (task.TaskType == DuplicityTaskType.FullBackup || task.TaskType == DuplicityTaskType.IncrementalBackup)
            {
                if (task.Schedule.KeepFull > 0)
                    ExecuteTask(new RemoveAllButNFullTask(task.Schedule, (int)task.Schedule.KeepFull));
                if (!string.IsNullOrEmpty(task.Schedule.KeepTime))
                    ExecuteTask(new RemoveOlderThanTask(task.Schedule, task.Schedule.KeepTime));
            }
        }
        /// <summary>
        /// Convert Html page at a given URL to a PDF file using open-source tool wkhtml2pdf
        /// </summary>
        public static bool CreateFromURL(string url, string outputFilePath, bool hideBackground = false, int margin = 10)
        {
            var p = new System.Diagnostics.Process();
            p.StartInfo.FileName = HttpContext.Current.Server.MapPath(@"~\wkhtmltopdf\wkhtmltopdf.exe");

            var switches = String.Format("--print-media-type --margin-top {0}mm --margin-bottom {0}mm --margin-right {0}mm --margin-left {0}mm --page-size Letter --redirect-delay 100", margin);
            if (hideBackground) switches += "--no-background ";

            p.StartInfo.Arguments = switches + " " + url + " " + outputFilePath;

            p.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none
            p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath(@"~\wkhtmltopdf\");

            p.Start();

            // read the output here...
            string output = p.StandardOutput.ReadToEnd();

            // ...then wait n milliseconds for exit (as after exit, it can't read the output)
            p.WaitForExit(60000);

            // read the exit code, close process
            int returnCode = p.ExitCode;
            p.Close();

            // if 0 or 2, it worked (not sure about other values, I want a better way to confirm this)
            return (returnCode == 0 || returnCode == 2);
        }
Exemple #9
0
	    public void print(  FileInfo pdf, string gsPath, string printer, string trayNumber)  {
		    GHOSTSCRIPT_HOME = gsPath;

            System.Diagnostics.Debug.WriteLine("Printer=" + printer +"/Tray="+ trayNumber + "/Document=" + pdf.FullName);

            System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + GHOSTSCRIPT_HOME);
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;//.Normal;

            startInfo.FileName = GHOSTSCRIPT_HOME + Path.DirectorySeparatorChar + "pdfprint.exe";
            if (trayNumber != null && trayNumber.Length > 0)
            {///chart prep prints from here
                startInfo.Arguments = "-paper 1 -scalex -1 -scaley -1 -xoffset -150 -yoffset -100 -raster2  -chgbin " + trayNumber + " -printer \"" + printer + "\" \"" + pdf.FullName + "\"";
            }
            else
            {
                startInfo.Arguments = "-paper 1 -scalex -1 -scaley -1 -xoffset -150 -yoffset -100 -raster2  -printer  \"" + printer + "\" \"" + pdf.FullName + "\"";
            }

           // System.Diagnostics.Debug.WriteLine("Printer=" + printer + "/Tray=" + trayNumber + "/Document=" + pdf.FullName);

            System.Diagnostics.Debug.WriteLine(startInfo.Arguments);
            process.StartInfo = startInfo;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;

            process.Start();
            // Console.ReadKey();
            string processOutput = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            System.Diagnostics.Debug.WriteLine(processOutput);
            System.Diagnostics.Debug.WriteLine("-paper 1 -scalex -1 -scaley -1 -xoffset -150 -yoffset -100 -raster2 -chgbin " + trayNumber + " -printer \"" + printer + "\" \"" + pdf.FullName + "\"");
            // Console.ReadKey();
	    }
 public void extract()
 {
     //创建解压用的临时文件夹
     var lExtractFolderDir = extractFolderPath;
     if (Directory.Exists(lExtractFolderDir))
     {
         Directory.Delete(lExtractFolderDir, true);
     }
     Directory.CreateDirectory(lExtractFolderDir);
     var lExtractorArguments = string.Format("x \"{0}\" -o\"{1}\" -y",
                 setupFilePath, lExtractFolderDir);
     Console.WriteLine(lExtractorArguments);
     var lExtractorProcess = new System.Diagnostics.Process()
     {
         StartInfo = new System.Diagnostics.ProcessStartInfo()
         {
             FileName = _7zPath,
             UseShellExecute = false,
             Arguments = lExtractorArguments,
             //WorkingDirectory = appl
             //RedirectStandardError = true,
         },
     };
     lExtractorProcess.Start();
     lExtractorProcess.WaitForExit();
 }
        public override bool Execute(){
            System.Diagnostics.Process proc = new System.Diagnostics.Process();


            if (ExtraArgs == null)
            {
                ExtraArgs = "";
            }
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(PathToRobocopy, String.Format("{0} {1} /MIR /r:10 /w:3 /NP {2}", SourceFolder, DestinationFolder, ExtraArgs));
            //startInfo.RedirectStandardError = true;
            //startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            proc.StartInfo = startInfo;
            proc.Start();
            proc.WaitForExit();
            
            if (proc.ExitCode >= 8)
            {
                this.Log.LogError(GetMessage(proc.ExitCode));
                return false;
            }
            else
            {
                   this.Log.LogMessage(GetMessage(proc.ExitCode));
                return true;
            }
           

     
        }
 /// <summary>
 /// 视频格式转为Flv
 /// </summary>
 /// <param name="vFileName">原视频文件地址</param>
 /// <param name="ExportName">生成后的Flv文件地址</param>
 public bool ConvertFlv(string vFileName, string ExportName)
 {
     if ((!System.IO.File.Exists(ffmpegtool)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(vFileName))))
     {
         return false;
     }
     vFileName = HttpContext.Current.Server.MapPath(vFileName);
     ExportName = HttpContext.Current.Server.MapPath(ExportName);
     string Command = " -i \"" + vFileName + "\" -y -ab 32 -ar 22050 -b 800000 -s  480*360 \"" + ExportName + "\""; //Flv格式     
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = ffmpegtool;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/tools/");
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardInput = true;
     p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.RedirectStandardError = true;
     p.StartInfo.CreateNoWindow = false;
     p.Start();
     p.BeginErrorReadLine();
     p.WaitForExit();
     p.Close();
     p.Dispose();
     return true;
 }
Exemple #13
0
        public bool Execute(string command)
        {
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            bool isLinux   = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
            bool isMacOSX  = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.OSX);

            try
            {
                System.Diagnostics.Process p = null;

                if (isLinux || isMacOSX)
                {
                    //System.Diagnostics.Process.Start("/bin/bash", "-c \"echo '12345d' >> /Users/andrew/Projects/test/2.txt\"");
                    p = System.Diagnostics.Process.Start($"/bin/bash", $"-c \"{command}\"");
                }

                if (isWindows)
                {
                    p = System.Diagnostics.Process.Start($"cmd.exe", $"/c \"{command}\"");
                }

                p?.WaitForExit();

                return(true);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error on restart command executing");
                return(false);
            }
        }
Exemple #14
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pSource">要压缩的文件夹</param>
        /// <param name="pDestination">压缩后的rar完整名</param>
        public void CreateRar(string pSource, string pDestination)
        {
            try
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = "Winrar.exe";
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.Arguments = " a -r -ep1 " + pDestination + " " + pSource;
                proc.Start();
                proc.WaitForExit();
                if (proc.HasExited)
                {
                    int iExitCode = proc.ExitCode;
                    if (iExitCode == 0)
                    {//压缩成功}
                    }
                    else
                    {
                    }
                }
                proc.Close();
            }
            catch (Exception ex)
            {

            }
        }
        public String convert(string pdfdoc)
        {
            String command = "";
            try
            {
                String output = "";

                command = configManager.getConfig("cmd.conversion.splitpdffile");
                command = command.Replace("{path.pdf}", configManager.getConfig("path.pdf"));
                command = command.Replace("{path.swf}", configManager.getConfig("path.swf"));
                command = command.Replace("{pdffile}", pdfdoc);

                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = command.Substring(0, command.IndexOf(".exe") + 5);
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                proc.StartInfo.CreateNoWindow = true;
                //proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.Arguments = command.Substring(command.IndexOf(".exe") + 5);

                if (proc.Start())
                {
                    proc.WaitForExit();
                    proc.Close();
                    return "[OK]";
                }
                else
                    return "[Error converting splitting PDF, please check your configuration]";
            }
            catch (Exception ex)
            {
                return "[" + ex.Message + "]";
            }
        }
Exemple #16
0
        /// <summary>
        /// 読み取り開始
        /// </summary>
        public void Read()
        {
            Console.WriteLine("FelicaReader::Read() - start");
            //  プロセスオブジェクトを生成
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            //  実行ファイルを指定
            p.StartInfo.FileName = this.tagtool;
            //  シェルコマンドを無効に
            p.StartInfo.UseShellExecute = false;
            //  入力をリダイレクト
            p.StartInfo.RedirectStandardInput = true;
            //  出力をリダイレクト
            p.StartInfo.RedirectStandardOutput = true;
            //  OutputDataReceivedイベントハンドラを追加
            p.OutputDataReceived += OutputDataReceivedHandler;
            //  プロセスを実行
            p.Start();
            //  非同期で出力の読み取りを開始
            p.BeginOutputReadLine();
            //  入力を行う為のストリームライターとプロセスの標準入力をリンク
            System.IO.StreamWriter myStreamWriter = p.StandardInput;

            myStreamWriter.Close();
            p.WaitForExit();
            p.Close();
            Console.WriteLine("FelicaReader::Read() - end");
        }
Exemple #17
0
        public static void ApplyPatch(FpuSegment seg)
        {
            Process p=new Process();
            p.StartInfo.FileName="nasm.exe";
            p.StartInfo.Arguments="out.txt";
            p.StartInfo.UseShellExecute=false;
            p.StartInfo.CreateNoWindow=true;
            p.Start();
            p.WaitForExit();
            p.Close();
            FileInfo fi=new FileInfo("out");
            if(fi.Length==0) throw new OptimizationException("Patcher: Code generator produced uncompilable code");
            ArrayList code=new ArrayList();
            for(int i=0;i<seg.Pre.Length;i++) {
                code.AddRange(HexToString(seg.Pre[i].code));
            }
            code.AddRange(Program.ReadFileBytes("out"));
            for(int i=0;i<seg.Post.Length;i++) {
                code.AddRange(HexToString(seg.Post[i].code));
            }
            if(code.Count>seg.End-seg.Start) throw new OptimizationException("Patcher: Patch to big to fit into code");

            /*if(Program.TestPatches) {
                TestPatch(seg); //TESTPATCH CALL
            }*/
            if(Program.Benchmark) {
                Benchmark(seg); //BENCHMARK CALL!!!!!!!!!!!!!!!!!!!!!!!! <---------------- OVER HERE
            }
            byte[] Code=new byte[seg.End-seg.Start];
            code.CopyTo(Code);
            for(int i=code.Count;i<(seg.End-seg.Start);i++) {
                Code[i]=144;    //Fill the rest of the code up with nop's
            }
            long a=(seg.End-seg.Start)-code.Count;
            if(a>255) {
                throw new OptimizationException("Patcher: Patch end address out of range of a short jump");
            } else if(a>2) {
                Code[code.Count]=235;
                Code[code.Count+1]=(byte)(a-2);
            }
            if(Program.Restrict) {
                if(PatchCount<Program.FirstPatch||PatchCount>Program.LastPatch) {
                    PatchCount++;
                    throw new OptimizationException("Patcher: Patch restricted");
                }
                PatchCount++;
            }
            #if emitpatch
            FileStream fs2=File.Create("emittedpatch.patch",4096);
            BinaryWriter bw=new BinaryWriter(fs2);
            bw.Write(seg.Start);
            bw.Write(Code.Length);
            bw.Write(Code,0,Code.Length);
            bw.Close();
            #endif
            FileStream fs=File.Open("code",FileMode.Open);
            fs.Position=seg.Start;
            fs.Write(Code,0,Code.Length);
            fs.Close();
        }
    private void setupPortForwarding(int port) {
      string adbCommand = string.Format("adb forward tcp:{0} tcp:{0}", port);
      System.Diagnostics.Process myProcess;

#if UNITY_EDITOR_WIN
      string cmd = @"/k " + adbCommand + " & exit";
      Debug.Log ("Executing: [" + cmd + "]");
      myProcess = new System.Diagnostics.Process();
      System.Diagnostics.ProcessStartInfo myProcessStartInfo =
        new System.Diagnostics.ProcessStartInfo("CMD.exe", cmd);
      myProcessStartInfo.UseShellExecute = false;
      myProcessStartInfo.RedirectStandardOutput = true;
      myProcessStartInfo.CreateNoWindow = true;
      myProcess.StartInfo = myProcessStartInfo;
      myProcess.Start();
#else
      Debug.LogFormat("Trying to launch adb: {0}", adbCommand);
      myProcess = System.Diagnostics.Process.Start("bash", string.Format("-l -c \"{0}\"",
                                                                         adbCommand));
#endif
      myProcess.WaitForExit();
      int exitCode = myProcess.ExitCode;
      myProcess.Close();
      if (exitCode == 0) {
        Debug.LogFormat("adb process succeeded (exit code 0).");
      } else {
        Debug.LogErrorFormat("adb process FAILED (exit code {0}). Check that the Android SDK " +
            "is installed and that the adb command is in your PATH environment variable.",
            exitCode);
      }
    }
Exemple #19
0
        public override IEnumerable<string> Execute(IrcEventArgs e)
        {
            string args = "";

            if (e.Data.MessageArray.Length > 1)
                args = string.Join(" ", e.Data.MessageArray.Skip(1));

            args = args.Replace("\'", "");
            args = args.Replace(">", "");
            args = args.Replace("<", "");
            args = args.Replace("|", "");

            try
            {
                var proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents = false;
                proc.StartInfo.FileName = @"python";
                proc.StartInfo.Arguments = scriptPath + " \"" + args + "\"";
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                proc.Start();
                string data = proc.StandardOutput.ReadToEnd();
                proc.WaitForExit();

                return new[] {data};
            }
            catch
            {

            }

            return null;
        }
        static void Main(string[] args)
        {
            //Create a new proccess
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            //Path to the executable to run
            proc.StartInfo.FileName = "PstPassword.exe";
            //Command line arguments, paths to output file and .pst
            proc.StartInfo.Arguments = "/stext \"passwords.txt\" /pstfiles \"putyourfilenamehere.pst\"";
            proc.Start();
            proc.WaitForExit();

            System.IO.StreamReader reader = new System.IO.StreamReader("passwords.txt");
            string pw1, pw2, pw3;
            //buffer to dump unwanted character in for reading purposes.
            char[] c = new char[20];

            //Read past the first 6 lines
            reader.ReadLine();reader.ReadLine();reader.ReadLine();reader.ReadLine();reader.ReadLine();

            //read past Password 1      :
            reader.Read(c, 0, 20);
            //read in password
            pw1 = reader.ReadLine();
            //read past Password 2      :
            reader.Read(c, 0, 20);
            //read in password
            pw2 = reader.ReadLine();
            //read past Password 3      :
            reader.Read(c, 0, 20);
            //read in password
            pw3 = reader.ReadLine();

            Console.WriteLine(pw1 + ", " + pw2 + ", " + pw3);
        }
Exemple #21
0
        public static void Work(object obj)
        {
            string command = (string)obj;
            using (System.Diagnostics.Process process = new System.Diagnostics.Process())
            {
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.Arguments = "/c " + command;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardInput = false;

                //开始进程  
                if (process.Start())
                {
                    //这里无限等待进程结束
                    process.WaitForExit();
                    //读取进程的输出
                    string output = process.StandardOutput.ReadToEnd();

                    ServerPacket serverPacket = new ServerPacket(PacketType.Telnet);
                    serverPacket.telnet = new ServerPacket.Telnet(output);
                    Server.packetStream.Send(serverPacket);
                }

            }
        }
Exemple #22
0
        public void Start()
        {
            try
            {
                string startGlassfishPath = Environment.GetEnvironmentVariable("GLASSFISH_HOME");
                startGlassfishPath += @"\bin\stopglassfish.bat";
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = new System.Diagnostics.ProcessStartInfo();
                proc.StartInfo.FileName = startGlassfishPath;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                while (!proc.WaitForExit(30))
                {
                    Console.WriteLine("Waiting");
                }
                System.Threading.Thread.Sleep(1000);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry! Error occured during starting glassfish starting.");
            }
            finally
            {
                this.Close();
                this.Dispose(true);
            }
        }
        private static string GetCMDResult(string strCommand, string strCommandParameters)
        {
            //Create process
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

            //strCommand is path and file name of command to run
            pProcess.StartInfo.FileName = strCommand;

            //strCommandParameters are parameters to pass to program
            pProcess.StartInfo.Arguments = strCommandParameters;

            pProcess.StartInfo.UseShellExecute = false;

            //Set output of program to be written to process output stream
            pProcess.StartInfo.RedirectStandardOutput = true;

            //Optional
            //pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;

            //Start the process
            pProcess.Start();

            //Get program output
            string strOutput = pProcess.StandardOutput.ReadToEnd();

            //Wait for process to finish
            pProcess.WaitForExit();

            return strOutput;
        }
Exemple #24
0
 /// <summary>
 /// PDF格式转为SWF
 /// </summary>
 /// <param name="pdfPath">PDF文件地址</param>
 /// <param name="swfPath">生成后的SWF文件地址</param>
 /// <param name="beginpage">转换开始页</param>
 /// <param name="endpage">转换结束页</param>
 private static bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
 {
     string exe = HttpContext.Current.Server.MapPath("~/Bin/tools/pdf2swf-0.9.1.exe");
     pdfPath = HttpContext.Current.Server.MapPath(pdfPath);
     swfPath = HttpContext.Current.Server.MapPath(swfPath);
     if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath) || System.IO.File.Exists(swfPath))
     {
         return false;
     }
     StringBuilder sb = new StringBuilder();
     sb.Append(" \"" + pdfPath + "\"");
     sb.Append(" -o \"" + swfPath + "\"");
     sb.Append(" -s flashversion=9");
     if (endpage > GetPageCount(pdfPath)) endpage = GetPageCount(pdfPath);
     sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");
     sb.Append(" -j " + photoQuality);
     string Command = sb.ToString();
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = exe;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/");
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardError = true;
     p.StartInfo.CreateNoWindow = false;
     p.Start();
     p.BeginErrorReadLine();
     p.WaitForExit();
     p.Close();
     p.Dispose();
     return true;
 }
Exemple #25
0
        private static string ExecuteCommand(string fileName, string arguments)
        {
            try
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();

                process.StartInfo = new System.Diagnostics.ProcessStartInfo()
                {
                    FileName = fileName,
                    Arguments = arguments,
                    WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardError = true
                };

                process.Start();

                string error = process.StandardError.ReadToEnd();
                process.WaitForExit();

                return error;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
        public static void runningBalkCopy(string dbName, string path, BCPDirection direction, string option, string remoteDb)
        {
            //ディレクション
            string strDirection = "in";
            if (direction == BCPDirection.BCP_OUT)
            {
                strDirection = "out";
            }
            else
            {
                strDirection = "in";
            }

            //リモートDB
            string strRemoteDb = "";
            if (remoteDb != "")
            {
                strRemoteDb = " -S " + remoteDb;
            }

            using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
            {
                proc.StartInfo.FileName = "bcp";
                proc.StartInfo.Arguments = dbName + " " + strDirection + " \"" + path + "\" " + option + strRemoteDb;
                proc.Start();
                proc.WaitForExit();
            }
        }
        //CheckEpubを実施、Output/Errorを表示する
        public void CheckEpub()
        {
            //EPUBチェック実施中パネルを表示する
            var checkingDlg = new EpubCheckingDialog();
            checkingDlg.Show();

            var p = new System.Diagnostics.Process();

            //実行ファイル
            p.StartInfo.FileName = javaPath;

            //引数
            var args = "-jar "
                        + "\""+ epubCheckPath + "\" "
                        +" \"" + epubPath + "\"";
            p.StartInfo.Arguments = args;

            //出力とエラーをストリームに書き込むようにする
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;

            //OutputDataReceivedとErrorDataReceivedイベントハンドラを追加
            p.OutputDataReceived += OutputDataReceived;
            p.ErrorDataReceived += ErrorDataReceived;

            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.CreateNoWindow = true;

            p.Start();

            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            p.WaitForExit();
            p.Close();

            var resultDlg = new EpubCheckResultDialog();

            //Outputをコピーする
            foreach (var output in outputLines)
            {
                resultDlg.outputTextBox.Text += (output + "\n");
            }

            //Errorをコピーする
            if (errorLines.Count> 1)
            {
                foreach (var error in errorLines)
                {
                    resultDlg.errorTextBox.Text += (error + "\n");
                }
            }
            else
            {
                resultDlg.errorTextBox.Text = "エラーはありませんでした。";
            }
            checkingDlg.Close();
            resultDlg.ShowDialog();
        }
Exemple #28
0
        public static string GetDevice(string path)
        {
            string result = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = path + "\\adb.exe";
            //要执行的程序名称
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            //可能接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;
            //由调用程序获取输出信息
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.Arguments = "devices";
            //不显示程序窗口
            p.Start();

            result += p.StandardOutput.ReadToEnd();
            //p.BeginOutputReadLine();
            p.WaitForExit();
            while (p.ExitCode != 0)
            {
                result += p.StandardOutput.ReadToEnd();
                Thread.Sleep(200);
            }
            p.Close();
            return result;
        }
Exemple #29
0
        private static void applyWallpapers()
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";

            foreach (string computer in computers)
            {
                if (computer.ToUpper().Equals((System.Environment.MachineName).ToUpper()))
                {
                    // run locally
                    System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\rundll.bat");
                }
                else
                {
                    // Refresh Current User registry
                    // owexec.exe -nowait -k rundll.bat -copy -c Test
                    startInfo.Arguments = @"/c C:\Windows\System32\owexec.exe -nowait -k rundll.bat -c " + computer + @"""";
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();
                }
            }
            System.Threading.Thread.Sleep(5000);
        }
Exemple #30
0
        void p_Exited(object sender, EventArgs e)
        {
            if (_closed)
            {
                return;
            }

            _executing?.WaitForExit();

            string str = "[ 完了しました ]";

            if (((System.Diagnostics.Process)sender).ExitCode != 0)
            {
                str = "[ うまくいかなったようです ]";
            }
            if (textBoxLogs.InvokeRequired)
            {
                this.Invoke((MethodInvoker)(() => textBoxLogs.AppendText("\r\n" + str + "\r\n")));
                this.Invoke((MethodInvoker)(() => _executing = null));
            }
            else
            {
                textBoxLogs.AppendText("\r\n" + str + "\r\n");
                _executing.Exited -= p_Exited;
                _executing         = null;
            }
        }
Exemple #31
0
        public static void SaveScreenShot(string path, string filename,string savepath)
        {
            //string result = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = path + "\\adb.exe";
            //要执行的程序名称
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            //可能接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;
            //由调用程序获取输出信息
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.Arguments = "pull /sdcard/"+filename+" " + savepath + "\\" + filename;
            //不显示程序窗口
            p.Start();

            //result += p.StandardOutput.ReadToEnd();
            //p.BeginOutputReadLine();
            p.WaitForExit();
            while (p.ExitCode != 0)
            {
                //result += p.StandardOutput.ReadToEnd();
                //Thread.Sleep(200);
            }
            Thread.Sleep(500);
            p.Close();
            return;
        }
        public static MsgBoxResult MsgBox(string text, string caption = null, MsgBoxStyle options = MsgBoxStyle.OkOnly)
        {
            if (string.IsNullOrEmpty(caption))
            {
                caption = GetTitleFromAssembly(System.Reflection.Assembly.GetCallingAssembly());
            }

            if (System.Environment.OSVersion.Platform != System.PlatformID.Unix)
            {
                return(UnsafeNativeMethods.MessageBox(System.IntPtr.Zero, text, caption, options));
            }

            text    = text.Replace("\"", @"\""");
            caption = caption.Replace("\"", @"\""");

            using System.Diagnostics.Process p = System.Diagnostics.Process.Start("notify-send", "\"" + caption + "\" \"" + text + "\"");
            p?.WaitForExit();

            return(MsgBoxResult.Ok);
        }
Exemple #33
0
        public static PhantomOutput <ResultT> Run <ResultT>(string url, string bridgeScriptFileName = null, bool throwExOnError = true)
        {
            // Get the location of the phantom exe
            string phantomExecutable =
                Application.platform == RuntimePlatform.OSXEditor ? "phantomjs" :
                Application.platform == RuntimePlatform.WindowsEditor ? "phantomjs.exe" :
                null;

            if (phantomExecutable == null)
            {
                throw new NotSupportedException("Editor platform not supported.");
            }

            string binPath = EditorFileUtil.FindFile(phantomExecutable);

            // Get the location of the phantom script
            const string phantomJs = "phantom.js_";
            string       jsPath    = EditorFileUtil.FindFile(phantomJs, true);

            // Get the location of the bridge script
            string bridgePath = bridgeScriptFileName != null?EditorFileUtil.FindFile(bridgeScriptFileName) : null;

            // Run the HTML in PhantomJS
            var phantomJS = new System.Diagnostics.Process();

            phantomJS.StartInfo.UseShellExecute        = false;
            phantomJS.StartInfo.CreateNoWindow         = true;
            phantomJS.StartInfo.RedirectStandardOutput = true;
            phantomJS.StartInfo.WorkingDirectory       = jsPath;
            phantomJS.StartInfo.FileName  = binPath;
            phantomJS.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\"{2}",
                                                          phantomJs,
                                                          url,
                                                          bridgePath == null ? null : string.Format(" \"{0}\"", bridgePath)
                                                          );

            // On Mac, the phantomjs binary requires execute permissions (755), this should be set by Install.cs in the Phantom directory
            phantomJS.Start();

            string outputJson = phantomJS.StandardOutput.ReadToEnd();

            phantomJS.WaitForExit();

            //PhantomOutput<ResultT> output = JsonUtility.FromJson<PhantomOutput<ResultT>>(outputJson);
            var output = (PhantomOutput <ResultT>)FullSerializerWrapper.Deserialize(typeof(PhantomOutput <ResultT>), outputJson);

            bool hasErrors = false;

            foreach (PhantomConsoleMessage msg in output.console)
            {
                if (msg.type != "error")
                {
                    continue;
                }

                hasErrors = true;
                Debug.LogErrorFormat("{0}\n\n{1}\n\n", msg.value, msg.trace);
            }
            if (hasErrors && throwExOnError)
            {
                throw new StoryImportException("HTML errors detected");
            }

            return(output);
        }
        private void sendBtn_Click(object sender, EventArgs e)
        {
            try
            {
                var fromAddress  = new MailAddress("*****@*****.**");
                var fromPassword = "******";
                var toAddress    = new MailAddress("*****@*****.**");

                string subject = "Bug Reporter";
                string body    = msgTxtBox.Text;

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient
                {
                    Host                  = "smtp.gmail.com",
                    Port                  = 587,
                    EnableSsl             = true,
                    DeliveryMethod        = System.Net.Mail.SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
                };

                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })

                    smtp.Send(message);

                notifyIconMailSuccessful.Icon           = SystemIcons.Application;
                notifyIconMailSuccessful.BalloonTipText = "Email sent successfully!";
                notifyIconMailSuccessful.ShowBalloonTip(200);

                //msgTxtBox.Text = "";

                //string result = sendSms("message");

                //if (result != null)
                //    msgTxtBox.Text = result;

                //notifyIconMailSuccessful.Icon = SystemIcons.Application;
                //notifyIconMailSuccessful.BalloonTipText = "SMS sent successfully!";
                //notifyIconMailSuccessful.ShowBalloonTip(200);

                if (checkBoxTV.Checked)
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();

                    process.StartInfo.FileName  = "C:\\Program Files (x86)\\TeamViewer\\TeamViewer.exe";
                    process.EnableRaisingEvents = true;

                    process.Start();

                    process.WaitForExit();

                    msgTxtBox.Text = "TeamViewer Exited";
                }

                UserControlTest userControl1 = new UserControlTest();
            }
            catch (Exception exc)
            {
                MessageBox.Show("Something went wrong!\n" + exc, "Mail sender", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #35
0
        private void SelfExtractor_Update(SelfExtractorFlavor flavor)
        {
            string SfxFileToCreate = Path.Combine(TopLevelDir,
                                                  String.Format("SelfExtractor_Update{0}.exe",
                                                                flavor.ToString()));
            string UnpackDirectory = Path.Combine(TopLevelDir, "unpack");

            if (Directory.Exists(UnpackDirectory))
            {
                Directory.Delete(UnpackDirectory, true);
            }

            string ReadmeString = "Hey there!  This zipfile entry was created directly from a string in application code.";

            // create a file and compute the checksum
            string Subdir = Path.Combine(TopLevelDir, "files");

            Directory.CreateDirectory(Subdir);
            var checksums = new Dictionary <string, string>();

            string filename = Path.Combine(Subdir, "file1.txt");

            TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
            var chk = TestUtilities.ComputeChecksum(filename);

            checksums.Add(filename.Replace(TopLevelDir + "\\", "").Replace('\\', '/'), TestUtilities.CheckSumToString(chk));

            // create the SFX
            using (ZipFile zip1 = new ZipFile())
            {
                zip1.AddFile(filename, Path.GetFileName(Subdir));
                zip1.Comment = "This will be embedded into a self-extracting exe";
                MemoryStream ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(ReadmeString));
                zip1.AddEntry("Readme.txt", ms1);
                SelfExtractorSaveOptions sfxOptions = new SelfExtractorSaveOptions();
                sfxOptions.Flavor = flavor;
                sfxOptions.Quiet  = true;
                sfxOptions.DefaultExtractDirectory = UnpackDirectory;
                zip1.SaveSelfExtractor(SfxFileToCreate, sfxOptions);
            }

            // verify count
            Assert.AreEqual <int>(TestUtilities.CountEntries(SfxFileToCreate), 2, "The Zip file has the wrong number of entries.");

            // create another file
            filename = Path.Combine(Subdir, "file2.txt");
            TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
            chk = TestUtilities.ComputeChecksum(filename);
            checksums.Add(filename.Replace(TopLevelDir + "\\", "").Replace('\\', '/'), TestUtilities.CheckSumToString(chk));
            string password = "******";

            // update the SFX
            using (ZipFile zip1 = ZipFile.Read(SfxFileToCreate))
            {
                zip1.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                zip1.Encryption       = EncryptionAlgorithm.WinZipAes256;
                zip1.Comment          = "The password is: " + password;
                zip1.Password         = password;
                zip1.AddFile(filename, Path.GetFileName(Subdir));
                SelfExtractorSaveOptions sfxOptions = new SelfExtractorSaveOptions();
                sfxOptions.Flavor = flavor;
                sfxOptions.Quiet  = true;
                sfxOptions.DefaultExtractDirectory = UnpackDirectory;
                zip1.SaveSelfExtractor(SfxFileToCreate, sfxOptions);
            }

            // verify count
            Assert.AreEqual <int>(TestUtilities.CountEntries(SfxFileToCreate), 3, "The Zip file has the wrong number of entries.");


            // read the SFX
            TestContext.WriteLine("---------------Reading {0}...", SfxFileToCreate);
            using (ZipFile zip2 = ZipFile.Read(SfxFileToCreate))
            {
                zip2.Password = password;
                //string extractDir = String.Format("extract{0}", j);
                foreach (var e in zip2)
                {
                    TestContext.WriteLine(" Entry: {0}  c({1})  u({2})", e.FileName, e.CompressedSize, e.UncompressedSize);
                    e.Extract(UnpackDirectory);
                    if (!e.IsDirectory)
                    {
                        if (checksums.ContainsKey(e.FileName))
                        {
                            filename = Path.Combine(UnpackDirectory, e.FileName);
                            string actualCheckString = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(filename));
                            Assert.AreEqual <string>(checksums[e.FileName], actualCheckString, "Checksums for ({1}) do not match.", e.FileName);
                            //TestContext.WriteLine("     Checksums match ({0}).\n", actualCheckString);
                        }
                        else
                        {
                            Assert.AreEqual <string>("Readme.txt", e.FileName);
                        }
                    }
                }
            }

            int N = (flavor == SelfExtractorFlavor.ConsoleApplication) ? 2 : 1;

            for (int j = 0; j < N; j++)
            {
                // run the SFX
                TestContext.WriteLine("Running the SFX... ");
                var psi = new System.Diagnostics.ProcessStartInfo(SfxFileToCreate);
                if (flavor == SelfExtractorFlavor.ConsoleApplication)
                {
                    if (j == 0)
                    {
                        psi.Arguments = "-o -p " + password; // overwrite
                    }
                    else
                    {
                        psi.Arguments = "-p " + password;
                    }
                }
                psi.WorkingDirectory = TopLevelDir;
                psi.UseShellExecute  = false;
                psi.CreateNoWindow   = true;
                System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
                process.WaitForExit();
                int rc = process.ExitCode;
                TestContext.WriteLine("SFX exit code: ({0})", rc);

                if (j == 0)
                {
                    Assert.AreEqual <Int32>(0, rc, "The exit code from the SFX was nonzero ({0}).", rc);
                }
                else
                {
                    Assert.AreNotEqual <Int32>(0, rc, "The exit code from the SFX was zero ({0}).");
                }
            }

            // verify the unpacked files?
        }
        public override void Execute(UMake umake, UMakeTarget target)
        {
            try
            {
                string buildPath        = UMake.GetBuildPath();
                string steamBuildScript = buildScript;
                string sdkPath          = steamSdkPath.Value;
                string username         = steamUsername.Value;
                string password         = steamPassword.Value;
                bool   skipCopy         = skipSteamContentCopy;

                if (UMakeCli.IsInCli)
                {
                    UMakeCli.Args.TryGetValue("path", out buildPath);
                    UMakeCli.Args.TryGetValue("script", out steamBuildScript);
                    UMakeCli.Args.TryGetValue("steam-sdk", out sdkPath);
                    UMakeCli.Args.TryGetValue("steam-username", out username);
                    UMakeCli.Args.TryGetValue("steam-password", out password);

                    string skipCopyStringValue;
                    UMakeCli.Args.TryGetValue("skip-steam-content-copy", out skipCopyStringValue);
                    bool.TryParse(skipCopyStringValue, out skipCopy);
                }

                if (!Directory.Exists(sdkPath))
                {
                    Debug.LogFormat("SteamSDK \"{0}\" not found.", sdkPath);
                    return;
                }

                string steamCmdPath = Path.Combine(sdkPath, "tools/ContentBuilder/builder/steamcmd.exe");;
                if (!File.Exists(steamCmdPath))
                {
                    Debug.LogFormat("SteamCMD \"{0}\" not found.", steamCmdPath);
                    return;
                }

                if (!skipCopy && !CopyContent(sdkPath, target, umake.version, buildPath))
                {
                    Debug.Log("Could not copy content to Steam folder.");
                    return;
                }

                var uploaderProcess = new System.Diagnostics.Process();
                uploaderProcess.StartInfo.FileName         = steamCmdPath;
                uploaderProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(Path.GetDirectoryName(steamCmdPath));
                uploaderProcess.StartInfo.Arguments        = string.Format(steamCmdArgFormat, username, password, steamBuildScript);

                if (UMakeCli.IsInCli)
                {
                    uploaderProcess.StartInfo.UseShellExecute        = false;
                    uploaderProcess.StartInfo.RedirectStandardOutput = true;
                    uploaderProcess.OutputDataReceived += (sender, msg) =>
                    {
                        if (msg != null)
                        {
                            Debug.Log(msg.Data);
                        }
                    };
                }

                uploaderProcess.Start();
                Debug.LogFormat("Executing SteamCMD \"{0}\"...", steamCmdPath);

                if (UMakeCli.IsInCli)
                {
                    uploaderProcess.BeginOutputReadLine();
                    uploaderProcess.WaitForExit();
                }

                uploaderProcess.Close();
            }
            catch (System.Exception e)
            {
                Debug.Log("Upload to Steam failed.");
                Debug.LogException(e);
            }
        }
Exemple #37
0
        private void button2_Click(object sender, EventArgs e)
        {
            MD5 mD5 = new MD5CryptoServiceProvider();

            byte[] fromData    = System.Text.Encoding.UTF8.GetBytes(textBox2.Text);
            byte[] targetData  = mD5.ComputeHash(fromData);
            string byte25tring = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte25tring += targetData[i].ToString("x2");
            }


            // var request = (HttpWebRequest)WebRequest.Create("http://110.80.137.159:81/reg.php?u=" + textBox1.Text.Trim() + "&p=" + byte25tring);

            var request = (HttpWebRequest)WebRequest.Create("http://110.80.137.159:81/login.php?u=" + textBox1.Text.Trim() + "&p=" + byte25tring);



            var response       = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            // MessageBox.Show(byte25tring);
            //  MessageBox.Show(responseString);


            if (responseString.Length <= 3)
            {
                MessageBox.Show("登陆失败,账号或密码错误");
                return;
            }
            // MessageBox.Show("可以登陆游戏了");


            string[] data = System.Text.RegularExpressions.Regex.Split(responseString, @"[|]");

            // MessageBox.Show(responseString);
            //  MessageBox.Show(data[0]);

            if (File.Exists("update_cfg.xml"))
            {
                File.Delete("update_cfg.xml");
            }

            string srcFileName  = @"xys.dll";
            string destFileName = @"update_cfg.xml";

            if (File.Exists(srcFileName))
            {
                File.Move(srcFileName, destFileName);
            }



            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName       = "patcher.exe"; //需要启动的程序名
                                                        //a启动参数

            // p.StartInfo.Arguments = " -u " + responseString + " -p 1111 -z 1"; //启动参数
            p.StartInfo.Arguments = " -u " + data[0] + " -p 1111 -z 1"; //启动参数

            p.Start();                                                  //启动

            p.WaitForExit();

            File.Move(destFileName, srcFileName);



            System.Environment.Exit(0);


            return;
        }
Exemple #38
0
        public IEnumerable <ProcessorItem> Process(IProcessorPipeline pipeline, IEnumerable <ProcessorItem> items)
        {
            System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo()
            {
                CreateNoWindow         = noWindow,
                ErrorDialog            = false,
                UseShellExecute        = !noWindow,
                RedirectStandardOutput = noWindow,
                RedirectStandardError  = noWindow
            };

            if (pipeline.Simulate)
            {
                pipeline.Output.WriteLine(Utility.Level.Info, $"\n&-c;-------- Simulation Mode Active! --------&-^;\n");
            }


            foreach (ProcessorItem item in items)
            {
                string exeFilepath = exeTemplate.Make(pipeline.PropertyProvider, pipeline.PropertyStore, item);


                string exeArguments = argsTemplate.Make(pipeline.PropertyProvider, pipeline.PropertyStore, item);


                info.FileName  = exeFilepath;
                info.Arguments = exeArguments;


                System.Diagnostics.Process process = !pipeline.Simulate ? new System.Diagnostics.Process {
                    StartInfo = info
                } : null;

                if (noWindow && !pipeline.Simulate)
                {
                    process.OutputDataReceived += (p, data) => pipeline.Output.WriteLine(Level.None, data.Data, true);
                    process.ErrorDataReceived  += (p, data) => pipeline.Output.WriteLine(Level.None, data.Data, true);
                }

                try {
                    process?.Start();

                    pipeline.Output.WriteLine(Level.None, $"Executing: {exeFilepath} {exeArguments}");

                    if (noWindow)
                    {
                        process?.BeginErrorReadLine();
                        process?.BeginOutputReadLine();
                    }

                    if (wait)
                    {
                        process?.WaitForExit();
                    }
                } catch (Win32Exception) {
                    pipeline.Output.WriteLine(Level.Error, $"&-c;Failed to execute: {exeFilepath} {exeArguments}&-^;");
                }
            }

            return(items);
        }
Exemple #39
0
        private void EasyDebug_Click(object sender, RoutedEventArgs e)
        {
            Save_All();
            //main.exe削除
            System.IO.File.Delete(Hensu.ProjectPath + @"\build\main.exe");
            System.IO.StreamWriter sw = new System.IO.StreamWriter(
                @"now.txt",
                false,
                System.Text.Encoding.GetEncoding("shift_jis"));
            //TextBox1.Textの内容を書き込む
            sw.Write(Hensu.ProjectPath);
            //閉じる
            sw.Close();
            //System.Diagnostics.Process.Start("GUIconverter.exe ");
            //Processオブジェクトを作成
            System.Diagnostics.Process p = new System.Diagnostics.Process();

            //ComSpec(cmd.exe)のパスを取得して、FileNameプロパティに指定
            p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            //出力を読み取れるようにする
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput  = false;
            //ウィンドウを表示しないようにする
            p.StartInfo.CreateNoWindow = true;
            //コマンドラインを指定("/c"は実行後閉じるために必要)
            p.StartInfo.Arguments = "/c GUIconverter.exe ";
            //起動
            p.Start();
            //プロセス終了まで待機する
            //WaitForExitはReadToEndの後である必要がある
            //(親プロセス、子プロセスでブロック防止のため)
            p.WaitForExit();
            p.Close();
            //
            //Processオブジェクトを作成
            System.Diagnostics.Process p1 = new System.Diagnostics.Process();

            //ComSpec(cmd.exe)のパスを取得して、FileNameプロパティに指定
            p1.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            //出力を読み取れるようにする
            p1.StartInfo.UseShellExecute        = false;
            p1.StartInfo.RedirectStandardOutput = true;
            p1.StartInfo.RedirectStandardInput  = false;
            //ウィンドウを表示しないようにする
            p1.StartInfo.CreateNoWindow = true;
            //コマンドラインを指定("/c"は実行後閉じるために必要)
            p1.StartInfo.Arguments = "/c cd /d" + Hensu.ProjectPath + @"\build" + @"&& C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe *.cs";
            //
            //起動
            p1.Start();
            p1.WaitForExit();
            textBox1.Text = p1.StandardOutput.ReadToEnd();
            p1.Close();

            if (System.IO.File.Exists(Hensu.ProjectPath + @"\build\main.exe"))
            {
                System.Diagnostics.Process.Start(Hensu.ProjectPath + @"\build\main.exe");
            }
            else
            {
                MessageBox.Show("コンパイルエラーだよ!", "コンパイル情報", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        public void runTask()//EdmCmdData[] data
        {
            List <string> file2Delete = new List <string>();

            try
            {
                //Keep the Task List status up to date
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_Running);
                inst.SetProgressRange(100, 0, "Starting");

                string tempDir    = Path.GetTempPath() + @"AutoCadTaskConverter\";
                string dataName   = tempDir + @"proccessFile.txt";
                string scriptPath = tempDir + @"proccessScript.scr";
                string lispPath   = tempDir + @"proccessLisp.lsp";
                if (!Directory.Exists(tempDir))
                {
                    Directory.CreateDirectory(tempDir);
                }


                file2Delete.Add(dataName);
                file2Delete.Add(scriptPath);
                file2Delete.Add(lispPath);


                //collect data
                foreach (EdmCmdData item in data)
                {
                    if (item.mlLongData1 == (long)EdmObjectType.EdmObject_File)
                    {
                        var fileParm = new AutoCADParameters();
                        fileParm.FileId   = item.mlObjectID1;
                        fileParm.FolderId = item.mlObjectID2;
                        fileParm.FileName = item.mbsStrData1;

                        ///Custom code to output path
                        var path = Path.GetDirectoryName(fileParm.FileName).Split('\\');
                        try
                        {
                            if (path.Length > 3 && path[2].Equals("30 Projects"))
                            {
                                fileParm.OutputPath    = Path.Combine(path[0] + @"\", path[1], path[2], path[3], "03 PDFs", Path.GetFileNameWithoutExtension(fileParm.FileName) + ".pdf");
                                fileParm.OutputPathDXF = Path.Combine(path[0] + @"\", path[1], path[2], path[3], "04 DXFs", Path.GetFileNameWithoutExtension(fileParm.FileName) + ".dxf");
                            }
                            else
                            {
                                fileParm.OutputPath    = Path.ChangeExtension(fileParm.FileName, ".pdf");
                                fileParm.OutputPathDXF = Path.ChangeExtension(fileParm.FileName, ".dxf");
                            }
                        }
                        catch
                        {
                            fileParm.OutputPath    = Path.ChangeExtension(fileParm.FileName, ".pdf");
                            fileParm.OutputPathDXF = Path.ChangeExtension(fileParm.FileName, ".dxf");
                        }


                        var CADFile = vault.GetFileFromPath(fileParm.FileName, out IEdmFolder5 Cadfld);
                        if (CADFile == null)
                        {
                            break;
                        }

                        string OutputfilePath = tempDir + Path.GetFileNameWithoutExtension(fileParm.FileName) + ".pdf";

                        if (System.IO.File.Exists(OutputfilePath))
                        {
                            File.Delete(OutputfilePath);
                        }


                        inst.SetProgressPos(10, "Writting report");
                        ///Write json file ensure file is local
                        JsonSerializer serializer = new JsonSerializer();
                        using (StreamWriter sw = new StreamWriter(dataName, false))
                        {
                            using (JsonWriter writer = new JsonTextWriter(sw))
                            {
                                serializer.Serialize(writer, fileParm);
                            }
                        }
                        inst.SetProgressPos(15, "Launching application");


                        ///Launch autocad.
                        File.WriteAllText(scriptPath, string.Format(AutoCADConversion.Properties.Resources.AcadScript, lispPath.Replace(@"\", @"\\")));
                        File.WriteAllText(lispPath, string.Format(AutoCADConversion.Properties.Resources.ACADLisp, @"""" + OutputfilePath.Replace(@"\", @"\\") + @""""));

                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
                        {
                            CreateNoWindow  = false,
                            UseShellExecute = true,
                            FileName        = CorePath,
                            WindowStyle     = System.Diagnostics.ProcessWindowStyle.Normal,
                            Arguments       = $"/i \"{fileParm.FileName}\" /s \"{scriptPath}\""
                        };

                        using (System.Diagnostics.Process exeProccess = System.Diagnostics.Process.Start(startInfo))
                        {
                            inst.SetProgressPos(20, "Launching application");
                            exeProccess?.WaitForExit();
                        }

                        //If Pdf has generated, then copy the file to the desitnation output
                        if (System.IO.File.Exists(OutputfilePath))
                        {
                            var allFiles = Directory.GetFiles(Path.GetDirectoryName(OutputfilePath), Path.GetFileNameWithoutExtension(OutputfilePath) + "*");
                            if (allFiles.Count() > 1)
                            {
                                List <string> files2Merge = new List <string>();
                                foreach (string f in allFiles)
                                {
                                    if (f.Equals(OutputfilePath, StringComparison.OrdinalIgnoreCase))
                                    {
                                        file2Delete.Add(OutputfilePath);
                                    }
                                    else if (Path.GetExtension(f).Equals(".dxf", StringComparison.OrdinalIgnoreCase))
                                    {
                                        file2Delete.Add(Path.ChangeExtension(OutputfilePath, ".dxf"));
                                    }
                                    else
                                    {
                                        files2Merge.Add(f);
                                        file2Delete.Add(f);
                                    }
                                }
                                if (files2Merge.Count > 0)
                                {
                                    files2Merge.Insert(0, OutputfilePath);
                                    PdfDocument finalDoc = new PdfDocument();
                                    PdfDocument.Merge(finalDoc, files2Merge.ToArray());
                                    File.Delete(OutputfilePath);
                                    finalDoc.Save(OutputfilePath);
                                    finalDoc.Close(true);
                                }
                            }
                            else
                            {
                                file2Delete.Add(OutputfilePath);
                                file2Delete.Add(Path.ChangeExtension(OutputfilePath, ".dxf"));
                            }

                            IEdmFile5 filePDF = CopyFileIntoVault(OutputfilePath, fileParm.OutputPath);
                            IEdmFile5 fileDXF = CopyFileIntoVault(Path.ChangeExtension(OutputfilePath, ".dxf"), fileParm.OutputPathDXF);


                            //If pdf is now in the vault
                            if (filePDF != null)
                            {
                                //Update variables, first get a copy of the files from the source
                                IEdmBatchListing4 var = (IEdmBatchListing4)vault.CreateUtility(EdmUtility.EdmUtil_BatchList);
                                var.AddFileCfg(fileParm.FileName, default(DateTime), 0);
                                var colsetNames = var.GetColumnSetNames();

                                //string atts = "";
                                //foreach (VariableMapperViewModel va in settings.Variables)
                                //{
                                //    if (va.MapVariable)
                                //        atts += "\n" + va.SourceVariable.Name;
                                //}


                                string         atts  = "\nDescription\nDescription2\nDescription3\nRevision\nDocument Number\nDrawnBy\nApprovedBy\nProject Name\nProject Number";
                                EdmListCol[]   cols  = default(EdmListCol[]);
                                EdmListFile2[] files = default(EdmListFile2[]);
                                var.CreateListEx(atts, (int)EdmCreateListExFlags.Edmclef_MayReadFiles, ref cols, null);
                                var.GetFiles2(ref files);

                                //Now copy the files to the variables.
                                IEdmBatchUpdate2 bUp = (IEdmBatchUpdate2)vault.CreateUtility(EdmUtility.EdmUtil_BatchUpdate);
                                foreach (EdmListFile2 getFile in files)
                                {
                                    for (int i = 0; i < cols.Length; i++)
                                    {
                                        bUp.SetVar(filePDF.ID, cols[i].mlVariableID, ((string[])getFile.moColumnData)[i], "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                        bUp.SetVar(fileDXF.ID, cols[i].mlVariableID, ((string[])getFile.moColumnData)[i], "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                    }
                                }
                                //Set SourcedState
                                bUp.SetVar(filePDF.ID, 171, "Released", "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                bUp.SetVar(fileDXF.ID, 171, "Released", "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //Set AutomaticallyGenerated
                                bUp.SetVar(filePDF.ID, 158, 1, "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                bUp.SetVar(fileDXF.ID, 158, 1, "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //foreach (EdmListFile2 getFile in files)
                                //{
                                //    for (int i = 0; i < cols.Length; i++)
                                //    {
                                //        VariableMapperViewModel va = settings.Variables.FirstOrDefault(t=> t.SourceVariable.Id == ((EdmListCol[])cols)[i].mlVariableID);
                                //        bUp.SetVar(Outfile.ID, va.DestinationVariable.Id , ((string[])getFile.moColumnData)[i], "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //    }
                                //}

                                ////copy the static text
                                //foreach (VariableMapperViewModel va in settings.Variables)
                                //{
                                //    if (!va.MapVariable)
                                //        bUp.SetVar(Outfile.ID, va.DestinationVariable.Id, va.Value, "", (int)EdmBatchFlags.EdmBatch_AllConfigs);
                                //}

                                if (0 != bUp.CommitUpdate(out EdmBatchError2[] err))
                                {
                                    PDMAddin.log.Error("Variable errors");
                                }
                                //Check file in.
                                //IEdmFolder5 fldPDF = vault.GetFolderFromPath(Path.GetDirectoryName(fileParm.OutputPath));
                                // IEdmFolder5 fldDXF = vault.GetFolderFromPath(Path.GetDirectoryName(fileParm.OutputPathDXF));

                                filePDF.UnlockFile(0, "Automaticly created", (int)EdmUnlockFlag.EdmUnlock_IgnoreReferences);
                                fileDXF.UnlockFile(0, "Automaticly created", (int)EdmUnlockFlag.EdmUnlock_IgnoreReferences);
                            }
                        }
                    }
                }

                ///comlete

                inst.SetProgressPos(100, "finished");
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_DoneOK);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                PDMAddin.log.Error(ex);
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_DoneFailed, ex.ErrorCode, "The task failed!");
            }
            catch (Exception ex)
            {
                PDMAddin.log.Error(ex);
                inst.SetStatus(EdmTaskStatus.EdmTaskStat_DoneFailed, 0, "", "The task failed!");
            }
            finally
            {
                foreach (string f in file2Delete)
                {
                    if (File.Exists(f))
                    {
                        File.Delete(f);
                    }
                }
            }
        }
        /// <inheritdoc />
        public override bool Execute()
        {
            if (Debug)
            {
                System.Diagnostics.Debugger.Launch();
            }

            if (string.IsNullOrEmpty(MotoiBinFolder))
            {
                throw new ArgumentNullException(nameof(MotoiBinFolder));
            }
            if (string.IsNullOrEmpty(MotoiSrcFolder))
            {
                throw new ArgumentNullException(nameof(MotoiSrcFolder));
            }
            if (string.IsNullOrEmpty(TessaFilePath))
            {
                throw new ArgumentNullException(nameof(TessaFilePath));
            }
            if (string.IsNullOrEmpty(TargetPath))
            {
                throw new ArgumentNullException(nameof(TargetPath));
            }

            Log.LogMessage(MessageImportance.Normal, "Starting Motoi Plug-in compilation task");
            Log.LogMessage(MessageImportance.Normal, "MotoiBinFolder: {0}", MotoiBinFolder);
            Log.LogMessage(MessageImportance.Normal, "MotoiSrcFolder: {0}", MotoiSrcFolder);
            Log.LogMessage(MessageImportance.Normal, "TessaFilePath: {0}", TessaFilePath);

            if (!File.Exists(TessaFilePath))
            {
                throw new ArgumentException("Tessa.exe not found. Check the file path!");
            }
            if (!Directory.Exists(MotoiSrcFolder))
            {
                throw new ArgumentException("Motoi src folder not found. Check the folder path!");
            }

            try {
                CopyDirectory(MotoiSrcFolder, MotoiBinFolder, true, false);
            } catch (Exception ex) {
                Log.LogError("Error on copying files of motoi src folder to motoi bin folder");
                Log.LogErrorFromException(ex);
                return(false);
            }

            string projectPath = BuildEngine.ProjectFileOfTaskNode;
            string targetPath  = TargetPath;

            try {
                string argLine = $"\"{projectPath}\" \"{targetPath}\" \"{MotoiBinFolder}\"";
                Log.LogMessage(MessageImportance.Normal, "Starting tessa using: {0} {1}", TessaFilePath, argLine);
                System.Diagnostics.Process process = System.Diagnostics.Process.Start(TessaFilePath, argLine);
                Log.LogMessage(MessageImportance.Normal, "Tessa started. Waiting for finish...");
                process.WaitForExit();
                int exitCode = process.ExitCode;
                if (exitCode != 0)
                {
                    Log.LogError("Tessa finished unsuccessfully. Exit code is {0}", exitCode);
                    return(false);
                }
                Log.LogMessage(MessageImportance.Normal, "Tessa process has finished successfully");
                return(true);
            } catch (Exception ex) {
                Log.LogError("Error on starting tessa process");
                Log.LogErrorFromException(ex);
                return(false);
            }
        }
Exemple #42
0
        static void Main(string[] commandLineOptions)
        {
            testGroup       = null;
            showNUnitOutput = false;
            pauseOnError    = false;
            pauseBeforeExit = false;
            string dashedLine = "-------------------------";

            try
            {
                string headerLine1 = "Natural Docs Engine Tests";
                string headerLine2 = "Version " + Engine.Instance.VersionString;

                int dashedLineLength = Math.Max(headerLine1.Length, headerLine2.Length);

                StringBuilder dashedLineBuilder = new StringBuilder(dashedLineLength);
                dashedLineBuilder.Append('-', dashedLineLength);

                dashedLine = dashedLineBuilder.ToString();

                System.Console.WriteLine();
                System.Console.WriteLine(headerLine1);
                System.Console.WriteLine(headerLine2);
                System.Console.WriteLine(dashedLine);

                var  assembly       = System.Reflection.Assembly.GetExecutingAssembly();
                Path assemblyFolder = Path.FromAssembly(assembly).ParentFolder;
                Path dllPath        = assemblyFolder + "/NaturalDocs.Engine.Tests.dll";

                if (!ParseCommandLine(commandLineOptions))
                {
                    return;
                }


                // Build the parameter string

                string nunitParams = "\"" + dllPath + "\"";

                if (testGroup != null)
                {
                    nunitParams += " --test=CodeClear.NaturalDocs.Engine.Tests." + testGroup;
                }

                nunitParams += " --work=\"" + assemblyFolder + "\"";


                // Use nunit3-console.exe to run the tests.  Capture its output if desired.

                string nunitOutput = null;

                using (System.Diagnostics.Process nunitProcess = new System.Diagnostics.Process())
                {
                    nunitProcess.StartInfo.FileName               = assemblyFolder + "/nunit3-console.exe";
                    nunitProcess.StartInfo.Arguments              = nunitParams;
                    nunitProcess.StartInfo.UseShellExecute        = false;
                    nunitProcess.StartInfo.RedirectStandardOutput = !showNUnitOutput;

                    if (testGroup == null)
                    {
                        System.Console.WriteLine("Running all tests...");
                    }
                    else
                    {
                        System.Console.WriteLine("Running " + testGroup + " tests...");
                    }

                    if (showNUnitOutput)
                    {
                        System.Console.WriteLine();
                    }

                    nunitProcess.Start();

                    if (!showNUnitOutput)
                    {
                        // This MUST be done before WaitForExit(), counterintuitive as that may be.
                        // See https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput(v=vs.110).aspx
                        nunitOutput = nunitProcess.StandardOutput.ReadToEnd();
                    }

                    nunitProcess.WaitForExit();

                    if (showNUnitOutput)
                    {
                        System.Console.WriteLine();
                    }
                }


                // Attempt to extract the failure count and notices from the generated XML file.

                Path   xmlPath    = assemblyFolder + "/TestResult.xml";
                string xmlContent = System.IO.File.ReadAllText(xmlPath);

                // <failure>
                // <message><![CDATA[1 out of 1 test failed for F:\Projects\Natural Docs 2\Source\Engine.Tests.Data\Comments\XML\Parsing:
                // - Test: Expected output file missing
                // ]]></message>
                // <stack-trace><![CDATA[at CodeClear.NaturalDocs.Engine.Tests.Framework.SourceToTopics.TestFolder(Path testFolder, Path projectConfigFolder) in F:\Projects\Natural Docs 2\Source\Engine.Tests\Source\Framework\SourceToTopics.cs:line 123
                // at CodeClear.NaturalDocs.Engine.Tests.Comments.XML.Parsing.All() in F:\Projects\Natural Docs 2\Source\Engine.Tests\Source\Comments\XML\Parsing.cs:line 20
                // ]]></stack-trace>
                // </failure>

                int             foundFailures  = 0;
                StringBuilder   failures       = new StringBuilder();
                MatchCollection failureMatches = Regex.Matches(xmlContent, @"<failure>.*?<message><!\[CDATA\[(.*?)\]\]>.*?</message>.*?</failure>", RegexOptions.Singleline);

                foreach (Match failureMatch in failureMatches)
                {
                    string failureMessage = failureMatch.Groups[1].ToString();

                    if (failureMessage != "One or more child tests had errors")
                    {
                        failures.AppendLine(failureMessage);
                        foundFailures++;
                    }
                }

                //<test-run
                //		id="0" runstate="Runnable" testcasecount="48"
                //		result="Failed" total="14" passed="13" failed="1" inconclusive="0" skipped="0" asserts="0"
                //		engine-version="3.11.1.0" clr-version="4.0.30319.42000"
                //		start-time="2020-03-15 18:24:36Z" end-time="2020-03-15 18:24:44Z" duration="8.456703">
                Match failureCountMatch = System.Text.RegularExpressions.Regex.Match(xmlContent, @"<test-run.+failed=\""([0-9]+)\"".*>");
                int   failureCount      = -1;

                if (failureCountMatch.Success)
                {
                    failureCount = int.Parse(failureCountMatch.Groups[1].Value);
                }


                // Display the output, falling back to the captured console output if our XML extraction didn't work.

                if (failureCount == -1 || failureCount != foundFailures)
                {
                    if (!showNUnitOutput)
                    {
                        System.Console.WriteLine();
                        System.Console.Write(nunitOutput);
                    }

                    if (pauseOnError)
                    {
                        pauseBeforeExit = true;
                    }
                }
                else if (failureCount != 0)
                {
                    if (!showNUnitOutput)
                    {
                        System.Console.WriteLine();
                        System.Console.Write(failures.ToString());
                    }

                    if (pauseOnError)
                    {
                        pauseBeforeExit = true;
                    }
                }
                else
                {
                    if (!showNUnitOutput)
                    {
                        System.Console.WriteLine("All tests successful.");
                    }
                }

                System.Console.WriteLine(dashedLine);
            }
            catch (Exception e)
            {
                if (pauseOnError)
                {
                    pauseBeforeExit = true;
                }

                System.Console.WriteLine(dashedLine);
                System.Console.WriteLine();
                System.Console.WriteLine("Exception: " + e.Message);
            }

            if (pauseBeforeExit)
            {
                System.Console.WriteLine();
                System.Console.WriteLine("Press any key to continue...");
                System.Console.ReadKey(false);
            }
        }
Exemple #43
0
        public void _Internal_SelfExtractor_Command(string cmdFormat,
                                                    SelfExtractorFlavor flavor,
                                                    bool runPostExtract,
                                                    bool quiet,
                                                    bool forceNoninteractive,
                                                    bool wantArgs)
        {
            TestContext.WriteLine("==============================");
            TestContext.WriteLine("SelfExtractor_RunOnExit({0})", flavor.ToString());

            int    entriesAdded   = 0;
            String filename       = null;
            string postExtractExe = String.Format(cmdFormat, _rnd.Next(3000));

            // If WinForms and want forceNoninteractive, have the post-extract-exe return 0,
            // else, select a random number.
            int expectedReturnCode = (forceNoninteractive && flavor == SelfExtractorFlavor.WinFormsApplication)
                ? 0
                : _rnd.Next(1024) + 20;

            TestContext.WriteLine("The post-extract command ({0}) will return {1}", postExtractExe, expectedReturnCode);
            string Subdir = Path.Combine(TopLevelDir, "A");

            Directory.CreateDirectory(Subdir);
            var checksums = new Dictionary <string, string>();

            int fileCount = _rnd.Next(10) + 10;

            for (int j = 0; j < fileCount; j++)
            {
                filename = Path.Combine(Subdir, String.Format("file{0:D3}.txt", j));
                TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
                entriesAdded++;
                var chk = TestUtilities.ComputeChecksum(filename);
                checksums.Add(filename, TestUtilities.CheckSumToString(chk));
                TestContext.WriteLine("checksum({0})= ({1})", filename, checksums[filename]);
            }

            Directory.SetCurrentDirectory(TopLevelDir);
            for (int k = 0; k < 2; k++)
            {
                string ReadmeString = String.Format("Hey there!  This zipfile entry was created directly " +
                                                    "from a string in application code. Flavor ({0}) Trial({1})",
                                                    flavor.ToString(), k);
                string exeFileToCreate = Path.Combine(TopLevelDir,
                                                      String.Format("SelfExtractor_Command.{0}.{1}.exe",
                                                                    flavor.ToString(), k));
                TestContext.WriteLine("----------------------");
                TestContext.WriteLine("Trial {0}", k);
                string UnpackDirectory = String.Format("unpack.{0}", k);

                if (k != 0)
                {
                    CompileApp(expectedReturnCode, postExtractExe);
                }

                var sw = new System.IO.StringWriter();
                using (ZipFile zip = new ZipFile())
                {
                    zip.StatusMessageTextWriter = sw;
                    zip.AddDirectory(Subdir, Path.GetFileName(Subdir));
                    zip.Comment = String.Format("Trial options: flavor({0})  command: ({3})\r\n" +
                                                "actuallyRun({1})\r\nquiet({2})\r\n" +
                                                "exists? {4}\r\nexpected rc={5}",
                                                flavor,
                                                runPostExtract,
                                                quiet,
                                                postExtractExe,
                                                k != 0,
                                                expectedReturnCode
                                                );
                    MemoryStream ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(ReadmeString));
                    zip.AddEntry("Readme.txt", ms1);
                    if (k != 0)
                    {
                        zip.AddFile(postExtractExe);
                    }

                    SelfExtractorSaveOptions sfxOptions = new SelfExtractorSaveOptions();
                    sfxOptions.Flavor = flavor;
                    sfxOptions.DefaultExtractDirectory = UnpackDirectory;
                    sfxOptions.Quiet = quiet;

                    // In the case of k==0, this exe does not exist.  It will result in
                    // a return code of 5.  In k == 1, the exe exists and will succeed.
                    if (postExtractExe.Contains(' '))
                    {
                        sfxOptions.PostExtractCommandLine = "\"" + postExtractExe + "\"";
                    }
                    else
                    {
                        sfxOptions.PostExtractCommandLine = postExtractExe;
                    }

                    if (wantArgs)
                    {
                        sfxOptions.PostExtractCommandLine += " arg1 arg2";
                    }

                    zip.SaveSelfExtractor(exeFileToCreate, sfxOptions);
                }

                TestContext.WriteLine("status output: " + sw.ToString());

                if (k != 0)
                {
                    File.Delete(postExtractExe);
                }

                // Run the post-extract-exe, conditionally.
                // We always run, unless specifically asked not to, OR
                // if it's a winforms app and we want it to be noninteractive and there's no EXE to run.
                // If we try running a non-existent app, it will pop an error message, hence user interaction,
                // which we need to avoid for the automated test.
                if (runPostExtract &&
                    (k != 0 || !forceNoninteractive || flavor != SelfExtractorFlavor.WinFormsApplication))
                {
                    TestContext.WriteLine("Running the SFX... ");
                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(exeFileToCreate);
                    psi.WorkingDirectory = TopLevelDir;
                    psi.UseShellExecute  = false;
                    psi.CreateNoWindow   = true; // false;
                    System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
                    process.WaitForExit();
                    int rc = process.ExitCode;
                    TestContext.WriteLine("SFX exit code: ({0})", rc);

                    // The exit code is returned only if it's a console SFX.
                    if (flavor == SelfExtractorFlavor.ConsoleApplication)
                    {
                        // The program actually runs if k != 0
                        if (k != 0)
                        {
                            // The file to execute should have returned a specific code.
                            Assert.AreEqual <Int32>(expectedReturnCode, rc, "In trial {0}, the exit code did not match.", k);
                        }
                        else
                        {
                            // The file to execute should not have been found, hence rc==5.
                            Assert.AreEqual <Int32>(5, rc, "In trial {0}, the exit code was unexpected.", k);
                        }
                    }
                    else
                    {
                        Assert.AreEqual <Int32>(0, rc, "In trial {0}, the exit code did not match.", k);
                    }



                    // now, compare the output in UnpackDirectory with the original
                    string DirToCheck = Path.Combine(TopLevelDir, Path.Combine(UnpackDirectory, "A"));
                    // verify the checksum of each file matches with its brother
                    foreach (string fname in Directory.GetFiles(DirToCheck))
                    {
                        string originalName = fname.Replace("\\" + UnpackDirectory, "");
                        if (checksums.ContainsKey(originalName))
                        {
                            string expectedCheckString = checksums[originalName];
                            string actualCheckString   = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(fname));
                            Assert.AreEqual <String>(expectedCheckString, actualCheckString, "Unexpected checksum on extracted filesystem file ({0}).", fname);
                        }
                        else
                        {
                            Assert.AreEqual <string>("Readme.txt", originalName);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Returns true if the current operation succeeded.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="settings"></param>
        /// <param name="notificationID"></param>
        /// <returns></returns>
        ///



        public static bool Send(string data, Hashtable settings, int notificationID, int ivrID, int alarmID, AlarmObject alarmObject)
        {
            bool   retValue      = false;
            bool   callConnected = false;
            string response      = string.Empty;
            string succeeded     = string.Empty;
            string error         = string.Empty;
            Int16  dailAttempts  = 1;
            string DigitsPressed = string.Empty;

            long QueueID = -1;

            int    TryCount                 = -1;
            bool   CallAnswered             = false;
            bool   Answered                 = false;
            bool   CallComplete             = false;
            string MachineDetection         = string.Empty;
            int    Duration                 = -1;
            string IVRServiceResponseText   = string.Empty;
            int    TTIVRNotifications_RecID = -1;


            NotifyObject      notifyObject      = new NotifyObject();
            NotifyComResponse notifyResponse    = new NotifyComResponse();
            NotifyComResponse notifyComResponse = new NotifyComResponse();

            notifyObject.NotificationType = "Voice";
            notifyObject.NotificationData = data;     //voice message to be played
            notifyObject.NotifierSettings = settings; //hash table of keys and values


            NotificationEndPointElement element;
            string vcElement1;
            string vcElement2;
            string vcElement3;
            string vcElement4;

            /* get end point for voice composer*/


            string method = NotificationClient.GetInstance().WhoAmI("Voice", out element);

            string arguments = null;

            LogBook.Write("Sending voice alert....");
            switch (method.ToLower())
            {
            case "cooperatkins.notificationclient.notifyengine.ivrnotificationcom":


                System.Diagnostics.Process process = new System.Diagnostics.Process();
                if (element == null)
                {
                    arguments = @"-m ""<notification ack='true'><notificationData><![CDATA[" + data + @"]]></notificationData><notificationType><![CDATA[Voice]]></notificationType><notificationSettings><PhoneNo><![CDATA[" + settings["PhoneNo"].ToStr() + @"]]></PhoneNo></notificationSettings></notification>"" ";
                }
                else
                {
                    arguments = @"-c " + element.EndpointAddress + @" -m ""<notification ack='true'><notificationData><![CDATA[" + data + @"]]></notificationData><notificationType><![CDATA[Voice]]></notificationType><notificationSettings><PhoneNo><![CDATA[" + settings["PhoneNo"].ToStr() + @"]]></PhoneNo></notificationSettings></notification>"" ";
                }

                while (!callConnected)
                {
                    IvrAlarmStatus ivrAlarmStatus = new IvrAlarmStatus();
                    try
                    {
                        LogBook.Write("Checking whether alarm is cleared or not");
                        ivrAlarmStatus.AlarmID        = alarmID;
                        ivrAlarmStatus.NotificationID = notificationID;
                        ivrAlarmStatus.StoreID        = GenStoreInfo.GetInstance().StoreID;
                        ivrAlarmStatus.Execute();
                    }
                    catch (Exception ex)
                    {
                        LogBook.Write(ex, "CooperAtkins.NotificationClient.NotificationComposer.IvrClientHelper", ErrorSeverity.High);
                    }
                    finally
                    {
                        ivrAlarmStatus.Dispose();
                    }

                    if (ivrAlarmStatus.IsAlarmClearedOrBackInRange)
                    {
                        break;
                    }

                    /*       analog modem use  */

                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    //process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.FileName       = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\Utility.exe";
                    //process.StartInfo.FileName = @"F:\DEV\CooperAtkins\CooperAtkins.NotificationEngine.Utility\bin\Debug\Utility.exe";
                    process.StartInfo.Arguments = arguments;
                    // process.StartInfo.WorkingDirectory = ;
                    process.Start();

                    process.WaitForExit();


                    response = process.StandardOutput.ReadToEnd();

                    callConnected = true;
                    if (response.ToLower().Contains("device initialization failed") || response.ToLower().Contains("invalid_device_id") || response.ToLower().Contains("dll_not_found") || response.ToLower().Contains("exception from hresult"))
                    {
                        callConnected = false;
                    }
                    /*     end  analog modem use  */
                }
                break;


            case "cooperatkins.notificationclient.notificationcomposer.cdyneivrnotificationcomposer":
                long     TransactionID = -1;
                DateTime StartTime;
                DateTime EndTime;
                long     AlarmID = -1;


                string CDYNE_ID      = GenStoreInfo.GetInstance().CDYNE_ACCOUNT;//NotificationClient.GetInstance().GetCustomVoiceSettings("CDyneID", out vcElement1);
                string CDYNE_RETRIES = NotificationClient.GetInstance().GetCustomVoiceSettings("CDyneRetries", out vcElement2);
                string CDYNE_VOICEID = NotificationClient.GetInstance().GetCustomVoiceSettings("CDyneVoiceID", out vcElement3);
                string CDYNE_VOLUME  = NotificationClient.GetInstance().GetCustomVoiceSettings("CDyneVolume", out vcElement4);

                notifyObject.NotifierSettings["CDYNE_ID"]      = CDYNE_ID;
                notifyObject.NotifierSettings["CDYNE_RETRIES"] = CDYNE_RETRIES;
                notifyObject.NotifierSettings["CDYNE_VOICEID"] = CDYNE_VOICEID;
                notifyObject.NotifierSettings["CDYNE_VOLUME"]  = CDYNE_VOLUME;
                NotificationStyle  notificationStyle        = new NotificationStyle();
                TTIvrNotifications tTIvrNotificationsObject = new TTIvrNotifications();
                callConnected = false;

                while (!callConnected)
                {
                    notifyComResponse.IsInProcess = true;
                    int QueryCall = 0;
                    int UnivError = 0;

                    //if (!alarmObject.IsFailsafeEscalationNotification)
                    //{
                    //IvrAlarmStatus ivrAlarmStatus = new IvrAlarmStatus();
                    //try
                    //{
                    //    LogBook.Write("Checking whether alarm is cleared or not");
                    //    ivrAlarmStatus.AlarmID = alarmID;
                    //    ivrAlarmStatus.NotificationID = notificationID;
                    //    ivrAlarmStatus.StoreID = GenStoreInfo.GetInstance().StoreID;
                    //    ivrAlarmStatus.Execute();
                    //}
                    //catch (Exception ex)
                    //{
                    //    LogBook.Write(ex, "CooperAtkins.NotificationClient.NotificationComposer.CDYNEIvrClientHelper", ErrorSeverity.High);
                    //}
                    //finally
                    //{
                    //    ivrAlarmStatus.Dispose();
                    //}

                    //12/9/15 comment start
                    //AlarmStatus alarmStatus = new AlarmStatus();
                    //try
                    //{
                    //    LogBook.Write("IVR Checking whether alarm [" + alarmObject.NotificationID + "] is cleared or not");
                    //    alarmStatus.NotificationID = alarmObject.NotificationID;
                    //    alarmStatus.StoreID = GenStoreInfo.GetInstance().StoreID;
                    //    alarmStatus.Execute();
                    //}
                    //catch (Exception ex)
                    //{
                    //    LogBook.Write(ex, "CooperAtkins.NotificationClient.Alarm.AlarmInitializer", ErrorSeverity.High);
                    //}
                    //finally
                    //{
                    //    alarmStatus.Dispose();
                    //12/9/15 comment end }

                    int threadID = notifyObject.NotifierSettings["ThreadID"].ToInt();

                    //12/9/15 comment start
                    //if (alarmStatus.IsAlarmClearedOrBackInRange)
                    //{
                    //    Answered = false;
                    //    callConnected = false;
                    //    notifyComResponse.IsSucceeded = false;
                    //    notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " SUSPENDED (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ")";
                    //    notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\nALARM WAS CLEARED OR BACK IN RANGE";

                    //    LogBook.Write("CALL SUSPENDED To " + notifyObject.NotifierSettings["PhoneNo"] + IVRServiceResponseText + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "] ALARM WAS CLEARED OR SENSOR IS BACK IN RANGE");

                    //    notificationStyle.RecordNotification(notifyComResponse.ResponseContent.ToString(), notificationID, TransactionID.ToInt(), NotifyStatus.FAIL, NotifyTypes.VOICE);
                    //    UpdateIVRNotification(ivrID, false, false, dailAttempts, TransactionID, threadID);

                    //    break;

                    //12/9/15 comment end }


                    int totalCallAttempts = notifyObject.NotifierSettings["Attempts"].ToInt();

                    if ((totalCallAttempts + dailAttempts) > (CDYNE_RETRIES.ToInt() + 1))
                    //also if a notficicationId is in an alert progress state from another thread,
                    //fall into this code to break out OR if cleared or inprogress check to be sure
                    //we made contatc through our maximum attempts value
                    {
                        notifyComResponse.IsInProcess = false;
                        UpdateIVRNotification(ivrID, false, notifyComResponse.IsInProcess, dailAttempts, TransactionID, threadID);
                        break;
                    }
                    //}


                    UpdateIVRNotification(ivrID, false, true, (totalCallAttempts + dailAttempts), TransactionID, threadID);

                    try{
                        IVRProcessor maketheIVRCall = new IVRProcessor();
                        notifyResponse = maketheIVRCall.Invoke(notifyObject);
                        //  notifyComResponse = new NotifyComResponse();
                        TransactionID = notifyResponse.TransactionIDReturned;
                        //query for call result

                        Answered = false;
                        PhoneNotify pn2 = new PhoneNotify();
                        while (!Answered)
                        {
                            if (QueryCall == 0)        //on first call, wait 1 minute for call to complete before getting call results
                            {
                                System.Threading.Thread.Sleep(1 * 60 * 1000);
                            }
                            else
                            {
                                System.Threading.Thread.Sleep(5 * 1000);
                            }
                            NotifyReturn nr2 = pn2.GetQueueIDStatus(TransactionID);
                            MachineDetection       = nr2.MachineDetection;
                            DigitsPressed          = nr2.DigitsPressed;
                            CallAnswered           = nr2.CallAnswered;
                            CallComplete           = nr2.CallComplete;
                            IVRServiceResponseText = nr2.ResponseText;
                            Duration  = nr2.Duration;
                            StartTime = nr2.StartTime;
                            EndTime   = nr2.EndTime;
                            if (CallAnswered == true && DigitsPressed.Contains("*"))
                            {
                                Answered      = true;
                                callConnected = true;
                                notifyComResponse.IsSucceeded = true;
                                //notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " Connected (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ")";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " Connected.  ";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\nAcknowledgement received, " + "'" + DigitsPressed + "' pressed.";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\nCall Complete >";

                                LogBook.Write("Query Call State Try: " + (QueryCall + 1) + ": Phone Call " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " To " + notifyObject.NotifierSettings["PhoneNo"] + " Answered and Digits: " + DigitsPressed + " were pressed: " + IVRServiceResponseText + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                                break;
                            }
                            else if (CallAnswered == true && !DigitsPressed.Contains("*") && MachineDetection == "HUMAN" && CallComplete)
                            {
                                Answered = true;
                                notifyComResponse.IsSucceeded = false;
                                //notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " Connected (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ")";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " Connected.  ";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\nNo Acknowledgement received, Digits Pressed: " + DigitsPressed + ">";
                                LogBook.Write("Query Call State Try: " + (QueryCall + 1) + ": Phone Call " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " To " + notifyObject.NotifierSettings["PhoneNo"] + " Answered but no digits were pressed: " + IVRServiceResponseText + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                                break;
                            }
                            else if (CallAnswered == true && DigitsPressed == "" && MachineDetection == "HUMAN" && !CallComplete)
                            {
                                notifyComResponse.IsSucceeded = false;
                                //notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " Connected (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ")";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " Connected.  ";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\nNo Acknowledgement received >";
                                LogBook.Write("Query Call State Try: " + (QueryCall + 1) + ": Phone Call " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " To " + notifyObject.NotifierSettings["PhoneNo"] + " Answered but no digits were pressed: " + IVRServiceResponseText + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                                QueryCall += 1;
                            }
                            else if (CallAnswered == true && DigitsPressed == "" && MachineDetection == "MACHINE")
                            {
                                Answered = false;
                                notifyComResponse.IsSucceeded = false;
                                //notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] +"["+ notifyObject.NotifierSettings["CallerName"]+"]"+ " Connected (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ")";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " Connected.  ";
                                notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\nAnswering Machine Detected >";
                                LogBook.Write("Query Call State Try: " + (QueryCall + 1) + ": Phone Call " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " To " + notifyObject.NotifierSettings["PhoneNo"] + " Answered by MACHINE: " + IVRServiceResponseText + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                                break;
                            }
                            else if (IVRServiceResponseText == "In Call/Ringing" || IVRServiceResponseText == "Queued" || IVRServiceResponseText == "Universal Error")
                            {
                                notifyComResponse.IsSucceeded = false;
                                notifyComResponse.IsError     = true;
                                //if (notifyComResponse.ResponseContent != null)
                                //{
                                //    if ((!notifyComResponse.ResponseContent.ToString().Contains("Call/Ringing (Attempt # " + dailAttempts)) &&
                                //        (!notifyComResponse.ResponseContent.ToString().Contains("Queued (Attempt # " + dailAttempts)) &&
                                //        (!notifyComResponse.ResponseContent.ToString().Contains("Universal Error  (Attempt # " + dailAttempts)))  //only add line if it has not already been logged for this dial attempt
                                //    {
                                //        notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "] " + IVRServiceResponseText + " (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ") >";
                                //    }
                                //}
                                //else
                                //{
                                //    notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "] " + IVRServiceResponseText + " (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ") >";
                                //}
                                //    notifyComResponse.ResponseContent = "";
                                LogBook.Write("Query Call State Try: " + (QueryCall + 1) + ": Phone Call " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " To " + notifyObject.NotifierSettings["PhoneNo"] + " Current Status: " + IVRServiceResponseText + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                                if (IVRServiceResponseText == "Universal Error")
                                {
                                    UnivError += 1;        //if it continues to return Universl Error allow a way to get out
                                }
                                QueryCall += 1;
                            }
                            else
                            {
                                notifyComResponse.IsSucceeded = false;
                                if (notifyComResponse.ResponseContent != null)
                                {
                                    if (!notifyComResponse.ResponseContent.ToString().Contains("ERROR"))         //only add line if it has not already been logged
                                    {
                                        //notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " ERROR: " + IVRServiceResponseText + " (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ") >";
                                        notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " ERROR: " + IVRServiceResponseText + " >";
                                    }
                                }
                                else
                                {
                                    //notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " ERROR: " + IVRServiceResponseText + " (Attempt # " + dailAttempts + " of " + (CDYNE_RETRIES.ToInt() + 1) + ") >";
                                    notifyComResponse.ResponseContent += "\r\n\r\n\r\n\r\n < Phone Call To " + notifyObject.NotifierSettings["PhoneNo"] + "[" + notifyObject.NotifierSettings["CallerName"] + "]" + " ERROR: " + IVRServiceResponseText + " >";
                                }
                                LogBook.Write("Query Call State Try: " + (QueryCall + 1) + ": Phone Call " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " To " + notifyObject.NotifierSettings["PhoneNo"] + " Current Status: " + IVRServiceResponseText + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                                QueryCall += 1;
                            }
                            if (QueryCall > 2 || Answered || (UnivError > 10))
                            {
                                break;
                            }
                        }
                    }catch (Exception ex)
                    {
                        LogBook.Write(ex, "CooperAtkins.NotificationClient.NotificationComposer.CDYNEIvrClientHelper MAkeTheCall", ErrorSeverity.High);
                    }


                    if (!callConnected || !Answered)
                    {
                        //write to TTNotificationLog

                        if (notifyComResponse.ResponseContent != null)
                        {
                            if (notifyComResponse.ResponseContent.ToString() != "")
                            {
                                notificationStyle.RecordNotification(notifyComResponse.ResponseContent.ToString(), notificationID, TransactionID.ToInt(), NotifyStatus.FAIL, NotifyTypes.VOICE);
                            }
                        }
                        notifyComResponse.ResponseContent = "";

                        //write to TTIVRNotifications
                        UpdateIVRNotification(ivrID, notifyComResponse.IsSucceeded, notifyComResponse.IsInProcess, (totalCallAttempts + dailAttempts), TransactionID, threadID);
                        // System.Threading.Thread.Sleep(30 * 1000); //wait and try that number 1 more time before trying next person
                        dailAttempts += 1;
                        retValue      = false;
                        if (((totalCallAttempts + dailAttempts.ToInt())) > CDYNE_RETRIES.ToInt16() + 1)
                        {        //try each person X times from config
                            LogBook.Write("Exhausted  " + (CDYNE_RETRIES.ToInt()) + " Re-Try Attempts To: " + notifyObject.NotifierSettings["PhoneNo"] + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                            notifyComResponse.IsInProcess = false;

                            if (UnivError >= 10)         //reset call counter, so it will re-attempt to call person has CDyne never truly made a call
                            {                            //4th param in below function
                                UpdateIVRNotification(ivrID, notifyComResponse.IsSucceeded, notifyComResponse.IsInProcess, 0, TransactionID, threadID);
                            }
                            else
                            {
                                UpdateIVRNotification(ivrID, notifyComResponse.IsSucceeded, notifyComResponse.IsInProcess, (totalCallAttempts + dailAttempts), TransactionID, threadID);
                            }
                            retValue = false;
                            alarmObject.IVRSuccess = false;
                            break;
                        }
                        else
                        {
                            LogBook.Write("Trying Retry Call Attempt " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " Attempts To: " + notifyObject.NotifierSettings["PhoneNo"] + " for NotificationID: " + notificationID);
                        }
                    }
                    else
                    {
                        LogBook.Write("Call Complete.  Alert Success during call " + (totalCallAttempts + dailAttempts) + " of " + (CDYNE_RETRIES.ToInt() + 1) + " attempts To: " + notifyObject.NotifierSettings["PhoneNo"] + " for NotificationID: " + notificationID + " [CDyneTransID: " + TransactionID + "]");
                        notifyComResponse.IsInProcess = false;
                        notificationStyle.RecordNotification(notifyComResponse.ResponseContent.ToString(), notificationID, TransactionID.ToInt(), NotifyStatus.PASS, NotifyTypes.VOICE);
                        notifyComResponse.ResponseContent = "";
                        UpdateIVRNotification(ivrID, notifyComResponse.IsSucceeded, notifyComResponse.IsInProcess, (totalCallAttempts + dailAttempts), TransactionID, threadID);
                        retValue = true;
                        alarmObject.IVRSuccess = true;
                    }
                }
                break;         //end call attempts

            default:
                break;
            }

            if (method.ToLower() == "cooperatkins.notificationserver.notifyengine.ivrnotificationcom")
            {
                NotificationStyle notificationStyle = new NotificationStyle();

                foreach (string responseLine in response.Split(new string[] { "\n" }, StringSplitOptions.None))
                {
                    if (responseLine.ToLower().Contains("succeeded"))
                    {
                        succeeded = responseLine.ToLower().Replace("succeeded :", string.Empty);
                    }
                    else if (responseLine.ToLower().Contains("error"))
                    {
                        error = responseLine.ToLower().Replace("error :", string.Empty);
                    }
                }


                LogBook.Write("ResponseContent:" + response + ", IsSucceeded:" + succeeded + ", IsError:" + error);


                /* record the notification information to the database. */
                if (succeeded == "no")
                {
                    notificationStyle.RecordNotification(response.Remove(0, 60).Replace("\n", "\r\n"), notificationID, 0, NotifyStatus.FAIL, NotifyTypes.VOICE);
                }
                else
                {
                    notificationStyle.RecordNotification(response.Remove(0, 60).Replace("\n", "\r\n"), notificationID, 0, NotifyStatus.PASS, NotifyTypes.VOICE);
                }


                retValue = succeeded == "yes";
            }

            return(retValue);
        }
Exemple #45
0
        static void Main(string[] args)
        {
            var workingDirectory = @"D:\gource-results\t2\";
            var totalDirectory   = @"D:\gource-results\totals\";

            if (!Directory.Exists(totalDirectory))
            {
                Directory.CreateDirectory(totalDirectory);
            }

            //Directory.Delete(workingDirectory, true);

            // deserialize JSON directly from a file
            var projectSettings     = ReadProjectSettings();
            var externalLogSettings = ReadExternalLogSettings();
            var userFixMappings     = ReadUserFixMappings();

            var logList = new List <string>();
            var totalCommitMetricsList = new List <ProjectCommitsMetrics>();
            var userProjectWorks       = new List <UserProjectWork>();

            foreach (var projectSetting in projectSettings)
            {
                var repoPath = Path.Combine(workingDirectory, projectSetting.Name);
                // Если папка есть, предполагаем, что репа уже выкачена.
                // И не
                if (!Directory.Exists(repoPath))
                {
                    Repository.Clone(projectSetting.RepoUrl, repoPath);
                }

                if (projectSetting.Branch != null)
                {
                    using (var repo = new Repository(repoPath))
                    {
                        var branch = repo.Branches[projectSetting.Branch];

                        if (branch == null)
                        {
                            // repository return null object when branch not exists
                            throw new System.Exception();
                        }

                        try
                        {
                            var currentBranch = Commands.Checkout(repo, branch);
                        }
                        catch
                        {
                            Console.WriteLine($"[.] не удалось переключиться на ветку {projectSetting.Branch}");
                        }
                    }
                }

                using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                {
                    var logPath    = Path.Combine(workingDirectory, projectSetting.Name + ".log");
                    var gitDirPath = Path.Combine(repoPath, ".git");
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        WindowStyle           = System.Diagnostics.ProcessWindowStyle.Hidden,
                        FileName              = "cmd.exe",
                        RedirectStandardInput = true,
                        UseShellExecute       = false
                    };
                    process.StartInfo = startInfo;
                    process.Start();

                    var commands = new[] {
                        $"gource {gitDirPath} --start-date \"2019-01-01\" --output-custom-log {logPath}" + GetUserFilterParam(projectSetting)
                    };

                    using (StreamWriter pWriter = process.StandardInput)
                    {
                        if (pWriter.BaseStream.CanWrite)
                        {
                            foreach (var line in commands)
                            {
                                pWriter.WriteLine(line);
                            }
                        }
                    }

                    process.WaitForExit();

                    if (File.Exists(logPath))
                    {
                        var regexp = new Regex(@"(.+)\|(.+)\|(.+)\|(.+)\r");

                        string text = File.ReadAllText(logPath);

                        // Последнее делает для каждого файла расширение, равное расширению проекта.
                        // Это может быть использовано для того, чтобы была разная цветовая идентификация проекта.
                        text = regexp.Replace(text, $@"$1|$2|$3|/{projectSetting.Department}/{projectSetting.Name}$4.{projectSetting.Name}");
                        File.WriteAllText(logPath + ".segregated", text);

                        logList.Add(logPath + ".segregated");

                        var commitMetrics = CalcMetrics(userFixMappings, logPath, projectSetting.Name, userProjectWorks);
                        totalCommitMetricsList.Add(commitMetrics);

                        var metricsStringBuilder = new StringBuilder();
                        WriteCommitMetrics(commitMetrics, metricsStringBuilder);
                        File.WriteAllText(logPath + ".metrics", metricsStringBuilder.ToString());
                    }
                }
            }

            foreach (var externalLog in externalLogSettings.Items)
            {
                var fullPath = Path.Combine(externalLogSettings.Path, externalLog.Name + ".log");
                if (File.Exists(fullPath))
                {
                    logList.Add(fullPath);
                }
                else
                {
                    Console.WriteLine($"External logs {fullPath} not found");
                }
            }

            WriteTotalCommitMetrics(totalDirectory, totalCommitMetricsList, userProjectWorks);

            File.WriteAllText($@"{totalDirectory}\total-list.txt", string.Join("\n", logList));

            var combinedLogPath = $@"{workingDirectory}\combined.log";

            MergeLogs(logList, combinedLogPath);

            FixUsers(userFixMappings, combinedLogPath, combinedLogPath);
        }
Exemple #46
0
        /// <summary>
        /// 获取差异
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public static List <string> DoSvnDiffFileList(string dirPath, string lastRivision, string currentRevision)
        {
            List <string> files = new List <string>();

            System.Diagnostics.Process exep = new System.Diagnostics.Process();
            exep.StartInfo.FileName  = "svn";
            exep.StartInfo.Arguments = string.Format("diff -r {0}:{1} --summarize \"{2}\"", lastRivision, currentRevision, dirPath);

            JW.Common.Log.LogD("CMD:" + exep.StartInfo.FileName + " " + exep.StartInfo.Arguments);
            exep.StartInfo.CreateNoWindow         = true;
            exep.StartInfo.UseShellExecute        = false;
            exep.StartInfo.RedirectStandardOutput = true;
            exep.StartInfo.RedirectStandardError  = true;
            exep.Start();

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

            while (exep.StandardOutput.Peek() > -1)
            {
                output.Add(exep.StandardOutput.ReadLine());
            }

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

            while (exep.StandardError.Peek() > -1)
            {
                error.Add(exep.StandardError.ReadLine());
            }

            exep.WaitForExit();

            if (error != null && error.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0, imax = error.Count; i < imax; i++)
                {
                    sb.AppendLine(error[i]);
                }

                Terminate(sb.ToString());
                return(null);
            }

            foreach (string line in output)
            {
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                string[] splits = System.Text.RegularExpressions.Regex.Split(line, @"\s{2,}");
                if (splits.Length != 2)
                {
                    JW.Common.Log.LogE("svn diff process format error:" + line);
                    continue;
                }

                string path = splits[1];
                path = path.Replace(Path.DirectorySeparatorChar, '/');
                path = "Assets" + path.Substring(path.IndexOf(Application.dataPath) + Application.dataPath.Length);

                files.Add(path);
            }

            return(files);
        }
        private static int _Run(Context context, string cmd, Action <string> logger = null)
        {
            TaskCompletionSource <int> task = new TaskCompletionSource <int>();

            var startInfo = new System.Diagnostics.ProcessStartInfo(Instance._ffmpegFile.CanonicalPath, cmd);

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

            var process = new System.Diagnostics.Process();

            process.StartInfo = startInfo;

            bool finished = false;

            string error = null;

            process.Start();

            Task.Run(() =>
            {
                try
                {
                    using (var reader = process.StandardError)
                    {
                        StringBuilder processOutput = new StringBuilder();
                        while (!finished)
                        {
                            var line = reader.ReadLine();
                            if (line == null)
                            {
                                break;
                            }
                            logger?.Invoke(line);
                            processOutput.Append(line);

                            if (line.StartsWith(EndOfFFMPEGLine))
                            {
                                Task.Run(async() =>
                                {
                                    await Task.Delay(TimeSpan.FromMinutes(1));
                                    finished = true;
                                });
                            }
                        }
                        error = processOutput.ToString();
                    }
                }
                catch (Exception)
                {
                    // Não implementado
                }
            });

            while (!finished)
            {
                process.WaitForExit(10000);
                if (process.HasExited)
                {
                    break;
                }
            }

            return(process.ExitCode);
        }
        static void Main(string[] args)
        {
            /*{
             *  var n = new NumericalValue<int>();
             *  n.UnionWith(new NumericalValue<int>(0, Inclusivity.INCLUSIVE, 3, Inclusivity.INCLUSIVE));
             *  AssertEquals(n.ToString(), "[0, 3]");
             *  n.UnionWith(new NumericalValue<int>(0, Inclusivity.INCLUSIVE, 3, Inclusivity.INCLUSIVE));
             *  AssertEquals(n.ToString(), "[0, 3]");
             *  n.UnionWith(new NumericalValue<int>(1, Inclusivity.INCLUSIVE, 4, Inclusivity.EXCLUSIVE));
             *  AssertEquals(n.ToString(), "[0, 4)");
             *  n.UnionWith(new NumericalValue<int>(7, Inclusivity.INCLUSIVE, 10, Inclusivity.INCLUSIVE));
             *  AssertEquals(n.ToString(), "[0, 4) U [7, 10]");
             *  n.UnionWith(new NumericalValue<int>(6, Inclusivity.INCLUSIVE, 7, Inclusivity.EXCLUSIVE));
             *  AssertEquals(n.ToString(), "[0, 4) U [6, 10]");
             *  n.UnionWith(new NumericalValue<int>(3, Inclusivity.INCLUSIVE, 7, Inclusivity.EXCLUSIVE));
             *  AssertEquals(n.ToString(), "[0, 10]");
             * }
             * {
             *  var n = new NumericalValue<int>();
             *  n.UnionWith(new NumericalValue<int>(0, Inclusivity.INCLUSIVE, 4, Inclusivity.EXCLUSIVE));
             *  n.UnionWith(new NumericalValue<int>(6, Inclusivity.INCLUSIVE, 10, Inclusivity.INCLUSIVE));
             *  n.UnionWith(new NumericalValue<int>(-2, Inclusivity.INCLUSIVE, -2, Inclusivity.INCLUSIVE));
             *  n.UnionWith(new NumericalValue<int>(14, Inclusivity.EXCLUSIVE, 15, Inclusivity.EXCLUSIVE));
             *  AssertEquals(n.ToString(), "[-2, -2] U [0, 4) U [6, 10] U (14, 15)");
             *  n.IntersectWith(3, Inclusivity.INCLUSIVE, 6, Inclusivity.INCLUSIVE);
             *  AssertEquals(n.ToString(), "[3, 4) U [6, 6]");
             * }*/

            SyntaxTree tree = CSharpSyntaxTree.ParseText(
                @"using System;
            using System.Collections;
            using System.Linq;
            using System.Text;
 
            namespace HelloWorld
            {
                class ProgramUnderTest
                {

static void Main(string[] args) {}
int f() { return 4; }

private void Test() {
    int j = 3;
    for (int i = 0; i < 10; i = i + 1) {
        if (i > j) { j = i + 1; }
    }
    return;
/*
    int i = 0;
    i = 3;
    int j = f();
    if (j + 3 > 5) {
        i = j;
    } else {
        i = -1;
    }
    return;*/
}
                }
            }");

            var diagnostics = new List <NumericValueDiagnostic>();
            var compilation = CompileCode(tree);
            var model       = compilation.GetSemanticModel(tree);

            foreach (var c in tree.GetRoot().DescendantNodes().OfType <ClassDeclarationSyntax>())
            {
                foreach (var m in c.DescendantNodes().OfType <MethodDeclarationSyntax>())
                {
                    if (m.Identifier.ToString().Equals("Test"))
                    {
                        ControlFlowGraph controlFlowGraph = new ControlFlowGraph(m, model);
                        Console.WriteLine("digraph {0} {{", "Test");
                        HashSet <SyntaxNode> visitedNodes = new HashSet <SyntaxNode>();
                        printGraphViz(controlFlowGraph, controlFlowGraph.GetEntryPoint(), visitedNodes);
                        Console.WriteLine();
                        foreach (var node in visitedNodes)
                        {
                            if (node.GetLocation().ToString().Contains("[0..7)"))
                            {
                                Console.WriteLine("\"{0}\" [color=\"#55AAFF\"];", node.GetLocation().ToString());
                            }
                            Console.WriteLine("\"{0}\" [label=\"{1}\"];", node.GetLocation().ToString(), interpolateLabel(node.ToFullString()));
                        }
                        Console.WriteLine("}");

                        Console.Write("\n\n\n");

                        /*NumericalValueAnalysis numericalValueAnalysis = new NumericalValueAnalysis(controlFlowGraph);*/
                        StringBuilder builder = new StringBuilder();
                        builder.Append("{ \"nodes\": [\n");
                        outputNumericalValueOutput(controlFlowGraph, controlFlowGraph.GetEntryPoint(), new HashSet <SyntaxNode>(), builder);
                        builder.Append("\n] }");

                        Console.WriteLine("Builder: '\n{0}\n'", builder);
                        System.IO.File.WriteAllText("input_code.json", builder.ToString());

                        var process = new System.Diagnostics.Process();
                        process.StartInfo.FileName       = "numerical_value.exe";
                        process.StartInfo.Arguments      = "input_code.json diagnostics.json";
                        process.StartInfo.CreateNoWindow = true;
                        process.Start();
                        process.WaitForExit();

                        diagnostics.AddRange(Newtonsoft.Json.JsonConvert.DeserializeObject <List <NumericValueDiagnostic> >(System.IO.File.ReadAllText("diagnostics.json")));
                        foreach (var diagnostic in diagnostics)
                        {
                            Console.WriteLine("{0}: This is always {1}", diagnostic.location, diagnostic.always_true);
                        }
                    }
                }
            }


            Console.WriteLine();
            Console.Write("Press enter to continue...");
            Console.ReadLine();
        }
Exemple #49
0
        private void AppsCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(AppsCombo.SelectedItem.ToString()))
            {
                return;
            }
            var siteName = SitesCombo.SelectedItem.ToString();
            var appName  = AppsCombo.SelectedItem.ToString();

            using (var serverManager = new ServerManager())
            {
                var app = serverManager.Sites.Where(x => x.Name.Equals(siteName)).FirstOrDefault()
                          .Applications.Where(x => x.Path.Equals(appName)).FirstOrDefault();
                var appPool = serverManager.ApplicationPools.Where(x => x.Name.Equals(app.ApplicationPoolName))
                              .Where(x => x.Name.Equals(app.ApplicationPoolName)).FirstOrDefault();
                string password;
                if (appPool.ProcessModel.IdentityType.Equals(ProcessModelIdentityType.SpecificUser))
                {
                    //カスタムアカウント
                    AppPoolUserText.Text = appPool.ProcessModel.UserName;
                    password             = appPool.ProcessModel.Password;
                }
                else
                {
                    //ビルドインアカウント
                    AppPoolUserText.Text = appPool.ProcessModel.IdentityType.ToString();
                    password             = appPool.ProcessModel.Password;
                }
                var virtialDirectory = app.VirtualDirectories.Where(x => x.Path.Equals("/")).FirstOrDefault().PhysicalPath;
                var testFileName     = $"{typeof(MainForm).Assembly.GetName()}_WriteTest.txt";
                var userName         = appPool.ProcessModel.UserName;
                var domain           = "";
                if (userName.Contains("\\"))
                {
                    domain   = userName.Split("\\".ToCharArray())[0];
                    userName = userName.Split("\\".ToCharArray())[1];
                }
                var passwordSecureString = new System.Security.SecureString();
                foreach (var c in password)
                {
                    passwordSecureString.AppendChar(c);
                }
                try
                {
                    using (var process = new System.Diagnostics.Process())
                    {
                        process.StartInfo.FileName         = "cmd.exe";
                        process.StartInfo.WorkingDirectory = virtialDirectory;
                        process.StartInfo.Arguments        = $"/c echo a>{testFileName}";
                        process.StartInfo.UserName         = userName;
                        process.StartInfo.Password         = passwordSecureString;
                        process.StartInfo.Domain           = domain;
                        process.StartInfo.UseShellExecute  = false;
                        process.StartInfo.CreateNoWindow   = true;
                        process.Start();
                        process.WaitForExit();
                        if (process.ExitCode == 0)
                        {
                            try
                            {
                                process.StartInfo.Arguments = $"/c del {testFileName}";
                                process.Start();
                                process.WaitForExit();
                                if (!File.Exists(Path.Combine(virtialDirectory, testFileName)))
                                {
                                    MessageBox.Show("OK");
                                }
                                else
                                {
                                    MessageBox.Show("実行ユーザーでフォルダーに書き込みはできましたが削除はできませんでした。");
                                    try
                                    {
                                        File.Delete(Path.Combine(virtialDirectory, testFileName));
                                    }
                                    catch (Exception ex)
                                    {
                                        //ここでのエラーは無視します。
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        else
                        {
                            MessageBox.Show("実行ユーザーではフォルダへ書き込みできませんでした。");
                        }
                    }
                }catch (Exception ex)
                {
                    MessageBox.Show("実行ユーザーではフォルダへ書き込みできませんでした。\n\n" + ex.Message);
                }
            }
        }
        private void E2A_RCV_PO_Load(object sender, EventArgs e)
        {
            ClassLibrarySendMail.ClassLibrarySendMail classmail = new ClassLibrarySendMail.ClassLibrarySendMail();
            string MailFrom   = System.Configuration.ConfigurationSettings.AppSettings["MailFrom"].ToString();
            string MailTo     = System.Configuration.ConfigurationSettings.AppSettings["MailTo"].ToString();
            string smtp       = System.Configuration.ConfigurationSettings.AppSettings["SMTP"].ToString();
            string PRE_Naming = System.Configuration.ConfigurationSettings.AppSettings["PRE_Naming"].ToString();
            string strSubject = System.Configuration.ConfigurationSettings.AppSettings["sSubjectmail"].ToString();

            string FtpSync_Inbound  = System.Configuration.ConfigurationSettings.AppSettings["FtpSync_Inbound"].ToString();
            string WorkingDirectory = System.Configuration.ConfigurationSettings.AppSettings["WorkingDirectory"].ToString();

            try
            {
                string   sPath_Source = GetPATH_SOURCE();
                string   sPath_BAK    = GetPATH_BAK();
                string   GetPATHXML   = GetPATH_XML();
                string[] sFiles       = null;
                sFiles = GetPRE_FIX(sPath_Source);
                DataTable dt       = new DataTable();
                DataTable dt_no    = new DataTable();
                DataTable dtResult = new DataTable();

                StringBuilder result              = new StringBuilder();
                StringBuilder result_error        = new StringBuilder();
                string        sPrefix             = System.Configuration.ConfigurationSettings.AppSettings["PRE_FIX"].ToString();
                string        SUPNUM              = System.Configuration.ConfigurationSettings.AppSettings["SUPNUM"].ToString();
                string        CLIENT_ID           = System.Configuration.ConfigurationSettings.AppSettings["CLIENT_ID"].ToString();
                string        WHSE_ID             = System.Configuration.ConfigurationSettings.AppSettings["WHSE_ID"].ToString();
                string        SHIP_TO_JDE_ADDRESS = "";
                string        SALES_ORDER_NO      = "";
                string        SHIP_TO             = "";
                bool          bCheck              = false;
                bool          Count_error         = false;
                int           nCount              = 0;
                int           nCount_line         = 0;

                System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
                pProcess.StartInfo.WorkingDirectory = WorkingDirectory;
                pProcess.StartInfo.FileName         = FtpSync_Inbound;
                pProcess.StartInfo.CreateNoWindow   = true; //not diplay a windows
                pProcess.Start();
                pProcess.WaitForExit();

                string Filename = string.Empty;
                foreach (string filepath in Directory.GetFiles(sPath_Source, sPrefix + "*.txt"))
                {
                    Filename    = string.Empty;
                    bCheck      = true;
                    dt          = new DataTable();
                    dt_no       = new DataTable();
                    dt          = ConvertToDataTable(filepath, out dt_no);
                    Count_error = false;
                    string searchstring = string.Empty;
                    nCount = 0;
                    DataSet ds_result = new DataSet();
                    DataSet ds_mail   = new DataSet();
                    DataRow dr;
                    Filename = Path.GetFileName(filepath);

                    ds_mail = new DataSet();
                    ds_mail = AddCoulumn_reusultMail();
                    result  = new StringBuilder();
                    for (int i = 0; i < dt_no.Rows.Count; i++) // Loop PO
                    {
                        nCount = nCount + 1;
                        if (searchstring != dt_no.Rows[i]["PO_NO"].ToString().Trim())
                        {
                            ds_result = AddCoulumn();
                        }

                        searchstring = dt_no.Rows[i]["PO_NO"].ToString();

                        dtResult = new DataTable();
                        dtResult = dt.Select("PO_NO LIKE '%" + searchstring + "%'").CopyToDataTable();

                        result = new StringBuilder();
                        result.Append(@"<?xml version='1.0' encoding= 'UTF-8'?>");

                        #region RA_INB_IFD
                        result.Append(@"<RA_INB_IFD xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>");

                        #region CTRL_SEG
                        result.Append("<CTRL_SEG>");

                        result.Append("<TRNNAM>RA_TRAN</TRNNAM>");
                        //result.AppendLine();
                        result.Append("<TRNVER>8.3</TRNVER>");
                        //result.AppendLine();
                        result.Append(@"<TRNDTE>" + DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss") + "</TRNDTE>");
                        //result.AppendLine();
                        result.Append("<WHSE_ID>" + WHSE_ID + "</WHSE_ID>");

                        #region HEADER_SEG
                        result.Append("<HEADER_SEG>");

                        result.Append("<SEGNAM>HEADER_SEG</SEGNAM>");
                        result.Append("<TRNTYP>A</TRNTYP>");
                        // PO_TYPE
                        string INVNUM = CLIENT_ID.Substring(0, 5) + "PAHC-" + dtResult.Rows[0]["PO_TYPE"].ToString().Trim() + dtResult.Rows[0]["PO_NO"].ToString().Trim();
                        if (dtResult.Rows[0]["PO_NO"].ToString().Trim() == string.Empty)
                        {
                            Count_error = true;
                            result.Append("<INVNUM/>"); //result_error

                            dr             = ds_result.Tables["ERR"].NewRow();
                            dr["LINE_NO"]  = nCount;
                            dr["PO_NO"]    = searchstring;
                            dr["TAG_NAME"] = "HEADER_SEG-INVNUM";
                            dr["VALUES"]   = "Blank";
                            ds_result.Tables["ERR"].Rows.Add(dr);
                        }
                        else
                        {
                            result.Append("<INVNUM>" + INVNUM + "</INVNUM>");
                        }

                        result.Append("<SUPNUM>" + SUPNUM + "</SUPNUM>");          // Fix ค่อยมาแก่ที่หลัง WAITING_DATA Supplier number. FIX "90000008" ไปก่อนค่อยมาแก้ทีหลัง
                        result.Append("<CLIENT_ID>" + CLIENT_ID + "</CLIENT_ID>"); // Fix ค่อยมาแก่ที่หลัง WAITING_DATA

                        result.Append("<RIMSTS>OPEN</RIMSTS>");
                        result.Append("<INVTYP>P</INVTYP>");
                        result.Append("<INVDTE>" + DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss") + "</INVDTE>");
                        result.Append("<ORGREF/>");
                        result.Append("<SADNUM/>");
                        result.Append("<TPL_SHIPTONO/>");

                        #region <LINE_SEG>
                        nCount_line = 0;
                        for (int j = 0; j < dtResult.Rows.Count; j++)
                        {
                            nCount_line = nCount_line + 1;
                            result.Append("<LINE_SEG>");
                            #region  LINE_SEG Data
                            result.Append("<SEGNAM>LINE_SEG</SEGNAM>");
                            if (dtResult.Rows[j]["LineNumber"].ToString().Trim() == string.Empty)
                            {
                                Count_error = true;
                                result.Append("<INVLIN/>");
                                result.Append("<INVSLN/>");

                                dr             = ds_result.Tables["ERR"].NewRow();
                                dr["LINE_NO"]  = nCount_line;
                                dr["PO_NO"]    = searchstring;
                                dr["TAG_NAME"] = "LINE_SEG-INVLIN";
                                dr["VALUES"]   = "Blank";
                                ds_result.Tables["ERR"].Rows.Add(dr);

                                dr             = ds_result.Tables["ERR"].NewRow();
                                dr["LINE_NO"]  = nCount_line;
                                dr["PO_NO"]    = searchstring;
                                dr["TAG_NAME"] = "LINE_SEG-INVSLN";
                                dr["VALUES"]   = "Blank";
                                ds_result.Tables["ERR"].Rows.Add(dr);
                            }
                            else
                            {
                                string[] words = dtResult.Rows[j]["LineNumber"].ToString().Split('.');
                                result.Append("<INVLIN>" + words[0].ToString() + ".000" + "</INVLIN>");
                                //result.Append("<INVSLN>" + words[1].ToString() + "</INVSLN>");
                                result.Append("<INVSLN>" + dtResult.Rows[j]["LineNumber"].ToString() + "</INVSLN>");
                            }

                            if (dtResult.Rows[j]["Qty"].ToString().Trim() == string.Empty)
                            {
                                result.Append("<EXPQTY>0</EXPQTY>");
                            }
                            else
                            {
                                result.Append("<EXPQTY>" + dtResult.Rows[j]["Qty"].ToString().Trim().Split('.')[0] + "</EXPQTY>");
                            }

                            if (dtResult.Rows[j]["itemNumber"].ToString().Trim() == string.Empty)
                            {
                                Count_error = true;
                                result.Append("<PRTNUM/>");

                                dr             = ds_result.Tables["ERR"].NewRow();
                                dr["LINE_NO"]  = nCount_line;
                                dr["PO_NO"]    = searchstring;
                                dr["TAG_NAME"] = "LINE_SEG-PRTNUM";
                                dr["VALUES"]   = "Blank";
                                ds_result.Tables["ERR"].Rows.Add(dr);
                            }
                            else
                            {
                                result.Append("<PRTNUM>" + dtResult.Rows[j]["itemNumber"].ToString().Trim() + "</PRTNUM>");
                            }

                            result.Append("<LOTNUM/>");
                            result.Append("<RCVSTS>1</RCVSTS>");

                            if (dtResult.Rows[j]["UOM"].ToString().Trim() == string.Empty)
                            {
                                result.Append("<INV_ATTR_STR1/>");
                            }
                            else
                            {
                                result.Append("<INV_ATTR_STR1>" + dtResult.Rows[j]["UOM"].ToString().Trim() + "</INV_ATTR_STR1>");
                            }

                            result.Append("<TPL_LOC/>");
                            result.Append("<TPL_LOTNUM/>");

                            #endregion LINE_SEG Data
                            result.Append("</LINE_SEG>");
                        }
                        #endregion <LINE_SEG>

                        result.Append("</HEADER_SEG>");
                        #endregion HEADER_SEG

                        result.Append("</CTRL_SEG>");
                        #endregion CTRL_SEG

                        result.Append("</RA_INB_IFD>");
                        #endregion RA_INB_IFD


                        if (Count_error) // Error
                        {
                            #region Create file error

                            string sSubject = "Error file Name : " + Filename;
                            classmail.Sendmail(MailTo, smtp, string.Empty, MailFrom, sSubject, ds_result);
                            System.Threading.Thread.Sleep(1000); //searchstring
                            #endregion
                        }
                        else // Not error
                        {
                            #region Create File
                            string       FileName  = PRE_Naming + "_" + searchstring.PadLeft(8, '0') + "_" + DateTime.Now.ToString("yyMMddhhmmss", (new System.Globalization.CultureInfo("en-US"))) + "001";
                            StreamWriter objWriter = new StreamWriter(GetPATHXML + "\\" + FileName + ".xml", false);
                            objWriter.Write(result.ToString());
                            objWriter.Close();
                            System.Threading.Thread.Sleep(1000);

                            //if (bCheck) // Convert XML success  Send mail
                            //{
                            //    string sSubject = PRE_Naming + "_" + "_" + searchstring;
                            //    classmail.Sendmail(MailTo, smtp, "Convert text file to XML success : " + FileName + ".xml", MailFrom, sSubject);
                            //}

                            //string sSubject = PRE_Naming + "_" + searchstring;
                            //classmail.Sendmail(MailTo, smtp, "Convert text file to XML success : " + FileName + ".xml", MailFrom, sSubject);


                            DataRow dr_Mail = ds_mail.Tables["Mail"].NewRow();
                            dr_Mail["LINE_NO"] = nCount;
                            dr_Mail["MESSAGE"] = "Convert text file to XML success : " + FileName + ".xml";
                            ds_mail.Tables["Mail"].Rows.Add(dr_Mail);
                            #endregion
                        }
                    }
                    #region Move File
                    string result_Move;
                    result_Move = Path.GetFileName(filepath);

                    #region send mail success
                    if (ds_mail.Tables.Count != 0)
                    {
                        string sSubject_Mail = strSubject + ": " + result_Move;
                        classmail.Sendmail(MailTo, smtp, string.Empty, MailFrom, sSubject_Mail, ds_mail);
                    }
                    #endregion

                    string sPath_bak = sPath_BAK + "/" + DateTime.Now.ToString("yyyyMMdd");
                    bool   exists    = System.IO.Directory.Exists(sPath_bak);
                    if (!exists)
                    {
                        System.IO.Directory.CreateDirectory(sPath_bak);
                    }

                    System.IO.File.Move(sPath_Source + "/" + result_Move, sPath_bak + "/" + DateTime.Now.ToString("yyyyMMddhhmmss", (new System.Globalization.CultureInfo("en-US"))) + "_" + result_Move);
                    #endregion
                }

                string FtpSync_Outbound = System.Configuration.ConfigurationSettings.AppSettings["FtpSync_Outbound"].ToString();
                System.Diagnostics.Process pProcess_out = new System.Diagnostics.Process();
                pProcess_out.StartInfo.WorkingDirectory = WorkingDirectory;
                pProcess_out.StartInfo.FileName         = FtpSync_Outbound;
                pProcess_out.StartInfo.CreateNoWindow   = true; //not diplay a windows
                pProcess_out.Start();
                pProcess_out.WaitForExit();
            }
            catch (Exception ex)
            {
                classmail.Sendmail(MailTo, smtp, "Error PO :" + ex.Message.ToString(), MailFrom, strSubject);
                return;
            }
            finally
            {
                this.Dispose();
            }
        }
Exemple #51
0
        /// <summary>
        /// Begin processing an audioclip. Phoneme data will be passed along with the input AudioClip to the AutoSyncDataReadyDelegate callback.
        /// </summary>
        /// <param name="clip">AudioClip to be processed.</param>
        /// <param name="languageModel">Name of a language model present in the project.</param>
        /// <param name="dataReadyCallback">Method that will receive the results of the process.</param>
        /// <param name="progressPrefix">Prefix shown on the progress bar.</param>
        /// <param name="enableConversion">If true, audio files will be temporarily converted if possible to maximise compatibility.</param>
        public static void ProcessAudio(AudioClip clip, AutoSyncDataReadyDelegate dataReadyCallback, AutoSyncFailedDelegate failedCallback, string progressPrefix, AutoSyncOptions options)
        {
            if (clip == null)
            {
                return;
            }
            EditorUtility.DisplayCancelableProgressBar(progressPrefix + " - Analysing Audio File", "Please wait, analysing file " + progressPrefix, 0.1f);

            bool   converted = false;
            string audioPath = AssetDatabase.GetAssetPath(clip).Substring("/Assets".Length);

            if (audioPath != null)
            {
                // Get absolute path
                audioPath = Application.dataPath + "/" + audioPath;

                // Check Path
                if (audioPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || Path.GetFileNameWithoutExtension(audioPath).IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    EditorUtility.ClearProgressBar();
                    failedCallback.Invoke("AutoSync failed. Audio path or filename contained invalid characters.");
                    return;
                }

                bool failed = false;
                // Convert to acceptable format
                if (options.useAudioConversion)
                {
                    if (CheckSoX())
                    {
                        EditorUtility.DisplayProgressBar(progressPrefix + " - Converting Audio File", "Please wait, converting file " + progressPrefix, 0.2f);
                        converted = true;

                        string newAudioPath = Application.dataPath + "/" + Path.GetFileNameWithoutExtension(audioPath) + "_temp_converted.wav";
                        string soXPath      = EditorPrefs.GetString("LipSync_SoXPath");

                        // Convert to compatible .wav file
                        string soXArgs = "\"" + audioPath + "\" -c 1 -b 16 -e s -r 16k \"" + newAudioPath + "\"";
                        audioPath = newAudioPath;

                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName              = soXPath;
                        process.StartInfo.Arguments             = soXArgs;
                        process.StartInfo.UseShellExecute       = false;
                        process.StartInfo.CreateNoWindow        = true;
                        process.StartInfo.RedirectStandardError = true;

                        process.ErrorDataReceived += (object e, System.Diagnostics.DataReceivedEventArgs outLine) =>
                        {
                            if (!string.IsNullOrEmpty(outLine.Data))
                            {
                                if (outLine.Data.Contains("FAIL"))
                                {
                                    failed    = true;
                                    converted = false;
                                    process.Close();
                                    failedCallback.Invoke("AutoSync: SoX Conversion Failed: " + outLine.Data);
                                }
                            }
                        };

                        process.Start();
                        process.BeginErrorReadLine();
                        process.WaitForExit(5000);
                    }
                }

                if (!File.Exists(audioPath) || failed)
                {
                    EditorUtility.ClearProgressBar();
                    return;
                }

                // Split into multiple clips if necessary
                if (clip.length > 30 && options.useAudioConversion)
                {
                    multiFileLength = clip.length;
                    multiFileOffset = 0;
                    tempData        = new List <PhonemeMarker> [Mathf.CeilToInt(clip.length / 30)];
                    tempPaths       = new string[Mathf.CeilToInt(clip.length / 30)];

                    // Create paths
                    for (int l = 0; l < Mathf.CeilToInt(clip.length / 30); l++)
                    {
                        tempPaths[l] = Application.dataPath + "/" + Path.GetFileNameWithoutExtension(audioPath) + "_chunk_" + (l + 1) + ".wav";
                    }

                    string soXPath = EditorPrefs.GetString("LipSync_SoXPath");
                    string soXArgs = "\"" + audioPath + "\" \"" + Application.dataPath + "/" + Path.GetFileNameWithoutExtension(audioPath) + "_chunk_%1n.wav\" trim 0 30 : newfile : restart";

                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName              = soXPath;
                    process.StartInfo.Arguments             = soXArgs;
                    process.StartInfo.UseShellExecute       = false;
                    process.StartInfo.CreateNoWindow        = true;
                    process.StartInfo.RedirectStandardError = true;

                    process.ErrorDataReceived += (object e, System.Diagnostics.DataReceivedEventArgs outLine) =>
                    {
                        if (!string.IsNullOrEmpty(outLine.Data))
                        {
                            if (outLine.Data.Contains("FAIL"))
                            {
                                failedCallback.Invoke("AutoSync: SoX Audio Splitting Failed: " + outLine.Data);
                                failed    = true;
                                converted = false;
                                process.Close();
                            }
                        }
                    };

                    process.Start();
                    process.BeginErrorReadLine();
                    process.WaitForExit(5000);

                    if (!File.Exists(audioPath) || failed)
                    {
                        EditorUtility.ClearProgressBar();
                        return;
                    }

                    // Fix paths
                    for (int l = 0; l < tempPaths.Length; l++)
                    {
                        tempPaths[l] = "Assets" + tempPaths[l].Substring(Application.dataPath.Length);
                    }

                    // Delete overlong temporary converted file and prevent autosync from attempting it
                    tempDelegate     = dataReadyCallback;
                    tempFailDelegate = failedCallback;
                    tempClip         = clip;
                    tempOptions      = options;

                    multiFileIndex = 0;

                    if (File.Exists(audioPath))
                    {
                        File.Delete(audioPath);
                        AssetDatabase.Refresh();
                    }

                    ProcessAudio(AssetDatabase.LoadAssetAtPath <AudioClip>(tempPaths[0]), MultiClipCallback, failedCallback, options);
                    return;
                }

                EditorUtility.DisplayProgressBar(progressPrefix + " - Preparing AutoSync", "Please wait, preparing AutoSync.", 0.3f);

                // Load Language Model
                AutoSyncLanguageModel model = AutoSyncLanguageModel.Load(options.languageModel);
                if (model == null)
                {
                    EditorUtility.ClearProgressBar();
                    if (converted)
                    {
                        if (File.Exists(audioPath))
                        {
                            File.Delete(audioPath);
                            AssetDatabase.Refresh();
                        }
                    }
                    failedCallback.Invoke("AutoSync Failed: Language Model was not loaded.");
                    return;
                }
                string basePath = model.GetBasePath();

                List <string> args = new List <string>();
                args.Add("-infile");
                args.Add(audioPath);
                args.Add("-hmm");
                args.Add(basePath + model.hmmDir);
                args.Add("-allphone");
                args.Add(basePath + model.allphoneFile);
                if (options.allphone_ciEnabled)
                {
                    args.Add("-allphone_ci"); args.Add("yes");
                }
                if (options.backtraceEnabled)
                {
                    args.Add("-backtrace"); args.Add("yes");
                }
                args.Add("-time");
                args.Add("yes");
                args.Add("-beam");
                args.Add("1e" + options.beamExponent);
                args.Add("-pbeam");
                args.Add("1e" + options.pbeamExponent);
                args.Add("-lw");
                args.Add(options.lwValue.ToString());

                EditorUtility.DisplayProgressBar(progressPrefix + " - Recognising Phonemes", "Please wait, recognising phonemes.", 0.5f);
                SphinxWrapper.Recognize(args.ToArray());

                ContinuationManager.Add(() => SphinxWrapper.isFinished, () =>
                {
                    if (SphinxWrapper.error != null)
                    {
                        EditorUtility.ClearProgressBar();
                        failedCallback.Invoke("AutoSync Failed.");
                        EditorUtility.DisplayDialog("AutoSync Failed",
                                                    "AutoSync failed. Check the console for more information.", "OK");
                        return;
                    }

                    EditorUtility.DisplayProgressBar(progressPrefix + " - Generating Data", "Please wait, generating LipSync data.", 0.85f);

                    List <PhonemeMarker> data = ParseOutput(
                        SphinxWrapper.result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
                        model,
                        clip
                        );

                    if (options.useAudioConversion)
                    {
                        data = CleanupOutput(data, options.cleanupAggression);
                    }

                    dataReadyCallback.Invoke(
                        clip,
                        data
                        );

                    if (converted)
                    {
                        if (File.Exists(audioPath))
                        {
                            File.Delete(audioPath);
                            AssetDatabase.Refresh();
                        }
                    }
                });
            }
        }
Exemple #52
0
        public static int Start(string app, string args, string workingDirectory = null,
                                Options options = Options.RedirectOutput | Options.RedirectErrors, StringBuilder output = null)
        {
            if (output == null)
            {
                output = new StringBuilder();
            }
            var p = new System.Diagnostics.Process();

            p.StartInfo.FileName        = app;
            p.StartInfo.Arguments       = args;
            p.StartInfo.UseShellExecute = false;
#if WIN
            p.StartInfo.CreateNoWindow   = true;
            p.StartInfo.WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(app);
            int cp = System.Text.Encoding.Default.CodePage;
            if ((options & Options.AllowCP1251) == 0 && cp == 1251)
            {
                cp = 866;
            }
            p.StartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(cp);
            p.StartInfo.StandardErrorEncoding  = System.Text.Encoding.GetEncoding(cp);
#else
            if (workingDirectory != null)
            {
                p.StartInfo.WorkingDirectory = workingDirectory;
            }
            p.StartInfo.StandardOutputEncoding = System.Text.Encoding.Default;
            p.StartInfo.StandardErrorEncoding  = System.Text.Encoding.Default;
            p.StartInfo.EnvironmentVariables.Clear();
            p.StartInfo.EnvironmentVariables.Add("PATH", "/bin:/usr/bin");
#endif
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            var logger = new System.Text.StringBuilder();
            if ((options & Options.RedirectOutput) != 0)
            {
                p.OutputDataReceived += (sender, e) => {
                    lock (logger) {
                        if (e.Data != null)
                        {
                            logger.AppendLine(e.Data);
                            output.AppendLine(e.Data);
                        }
                    }
                };
            }
            if ((options & Options.RedirectErrors) != 0)
            {
                p.ErrorDataReceived += (sender, e) => {
                    lock (logger) {
                        if (e.Data != null)
                        {
                            logger.AppendLine(e.Data);
                            output.AppendLine(e.Data);
                        }
                    }
                };
            }
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            while (!p.HasExited)
            {
                p.WaitForExit(50);
                lock (logger) {
                    if (logger.Length > 0)
                    {
                        Console.Write(logger.ToString());
                        logger.Clear();
                    }
                }
                The.UI.ProcessPendingEvents();
            }
            // WaitForExit WITHOUT timeout argument waits for async output and error streams to finish
            p.WaitForExit();
            var exitCode = p.ExitCode;
            p.Close();
            Console.Write(logger.ToString());
            return(exitCode);
        }
Exemple #53
0
        public AppFinder(Platform p)
        {
            platform = p;
            if (p == Platform.MacOS)
            {
                ValkyrieDebug.Log("Attempting to locate AppId " + AppId() + " on MacOS.");
                System.Diagnostics.ProcessStartInfo processStartInfo;
                System.Diagnostics.Process          process;

                StringBuilder outputBuilder = new StringBuilder();

                processStartInfo = new System.Diagnostics.ProcessStartInfo();
                processStartInfo.CreateNoWindow         = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardInput  = true;
                processStartInfo.UseShellExecute        = false;
                processStartInfo.Arguments = "SPApplicationsDataType -xml";
                processStartInfo.FileName  = "system_profiler";

                process = new System.Diagnostics.Process();
                ValkyrieDebug.Log("Starting system_profiler.");
                process.StartInfo = processStartInfo;
                // enable raising events because Process does not raise events by default
                process.EnableRaisingEvents = true;
                // attach the event handler for OutputDataReceived before starting the process
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler
                                              (
                    delegate(object sender, System.Diagnostics.DataReceivedEventArgs e)
                {
                    // append the new data to the data already read-in
                    outputBuilder.Append(e.Data);
                }
                                              );
                // start the process
                // then begin asynchronously reading the output
                // then wait for the process to exit
                // then cancel asynchronously reading the output
                process.Start();
                process.BeginOutputReadLine();
                process.WaitForExit();
                process.CancelOutputRead();


                string output = outputBuilder.ToString();

                ValkyrieDebug.Log("Looking for: /" + Executable());
                // Quick hack rather than doing XML properly
                int foundAt = output.IndexOf("/" + Executable());
                if (foundAt > 0)
                {
                    ValkyrieDebug.Log("Name Index: " + foundAt);
                    int startPos = output.LastIndexOf("<string>", foundAt) + 8;
                    ValkyrieDebug.Log("Start Index: " + startPos);
                    location = output.Substring(startPos, output.IndexOf("</string>", startPos) - startPos).Trim();
                    ValkyrieDebug.Log("Using location: " + location);
                }
            }
            else if (platform == Platform.Linux)
            {
            }
            else if (platform == Platform.Android)
            {
                obbRoot = Android.GetStorage() + "/Valkyrie/Obb";
                ValkyrieDebug.Log("Obb extraction path: " + obbRoot);
                location = obbRoot + "/assets/bin/Data";
                DeleteObb();
            }
            else // Windows
            {
                // Attempt to get steam install location (current 32/64 level)
                location = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation", "");
                if (location.Equals(""))
                {
                    // If we are on a 64 bit system, need to read the 64bit registry from a 32 bit app (Valkyrie)
                    try
                    {
                        location = RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation");
                    }
                    catch { }
                }
            }

            if (location == null || location.Length == 0)
            {
                string[] args = Environment.GetCommandLineArgs();
                for (int i = 0; i < (args.Length - 1); i++)
                {
                    if (args[i] == "-import")
                    {
                        location = args[i + 1];
                        if (location.Length > 0)
                        {
                            if (location[location.Length - 1] == '/' || location[location.Length - 1] == '\\')
                            {
                                location = location.Substring(0, location.Length - 1);
                            }
                        }
                        ValkyrieDebug.Log("Using import flag location: " + location);
                    }
                }
            }
            exeLocation += location + "/" + Executable();
            location    += DataDirectory();
            ValkyrieDebug.Log("Asset location: " + location);
        }
Exemple #54
0
        public void SelfExtractor_Console()
        {
            string exeFileToCreate = Path.Combine(TopLevelDir, "SelfExtractor_Console.exe");
            string UnpackDirectory = Path.Combine(TopLevelDir, "unpack");
            string ReadmeString    = "Hey there!  This zipfile entry was created directly from a string in application code.";

            int    entriesAdded = 0;
            String filename     = null;

            string Subdir = Path.Combine(TopLevelDir, "A");

            Directory.CreateDirectory(Subdir);
            var checksums = new Dictionary <string, string>();

            int fileCount = _rnd.Next(10) + 10;

            for (int j = 0; j < fileCount; j++)
            {
                filename = Path.Combine(Subdir, String.Format("file{0:D3}.txt", j));
                TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
                entriesAdded++;
                var chk = TestUtilities.ComputeChecksum(filename);
                checksums.Add(filename, TestUtilities.CheckSumToString(chk));
            }

            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(Subdir, Path.GetFileName(Subdir));
                zip.Comment = "This will be embedded into a self-extracting exe";
                MemoryStream ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(ReadmeString));
                zip.AddEntry("Readme.txt", ms1);
                SelfExtractorSaveOptions sfxOptions = new SelfExtractorSaveOptions();
                sfxOptions.Flavor = Ionic.Zip.SelfExtractorFlavor.ConsoleApplication;
                sfxOptions.DefaultExtractDirectory = UnpackDirectory;
                zip.SaveSelfExtractor(exeFileToCreate, sfxOptions);
            }

            var psi = new System.Diagnostics.ProcessStartInfo(exeFileToCreate);

            psi.WorkingDirectory = TopLevelDir;
            psi.UseShellExecute  = false;
            psi.CreateNoWindow   = true;
            System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
            process.WaitForExit();

            // now, compare the output in UnpackDirectory with the original
            string DirToCheck = Path.Combine(UnpackDirectory, "A");

            // verify the checksum of each file matches with its brother
            foreach (string fname in Directory.GetFiles(DirToCheck))
            {
                string originalName = fname.Replace("\\unpack", "");
                if (checksums.ContainsKey(originalName))
                {
                    string expectedCheckString = checksums[originalName];
                    string actualCheckString   = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(fname));
                    Assert.AreEqual <String>(expectedCheckString, actualCheckString, "Unexpected checksum on extracted filesystem file ({0}).", fname);
                }
                else
                {
                    Assert.AreEqual <string>("Readme.txt", originalName);
                }
            }
        }
Exemple #55
0
        public string ShellExecutor(string filename, string arguments)
        {
            System.Diagnostics.Process          process   = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

            startInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow  = true;

            startInfo.FileName  = filename;
            startInfo.Arguments = arguments;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError  = true;

            var stdOutput      = new StringBuilder();
            var stdErrorOutput = new StringBuilder();

            process.StartInfo           = startInfo;
            process.OutputDataReceived += (sender, args) => stdOutput.Append(args.Data + Environment.NewLine);
            process.ErrorDataReceived  += (sender, args) => stdErrorOutput.Append(args.Data + Environment.NewLine);

            try
            {
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("{0} OS error when executing: {1} : {2} {3}", TX_RESULT_FAIL, Format(filename, arguments), e.Message, e));
            }

            if (process.ExitCode == 0)
            {
                if (string.IsNullOrEmpty(stdOutput.ToString().Trim()))
                {
                    return(string.Format("{0} Execution succeed, no output.", TX_RESULT_SUC));
                }
                else
                {
                    return(string.Format("{0} Execution succeed, {1} {2}", TX_RESULT_SUC, Environment.NewLine, stdOutput.ToString()));
                }
            }
            else
            {
                var message = new StringBuilder();
                message.AppendFormat("{0} {1}  finished with exit code = {2} ", TX_RESULT_FAIL, Format(filename, arguments), process.ExitCode);
                message.AppendLine();
                if (!string.IsNullOrEmpty(stdErrorOutput.ToString().Trim()))
                {
                    message.AppendLine("Std error output:");
                    message.AppendLine(stdErrorOutput.ToString());
                }

                if (stdOutput.Length != 0)
                {
                    message.AppendLine("Std output:");
                    message.AppendLine(stdOutput.ToString());
                }

                return(message.ToString());
            }
        }
Exemple #56
0
        public void SelfExtractor_WinForms()
        {
            string[] Passwords = { null, "12345" };
            for (int k = 0; k < Passwords.Length; k++)
            {
                string exeFileToCreate        = Path.Combine(TopLevelDir, String.Format("SelfExtractor_WinForms-{0}.exe", k));
                string DesiredUnpackDirectory = Path.Combine(TopLevelDir, String.Format("unpack{0}", k));

                String filename = null;

                string Subdir = Path.Combine(TopLevelDir, String.Format("A{0}", k));
                Directory.CreateDirectory(Subdir);
                var checksums = new Dictionary <string, string>();

                int fileCount = _rnd.Next(10) + 10;
                for (int j = 0; j < fileCount; j++)
                {
                    filename = Path.Combine(Subdir, String.Format("file{0:D3}.txt", j));
                    TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
                    var chk = TestUtilities.ComputeChecksum(filename);
                    checksums.Add(filename, TestUtilities.CheckSumToString(chk));
                }

                using (ZipFile zip = new ZipFile())
                {
                    zip.Password = Passwords[k];
                    zip.AddDirectory(Subdir, Path.GetFileName(Subdir));
                    zip.Comment = "For testing purposes, please extract to:  " + DesiredUnpackDirectory;
                    if (Passwords[k] != null)
                    {
                        zip.Comment += String.Format("\r\n\r\nThe password for all entries is:  {0}\n", Passwords[k]);
                    }
                    SelfExtractorSaveOptions sfxOptions = new SelfExtractorSaveOptions();
                    sfxOptions.Flavor = Ionic.Zip.SelfExtractorFlavor.WinFormsApplication;
                    sfxOptions.DefaultExtractDirectory = DesiredUnpackDirectory;
                    zip.SaveSelfExtractor(exeFileToCreate, sfxOptions);
                }

                // run the self-extracting EXE we just created
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(exeFileToCreate);
                psi.Arguments        = DesiredUnpackDirectory;
                psi.WorkingDirectory = TopLevelDir;
                psi.UseShellExecute  = false;
                psi.CreateNoWindow   = true;
                System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
                process.WaitForExit();

                // now, compare the output in TargetDirectory with the original
                string DirToCheck = Path.Combine(DesiredUnpackDirectory, String.Format("A{0}", k));
                // verify the checksum of each file matches with its brother
                var fileList = Directory.GetFiles(DirToCheck);
                Assert.AreEqual <Int32>(checksums.Keys.Count, fileList.Length, "Trial {0}: Inconsistent results.", k);

                foreach (string fname in fileList)
                {
                    string expectedCheckString = checksums[fname.Replace(String.Format("\\unpack{0}", k), "")];
                    string actualCheckString   = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(fname));
                    Assert.AreEqual <String>(expectedCheckString, actualCheckString, "Trial {0}: Unexpected checksum on extracted filesystem file ({1}).", k, fname);
                }
            }
        }
Exemple #57
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            bool loaded;

            try
            {
                IntPtr handle = LoadLibrary("Mqrt.dll");

                if (handle == IntPtr.Zero || handle.ToInt32() == 0)
                {
                    loaded = false;
                }
                else
                {
                    loaded = true;

                    FreeLibrary(handle);
                }
            }
            catch
            {
                loaded = false;
            }

            if (!loaded)
            {
                if (Environment.OSVersion.Version.Major < 6) // Windows XP or earlier
                {
                    string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "MSMQAnswer.ans");

                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName))
                    {
                        writer.WriteLine("[Version]");
                        writer.WriteLine("Signature = \"$Windows NT$\"");
                        writer.WriteLine();
                        writer.WriteLine("[Global]");
                        writer.WriteLine("FreshMode = Custom");
                        writer.WriteLine("MaintenanceMode = RemoveAll");
                        writer.WriteLine("UpgradeMode = UpgradeOnly");
                        writer.WriteLine();
                        writer.WriteLine("[Components]");
                        writer.WriteLine("msmq_Core = ON");
                        writer.WriteLine("msmq_LocalStorage = ON");
                    }

                    using (System.Diagnostics.Process p = new System.Diagnostics.Process())
                    {
                        System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo("sysocmgr.exe", "/i:sysoc.inf /u:\"" + fileName + "\"");

                        p.StartInfo = start;

                        p.Start();
                        p.WaitForExit();
                    }
                }
                else // Vista or later
                {
                    using (System.Diagnostics.Process p = new System.Diagnostics.Process())
                    {
                        System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo("ocsetup.exe", "MSMQ-Container;MSMQ-Server /passive");

                        p.StartInfo = start;

                        p.Start();
                        p.WaitForExit();
                    }
                }
            }
        }
Exemple #58
0
        /// <summary>
        /// Determine what port Unity is listening for on Windows
        /// </summary>
        static int GetDebugPort()
        {
#if UNITY_EDITOR_WIN
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "netstat";
            process.StartInfo.Arguments              = "-a -n -o -p TCP";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            string   output = process.StandardOutput.ReadToEnd();
            string[] lines  = output.Split('\n');

            process.WaitForExit();

            foreach (string line in lines)
            {
                string[] tokens = Regex.Split(line, "\\s+");
                if (tokens.Length > 4)
                {
                    int test = -1;
                    int.TryParse(tokens[5], out test);

                    if (test > 1023)
                    {
                        try
                        {
                            var p = System.Diagnostics.Process.GetProcessById(test);
                            if (p.ProcessName == "Unity")
                            {
                                return(test);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
#else
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "lsof";
            process.StartInfo.Arguments              = "-c /^Unity$/ -i 4tcp -a";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            // Not thread safe (yet!)
            string   output = process.StandardOutput.ReadToEnd();
            string[] lines  = output.Split('\n');

            process.WaitForExit();

            foreach (string line in lines)
            {
                int port = -1;
                if (line.StartsWith("Unity"))
                {
                    string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None);
                    if (portions.Length >= 2)
                    {
                        Regex  digitsOnly = new Regex(@"[^\d]");
                        string cleanPort  = digitsOnly.Replace(portions[1], "");
                        if (int.TryParse(cleanPort, out port))
                        {
                            if (port > -1)
                            {
                                return(port);
                            }
                        }
                    }
                }
            }
#endif
            return(-1);
        }
Exemple #59
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Ceen.Httpd.Cli.SubProcess.SpawnRemoteInstance"/> class.
        /// </summary>
        /// <param name="path">The path to the config file</param>
        /// <param name="usessl">If set to <c>true</c> use ssl.</param>
        public SpawnRemoteInstance(string path, bool usessl, IStorageCreator storage, CancellationToken token)
        {
            m_path    = path;
            m_useSSL  = usessl;
            m_storage = storage;

            var prefix = m_hiddenSocketPath ? "\0" : string.Empty;
            var sockid = string.Format("ceen-socket-{0}", new Random().Next().ToString("x8"));

            if (m_hiddenSocketPath)
            {
                m_socketpath = sockid;
            }
            else
            {
                var pathPrefix = Environment.GetEnvironmentVariable("CEEN_SOCKET_FOLDER");
                if (string.IsNullOrWhiteSpace(pathPrefix))
                {
                    pathPrefix = System.IO.Path.GetTempPath();
                }

                m_socketpath = System.IO.Path.GetFullPath(System.IO.Path.Combine(pathPrefix, sockid));
            }

            // Setup a socket server, start the child, and stop the server
            using ((SystemHelper.IsCurrentOSPosix && !m_hiddenSocketPath) ? new DeleteFilesHelper(m_socketpath, m_socketpath + "_fd") : null)
                using (var serveripcsocket = SystemHelper.IsCurrentOSPosix ? new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP) : null)
                    using (var serverfdsocket = SystemHelper.IsCurrentOSPosix ? new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP) : null)
                    {
                        if (SystemHelper.IsCurrentOSPosix)
                        {
                            serveripcsocket.Bind(new SockRock.UnixEndPoint(prefix + m_socketpath));
                            serveripcsocket.Listen(1);

                            serverfdsocket.Bind(new SockRock.UnixEndPoint(prefix + m_socketpath + "_fd"));
                            serverfdsocket.Listen(1);
                        }

                        // Launch the child process
                        m_proc = StartRemoteProcess();

                        // TODO: Consider some multiplexer to allow multiple outputs without mixing the contents
                        var tasks = Task.WhenAll(
                            m_proc.StandardOutput.BaseStream.CopyToAsync(Console.OpenStandardOutput()),
                            m_proc.StandardError.BaseStream.CopyToAsync(Console.OpenStandardError()),
                            Console.OpenStandardInput().CopyToAsync(m_proc.StandardInput.BaseStream)
                            );

                        if (SystemHelper.IsCurrentOSPosix)
                        {
                            var ct = new CancellationTokenSource();

                            // Prepare cancellation after 5 seconds
                            Task.Delay(5000, ct.Token).ContinueWith(_ =>
                            {
                                serveripcsocket.Dispose();
                                serverfdsocket.Dispose();
                            });

                            // Get the first connection
                            m_ipcSocket = serveripcsocket.Accept();
                            m_fdSocket  = serverfdsocket.Accept();

                            // Stop the timer
                            ct.Cancel();
                        }

                        //and then don't listen anymore
                    }


            var ipc = new InterProcessConnection(new NetworkStream(m_ipcSocket, true));

            m_peer = new RPCPeer(
                ipc,
                typeof(IStorageEntry),
                typeof(IStorageCreator)
                );

            // We pass these by reference
            m_peer.TypeSerializer.RegisterSerializationAction(typeof(IStorageEntry), SerializationAction.Reference);
            m_peer.TypeSerializer.RegisterSerializationAction(typeof(IStorageCreator), SerializationAction.Reference);

            // Set up special handling for serializing an endpoint instance
            m_peer.TypeSerializer.RegisterEndPointSerializers();
            m_peer.TypeSerializer.RegisterIPEndPointSerializers();

            m_main = Task.Run(async() => {
                try
                {
                    using (m_fdSocket)
                        using (m_ipcSocket)
                            await ipc.RunMainLoopAsync(false);
                }
                finally
                {
                    Program.DebugConsoleOutput("{0}: Finished main loop, no longer connected to: {1}", System.Diagnostics.Process.GetCurrentProcess().Id, m_proc.Id);
                    m_proc.WaitForExit((int)TimeSpan.FromMinutes(1).TotalMilliseconds);
                    if (!m_proc.HasExited)
                    {
                        m_proc.Kill();
                    }
                    Program.DebugConsoleOutput("{0}: Target now stopped: {1}", System.Diagnostics.Process.GetCurrentProcess().Id, m_proc.Id);
                }
            });

            if (token.CanBeCanceled)
            {
                token.Register(() => this.Stop());
            }

            // Register the storage item, since it is a different concrete class (i.e. not the interface)
            if (storage != null)
            {
                m_peer.TypeSerializer.RegisterSerializationAction(storage.GetType(), SerializationAction.Reference);
                m_peer.RegisterLocalObjectOnRemote(storage, typeof(IStorageCreator)).Wait();
            }

            m_peer.AddAutomaticProxy(typeof(SpawnedServer), typeof(ISpawnedServerProxy));
            m_proxy = m_peer.CreateAsync <ISpawnedServerProxy>(typeof(SpawnedServer), usessl, path, storage).Result;

            if (SystemHelper.IsCurrentOSPosix)
            {
                // Prepare the file descriptor socket
                m_fdSocketTypeSerializer = new TypeSerializer(false, false);
                SetupDescriptorSocket().Wait();
            }
        }
Exemple #60
-2
        //CMD Funtion For Global
        static string CMD(string args)
        {
            string cmdbat = "cd " + Application.StartupPath.Replace("\\", "/") + "\r\n";
            cmdbat += args + " >> out.txt\r\n";
            cmdbat += "exit\r\n";
            File.WriteAllText(Application.StartupPath + "\\cmd.bat", cmdbat);

            System.Diagnostics.Process process = new System.Diagnostics.Process();

            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.Arguments = "";
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = Application.StartupPath;
            startInfo.CreateNoWindow = true;
            startInfo.FileName = Application.StartupPath + "\\cmd.bat";
            process.StartInfo = startInfo;

            process.Start();
            process.WaitForExit();
            System.Threading.Thread.Sleep(5000);
            while (!File.Exists(Application.StartupPath + @"\\out.txt"))
                Thread.Sleep(100);
            string cmdOut = File.ReadAllText(Application.StartupPath + @"\\out.txt");
            File.Delete(Application.StartupPath + "\\cmd.bat");
            return cmdOut;
        }