Ejemplo n.º 1
1
        //-------------------------------------------------------------------//
        //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]);
            }
        }
Ejemplo n.º 2
0
        private static void RunGitCmd(string serviceName, bool advertiseRefs, string workingDir, string gitPath, Stream inStream, Stream outStream)
        {
            var args = serviceName + " --stateless-rpc";
            if (advertiseRefs)
            {
                args += " --advertise-refs";
            }
            args += " \"" + workingDir + "\"";

            var info = new System.Diagnostics.ProcessStartInfo(gitPath, args)
            {
                CreateNoWindow = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                WorkingDirectory = Path.GetDirectoryName(UserConfiguration.Current.Repositories),
            };

            using (var process = System.Diagnostics.Process.Start(info))
            {
                inStream.CopyTo(process.StandardInput.BaseStream);
                process.StandardInput.Write('\0');

                var buffer = new byte[16 * 1024];
                int read;
                while ((read = process.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    outStream.Write(buffer, 0, read);
                    outStream.Flush();
                }

                process.WaitForExit();
            }
        }
Ejemplo n.º 3
0
        private void btnReconfigure_Click(object sender, EventArgs e)
        {
            string strAeXConfigPath = Path.Combine(m_NSInstallPath, "Bin") + "\\AeXConfig.exe";

            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                DataRow drMsiRow = ((DataRowView)row.DataBoundItem).Row;

                if (!drMsiRow.IsNull("InstallLocation") && !drMsiRow.IsNull("ProductConfig") &&
                    !String.IsNullOrEmpty((string)drMsiRow["InstallLocation"]) &&
                    !String.IsNullOrEmpty((string)drMsiRow["ProductConfig"]))
                {
                    // Hardcoded to use <ProductInstallDir>\Config\<ProductConfigFile>
                    string strCommandLine = "/configure \"" + Path.Combine((string)drMsiRow["InstallLocation"], "Config\\" + drMsiRow["ProductConfig"]) + "\"";

                    var psInfo = new System.Diagnostics.ProcessStartInfo(strAeXConfigPath, strCommandLine)
                        {
                            UseShellExecute = false,
                            WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized
                        };
                    System.Diagnostics.Process procUninstall = System.Diagnostics.Process.Start(psInfo);
                    procUninstall.WaitForExit();
                }
            }
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            string exedir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            string sargs = "";
            {
                StringBuilder sbargs = new StringBuilder(1000);
                for (int i = 0; i < args.Length; i++)
                {
                    if (0 != sbargs.Length)
                    {
                        sbargs.Append(' ');
                    }
                    if (-1 != args[i].IndexOf(' '))
                    {
                        sbargs.Append('"');
                        sbargs.Append(args[i].Replace("\"", "\\\""));
                        sbargs.Append('"');
                    }
                    else
                    {
                        sbargs.Append(args[i].Replace("\"", "\\\""));
                    }
                }
                sargs = sbargs.ToString();
            }

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(exedir + @"\dspace.exe", sargs);
            psi.UseShellExecute = false;
            psi.EnvironmentVariables["MDORedir"] = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
            proc.WaitForExit();
            proc.Close();

        }
Ejemplo n.º 5
0
        private static void RunApplication()
        {
            RegistryKey reg = Registry.CurrentUser.CreateSubKey(Program.KEY);
            string filePath = (string)reg.GetValue("FilePath", "");
            string fileArgs = (string)reg.GetValue("FileArgs", "");
            reg.Close();

            if (!File.Exists(filePath))
            {
                return;
            }

            //string filename = "D:\\Development\\WebkitScreenSaverWPF\\WebkitScreenSaverWPF\\bin\\Debug\\WebkitScreenSaverWPF.exe";
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filePath, fileArgs);
            psi.WorkingDirectory = Path.GetDirectoryName(filePath);
            //psi.WorkingDirectory = "D:\\Development\\WebkitScreenSaverWPF\\WebkitScreenSaverWPF\\bin\\Debug\\";
            psi.RedirectStandardOutput = false;
            psi.RedirectStandardError = false;
            psi.RedirectStandardInput = false;
            // psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;

            System.Diagnostics.Process listFiles;

            listFiles = System.Diagnostics.Process.Start(psi);
            //System.IO.StreamReader myOutput = listFiles.StandardOutput;
            listFiles.WaitForExit();

            //if (!listFiles.HasExited)
            //{
            //    listFiles.Kill();
            //}
        }
Ejemplo n.º 6
0
        public void Send(MailMessage msg)
        {
            if (msg == null) throw new ArgumentNullException("msg");

            var sb = new StringBuilder();

            var to = msg.To.FirstOrDefault();
            if (to == null) throw new ArgumentException("to field contains no adress", "msg");
            sb.AppendFormat("mailto:{0}?", to.Address);

            if (!string.IsNullOrEmpty(msg.Subject))
            {
                sb.AppendFormat("subject={0}&", Uri.EscapeUriString(msg.Subject));
            }

            if (!string.IsNullOrEmpty(msg.Body))
            {
                sb.AppendFormat("body={0}&", Uri.EscapeUriString(msg.Body));
            }

            if (msg.CC.Count > 0)
            {
                sb.AppendFormat("cc={0}", string.Join( " ", msg.CC.Select(i => i.Address).ToArray()));
            }

            if (msg.Bcc.Count > 0)
            {
                sb.AppendFormat("bcc={0}", string.Join(" ", msg.Bcc.Select(i => i.Address).ToArray()));
            }

            System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo();
            si.UseShellExecute = true;
            si.FileName = sb.ToString();
            System.Diagnostics.Process.Start(si);
        }
Ejemplo n.º 7
0
 public void OpenLink(string sUrl)
 {
     try
     {
         System.Diagnostics.Process.Start(sUrl);
     }
     catch (Exception exc1)
     {
         // System.ComponentModel.Win32Exception is a known exception that occurs when Firefox is default browser.
         // It actually opens the browser but STILL throws this exception so we can just ignore it.  If not this exception,
         // then attempt to open the URL in IE instead.
         if (exc1.GetType().ToString() != "System.ComponentModel.Win32Exception")
         {
             // sometimes throws exception so we have to just ignore
             // this is a common .NET bug that no one online really has a great reason for so now we just need to try to open
             // the URL using IE if we can.
             try
             {
                 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("IExplore.exe", sUrl);
                 System.Diagnostics.Process.Start(startInfo);
                 startInfo = null;
             }
             catch (Exception exc2)
             {
                 // still nothing we can do so just show the error to the user here.
             }
         }
     }
 }
Ejemplo n.º 8
0
        static string RunTool(string path, params string[] args)
        {
            string args_combined = "";
            foreach (var a in args)
                args_combined += EscapeArgument(a) + " ";
            args_combined.TrimEnd(' ');

            var psi = new System.Diagnostics.ProcessStartInfo();
            psi.Arguments = args_combined;
            psi.FileName = path;
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            var proc = new System.Diagnostics.Process();
            proc.StartInfo = psi;
            proc.Start();

            string output = "";
            while (!proc.StandardOutput.EndOfStream)
            {
                output += proc.StandardOutput.ReadLine();
                // do something with line
            }

            return output;
        }
Ejemplo n.º 9
0
        public static void jarAndScp()
        {
            TextReader r = File.OpenText( "jarAndScp.txt" );
            string dir = r.ReadLine();
            string host = r.ReadLine();
            string path = r.ReadLine();
            string user = r.ReadLine();
            string pass = r.ReadLine();
            r.Close();
            string file = dir+".jar";
            string jarFile = "\""+dir+".jar\"";
            //dir = "\""+dir+"\"";
            System.Diagnostics.ProcessStartInfo p = new System.Diagnostics.ProcessStartInfo(@"D:\Program Files\Java\jdk1.5.0_03\bin\jar.exe");
            p.WorkingDirectory = Directory.GetParent(dir).FullName;
            p.Arguments = "-cf "+jarFile+" "+ Path.GetFileName(dir);
            p.UseShellExecute = false;
            //			p.RedirectStandardOutput = true;
            //			p.RedirectStandardError = true;
            System.Diagnostics.Process.Start(p);
            System.Diagnostics.Process pr = new System.Diagnostics.Process();
            pr.StartInfo = p;
            pr.Start();
            pr.WaitForExit();

            String[] arg = new string[]{file, user+"@"+host+":"+path+Path.GetFileName(file)};
            //Tamir.SharpSsh.Scp.To(file, host, path+Path.GetFileName(file), user, pass);
        }
Ejemplo n.º 10
0
 static void Main(string[] args)
 {
     /**
      * 当前用户是管理员的时候,直接启动应用程序
      * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
      */
     //获得当前登录的Windows用户标示
     System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     //判断当前登录用户是否为管理员
     //如果不是管理员,则以管理员方式运行
     if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         //创建启动对象
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
         startInfo.UseShellExecute = true;
         startInfo.WorkingDirectory = Environment.CurrentDirectory;
         startInfo.FileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
         //设置启动动作,确保以管理员身份运行
         startInfo.Verb = "runas";
         try
         {
             System.Diagnostics.Process.Start(startInfo);
         }
         catch (Exception ex)
         {
             throw ex;
         }
         System.Environment.Exit(0);
     }
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new FrmMain(args));
 }
Ejemplo n.º 11
0
        public void Report(string message, string description, System.Drawing.Bitmap screenshot, Exception exeption)
        {
            try
            {
                System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo();
                var filename = Helper.PathCombine(ProgramFilesx86(), "FogBugz", "Screenshot", "screenshot.exe");
                if (!File.Exists(filename))
                {
                    filename = Helper.PathCombine(ProgramFilesx86(), "Screenshot", "screenshot.exe"); ;
                    if (!File.Exists(filename))
                    {
                        Logging.Log.Error("FogBugz screenshot tool not found. Maybe it's not installed. screenshot.exe neither found in %ProgramFilesx86%\\FogBugz\\Screenshot nor %ProgramFilesx86%\\Screenshot");
                    }
                }

                si.FileName = filename;
                si.Arguments = "/picture";
                System.Diagnostics.Process.Start(si);
            }
            catch (Exception ex)
            {
                Logging.Log.Error(ex.ToString());
                throw;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Executes a shell command synchronously.
        /// </summary>
        /// <param name="command">string command</param>
        /// <returns>string, as output of the command.</returns>
        public void ExecuteCommandSync(object command)
        {
            try {
                // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
                // The following commands are needed to redirect the standard output.
                //This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();

                // Get the output into a string
                string result = proc.StandardOutput.ReadToEnd();

                Console.WriteLine(command);

                // Display the command output.
                Console.WriteLine(result);
            } catch (Exception objException) {
                // Log the exception
            }
        }
Ejemplo n.º 13
0
 internal SystemProcess Exec (string[] cmd, string[] envp, FilePath dir)
 {
     try {
         ProcessStartInfo psi = new ProcessStartInfo ();
         psi.FileName = cmd[0];
         psi.Arguments = string.Join (" ", cmd, 1, cmd.Length - 1);
         if (dir != null) {
             psi.WorkingDirectory = dir.GetPath ();
         }
         psi.UseShellExecute = false;
         psi.RedirectStandardInput = true;
         psi.RedirectStandardError = true;
         psi.RedirectStandardOutput = true;
         psi.CreateNoWindow = true;
         if (envp != null) {
             foreach (string str in envp) {
                 int index = str.IndexOf ('=');
                 psi.EnvironmentVariables[str.Substring (0, index)] = str.Substring (index + 1);
             }
         }
         return SystemProcess.Start (psi);
     } catch (System.ComponentModel.Win32Exception ex) {
         throw new IOException (ex.Message);
     }
 }
Ejemplo n.º 14
0
 public void ShutdownComputer()
 {
     var pi = new System.Diagnostics.ProcessStartInfo();
     pi.FileName = GetPathToShutdownExe();
     pi.Arguments = @"/f /s /t 10";
     System.Diagnostics.Process.Start(pi);
 }
Ejemplo n.º 15
0
 bool runRegisterScript()
 {
     using (System.Diagnostics.Process p = new System.Diagnostics.Process())
     {
         System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(@"ruby");
         info.Arguments = "C:\\Users\\Saulo\\Documents\\RPGVXAce\\projectNOMAD\\Scripts\\register.rb"+name+" "+email+" "+ username + " " + password; // set args
         info.RedirectStandardInput = true;
         info.RedirectStandardOutput = true;
         info.UseShellExecute = false;
         p.StartInfo = info;
         p.Start();
         String output = p.StandardOutput.ReadToEnd();
         // process output
         if (output == "0")
         {
             MessageBox.Show("An error occoured, please try again");
             return false;
         }
         else
         {
             MessageBox.Show("Account Successfully created");
             return true;
         }
     }
 }
Ejemplo n.º 16
0
        private static int Execute(string app, string workdir, string args)
        {
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(app, args);
            psi.CreateNoWindow = true;
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            psi.WorkingDirectory = workdir;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
            psi.UseShellExecute = false;

            System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
            p.WaitForExit(5 * 60 * 1000); //Wait up to five minutes
            if (!p.HasExited)
            {
                try { p.Kill(); }
                catch { }

                Console.WriteLine("Stdout: " + p.StandardOutput.ReadToEnd());
                Console.WriteLine("Stderr: " + p.StandardError.ReadToEnd());

                throw new Exception(string.Format("Application {0} hung", app));
            }

            Console.WriteLine();
            Console.WriteLine(p.StandardOutput.ReadToEnd());
            Console.WriteLine(p.StandardError.ReadToEnd());
            Console.WriteLine();

            return p.ExitCode;
        }
Ejemplo n.º 17
0
 private void bSaveAndStart_Click(object sender, EventArgs e)
 {
     WriteConfig();
     System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("GPSTrackingServer.exe");
     System.Diagnostics.Process.Start(psi);
     Environment.Exit(0);
 }
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
0
        // http://www.codeproject.com/Articles/25983/How-to-Execute-a-Command-in-C
        /// <summary>
        /// Executes a shell command synchronously.
        /// </summary>
        /// <param name="command">string command</param>
        /// <returns>string, as output of the command</returns>
        private static string ExecuteCommandSync( string command )
        {
            try {
                // create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows,
                // and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo =
            //new System.Diagnostics.ProcessStartInfo( "cmd", "/c " + command );
                    new System.Diagnostics.ProcessStartInfo( "cmd", command );

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                //procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();

                string s = proc.StandardOutput.ReadToEnd();
                Console.WriteLine( "Result: " );
                Console.WriteLine( s );
                proc.WaitForExit();
                // Get the output into a string
                return s;
            } catch ( Exception objException ) {
                // Log the exception
                Console.WriteLine( objException.Message );
                return null;
            }
        }
Ejemplo n.º 20
0
        public static bool OpenInternetBrowser(string url)
        {
#if XB1
			return true;
#else
			try
            {
                try
                {
                    System.Diagnostics.Process.Start(url);
                }
                // System.ComponentModel.Win32Exception is a known exception that occurs when Firefox is default browser.  
                // It actually opens the browser but STILL throws this exception so we can just ignore it.  If not this exception,
                // then attempt to open the URL in IE instead.
                catch (System.ComponentModel.Win32Exception)
                {
                    // sometimes throws exception so we have to just ignore
                    // this is a common .NET bug that no one online really has a great reason for so now we just need to try to open
                    // the URL using IE if we can.
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(IE_PROCESS, url);
                    System.Diagnostics.Process.Start(startInfo);
                    startInfo = null;
                }
            }
            catch (Exception)
            {
                // oper browser failed
                return false;
            }
            return true;
#endif
		}
Ejemplo n.º 21
0
        public formMain()
        {
            InitializeComponent();

            proInfo = new System.Diagnostics.ProcessStartInfo();
            pro = new System.Diagnostics.Process();
        }
    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);
      }
    }
Ejemplo n.º 23
0
        public static bool Handle(int instanceID, int line)
        {
            string path = AssetDatabase.GetAssetPath(EditorUtility.InstanceIDToObject(instanceID));
            string name = Application.dataPath + "/" + path.Replace("Assets/", "");

            if (name.EndsWith(".shader"))
            {
                string program = "";
                if (EditorPrefs.HasKey("ShaderEditor"))
                    program = EditorPrefs.GetString("ShaderEditor");

                if (System.IO.File.Exists(program))
                {
                    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 = program;
                        startInfo.Arguments = name;
                        process.StartInfo = startInfo;

                        return process.Start();
                    }
                    catch
                    {
                        return false;
                    }
                }
            }

            return false;
        }
Ejemplo n.º 24
0
 // Method that runs update process
 public static void processUpdateRequest()
 {
     if(Common.Raffle != null && Common.Raffle.raffleIsActive())
     {
         Console.WriteLine("Update request placed in command queue.");
         return;
     }
     UpdateDetails details = WebCalls.downloadUpdateDetails().Result;
     if (!details.RequestSuccessful || !details.UpdateAvailable)
     {
         Console.WriteLine("RequestSuccessful: " + details.RequestSuccessful + ", UpdateAvailable: " + details.UpdateAvailable);
         return;
     }
     Console.WriteLine("Downloading new bot and updater...");
     WebCalls.downloadFile(details.DownloadLocation, "bot.exe");
     Console.WriteLine("new bot downloaded");
     WebCalls.downloadFile(details.UpdaterLocation, "updater.exe");
     Console.WriteLine("Finished! Starting updater and exiting.");
     System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
     pInfo.FileName = "updater.exe";
     pInfo.ErrorDialog = true;
     pInfo.UseShellExecute = false;
     pInfo.RedirectStandardOutput = true;
     pInfo.RedirectStandardError = true;
     pInfo.WorkingDirectory = Path.GetDirectoryName("updater.exe");
     System.Diagnostics.Process.Start(pInfo);
     Environment.Exit(1);
 }
Ejemplo n.º 25
0
        public MainWindow()
        {
            _startedprocess = null;

            InitializeComponent();

            try
            {
                System.IO.StreamReader ipfile = new System.IO.StreamReader("patchip.cfg");
                string ipString = ipfile.ReadToEnd();
                ipfile.Close();

                System.Diagnostics.ProcessStartInfo psi =
                    new System.Diagnostics.ProcessStartInfo(@"patchingclient");
                psi.Arguments = " --IcePatch2.Remove=0 --IcePatch2.Endpoints=\"tcp -h "+ipString+" -p 10000\" .";
                psi.CreateNoWindow = true;
                psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                psi.UseShellExecute = true;
                _startedprocess = System.Diagnostics.Process.Start(psi);
            }
            catch (Exception ex)
            {
                labelInfo.Text = "Error during patching: " + ex.Message;
            }
        }
Ejemplo n.º 26
0
        public void RunGitCmd(string serviceName, bool advertiseRefs, string workingDir, Stream inStream, Stream outStream)
        {
            var args = serviceName + " --stateless-rpc";
            if (advertiseRefs)
                args += " --advertise-refs";
            args += " \"" + workingDir + "\"";

            var info = new System.Diagnostics.ProcessStartInfo(System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["GitPath"]), args)
            {
                CreateNoWindow = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                WorkingDirectory = Path.GetDirectoryName(UserConfiguration.Current.Repositories),
            };

            using (var process = System.Diagnostics.Process.Start(info))
            {
                inStream.CopyTo(process.StandardInput.BaseStream);
                process.StandardInput.Write('\0');
                process.StandardOutput.BaseStream.CopyTo(outStream);

                process.WaitForExit();
            }
        }
Ejemplo n.º 27
0
    static public bool ExecuteControlPanelItem(String cmd) {
      // Discard control panel items
      String cpName = @"::{26EE0668-A00A-44D7-9371-BEB064C98683}";

      int cpIndex = cmd.IndexOf(cpName);

      if (cpIndex != 0) return false;

      //if (cmd.IndexOf(@"\::", cpIndex + cpName.Length) <= 0 && cmd != cpName) return false;
      if (!cmd.StartsWith(cpName)) return false;

      String explorerPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
      explorerPath += @"\Explorer.exe";

      cmd = cmd.Replace("Fonts", "::{BD84B380-8CA2-1069-AB1D-08000948F534}");

      System.Diagnostics.ProcessStartInfo procStartInfo =
          new System.Diagnostics.ProcessStartInfo(explorerPath, cmd);

      // Now we create a process, assign its ProcessStartInfo and start it
      System.Diagnostics.Process proc = new System.Diagnostics.Process();
      proc.StartInfo = procStartInfo;

      proc.Start();
      return true;
    }
Ejemplo n.º 28
0
 private void button2_Click(object sender, EventArgs e)
 {
     System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
     startinfo.FileName = this.sender.getSteamCmd();
     if (appId.Text == "")
     {
         MessageBox.Show("Please enter an app id", "Invalid App ID", MessageBoxButtons.OK);
         return;
     }
     startinfo.Arguments = String.Format("+login anonymous +force_install_dir {0} +app_update {1} validate +quit",
         new System.IO.FileInfo(this.sender.getSelectedMon().getExe()).Directory.FullName, appId.Text);
     System.Diagnostics.Process proc = new System.Diagnostics.Process();
     proc.StartInfo = startinfo;
     try
     {
         proc.Start();
     }
     catch (Exception ex)
     {
         if (ex.GetType() == typeof(System.ComponentModel.Win32Exception))
         {
             MessageBox.Show("The path to the steamcmd executable was invalid", "SteamCMD not foud");
             return;
         }
         else
         {
             throw;
         }
     }
     this.Dispose();
 }
Ejemplo n.º 29
0
        /// <summary>
        /// 截取视频缩略图
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="imgFile"></param>
        /// <returns></returns>
        public static bool CatchImg(string fileName, string imgFile)
        {
            const string ffmpeg = "ffmpeg.exe";
            //string flvImg = imgFile + ".jpg";
            string flvImgSize = "640*480";
            MediaPlayerFactory m_factory = new MediaPlayerFactory();
            IVideoPlayer m_player = m_factory.CreatePlayer<IVideoPlayer>();
            IMediaFromFile m_media = m_factory.CreateMedia<IMediaFromFile>(fileName);
            m_player.Open(m_media);
            m_media.Parse(true);

            System.Drawing.Size size = m_player.GetVideoSize(0);
            if (!size.IsEmpty)
                flvImgSize = size.Width.ToString() + "*" + size.Height.ToString();
            //m_player.TakeSnapShot(1, @"C:");
            System.Diagnostics.ProcessStartInfo ImgstartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            ImgstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            ImgstartInfo.Arguments = "   -i   " + fileName + "  -y  -f  image2   -ss 2 -vframes 1  -s   " + flvImgSize +
                                     "   " + imgFile;
            try
            {
                System.Diagnostics.Process.Start(ImgstartInfo);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }
Ejemplo n.º 30
0
        private static async Task parseJAVA(IOwinContext context, FormData formdata)
        {
            try
            {
                string dictname  = null;
                string classname = null;
                var    file      = formdata.mapFiles["file"];
                var    code      = System.Text.Encoding.UTF8.GetString(file);

                //准备临时目录
                {
                    Random i   = new Random();
                    var    num = i.Next();

                    while (System.IO.Directory.Exists("tmp_" + num.ToString("X08")))
                    {
                        num++;
                    }
                    dictname = "tmp_" + num.ToString("X08");

                    var fc     = code.IndexOf("class");
                    int ibegin = -1;

                    for (int ib = fc + 6; ib < fc + 100; ib++)
                    {
                        if (ibegin < 0)
                        {
                            if (code[ib] == ' ')
                            {
                                continue;
                            }
                            else
                            {
                                ibegin = ib;
                            }
                        }
                        else
                        {
                            if (code[ib] == ' ' || code[ib] == '}')
                            {
                                classname = code.Substring(ibegin, ib - ibegin);
                                break;
                            }
                        }
                    }
                }
                System.IO.Directory.CreateDirectory(dictname);
                string filename = System.IO.Path.Combine(dictname, classname + ".java");
                System.IO.File.WriteAllText(filename, code);
                string jarfile = "AntShares.SmartContract.Framework.jar";
                System.IO.File.Copy(jarfile, System.IO.Path.Combine(dictname, jarfile));

                //编译
                try
                {
                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                    info.FileName               = "cmd.exe";
                    info.UseShellExecute        = false;
                    info.RedirectStandardOutput = true;
                    info.RedirectStandardInput  = true;
                    info.RedirectStandardError  = true;
                    info.WorkingDirectory       = dictname;
                    var proc = System.Diagnostics.Process.Start(info);
                    proc.StandardInput.WriteLine("javac -cp " + jarfile + " " + classname + ".java");
                    proc.StandardInput.WriteLine("exit");


                    string        back      = proc.StandardError.ReadToEnd();
                    string        inerror   = "";
                    int           line      = -1;
                    string        tag       = "";
                    List <string> outline   = new List <string>();
                    List <int>    errorline = new List <int>();
                    List <string> errorTag  = new List <string>();
                    string[]      lines     = back.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    for (var i = 0; i < lines.Length; i++)
                    {
                        if (inerror == "")
                        {
                            var mm = lines[i].Split(':');
                            if (mm.Length > 3)
                            {
                                line     = int.Parse(mm[1]);
                                inerror += mm[3];
                                tag      = mm[2];
                            }
                        }
                        else
                        {
                            if (lines[i].IndexOf("^") >= 0)
                            {
                                outline.Add(inerror);
                                errorline.Add(line);
                                errorTag.Add(tag);
                                inerror = "";
                            }
                            else
                            {
                                inerror += "\n" + lines[i];
                            }
                        }
                    }

                    if (outline.Count == 0)
                    {
                        //succ
                    }
                    else
                    {
                        MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                        json["tag"] = new MyJson.JsonNode_ValueNumber(-3);
                        json["msg"] = new MyJson.JsonNode_ValueString("compile fail.");

                        MyJson.JsonNode_Array errs = new MyJson.JsonNode_Array();
                        json["errors"] = errs;
                        for (var i = 0; i < outline.Count; i++)
                        {
                            MyJson.JsonNode_Object errtag = new MyJson.JsonNode_Object();
                            errs.Add(errtag);
                            errtag.SetDictValue("msg", outline[i]);
                            errtag.SetDictValue("line", errorline[i]);
                            errtag.SetDictValue("tag", errorTag[i]);
                            //errtag.SetDictValue("col", r.Errors[i].Column);
                        }
                        await context.Response.WriteAsync(json.ToString());

                        return;
                    }
                }
                catch (Exception err)
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("unknown fail on comp.");
                    json["err"] = new MyJson.JsonNode_ValueString(err.ToString());
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }

                //conv
                try
                {
                    JavaModule module = new JavaModule();
                    module.LoadJar(jarfile);
                    module.LoadClass(System.IO.Path.Combine(dictname, classname + ".class"));
                    var logjson = new Log2Json();
                    var conv    = new AntShares.Compiler.JVM.ModuleConverter(logjson);
                    var bs      = conv.Convert(module).Build();
                    if (bs != null)
                    {
                        MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                        json["tag"] = new MyJson.JsonNode_ValueNumber(0);
                        StringBuilder sb     = new StringBuilder();
                        StringBuilder sb2    = new StringBuilder();
                        var           hash   = System.Security.Cryptography.SHA256.Create();
                        var           hashbs = hash.ComputeHash(bs);
                        foreach (var b in bs)
                        {
                            sb.Append(b.ToString("X02"));
                        }
                        foreach (var b in hashbs)
                        {
                            sb2.Append(b.ToString("X02"));
                        }
                        json["hex"]  = new MyJson.JsonNode_ValueString(sb.ToString());
                        json["hash"] = new MyJson.JsonNode_ValueString(sb2.ToString());

                        await context.Response.WriteAsync(json.ToString());

                        return;
                    }


                    else
                    {
                        {
                            MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                            json["tag"]  = new MyJson.JsonNode_ValueNumber(-4);
                            json["msg"]  = new MyJson.JsonNode_ValueString("compile fail.");
                            json["info"] = logjson.array;
                            await context.Response.WriteAsync(json.ToString());

                            return;
                        }
                    }
                }
                catch (Exception err)
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("unknown fail on conv.");
                    json["err"] = new MyJson.JsonNode_ValueString(err.ToString());
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }
            }
            catch
            {
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("parse fail.");
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Plays the selected node.
        /// If it is an episode it will set it as lastWatched.
        /// Refreshes nodes. (because of possible lastWatched change)
        /// </summary>
        public void playSelectedNode()
        {
            if (nodeListView.SelectedIndices.Count > 0)
            {
                // Increment the watched list by one
                nodes[nodeListView.SelectedIndices[0]].TimesPlayed++;
                db.incrementPlayed(nodes[nodeListView.SelectedIndices[0]]);
                // Mark as lastPlayed
                if (nodes[nodeListView.SelectedIndices[0]].IsEpisode)
                {
                    db.lastWatched(nodes[nodeListView.SelectedIndices[0]]);
                    nodes[nodeListView.SelectedIndices[0]].Episode.LastWatched = true;
                }

                // Check if what is selected can be played just incase something got through
                if (nodes[nodeListView.SelectedIndices[0]].IsYouTube ||
                    nodes[nodeListView.SelectedIndices[0]].IsHulu ||
                    nodes[nodeListView.SelectedIndices[0]].IsFile)
                {
                    // If YouTube video
                    if (nodes[nodeListView.SelectedIndices[0]].IsYouTube)
                    {
                        // If set to use the WebPlayer use it else use default web browser
                        if ((Properties.Settings.Default.YouTubeWebPlayer == true) &&
                            (nodes[nodeListView.SelectedIndices[0]].embedded != null))
                        {
                            this.WindowState = FormWindowState.Minimized;
                            nodes[nodeListView.SelectedIndices[0]].Play();
                        }
                        else
                        {
                            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(nodes[nodeListView.SelectedIndices[0]].Url);
                            System.Diagnostics.Process.Start(psi);
                        }
                    }

                    // If Hulu video
                    if (nodes[nodeListView.SelectedIndices[0]].IsHulu)
                    {
                        // If set to use the WebPlayer use it else use default web browser
                        if ((Properties.Settings.Default.HuluWebPlayer == true) &&
                            (nodes[nodeListView.SelectedIndices[0]].embedded != null))
                        {
                            this.WindowState = FormWindowState.Minimized;
                            nodes[nodeListView.SelectedIndices[0]].Play();
                        }
                        else
                        {
                            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(nodes[nodeListView.SelectedIndices[0]].Url);
                            System.Diagnostics.Process.Start(psi);
                        }
                    }

                    // Plays files using whatever program has been set as a default for that file format.
                    // This should be the most user friendly way but maybe could be setup to always run
                    //  a specific application to play it. The benefits from this I dont know.
                    if (nodes[nodeListView.SelectedIndices[0]].IsFile)
                    {
                        this.WindowState = FormWindowState.Minimized;
                        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(nodes[nodeListView.SelectedIndices[0]].File.Uri.LocalPath);
                        System.Diagnostics.Process          tempPlayer;
                        tempPlayer = System.Diagnostics.Process.Start(psi);
                        // Look into this a bit more as it makes teh minimize look odd
                        // WMP doesn't do this right
                        if (tempPlayer != null)
                        {
                            tempPlayer.WaitForExit();
                        }
                    }
                    this.WindowState = FormWindowState.Normal;
                    db.refreshNodes(ref nodes);
                    loadNodes();
                }

                // If there is a search dont do a normal refresh.
                if (nodeSearchTextBox.Text != "")
                {
                    db.refreshNodes(ref nodes);
                    loadNodes();
                }
                else
                {
                    nodeSearchAllCheckBox_CheckedChanged(null, null);
                }
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 执行压缩
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExecute_Click(object sender, EventArgs e)
        {
            try
            {
                panelSetting.Enabled    = false;
                btnExecute.Enabled      = false;
                btnStopCompress.Enabled = true;
                IsCompressing           = true;
                IsCancel = false;

                Int32?totalCount = 1;

                // 构建process信息
                System.Diagnostics.ProcessStartInfo psinfo = new System.Diagnostics.ProcessStartInfo();
                psinfo.FileName    = rbtUse7Z.Checked ? txt7ZCommandLine.Text : txtWinRARCommandLine.Text;
                psinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

                // 获取要压缩的文件夹下的文件和目录信息
                DirectoryInfo   basefolder = new DirectoryInfo(txtTargetFolder.Text);
                FileInfo[]      files      = basefolder.GetFiles();
                DirectoryInfo[] dirs       = basefolder.GetDirectories();
                if (chkIsParentFolder.Checked)
                {
                    totalCount = files?.Length + dirs?.Length;
                }

                // 设置进度条相关参数
                progressBar1.Maximum = (Int32)totalCount;
                progressBar1.Step    = 1;
                progressBar1.Style   = ProgressBarStyle.Continuous;

                Int32 currentIndex = 0;
                Task  t            = new Task(() => {
                    if (!chkIsParentFolder.Checked)
                    {
                        // 将所选择的目录压缩为一个单文件
                        psinfo.Arguments = GenerateArguements(basefolder.FullName, basefolder.Name, basefolder.FullName);
#if DEBUG
                        WriteConsole(psinfo.FileName);
                        WriteConsole(psinfo.Arguments);
#endif

                        currentIndex += 1;
                        this.BeginInvoke(new Action(() => {
                            progressBar1.PerformStep();
                            lblState.Text = String.Format("正在处理第【{0}】个/共【{1}】个", currentIndex, totalCount);
                        }));

                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(psinfo);
                        p.WaitForExit();
                        if (p.ExitCode != 0)
                        {
                            WriteConsole("目录【" + basefolder.FullName + "】压缩失败,退出代码:" + p.ExitCode.ToString());
                        }
                        else
                        {
                            WriteConsole("目录【" + basefolder.FullName + "】压缩完成!");
                        }
                    }
                    else
                    {
                        foreach (FileInfo file in files)
                        {
                            if (IsCancel)
                            {
                                WriteConsole("用户已取消操作!");
                                break;
                            }
                            psinfo.Arguments = GenerateArguements(file.DirectoryName, System.IO.Path.GetFileNameWithoutExtension(file.Name), file.FullName);
#if DEBUG
                            WriteConsole(psinfo.FileName);
                            WriteConsole(psinfo.Arguments);
#endif

                            currentIndex += 1;
                            this.BeginInvoke(new Action(() => {
                                progressBar1.PerformStep();
                                lblState.Text = String.Format("正在处理第【{0}】个/共【{1}】个", currentIndex, totalCount);
                            }));

                            System.Diagnostics.Process p = System.Diagnostics.Process.Start(psinfo);
                            p.WaitForExit();
                            if (p.ExitCode != 0)
                            {
                                WriteConsole("文件【" + file.FullName + "】压缩失败,退出代码:" + p.ExitCode.ToString());
                            }
                            else
                            {
                                WriteConsole("文件【" + file.FullName + "】压缩完成!");
                            }
                        }
                        // 压缩目录
                        foreach (DirectoryInfo dir in dirs)
                        {
                            if (IsCancel)
                            {
                                WriteConsole("用户已取消操作!");
                                break;
                            }
                            psinfo.Arguments = GenerateArguements(dir.Parent.FullName, dir.Name, dir.FullName);
#if DEBUG
                            WriteConsole(psinfo.FileName);
                            WriteConsole(psinfo.Arguments);
#endif

                            currentIndex += 1;
                            this.BeginInvoke(new Action(() => {
                                progressBar1.PerformStep();
                                lblState.Text = String.Format("正在处理第【{0}】个/共【{1}】个", currentIndex, totalCount);
                            }));

                            System.Diagnostics.Process p = System.Diagnostics.Process.Start(psinfo);
                            p.WaitForExit();
                            if (p.ExitCode != 0)
                            {
                                WriteConsole("目录【" + dir.FullName + "】压缩失败,退出代码:" + p.ExitCode.ToString());
                            }
                            else
                            {
                                WriteConsole("目录【" + dir.FullName + "】压缩完成!");
                            }
                        }
                    }
                });
                t.Start();
                t.ContinueWith((x) => {
                    WriteConsole(String.Format("执行结束!!IsCompleted:{0},IsCanceled:{1},IsFaulted:{2}", x.IsCompleted, x.IsCanceled, x.IsFaulted));
                    IsCompressing           = false;
                    panelSetting.Enabled    = true;
                    btnExecute.Enabled      = true;
                    btnStopCompress.Enabled = false;

                    progressBar1.Value = 0;
                    lblState.Text      = "就绪!";
                });
            }
            catch (Exception ex)
            {
                WriteConsole("压缩异常:" + ex.Message);

                IsCompressing           = false;
                panelSetting.Enabled    = true;
                btnExecute.Enabled      = true;
                btnStopCompress.Enabled = false;

                progressBar1.Value = 0;
                lblState.Text      = "就绪!";
            }
            finally
            {
            }
        }
Ejemplo n.º 33
0
        private void getCheckoutFiles(string searchPath)
        {
            string tmpPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            tmpPath += @"\Temp\nROfiles.txt";
            logTxBox.SelectionColor = this.logTxBox.ForeColor;
            logTxBox.SelectedText   = "TempFilePath: \"" + tmpPath + "\"\r\n";
            System.Diagnostics.Process          cmdProc     = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo cmdProcInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            //cmdProcInfo.UseShellExecute = false;
            //cmdProcInfo.CreateNoWindow = true;
            //cmdProcInfo.RedirectStandardOutput = true;
            //to run any dos command use '/c' before the command and its arguments
            //cmdProcInfo.Arguments = @"/c dir /b /A:-R-H-D-S /S " + searchPath;
            cmdProcInfo.Arguments = @"/c dir /b /A:-R-H-D-S /S " + searchPath + "> " + tmpPath;
            cmdProc.StartInfo     = cmdProcInfo;
            cmdProc.Start();
            //StreamReader cmdProcSR = cmdProc.StandardOutput;
            int elapsedTime = 0;

            while (!cmdProc.HasExited)
            {
                this.searchProgBar.PerformStep();
                this.searchProgBar.Invalidate();
                this.searchProgBar.Refresh();
                this.Refresh();
                if (elapsedTime > (1000 * 60))
                {
                    cmdProc.Kill();
                }

                System.Threading.Thread.Sleep(5);
                elapsedTime += 5;
                if (this.searchProgBar.Value == this.searchProgBar.Maximum)
                {
                    this.searchProgBar.Value = 0;
                }
            }

            if (cmdProc != null)
            {
                cmdProc.Close();
            }

            System.Collections.ArrayList mList = new System.Collections.ArrayList();
            if (System.IO.File.Exists(tmpPath))
            {
                StreamReader cmdProcSR = new StreamReader(tmpPath);
                string       line;
                while ((line = cmdProcSR.ReadLine()) != null)
                {
                    if (isDBfile(line))
                    {
                        this.checkedOutFiless.Add(line);
                    }
                }
                cmdProcSR.Close();
            }
            else
            {
                logTxBox.SelectionColor = this.logTxBox.ForeColor;
                logTxBox.SelectedText   = "60 sec has elapsed before search is completed\r\n";
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Prints a set of claims using a given database connection
        /// </summary>
        /// <param name="toPrint"></param>
        /// <param name="dbConnection"></param>
        public static void PrintClaims(List <claim> toPrint, SqlConnection dbConnection)
        {
            NHDG.NHDGCommon.Claims.ClaimBatch    cb = new NHDG.NHDGCommon.Claims.ClaimBatch();
            System.Data.SqlClient.SqlTransaction trans;
            string _errorClaims = string.Empty;

            try
            {
                trans = dbConnection.BeginTransaction();
            }
            catch
            {
                MessageBox.Show("Could not connect to Dentrix to print claim.");
                return;
            }


            try
            {
                string _xmlPath = GetFileName(".xml", Application.StartupPath + "\\Processed XML\\Temp\\");
                string _pdfPath = GetFileName(".pdf", Application.StartupPath + "\\Claims\\");

                foreach (claim c in toPrint)
                {
                    NHDG.NHDGCommon.Claims.Claim aClaim;
                    try
                    {
                        if (C_DentalClaimTracker.Properties.Settings.Default.ShowPaymentLineOnSecondary)
                        {
                            aClaim = new NHDG.NHDGCommon.Claims.Claim(c, trans, false, true);
                        }
                        else
                        {
                            aClaim = new NHDG.NHDGCommon.Claims.Claim(c, trans, true, true);
                        }

                        CheckForEligibilityRestrictions(c, aClaim);

                        // Special code for teeth
                        aClaim.PutToothStringInTooth();
                        aClaim.CleanAddresses();
                        cb.Claims.Add(aClaim);
                    }
                    catch (Exception err)
                    {
                        string    errDisplay = err.Message;
                        Exception e          = err.InnerException;
                        while (e != null)
                        {
                            errDisplay += "\n)" + e.Message;
                            e           = e.InnerException;
                        }

                        _errorClaims = "\n" + c.created_on.Value.ToShortDateString() + ", " +
                                       c.PatientLastNameCommaFirst + "; " + c.LinkedCompany.name + "\nSystem error:" + errDisplay;
                    }
                }

                if (cb.Claims.Count > 0)
                {
                    NHDG.NHDGCommon.Utilities.SerializeToFile(cb, typeof(NHDG.NHDGCommon.Claims.ClaimBatch), _xmlPath);

                    try
                    {
                        NHDG.ProphySplitter.ProphySplitter ps = new NHDG.ProphySplitter.ProphySplitter();
                        ps.PerformSplit(_xmlPath);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show("An error occurred splitting the procedures (for example, splitting D1110 into " +
                                        "multiple procedures. Please report the following error to a system administrator: \n\n" + err.Message, "Error Splitting");
                    }

                    try
                    {
                        ProcedureCombiner pc = new ProcedureCombiner();
                        pc.Combine(_xmlPath);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show("An error occurred combining the procedures." +
                                        " Please report the following error to a system administrator: \n\n" + err.Message, "Error Combining");
                    }

                    string workingDir  = Application.StartupPath + "\\ada-form\\";
                    string fileToStart = "ruby";

                    string arguments = "ada_report.rb \"" +
                                       _xmlPath + "\" \"" + _pdfPath + "\"";

                    Clipboard.SetText(fileToStart + " " + arguments);
                    System.Diagnostics.ProcessStartInfo pi = new System.Diagnostics.ProcessStartInfo(fileToStart, arguments);
                    pi.WorkingDirectory = workingDir;
                    pi.UseShellExecute  = true;

                    System.Diagnostics.Process p = System.Diagnostics.Process.Start(pi);

                    p.WaitForExit(45000);

                    if (File.Exists(_pdfPath))
                    {
                        System.Diagnostics.Process.Start(_pdfPath);
                    }
                    else
                    {
                        while (MessageBox.Show("The .pdf document appears to be taking a while to generate. Would you like to continue waiting?\n\nThis question appears every 45 seconds.",
                                               "PDF not generated", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            p.WaitForExit(45000);
                            if (File.Exists(_pdfPath))
                            {
                                System.Diagnostics.Process.Start(_pdfPath);
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                string innerText = "";

                innerText += err.Message;

                Exception e = err;

                while (e.InnerException != null)
                {
                    innerText += "\n\n" + e.InnerException.Message;
                    e          = e.InnerException;

                    if (innerText.Length > 5000) // Just in case it's getting too long, break out
                    {
                        break;
                    }
                }

                LoggingHelper.Log("Error printing claim in ClaimTrackerCommon.PrintClaims\n" + innerText, LogSeverity.Error);
                MessageBox.Show("An unexpected error occurred trying to print the claim.\n\n" + innerText, "Unexpected Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (_errorClaims != string.Empty)
            {
                LoggingHelper.Log("Errors occurred printing claim in ClaimTrackerCommon.PrintClaims\n" + _errorClaims, LogSeverity.Error);
                MessageBox.Show("Some of the claims could not be printed.\n\n" + _errorClaims);
            }
        }
Ejemplo n.º 35
0
        public static void CompileResxFiles(string folder, List <string> excludeFolders, string @namespace, string assemblyname, string versionAssembly, string keyfile, string culture, string productname)
        {
            string resgenexe;
            string alexe;

            if (Duplicati.Library.Utility.Utility.IsClientLinux)
            {
                resgenexe = ExecuteAndRead("which", "resgen");
                alexe     = ExecuteAndRead("which", "al");
            }
            else             //Windows
            {
                //Order of these paths is also the search order
                string[] known_sdk_paths =
                {
                    Environment.ExpandEnvironmentVariables("%WINDIR%\\Microsoft.Net\\Framework\\v4.0\\"),
                    Environment.ExpandEnvironmentVariables("%WINDIR%\\Microsoft.Net\\Framework\\v4.0.30319\\"),
                    Environment.ExpandEnvironmentVariables("%WINDIR%\\Microsoft.Net\\Framework\\v3.5\\"),
                    Environment.ExpandEnvironmentVariables("%WINDIR%\\Microsoft.Net\\Framework\\v3.0\\"),
                    Environment.ExpandEnvironmentVariables("%WINDIR%\\Microsoft.Net\\Framework\\v2.0.50727\\"),

                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES%\\Microsoft SDKs\\Windows\\v8.0A\\bin\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES%\\Microsoft SDKs\\Windows\\v7.1\\Bin\\NETFX 4.0 Tools\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES%\\Microsoft SDKs\\Windows\\v7.0A\\bin\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES%\\Microsoft SDKs\\Windows\\v6.0A\\bin\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES%\\Microsoft.NET\\SDK\\v2.0\\bin\\"),

                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES(X86)%\\Microsoft SDKs\\Windows\\v8.0A\\bin\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES(X86)%\\Microsoft SDKs\\Windows\\v7.1\\Bin\\NETFX 4.0 Tools\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES(X86)%\\Microsoft SDKs\\Windows\\v7.0A\\bin\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES(X86)%\\Microsoft SDKs\\Windows\\v6.0A\\bin\\"),
                    Environment.ExpandEnvironmentVariables("%PROGRAMFILES(X86)%\\Microsoft.NET\\SDK\\v2.0\\bin\\"),
                };

                resgenexe = "resgen.exe";
                alexe     = "al.exe";

                foreach (var p in known_sdk_paths)
                {
                    if (System.IO.File.Exists(System.IO.Path.Combine(p, resgenexe)))
                    {
                        resgenexe = System.IO.Path.Combine(p, resgenexe);
                        break;
                    }
                }

                foreach (var p in known_sdk_paths)
                {
                    if (System.IO.File.Exists(System.IO.Path.Combine(p, alexe)))
                    {
                        alexe = System.IO.Path.Combine(p, alexe);
                        break;
                    }
                }
            }
            if (!System.IO.File.Exists(resgenexe))
            {
                Console.WriteLine("Unable to locate file: {0}", resgenexe);
                Console.WriteLine("This can be fixed by installing a microsoft platform SDK, or visual studio (express is fine)");
                return;
            }

            if (!System.IO.File.Exists(alexe))
            {
                Console.WriteLine("Unable to locate file: {0}", alexe);
                Console.WriteLine("This can be fixed by installing the .Net framework version 2.0");
                return;
            }

            if (!string.IsNullOrEmpty(keyfile) && Duplicati.Library.Utility.Utility.IsClientLinux)
            {
                keyfile = keyfile.Replace("\\", System.IO.Path.DirectorySeparatorChar.ToString());
            }


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

            folder = Duplicati.Library.Utility.Utility.AppendDirSeparator(folder);

            foreach (string s in Duplicati.Library.Utility.Utility.EnumerateFiles(folder))
            {
                if (s.ToLower().EndsWith("." + culture.ToLower() + ".resx"))
                {
                    if (excludeFolders.Any(xf => s.ToLower().StartsWith(Duplicati.Library.Utility.Utility.AppendDirSeparator(xf).ToLower())))
                    {
                        continue;
                    }

                    string resname = System.IO.Path.ChangeExtension(s, ".resources");

                    if (!System.IO.File.Exists(resname) || System.IO.File.GetLastWriteTime(resname) < System.IO.File.GetLastWriteTime(s))
                    {
                        Console.WriteLine("Compiling: " + s);
                        System.Diagnostics.ProcessStartInfo pi = new System.Diagnostics.ProcessStartInfo(resgenexe, "\"" + s + "\"");
                        pi.CreateNoWindow         = true;
                        pi.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                        pi.RedirectStandardOutput = true;
                        pi.RedirectStandardError  = true;
                        pi.UseShellExecute        = false;
                        pi.WorkingDirectory       = System.IO.Path.GetDirectoryName(s);

                        System.Diagnostics.Process pr = System.Diagnostics.Process.Start(pi);
                        pr.WaitForExit();

                        if (pr.ExitCode != 0)
                        {
                            Console.WriteLine("Error");
                            Console.WriteLine(pr.StandardOutput.ReadToEnd());
                            Console.WriteLine(pr.StandardError.ReadToEnd());
                            throw new Exception("Resgen failure: " + s);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Not modified: " + s);
                    }

                    resources.Add(resname);
                }
            }

            if (resources.Count == 0)
            {
                return;
            }

            if (!System.IO.File.Exists(versionAssembly) && Duplicati.Library.Utility.Utility.IsClientLinux)
            {
                versionAssembly = versionAssembly.Replace("\\", System.IO.Path.DirectorySeparatorChar.ToString());
            }

            if (!System.IO.File.Exists(versionAssembly))
            {
                Console.WriteLine("Unable to locate file: {0}", versionAssembly);
                Console.WriteLine("This can be fixed by compiling the application or modifying the file configuration.xml");
                return;
            }

            using (Duplicati.Library.Utility.TempFile tf = new Duplicati.Library.Utility.TempFile())
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(tf))
                {
                    System.Reflection.Assembly asm = System.Reflection.Assembly.ReflectionOnlyLoadFrom(versionAssembly);

                    sw.WriteLine("/t:lib");
                    sw.WriteLine("/out:\"" + assemblyname + "\"");
                    sw.WriteLine("/product:\"" + productname + "\"");
                    sw.WriteLine("/title:\"" + productname + "\"");
                    sw.WriteLine("/version:" + asm.GetName().Version.ToString());
                    if (!string.IsNullOrEmpty(keyfile))
                    {
                        sw.WriteLine("/keyfile:\"" + keyfile + "\"");
                    }
                    sw.WriteLine("/culture:" + culture);

                    foreach (string s in resources)
                    {
                        string resname = s.Substring(folder.Length);
                        resname = resname.Replace("\\", ".");
                        resname = resname.Replace(" ", "_");
                        resname = @namespace + "." + resname;

                        sw.WriteLine("/embed:\"" + s + "\"," + resname);
                    }
                }

                Console.WriteLine("Linking ...");
                System.Diagnostics.ProcessStartInfo pi = new System.Diagnostics.ProcessStartInfo(alexe, "@\"" + tf + "\"");
                pi.CreateNoWindow = true;
                pi.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Hidden;

                System.Diagnostics.Process pr = System.Diagnostics.Process.Start(pi);
                pr.WaitForExit();

                if (pr.ExitCode != 0)
                {
                    throw new Exception("Linker failure");
                }
            }
        }
Ejemplo n.º 36
0
        private void AutoBuild(Action showProgress, Action <string> updateProgress)
        {
            showProgress();

            Dictionary <string, SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType> assemblies =
                new Dictionary <string, SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType>();

            string modFolder = Path.Combine(Program.Settings.GetModPathForGame(game),
                                            projectName);

            Directory.CreateDirectory(modFolder);

            updateProgress("Getting Assemblies");
            switch (game)
            {
            case SA_Tools.Game.SADX:
                List <String> sadxAssemblyNames = GetSADXAssemblyNames();

                // check for chrmodels or chrmodels_orig
                string chrmodels     = "chrmodels";
                string chrmodelsOrig = "chrmodels_orig";

                string chrmodelsCompletePath     = Path.Combine(projectFolder, chrmodels + "_data.ini");
                string chrmodelsOrigCompletePath = Path.Combine(projectFolder, chrmodelsOrig + "_data.ini");

                if (File.Exists(chrmodelsCompletePath))
                {
                    sadxAssemblyNames.Add(chrmodels);
                }
                else
                {
                    sadxAssemblyNames.Add(chrmodelsOrig);
                }

                assemblies.Add("sonic", SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType.Exe);

                foreach (string assemblyName in sadxAssemblyNames)
                {
                    assemblies.Add(assemblyName, SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType.DLL);
                }
                break;

            case SA_Tools.Game.SA2B:
                // dll
                assemblies.Add("Data_DLL", SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType.DLL);

                // exe
                assemblies.Add("sonic2app", SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType.Exe);
                break;

            default:
                break;
            }

            // export only the modified items in each assembly
            updateProgress("Exporting Assembies");

            foreach (KeyValuePair <string, SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType> assembly in
                     assemblies)
            {
                string iniPath = Path.Combine(projectFolder, assembly.Key + "_data.ini");

                Dictionary <string, bool> itemsToExport = new Dictionary <string, bool>();

                switch (assembly.Value)
                {
                case SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType.Exe:
                    SA_Tools.IniData iniData = SonicRetro.SAModel.SAEditorCommon.StructConverter.StructConverter.LoadINI(iniPath, ref itemsToExport);

                    SonicRetro.SAModel.SAEditorCommon.StructConverter.StructConverter.ExportINI(iniData,
                                                                                                itemsToExport, Path.Combine(modFolder, assembly.Key + "_data.ini"));
                    break;

                case SonicRetro.SAModel.SAEditorCommon.ManualBuildWindow.AssemblyType.DLL:
                    SonicRetro.SAModel.SAEditorCommon.DLLModGenerator.DllIniData dllIniData =
                        SonicRetro.SAModel.SAEditorCommon.DLLModGenerator.DLLModGen.LoadINI(iniPath, ref itemsToExport);

                    SonicRetro.SAModel.SAEditorCommon.DLLModGenerator.DLLModGen.ExportINI(dllIniData,
                                                                                          itemsToExport, Path.Combine(modFolder, assembly.Key + "_data.ini"));
                    break;

                default:
                    break;
                }
            }

            // copy system folder
            updateProgress("Copying System Folder");
            CopySystemFolder(modFolder);

            // generate final mod.ini based off of one in project folder
            updateProgress("Creating Mod.ini");

            string baseModIniPath   = Path.Combine(projectFolder, "mod.ini");
            string outputModIniPath = Path.Combine(modFolder, "mod.ini");

            switch (game)
            {
            case SA_Tools.Game.SADX:
                SADXModInfo sadxModInfo = SA_Tools.IniSerializer.Deserialize <SADXModInfo>(baseModIniPath);

                // set all of our assemblies properly
                string ADV00MODELS               = "ADV00MODELS";
                string ADV01CMODELS              = "ADV01CMODELS";
                string ADV01MODELS               = "ADV01MODELS";
                string ADV02MODELS               = "ADV02MODELS";
                string ADV03MODELS               = "ADV03MODELS";
                string BOSSCHAOS0MODELS          = "BOSSCHAOS0MODELS";
                string CHAOSTGGARDEN02MR_DAYTIME = "CHAOSTGGARDEN02MR_DAYTIME";
                string CHAOSTGGARDEN02MR_EVENING = "CHAOSTGGARDEN02MR_EVENING";
                string CHAOSTGGARDEN02MR_NIGHT   = "CHAOSTGGARDEN02MR_NIGHT";

                string dataSuffix = "_data.ini";

                if (assemblies.ContainsKey(ADV00MODELS))
                {
                    sadxModInfo.ADV00MODELSData = ADV00MODELS + dataSuffix;
                }
                if (assemblies.ContainsKey(ADV01CMODELS))
                {
                    sadxModInfo.ADV01CMODELSData = ADV01CMODELS + dataSuffix;
                }
                if (assemblies.ContainsKey(ADV01MODELS))
                {
                    sadxModInfo.ADV01MODELSData = ADV01MODELS + dataSuffix;
                }
                if (assemblies.ContainsKey(ADV02MODELS))
                {
                    sadxModInfo.ADV02MODELSData = ADV02MODELS + dataSuffix;
                }
                if (assemblies.ContainsKey(ADV03MODELS))
                {
                    sadxModInfo.ADV03MODELSData = ADV03MODELS + dataSuffix;
                }
                if (assemblies.ContainsKey(BOSSCHAOS0MODELS))
                {
                    sadxModInfo.BOSSCHAOS0MODELSData = BOSSCHAOS0MODELS + dataSuffix;
                }
                if (assemblies.ContainsKey(CHAOSTGGARDEN02MR_DAYTIME))
                {
                    sadxModInfo.CHAOSTGGARDEN02MR_DAYTIMEData = CHAOSTGGARDEN02MR_DAYTIME + dataSuffix;
                }
                if (assemblies.ContainsKey(CHAOSTGGARDEN02MR_EVENING))
                {
                    sadxModInfo.CHAOSTGGARDEN02MR_EVENINGData = CHAOSTGGARDEN02MR_EVENING + dataSuffix;
                }
                if (assemblies.ContainsKey(CHAOSTGGARDEN02MR_NIGHT))
                {
                    sadxModInfo.CHAOSTGGARDEN02MR_NIGHTData = CHAOSTGGARDEN02MR_NIGHT + dataSuffix;
                }
                if (assemblies.ContainsKey("sonic"))
                {
                    sadxModInfo.EXEData = "sonic_data.ini";
                }

                // save our output
                SA_Tools.IniSerializer.Serialize(sadxModInfo, outputModIniPath);
                break;

            case SA_Tools.Game.SA2B:
                SA2ModInfo sa2ModInfo = SA_Tools.IniSerializer.Deserialize <SA2ModInfo>(baseModIniPath);

                sa2ModInfo.EXEFile = "sonic2app_data.ini";
                sa2ModInfo.DLLFile = "Data_DLL_data.ini";

                // save our output
                SA_Tools.IniSerializer.Serialize(sa2ModInfo, outputModIniPath);
                break;

            default:
                break;
            }

            // execute our post-build script
            string projectSettingsPath = Path.Combine(projectFolder, "ProjectSettings.ini");

            if (File.Exists(projectSettingsPath))
            {
                ProjectSettings projectSettings = SA_Tools.IniSerializer.Deserialize <ProjectSettings>(projectSettingsPath);

                string storedEnvironmentDirectory = Environment.CurrentDirectory;

                if (File.Exists(projectSettings.PostBuildScript))
                {
                    System.Diagnostics.ProcessStartInfo procStartInfo =
                        new System.Diagnostics.ProcessStartInfo(projectSettings.PostBuildScript);

                    System.Diagnostics.Process process = System.Diagnostics.Process.Start(procStartInfo);

                    while (!process.HasExited)
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    Environment.CurrentDirectory = storedEnvironmentDirectory;
                }
            }
        }
Ejemplo n.º 37
0
        private void StartProcess()
        {
            var startinfo = new System.Diagnostics.ProcessStartInfo();
            var cmd       = this.Description.CommandLine;
            var args      =
                System.Text.RegularExpressions.Regex.Matches(cmd, @"(?:""[^""]+?"")|(?:\S+)")
                .Cast <System.Text.RegularExpressions.Match>()
                .Select(match => match.ToString())
                .ToArray();

            startinfo.WorkingDirectory       = this.Description.BasePath;
            startinfo.UseShellExecute        = false;
            startinfo.FileName               = args.First();
            startinfo.Arguments              = String.Join(" ", args.Skip(1));
            startinfo.CreateNoWindow         = true;
            startinfo.ErrorDialog            = false;
            startinfo.RedirectStandardInput  = true;
            startinfo.RedirectStandardOutput = true;
            startinfo.RedirectStandardError  = true;
            startinfo.StandardOutputEncoding = System.Text.Encoding.ASCII;
            startinfo.StandardErrorEncoding  = System.Text.Encoding.Default;
            processCancellationToken         = new CancellationTokenSource();
            var cancel = processCancellationToken.Token;

            process     = System.Diagnostics.Process.Start(startinfo);
            pipePackets = new WaitableQueue <byte[]>();
            var stdout = process.StandardOutput.BaseStream;
            var stdin  = process.StandardInput.BaseStream;
            var stderr = process.StandardError;

            stdErrorTask = Task.Run(async() => {
                try {
                    Logger logger = new Logger(typeof(CustomFilterContentSink), this.Description.Name);
                    while (!cancel.IsCancellationRequested)
                    {
                        var line = await stderr.ReadLineAsync().ConfigureAwait(false);
                        if (line == null)
                        {
                            break;
                        }
                        if (Description.Logging)
                        {
                            logger.Debug(line);
                        }
                    }
                    stderr.Close();
                }
                catch (System.IO.IOException) {
                }
                catch (ObjectDisposedException) {
                }
            });
            stdOutTask = Task.Run(async() => {
                try {
                    long pos   = 0;
                    var buffer = new byte[1024 * 15];
                    while (!cancel.IsCancellationRequested)
                    {
                        var len = await stdout.ReadAsync(buffer, 0, buffer.Length, cancel).ConfigureAwait(false);
                        System.Console.WriteLine("stdout {0}", len);
                        if (len <= 0)
                        {
                            break;
                        }
                        Sink.OnContent(new Content(lastContent.Stream, lastContent.Timestamp, pos, buffer, 0, len, PCPChanPacketContinuation.None));
                        pos += len;
                    }
                    stdout.Close();
                }
                catch (System.IO.IOException) {
                }
                catch (ObjectDisposedException) {
                }
                finally {
                    System.Console.WriteLine("stdoutclosed");
                }
            });
            writable  = true;
            stdInTask = Task.Run(async() => {
                try {
                    while (!cancel.IsCancellationRequested)
                    {
                        var packet = await pipePackets.DequeueAsync(cancel).ConfigureAwait(false);
                        if (packet != null)
                        {
                            await stdin.WriteAsync(packet, 0, packet.Length, cancel).ConfigureAwait(false);
                            if (pipePackets.IsEmpty)
                            {
                                await stdin.FlushAsync().ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            stdin.Close();
                            break;
                        }
                    }
                }
                catch (System.IO.IOException) {
                }
                catch (ObjectDisposedException) {
                }
                finally {
                    writable = false;
                    System.Console.WriteLine("stdinclosed");
                }
                //TODO:子プロセスが死んだ時に上流か下流かに伝える必要がある
            });
        }
Ejemplo n.º 38
0
        private void bInstall_Click(object sender, EventArgs e)
        {
            try
            {
                if (containNotInstall) //安装
                {
                    if (ShowConfirm("如果您之前执行过安装操作,请先使用原程序卸载服务再使用本程序执行安装操作!"))
                    {
                        using (TransactedInstaller transactedInstaller = new TransactedInstaller())
                        {
                            var installLog = new Hashtable();
                            AssemblyInstaller assemblyInstaller = new AssemblyInstaller(Application.ExecutablePath, null);
                            transactedInstaller.Installers.Add(assemblyInstaller);
                            transactedInstaller.Install(installLog);
                        }

                        //修改ImagePath
                        foreach (var service in GetServicesFromMef())
                        {
                            if (service is WindowsServiceBase)
                            {
                                bool        delayedAutoStart;
                                ServiceInfo serviceInfo = ServiceHelper.QueryServiceConfig(service.ServiceName, out delayedAutoStart);
                                ServiceHelper.ChangeExePath(service.ServiceName, $"{serviceInfo.binaryPathName} -Daemon {service.ServiceName}");
                            }
                        }
                        updateInstallButton();

                        logInfo("安装所有Windows服务成功");
                    }
                }
                else //卸载
                {
                    if (ShowConfirm("确定要卸载本控制台中的所有Windows服务吗?"))
                    {
                        using (TransactedInstaller transactedInstaller = new TransactedInstaller())
                        {
                            AssemblyInstaller assemblyInstaller = new AssemblyInstaller(Application.ExecutablePath, null);
                            transactedInstaller.Installers.Add(assemblyInstaller);
                            transactedInstaller.Uninstall(null);
                        }
                        updateInstallButton();

                        logInfo("卸载所有Windows服务成功");
                    }
                }
            }
            catch (Exception ex)
            {
                logError("操作失败:" + ex.Message, ex);
                if (ShowConfirm($"操作失败【{ex.Message}】,是否以管理员权限重启本程序以执行操作?"))
                {
                    //退出
                    tsmiExit.PerformClick();

                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.UseShellExecute  = true;
                    startInfo.WorkingDirectory = Environment.CurrentDirectory;
                    startInfo.FileName         = Application.ExecutablePath;
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    try
                    {
                        System.Diagnostics.Process.Start(startInfo);
                    }
                    catch { }
                }
            }
        }
Ejemplo n.º 39
0
        public static bool BuildAppxFromSolution(string productName, string msBuildVersion, bool forceRebuildAppx, string buildConfig, string buildDirectory, bool incrementVersion)
        {
            // GetStringResult and validate the msBuild path...
            string vs = CalcMSBuildPath(msBuildVersion);

            if (!File.Exists(vs))
            {
                Debug.LogError("MSBuild.exe is missing or invalid (path=" + vs + "). Note that the default version is " + DefaultMSBuildVersion);
                return(false);
            }

            // GetStringResult the path to the NuGet tool
            string unity               = Path.GetDirectoryName(EditorApplication.applicationPath);
            string nugetPath           = Path.Combine(unity, @"Data\PlaybackEngines\MetroSupport\Tools\NuGet.exe");
            string storePath           = Path.GetFullPath(Path.Combine(Path.Combine(Application.dataPath, ".."), buildDirectory));
            string solutionProjectPath = Path.GetFullPath(Path.Combine(storePath, productName + @".sln"));

            // Before building, need to run a nuget restore to generate a json.lock file. Failing to do
            // this breaks the build in VS RTM
            var nugetPInfo = new System.Diagnostics.ProcessStartInfo();

            nugetPInfo.FileName         = nugetPath;
            nugetPInfo.WorkingDirectory = buildDirectory;
            nugetPInfo.UseShellExecute  = false;
            nugetPInfo.Arguments        = @"restore " + PlayerSettings.productName + "/project.json";
            using (var nugetP = new System.Diagnostics.Process())
            {
                Debug.Log(nugetPath + " " + nugetPInfo.Arguments);
                nugetP.StartInfo = nugetPInfo;
                nugetP.Start();
                nugetP.WaitForExit();
            }

            // Ensure that the generated .appx version increments by modifying
            // Package.appxmanifest
            if (incrementVersion)
            {
                IncrementPackageVersion();
            }

            // Now do the actual build
            var pinfo = new System.Diagnostics.ProcessStartInfo();

            pinfo.FileName        = vs;
            pinfo.UseShellExecute = false;
            string buildType = forceRebuildAppx ? "Rebuild" : "Build";

            pinfo.Arguments = string.Format("\"{0}\" /t:{2} /p:Configuration={1} /p:Platform=x86", solutionProjectPath, buildConfig, buildType);
            var p = new System.Diagnostics.Process();

            Debug.Log(vs + " " + pinfo.Arguments);
            p.StartInfo = pinfo;
            p.Start();

            p.WaitForExit();
            if (p.ExitCode == 0)
            {
                Debug.Log("APPX build succeeded!");
            }
            else
            {
                Debug.LogError("MSBuild error (code = " + p.ExitCode + ")");
            }

            if (p.ExitCode != 0)
            {
                EditorUtility.DisplayDialog(PlayerSettings.productName + " build Failed!", "Failed to build appx from solution. Error code: " + p.ExitCode, "OK");
                return(false);
            }
            else
            {
                // Build succeeded. Allow user to install build on remote PC
                BuildDeployWindow.OpenWindow();
                return(true);
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// インストール開始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            var targetFolder = textBox1.Text;
            var myShogiPath  = Path.Combine(targetFolder, "myshogi.exe");

            if (!File.Exists(myShogiPath))
            {
                MessageBox.Show($"選択されたインストール先にmyshogi.exeがありません。\r\nこのフォルダには、{ViewModel.ProductName}がインストールされていません。");
                return;
            }

            // インストール先のフォルダは、このtargetFolderに変更。
            ViewModel.InstallFolder = targetFolder;

            // インストール開始
            // 権限昇格しないといけない…。
            try
            {
                button1.Enabled = false;

                // 管理者として実行されているのか?
                var isAdmin = PatchMaker.IsAdministrator();

                // AutoInstallが予約されている。
                if (ViewModel.AutoInstall)
                {
                    if (isAdmin)
                    {
                        workerThread = new Thread(worker);
                        workerThread.Start();
                    }
                    else
                    {
                        //「ユーザーアカウント制御」ダイアログでキャンセルされたなどによって起動できなかった時
                        MessageBox.Show("管理者になれませんでした。UACの設定を確認してください。");
                    }
                }
                else if (isAdmin)
                {
                    // このまま実行できる。
                    workerThread = new Thread(worker);
                    workerThread.Start();
                }
                else
                {
                    //管理者として自分自身を起動する
                    var psi = new System.Diagnostics.ProcessStartInfo();
                    psi.UseShellExecute = true;
                    psi.FileName        = Application.ExecutablePath;
                    psi.Verb            = "runas"; // 管理者
                    psi.Arguments       = $"FolderCopy \"{targetFolder}\"";
                    // このコマンドを実行してもらう。
                    try
                    {
                        //起動する
                        var process = System.Diagnostics.Process.Start(psi);
                        Application.Exit(); // このプロセスは終了させる。
                    }
                    catch (System.ComponentModel.Win32Exception ex)
                    {
                        //「ユーザーアカウント制御」ダイアログでキャンセルされたなどによって起動できなかった時
                        MessageBox.Show("起動しませんでした: " + ex.Message);
                    }
                }

                //PatchMaker.FolderCopy(ViewModel.SourceFolder, targetFolder);
            }
            catch (Exception ex)
            {
                MessageBox.Show("例外が発生しました。\r\n" + ex.Message);
            }
            finally
            {
                button1.Enabled = true;
            }
        }
Ejemplo n.º 41
0
        static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
        {
                        #if UNITY_5
            if (target == BuildTarget.WSAPlayer || target == BuildTarget.WP8Player)
                        #else
            if (target == BuildTarget.MetroPlayer || target == BuildTarget.WP8Player)
                        #endif
            {
                                #if UNITY_WP8
                var productName = PlayerSettings.productName.Replace(" ", "").Replace("_", "");
                                #else
                var productName = PlayerSettings.productName;
                                #endif

                                #if UNITY_5
                if (EditorUserBuildSettings.wsaSDK == WSASDK.UniversalSDK81 && EditorUserBuildSettings.activeBuildTarget != BuildTarget.WP8Player)
                                #else
                if (EditorUserBuildSettings.metroSDK == MetroSDK.UniversalSDK81 && EditorUserBuildSettings.activeBuildTarget != BuildTarget.WP8Player)
                                #endif
                {
                    var projPath = string.Format("{0}/{1}/{1}.Shared/{1}.Shared.projItems", pathToBuiltProject, productName);
                    Debug.Log("Modifying Proj: " + projPath);
                    var doc = XDocument.Load(projPath);
                    addPostProjectReferences(doc, pathToBuiltProject, string.Format("/{0}.Shared", productName), productName, "$(MSBuildThisFileDirectory)");
                    doc.Save(projPath);

                    projPath = string.Format("{0}/{1}/{1}.Windows/{1}.Windows.csproj", pathToBuiltProject, productName);
                    Debug.Log("Modifying Proj: " + projPath);
                    doc = XDocument.Load(projPath);
                    addPostProjectCompilerDirectives(doc);
                    doc.Save(projPath);

                    projPath = string.Format("{0}/{1}/{1}.WindowsPhone/{1}.WindowsPhone.csproj", pathToBuiltProject, productName);
                    Debug.Log("Modifying Proj: " + projPath);
                    doc = XDocument.Load(projPath);
                    addPostProjectCompilerDirectives(doc);
                    doc.Save(projPath);
                }
                else
                {
                    var projPath = string.Format("{0}/{1}/{1}.csproj", pathToBuiltProject, productName);
                    Debug.Log("Modifying Proj: " + projPath);

                    var doc = XDocument.Load(projPath);
                    addPostProjectCompilerDirectives(doc);
                    addPostProjectReferences(doc, pathToBuiltProject, "", productName, "");
                    doc.Save(projPath);
                }
            }
                        #if UNITY_IOS && UNITY_5
            else if (target == BuildTarget.iOS)
            {
                string projPath = pathToBuiltProject + "/Unity-iPhone.xcodeproj/project.pbxproj";

                var proj = new PBXProject();
                proj.ReadFromString(File.ReadAllText(projPath));

                string targetID = proj.TargetGuidByName("Unity-iPhone");

                // set custom link flags
                proj.AddBuildProperty(targetID, "OTHER_LDFLAGS", "-all_load");
                proj.AddBuildProperty(targetID, "OTHER_LDFLAGS", "-ObjC");

                // add frameworks
                proj.AddFrameworkToProject(targetID, "AdSupport.framework", true);
                proj.AddFrameworkToProject(targetID, "CoreTelephony.framework", true);
                proj.AddFrameworkToProject(targetID, "EventKit.framework", true);
                proj.AddFrameworkToProject(targetID, "EventKitUI.framework", true);
                proj.AddFrameworkToProject(targetID, "iAd.framework", true);
                proj.AddFrameworkToProject(targetID, "MessageUI.framework", true);
                proj.AddFrameworkToProject(targetID, "StoreKit.framework", true);
                proj.AddFrameworkToProject(targetID, "Security.framework", true);
                proj.AddFrameworkToProject(targetID, "GameKit.framework", true);
                proj.AddFrameworkToProject(targetID, "GoogleMobileAds.framework", false);

                // change GoogleMobileAds to use reletive path
                string projData = proj.WriteToString();
                projData = projData.Replace
                           (
                    @"/* GoogleMobileAds.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GoogleMobileAds.framework; path = System/Library/Frameworks/GoogleMobileAds.framework; sourceTree = SDKROOT; };",
                    @"/* GoogleMobileAds.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GoogleMobileAds.framework; path = Frameworks/GoogleMobileAds.framework; sourceTree = ""<group>""; };"
                    //@"/* GoogleMobileAds.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GoogleMobileAds.framework; path = """ + pathToBuiltProject+"/Frameworks/GoogleMobileAds.framework" + @"""; sourceTree = ""<absolute>""; };"
                           );

                // change framework search path to include local framework directory
                projData = projData.Replace
                           (
                    @"FRAMEWORK_SEARCH_PATHS = ""$(inherited)"";",
                    @"FRAMEWORK_SEARCH_PATHS = (""$(inherited)"", ""$(PROJECT_DIR)/Frameworks"",);"
                           );

                // save proj data
                File.WriteAllText(projPath, projData);

                // extract GoogleMobileAds.framework.zip to xcode framework path
                if (!Directory.Exists(pathToBuiltProject + "/Frameworks/GoogleMobileAds.framework"))
                {
                    var startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.Arguments      = Application.dataPath + "/Plugins/IOS/GoogleMobileAds.framework.zip" + " -d " + pathToBuiltProject + "/Frameworks";
                    startInfo.FileName       = "unzip";
                    startInfo.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Hidden;
                    startInfo.CreateNoWindow = true;
                    using (var process = System.Diagnostics.Process.Start(startInfo))
                    {
                        process.WaitForExit();
                        int exitCode = process.ExitCode;
                        if (exitCode != 0)
                        {
                            Debug.LogError("Failed to unzip GoogleMobileAds.framework.zip with ErrorCode: " + exitCode);
                        }
                    }
                }
            }
                        #endif
        }
Ejemplo n.º 42
0
        public IDictionary <string, string> Execute(IDictionary <string, string> options)
        {
            string k;

            options.TryGetValue(KEY_CONFIGTYPE, out k);

            ConfigType ct;

            if (!Enum.TryParse <ConfigType>(k, true, out ct))
            {
                ct = DEFAULT_CONFIG_TYPE;
            }

            var d = new Dictionary <string, string>();

            switch (ct)
            {
            case ConfigType.Install:

                try
                {
                    var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "mozroots.exe");
                    var pi   = new System.Diagnostics.ProcessStartInfo(path, "--import --sync --quiet");
                    pi.UseShellExecute = false;
                    var p = System.Diagnostics.Process.Start(pi);
                    p.WaitForExit((int)TimeSpan.FromMinutes(5).TotalMilliseconds);
                }
                catch (Exception ex)
                {
                    d["error"] = ex.ToString();
                }

                d["count"] = CheckForInstalledCerts().ToString();
                break;

            case ConfigType.Test:
                try
                {
                    var req = System.Net.WebRequest.CreateHttp("https://updates.duplicati.com");
                    req.Method            = "HEAD";
                    req.AllowAutoRedirect = false;

                    using (var resp = (System.Net.HttpWebResponse)req.GetResponse())
                    {
                        d["status"]      = resp.StatusDescription;
                        d["status_code"] = ((int)resp.StatusCode).ToString();
                    }
                }
                catch (Exception ex)
                {
                    d["error"] = ex.ToString();
                }
                break;

            case ConfigType.List:
            default:
                d["count"]   = CheckForInstalledCerts().ToString();
                d["mono"]    = Library.Utility.Utility.IsMono.ToString();
                d["message"] = Strings.CheckMonoSSL.ErrorMessage;
                break;
            }

            return(d);
        }
Ejemplo n.º 43
0
 public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo startInfo)
 {
     throw null;
 }
Ejemplo n.º 44
0
        /// <summary>
        /// 获取本计算机唯一的机器码
        /// </summary>
        /// <returns>字符串形式的机器码</returns>
        public static string GetInfo(bool UseAdmin)
        {
            //说明 这个方法所有的获取hwid的行为均在Ring3模式下获取 方法前半部分为WMI 后半部分为S.M.A.R.T.(DeviceIoControl())
            //程序依赖kernel32.dll不能运行在wince下 纯c#解决方案几乎不可能在Ring0模式下获取 如果有更高的要求建议加密狗
            string unique = "";

            //bios名称
            unique += HWID.BIOS + "|";
            //cpu信息
            unique += HWID.CPU + "|";
            //硬盘信息
            unique += HWID.HDD + "|";
            //主板信息
            unique += HWID.BaseBoard + "|";
            //unique += HWID.MAC + "|";
            //是否存在scsi
            if (HWID.IsServer)
            {
                unique += HWID.SCSI + "|";
            }

            //获取系统盘ID 新增 较为稳定
            string           systempath        = Environment.GetEnvironmentVariable("systemdrive");//获取当前系统盘
            string           win32_logicaldisk = "\"" + systempath + "\"";
            ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=" + win32_logicaldisk);

            dsk.Get();
            unique += dsk["VolumeSerialNumber"].ToString();
            unique += "|";
            //获取SMBIOS的id
            ManagementClass            cimobject3 = new ManagementClass("Win32_ComputerSystemProduct");
            ManagementObjectCollection moc3       = cimobject3.GetInstances();

            foreach (ManagementObject mo in moc3)
            {
                unique += (string)mo.Properties["UUID"].Value;
                break;
            }
            unique += "|";
            //如果启用了管理员模式 则读取hwid
            if (UseAdmin)
            {
                WindowsIdentity  current          = WindowsIdentity.GetCurrent();
                WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
                bool             IsAdmin          = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
                //硬盘物理id
                if (IsAdmin)
                {
                    var HddInfo = GetHddInfo();
                    unique += HddInfo.SerialNumber;
                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        //设置运行文件
                        FileName = System.Windows.Forms.Application.ExecutablePath,
                        //设置启动动作,确保以管理员身份运行
                        Verb = "runas"
                    };
                    //如果不是管理员,则启动UAC
                    System.Diagnostics.Process.Start(startInfo);
                    //退出
                    System.Windows.Forms.Application.Exit();
                }
            }

            SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
            var md5 = ConvertUtils.ByteToHexString(SHA1.ComputeHash(Encoding.Unicode.GetBytes(unique)));

            return(md5.Substring(0, 25));
        }
Ejemplo n.º 45
0
        public async Task <IImageData> Convert(
            MemoryStream s,
            int bitDepth,
            string rawType,
            ImageMetaData metaData,
            CancellationToken token = default)
        {
            return(await Task.Run(async() => {
                using (MyStopWatch.Measure()) {
                    var fileextension = ".raw";
                    var filename = Path.GetRandomFileName();
                    var rawfile = Path.Combine(Utility.APPLICATIONTEMPPATH, filename + fileextension);

                    using (var filestream = new System.IO.FileStream(rawfile, System.IO.FileMode.Create)) {
                        s.WriteTo(filestream);
                    }

                    ImageData data = null;
                    var outputFile = Path.Combine(Utility.APPLICATIONTEMPPATH, filename + ".tiff");
                    try {
                        System.Diagnostics.Process process;
                        System.Diagnostics.ProcessStartInfo startInfo;
                        var sb = new StringBuilder();
                        using (MyStopWatch.Measure("DCRawStart")) {
                            process = new System.Diagnostics.Process();
                            startInfo = new System.Diagnostics.ProcessStartInfo();
                            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                            startInfo.FileName = DCRAWLOCATION;
                            startInfo.UseShellExecute = false;
                            startInfo.RedirectStandardOutput = true;
                            startInfo.RedirectStandardError = true;
                            startInfo.RedirectStandardInput = true;
                            startInfo.CreateNoWindow = true;
                            startInfo.Arguments = "-4 -d -T -t 0 -v \"" + rawfile + "\"";
                            process.StartInfo = startInfo;
                            process.EnableRaisingEvents = true;

                            process.OutputDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => {
                                sb.AppendLine(e.Data);
                            };

                            process.ErrorDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => {
                                sb.AppendLine(e.Data);
                            };

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

                            await process.WaitForExitAsync(token);

                            Logger.Trace(sb.ToString());
                        }

                        using (MyStopWatch.Measure("DCRawReadIntoImageArray")) {
                            if (File.Exists(outputFile))
                            {
                                TiffBitmapDecoder TifDec = new TiffBitmapDecoder(new Uri(outputFile), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                                BitmapFrame bmp = TifDec.Frames[0];
                                ushort[] pixels = new ushort[bmp.PixelWidth *bmp.PixelHeight];
                                bmp.CopyPixels(pixels, 2 * bmp.PixelWidth, 0);

                                //Due to the settings of dcraw decoding the values will be stretched to 16 bits
                                bitDepth = 16;

                                var imageArray = new ImageArray(flatArray: pixels, rawData: s.ToArray(), rawType: rawType);
                                data = new ImageData(
                                    imageArray: imageArray,
                                    width: (int)bmp.PixelWidth,
                                    height: (int)bmp.PixelHeight,
                                    bitDepth: bitDepth,
                                    isBayered: true,
                                    metaData: metaData);
                            }
                            else
                            {
                                Logger.Error("File not found: " + outputFile);
                                throw new Exception("Error occured during DCRaw conversion." + Environment.NewLine + sb.ToString());
                            }
                        }
                    } catch (Exception ex) {
                        Notification.Notification.ShowError(ex.Message);
                        Logger.Error(ex);
                    } finally {
                        if (File.Exists(rawfile))
                        {
                            File.Delete(rawfile);
                        }
                        if (File.Exists(outputFile))
                        {
                            File.Delete(outputFile);
                        }
                    }
                    return data;
                }
            }));
        }
Ejemplo n.º 46
0
            /// <summary>
            /// This is our scanner. Expects at least a filename of classes to scan
            /// </summary>
            /// <param name="PLEFileName">List of classes to scan, in a Comma Separated Value format</param>
            /// <param name="TimerBetweenScans">PLE can be a pain when starting too many jobs at once. This delays the start of the next set of classes. Defaults to 30 seconds</param>
            /// <param name="WaitForMIDASLogin">After your first class is sent to the scanner, this pauses the action until you have successfully logged in. Defaults to true</param>
            /// <param name="OutputLog">This reports back a log of operations. Useful when needing to send a report of classes that Do Not Exist (DNE)</param>
            /// <returns>Integer based on what happened:
            ///  * 0: Success
            ///  * 1: One or more classes report DNE
            ///  * 2: CSV File does not exist
            ///  * 3: CSV File not in correct format
            ///  * 4: Network Connection is down (either on your end or remote end)
            /// </returns>
            public static int ClassScanner(string PLEFileName, string YourName, string OutputLog, int TimerBetweenScans = 30, bool WaitForMIDASLogin = true)
            {
                try
                {
                    // Create our Streams
                    System.IO.StreamReader CSVFile = new System.IO.StreamReader(PLEFileName);
                    int errCode = 0;

                    // Create our Log file
                    PLEMassScanner.PLELog PleLog = new PLEMassScanner.PLELog(OutputLog);

                    // How long is our CSV
                    int CSVLen = System.IO.File.ReadLines(PLEFileName).Count();

                    // Get system clock info for logging
                    System.DateTime today    = System.DateTime.Today;
                    DateTime        nowBegin = DateTime.Now;

                    // Write data to the log file
                    PleLog.WriteFileHeader();
                    PleLog.WriteBodyOpener(YourName);

                    // Show our Progress Dialog
                    ScanProgress ScanningProgress = new ScanProgress();
                    ScanningProgress.SetProgressMax(CSVLen);
                    ScanningProgress.SetProgressMin();
                    ScanningProgress.SetLabel("Starting Up...");
                    ScanningProgress.TimerLabel("");
                    ScanningProgress.Show();
                    Application.DoEvents();



                    // Now, let's play with our CSV
                    string[] CSVLines = System.IO.File.ReadAllLines(PLEFileName);
                    int      i        = 0;
                    while (i < CSVLines.Length)
                    {
                        // Re-Declare Current DateTime for logging
                        DateTime now = DateTime.Now;
                        // For when the year and semester are combined, and need to be split off
                        string[] CSVArray = new string[3];
                        if (CSVLines[i].Contains("_"))
                        {
                            CSVArray = CourseIDToArray(CSVLines[i]);
                        }

                        // Fix formatting errors
                        for (int j = 0; j <= 2; j++)
                        {
                            string trimmed = String.Concat(CSVArray[j].Where(c => !Char.IsWhiteSpace(c)));
                        }

                        ScanningProgress.SetLabel("Starting Job " + (i + 1) + " of " + CSVLen);
                        // Build our URI
                        string BaseURI = "http://ple.odu.edu/courses/" + CSVArray[CourseYear] + CSVArray[CourseSemester] + "/" + CSVArray[CourseName] + "/editor/options/accessibility_scan?" + CSVArray[CourseName] + "_" + CSVArray[CourseYear] + CSVArray[CourseSemester];

                        // Converts our string to a URI Object
                        Uri PLEWebsite = new Uri(BaseURI);

                        // Check for PLE Errors
                        if (DoesPLEExist(PLEWebsite))
                        {
                            // Launch our website in the default browser
                            // All this mess to get around a bug in .NET Core that hasn't been fixed in years
                            var psi = new System.Diagnostics.ProcessStartInfo
                            {
                                FileName        = "cmd",
                                WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden,
                                UseShellExecute = false,
                                CreateNoWindow  = true,
                                Arguments       = $"/c start " + PLEWebsite.ToString()
                            };
                            System.Diagnostics.Process.Start(psi);

                            // Log a successful launch
                            PleLog.WriteLogEntry(CSVArray[CourseName], i, Convert.ToInt32(CSVArray[CourseYear]), Convert.ToInt32(CSVArray[CourseSemester]), now.ToLongDateString(), now.ToLongTimeString(), true);

                            // First time user, so we can wait for login
                            if (i == 0)
                            {
                                if (WaitForMIDASLogin)
                                {
                                    ScanningProgress.TimerLabel("");
                                    MessageBox.Show("Your browser should be sending you to the MIDAS Login. Once you are logged in and the pages is loaded, you may continue", PLEApplication.ApplicationNameWithVersion(), MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }

                            // Kick off our timer so that PLE is not overwhelmed unless this is the last one
                            if (i != CSVLen - 1)
                            {
                                // Sleep
                                for (int Ticks = TimerBetweenScans; Ticks >= 0; Ticks--)
                                {
                                    ScanningProgress.TimerLabel("Next Job in " + Ticks + " Seconds");
                                    System.Threading.Thread.Sleep(1000);
                                }
                            }
                        }
                        else
                        {
                            // PLE class does not exist. Report DNE in our log
                            PleLog.WriteLogEntry(CSVArray[CourseName], i, Convert.ToInt32(CSVArray[CourseYear]), Convert.ToInt32(CSVArray[CourseSemester]), now.ToLongDateString(), now.ToLongTimeString(), false);
                            errCode = 1;
                        }


                        ScanningProgress.SetProgressValue(i);
                        i++;
                    }
                    // Complete our logs and close our files
                    DateTime nowEnd = DateTime.Now;
                    PleLog.WriteHTMLBottom();
                    CSVFile.Close();
                    ScanningProgress.Close();
                    if (errCode == 1)
                    {
                        return(1);
                    }
                }
                catch (System.IO.FileNotFoundException ex)
                {
                    return(2);
                }



                // Success!
                return(0);
            }
        static void Main(string[] args)
        {
            System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo();
            start.FileName    = @"\ServerTest.exe";
            start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            TcpListener serverSocket = new TcpListener(54206);
            TcpClient   clientSocket = default(TcpClient);
            int         counter      = 0;

            serverSocket.Start();
            Console.WriteLine("Chat Server Started ....");
            counter = 0;
            while ((true))
            {
                counter     += 1;
                clientSocket = serverSocket.AcceptTcpClient();



                byte[] bytesFrom      = new byte[10025];
                string dataFromClient = null;
                string clientPubKey   = null;

                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                networkStream.Flush();

                //lets take a new CSP with a new 2048 bit rsa key pair
                var csp = new RSACryptoServiceProvider(2048);

                //how to get the private key
                Globals.privKey = csp.ExportParameters(true);

                //and the public key ...
                var pubKey = csp.ExportParameters(false);

                //converting the public key into a string representation
                string pubKeyString;
                {
                    //we need some buffer
                    var sw = new System.IO.StringWriter();
                    //we need a serializer
                    var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                    //serialize the key into the stream
                    xs.Serialize(sw, pubKey);
                    //get the string from the stream
                    pubKeyString = sw.ToString();
                }
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(pubKeyString + "$");

                networkStream.Write(outStream, 0, outStream.Length);

                Thread.Sleep(500);


                networkStream.Read(bytesFrom, 0, bytesFrom.Length);

                clientPubKey = System.Text.Encoding.ASCII.GetString(bytesFrom);
                clientPubKey = clientPubKey.Substring(0, clientPubKey.IndexOf("$"));

                clientsList.Add(dataFromClient, clientSocket);

                var per = new Person();
                per.hash      = clientSocket.GetHashCode();
                per.initials  = dataFromClient.Substring(1);
                per.publicKey = clientPubKey;
                personList.Add(per);

                broadcast("3**" + dataFromClient.Substring(1) + " Joined**", dataFromClient, false);

                Console.WriteLine(dataFromClient.Substring(1) + " Joined chat room ");
                handleClinet client = new handleClinet();
                client.startClient(clientSocket, "0" /*dataFromClient.Substring(1)*/, clientsList);
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine("exit");
            Console.ReadLine();
        }
 protected void AddEnvironmentVariablesToProcess(System.Diagnostics.ProcessStartInfo startInfo, System.Collections.Generic.IDictionary <string, string> environmentVariables)
 {
 }
Ejemplo n.º 49
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (!cam_mode && openFileDialog1.FileName == "")
            {
                return;
            }

            string model_size = "432x368";
            string model      = comboBox1.Text;

            if (comboBox1.Text == "cmu")
            {
                model_size = "656x368";
            }
            if (comboBox1.Text == "mobilenet_thin")
            {
                model_size = "432x368";
            }
            if (comboBox1.Text == "mobilenet_v2_large")
            {
                model_size = "432x368";
            }
            if (comboBox1.Text == "mobilenet_v2_small")
            {
                model_size = "432x368";
            }

            var apppath = System.IO.Path.GetDirectoryName(
                System.IO.Path.GetFullPath(
                    Environment.GetCommandLineArgs()[0]));

            //apppath = @"D:\tfPoseEstimation_app\tfPoseEstimation_application\tfPoseEstimation_application\dist";
            System.Environment.CurrentDirectory = apppath + "\\main";

            System.IO.Directory.SetCurrentDirectory(apppath + "\\main");

            if (!video_mode && !cam_mode)
            {
                string newfile1 = "input_.png";
                pictureBox1.Image.Save(newfile1, System.Drawing.Imaging.ImageFormat.Png);

                string newfile2    = "tfpose\\input.png";
                var    imagemagick = new System.Diagnostics.ProcessStartInfo();
                imagemagick.FileName        = "cmd.exe";
                imagemagick.UseShellExecute = true;
                imagemagick.Arguments       = "/c";
                imagemagick.Arguments      += " ..\\conv.bat";
                imagemagick.Arguments      += " " + newfile1;
                imagemagick.Arguments      += " " + model_size;
                imagemagick.Arguments      += " " + newfile2;
                System.Diagnostics.Process imagemagick_p = System.Diagnostics.Process.Start(imagemagick);
                imagemagick_p.WaitForExit();
                File.Delete(newfile1);

                var app = new System.Diagnostics.ProcessStartInfo();
                app.FileName        = "cmd.exe";
                app.UseShellExecute = true;
                app.Arguments       = "/c";
                app.Arguments      += " run_image.bat ";
                app.Arguments      += model;

                string directoryName = System.IO.Path.GetDirectoryName(openFileDialog1.FileName);
                string fileName      = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
                string extension     = System.IO.Path.GetExtension(openFileDialog1.FileName);

                System.Diagnostics.Process p = System.Diagnostics.Process.Start(app);
                p.WaitForExit();

                string outfile = "";
                outfile           = "tfpose\\output.jpg";
                pictureBox2.Image = CreateImage(outfile);
            }
            if (video_mode && !cam_mode)
            {
                var app = new System.Diagnostics.ProcessStartInfo();
                app.FileName        = "cmd.exe";
                app.UseShellExecute = true;
                app.Arguments       = "/c";
                app.Arguments      += " run_video.bat ";
                app.Arguments      += " " + "\"" + openFileDialog1.FileName + "\"" + " ";
                app.Arguments      += model;

                System.Diagnostics.Process p = System.Diagnostics.Process.Start(app);
                p.WaitForExit();
            }
            if (!video_mode && cam_mode)
            {
                var app = new System.Diagnostics.ProcessStartInfo();
                app.FileName        = "cmd.exe";
                app.UseShellExecute = true;
                app.Arguments       = "/c";
                app.Arguments      += " run_cam.bat ";
                app.Arguments      += " " + numericUpDown1.Value.ToString() + " ";
                app.Arguments      += model;

                System.Diagnostics.Process p = System.Diagnostics.Process.Start(app);
                p.WaitForExit();
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Executes specified actions.
        /// </summary>
        /// <param name="dvActions">Dataview what contains actions to be executed.</param>
        /// <param name="server">Reference to owner virtual server.</param>
        /// <param name="message">Recieved message.</param>
        /// <param name="sender">MAIL FROM: command value.</param>
        /// <param name="to">RCPT TO: commands values.</param>
        public GlobalMessageRuleActionResult DoActions(DataView dvActions, VirtualServer server, Stream message, string sender, string[] to)
        {
            // TODO: get rid of MemoryStream, move to Stream

            //    bool   messageChanged = false;
            bool   deleteMessage = false;
            string storeFolder   = null;
            string errorText     = null;

            // Loop actions
            foreach (DataRowView drV in dvActions)
            {
                GlobalMessageRuleAction_enum action = (GlobalMessageRuleAction_enum)drV["ActionType"];
                byte[] actionData = (byte[])drV["ActionData"];

                // Reset stream position
                message.Position = 0;

                #region AutoResponse

                /* Description: Sends specified autoresponse message to sender.
                 *  Action data structure:
                 *      <ActionData>
                 *          <From></From>
                 *          <Message></Message>
                 *      </ActionData>
                 */

                if (action == GlobalMessageRuleAction_enum.AutoResponse)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    string smtp_from   = table.GetValue("From");
                    string responseMsg = table.GetValue("Message");

                    // See if we have header field X-LS-MailServer-AutoResponse, never answer to auto response.
                    MIME_h_Collection header = new MIME_h_Collection(new MIME_h_Provider());
                    header.Parse(new SmartStream(message, false));
                    if (header.Contains("X-LS-MailServer-AutoResponse"))
                    {
                        // Just skip
                    }
                    else
                    {
                        Mail_Message autoresponseMessage = Mail_Message.ParseFromByte(System.Text.Encoding.Default.GetBytes(responseMsg));

                        // Add header field 'X-LS-MailServer-AutoResponse:'
                        autoresponseMessage.Header.Add(new MIME_h_Unstructured("X-LS-MailServer-AutoResponse", ""));
                        // Update message date
                        autoresponseMessage.Date = DateTime.Now;

                        // Set To: if not explicity set
                        if (autoresponseMessage.To == null || autoresponseMessage.To.Count == 0)
                        {
                            if (autoresponseMessage.To == null)
                            {
                                Mail_t_AddressList t = new Mail_t_AddressList();
                                t.Add(new Mail_t_Mailbox(null, sender));
                                autoresponseMessage.To = t;
                            }
                            else
                            {
                                autoresponseMessage.To.Add(new Mail_t_Mailbox(null, sender));
                            }
                        }
                        // Update Subject: variables, if any
                        if (autoresponseMessage.Subject != null)
                        {
                            if (header.Contains("Subject"))
                            {
                                autoresponseMessage.Subject = autoresponseMessage.Subject.Replace("#SUBJECT", header.GetFirst("Subject").ValueToString().Trim());
                            }
                        }

                        server.ProcessAndStoreMessage(smtp_from, new string[] { sender }, new MemoryStream(autoresponseMessage.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8)), null);
                    }
                }

                #endregion

                #region Delete Message

                /* Description: Deletes message.
                 *  Action data structure:
                 *      <ActionData>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.DeleteMessage)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    deleteMessage = true;
                }

                #endregion

                #region ExecuteProgram

                /* Description: Executes specified program.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Program></Program>
                 *          <Arguments></Arguments>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ExecuteProgram)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
                    pInfo.FileName       = table.GetValue("Program");
                    pInfo.Arguments      = table.GetValue("Arguments");
                    pInfo.CreateNoWindow = true;
                    System.Diagnostics.Process.Start(pInfo);
                }

                #endregion

                #region ForwardToEmail

                /* Description: Forwards email to specified email.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Email></Email>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ForwardToEmail)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    // See If message has X-LS-MailServer-ForwardedTo: and equals to "Email".
                    // If so, then we have cross reference forward, don't forward that message
                    MIME_h_Collection header = new MIME_h_Collection(new MIME_h_Provider());
                    header.Parse(new SmartStream(message, false));
                    bool forwardedAlready = false;
                    if (header.Contains("X-LS-MailServer-ForwardedTo"))
                    {
                        foreach (MIME_h headerField in header["X-LS-MailServer-ForwardedTo"])
                        {
                            if (headerField.ValueToString().Trim() == table.GetValue("Email"))
                            {
                                forwardedAlready = true;
                                break;
                            }
                        }
                    }

                    // Reset stream position
                    message.Position = 0;

                    if (forwardedAlready)
                    {
                        // Just skip
                    }
                    else
                    {
                        // Add header field 'X-LS-MailServer-ForwardedTo:'
                        MemoryStream msFwMessage = new MemoryStream();
                        byte[]       fwField     = System.Text.Encoding.Default.GetBytes("X-LS-MailServer-ForwardedTo: " + table.GetValue("Email") + "\r\n");
                        msFwMessage.Write(fwField, 0, fwField.Length);
                        SCore.StreamCopy(message, msFwMessage);

                        server.ProcessAndStoreMessage(sender, new string[] { table.GetValue("Email") }, msFwMessage, null);
                    }
                }

                #endregion

                #region ForwardToHost

                /* Description: Forwards email to specified host.
                 *              All RCPT TO: recipients are preserved.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Host></Host>
                 *          <Port></Port>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ForwardToHost)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    foreach (string t in to)
                    {
                        message.Position = 0;
                        server.RelayServer.StoreRelayMessage(
                            null,
                            Guid.NewGuid().ToString(),
                            message,
                            HostEndPoint.Parse(table.GetValue("Host") + ":" + table.GetValue("Port")),
                            sender,
                            t,
                            null,
                            SMTP_DSN_Notify.NotSpecified,
                            SMTP_DSN_Ret.NotSpecified
                            );
                    }
                    message.Position = 0; // TODO: does it later that needed there, must do in called place instead ?
                }

                #endregion

                #region StoreToDiskFolder

                /* Description: Stores message to specified disk folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToDiskFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    string folder = table.GetValue("Folder");
                    if (!folder.EndsWith("\\"))
                    {
                        folder += "\\";
                    }

                    if (Directory.Exists(folder))
                    {
                        using (FileStream fs = File.Create(folder + DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml")){
                            SCore.StreamCopy(message, fs);
                        }
                    }
                    else
                    {
                        // TODO: log error somewhere
                    }
                }

                #endregion

                #region StoreToIMAPFolder

                /* Description: Stores message to specified IMAP folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToIMAPFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);
                    storeFolder = table.GetValue("Folder");
                }

                #endregion

                #region AddHeaderField

                /* Description: Add specified header field to message main header.
                 *  Action data structure:
                 *      <ActionData>
                 *          <HeaderFieldName></HeaderFieldName>
                 *          <HeaderFieldValue></HeaderFieldValue>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.AddHeaderField)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    mime.Header.Add(new MIME_h_Unstructured(table.GetValue("HeaderFieldName"), table.GetValue("HeaderFieldValue")));
                    message.SetLength(0);
                    mime.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    //  messageChanged = true;
                }

                #endregion

                #region RemoveHeaderField

                /* Description: Removes specified header field from message mian header.
                 *  Action data structure:
                 *      <ActionData>
                 *          <HeaderFieldName></HeaderFieldName>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.RemoveHeaderField)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    mime.Header.RemoveAll(table.GetValue("HeaderFieldName"));
                    message.SetLength(0);
                    mime.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    //    messageChanged = true;
                }

                #endregion

                #region SendErrorToClient

                /* Description: Sends error to currently connected client. NOTE: Error text may contain ASCII printable chars only and maximum length is 500.
                 *  Action data structure:
                 *      <ActionData>
                 *          <ErrorText></ErrorText>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.SendErrorToClient)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    errorText = table.GetValue("ErrorText");
                }

                #endregion

                #region StoreToFTPFolder

                /* Description: Stores message to specified FTP server folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Server></Server>
                 *          <Port></Server>
                 *          <User></User>
                 *          <Password></Password>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToFTPFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    _MessageRuleAction_FTP_AsyncSend ftpSend = new _MessageRuleAction_FTP_AsyncSend(
                        table.GetValue("Server"),
                        Convert.ToInt32(table.GetValue("Port")),
                        table.GetValue("User"),
                        table.GetValue("Password"),
                        table.GetValue("Folder"),
                        message,
                        DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml"
                        );
                }

                #endregion

                #region PostToNNTPNewsGroup

                /* Description: Posts message to specified NNTP newsgroup.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Server></Server>
                 *          <Port></Server>
                 *          <User></User>
                 *          <Password></Password>
                 *          <Newsgroup></Newsgroup>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.PostToNNTPNewsGroup)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    // Add header field "Newsgroups: newsgroup", NNTP server demands it.
                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    if (!mime.Header.Contains("Newsgroups:"))
                    {
                        mime.Header.Add(new MIME_h_Unstructured("Newsgroups:", table.GetValue("Newsgroup")));
                    }

                    _MessageRuleAction_NNTP_Async nntp = new _MessageRuleAction_NNTP_Async(
                        table.GetValue("Server"),
                        Convert.ToInt32(table.GetValue("Port")),
                        table.GetValue("Newsgroup"),
                        new MemoryStream(mime.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8))
                        );
                }

                #endregion

                #region PostToHTTP

                /* Description: Posts message to specified page via HTTP.
                 *  Action data structure:
                 *      <ActionData>
                 *          <URL></URL>
                 *          <FileName></FileName>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.PostToHTTP)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    _MessageRuleAction_HTTP_Async http = new _MessageRuleAction_HTTP_Async(
                        table.GetValue("URL"),
                        message
                        );
                }

                #endregion
            }

            return(new GlobalMessageRuleActionResult(deleteMessage, storeFolder, errorText));
        }
Ejemplo n.º 51
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public MagickImage getImg(String inputPath, String type)
        {
            if (M.c_影像.func_判斷_RAW(type))
            {
                string dcRawExe  = M.fun_執行檔路徑() + "/data/dcraw-9.27-ms-32-bit.exe";
                var    startInfo = new System.Diagnostics.ProcessStartInfo(dcRawExe)
                {
                    Arguments = "-c -e \"" + inputPath + "\"",
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true
                };

                try {
                    using (var process = System.Diagnostics.Process.Start(startInfo)) {
                        Stream st           = process.StandardOutput.BaseStream;
                        var    memoryStream = new MemoryStream();
                        st.CopyTo(memoryStream);
                        memoryStream.Position = 0;

                        MagickImage mmm = null;

                        if (type == "X3F")
                        {
                            mmm = new MagickImage(new System.Drawing.Bitmap(memoryStream));
                        }
                        else
                        {
                            mmm = new MagickImage((memoryStream));
                        }



                        return(mmm);
                    }
                } catch (Exception e) {
                    System.Console.WriteLine("MagickImage錯誤" + e.ToString());
                }
            }



            if (type == "CR2")
            {
                //raw。必須從stream讀取圖片,不然會有BUG
                using (FileStream logFileStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                    return(new MagickImage(logFileStream));
                }
            }
            else if (type == "PDF" || type == "SVG" || type == "AI" || type == "WMF" || type == "EMF")
            {
                //設定輸出的解析度,用於向量圖片(svg、ai、pdf
                MagickReadSettings settings = new MagickReadSettings();
                settings.Density = new Density(300, 300);
                return(new MagickImage(inputPath, settings));
            }
            else
            {
                //一般
                return(new MagickImage(inputPath));
            }
        }
Ejemplo n.º 52
0
        private void ExporteExecute(object obj)
        {
            var dataGrid = obj as SfDataGrid;

            if (dataGrid == null)
            {
                return;
            }
            try
            {
                if ((dataGrid.DataContext as ViewModel).ComboBoxExportSelectedItem.ToString() == "Excel")
                {
                    ExcelEngine    excelEngine = dataGrid.ExportCollectionToExcel(dataGrid.View, ExcelVersion.Excel2007, exportingHandler, cellsExportingHandler, true);
                    IWorkbook      workBook    = excelEngine.Excel.Workbooks[0];
                    SaveFileDialog sfd         = new SaveFileDialog
                    {
                        FilterIndex = 1,
                        Filter      = "Excel 2007 to 2010 Files(*.xlsx)|*.xlsx|Excel 97 to 2003 Files(*.xls)|*.xls"
                    };

                    if (sfd.ShowDialog() == true)
                    {
                        using (Stream stream = sfd.OpenFile())
                        {
                            if (sfd.FilterIndex == 1)
                            {
                                workBook.Version = ExcelVersion.Excel2010;
                            }
                            else
                            {
                                workBook.Version = ExcelVersion.Excel97to2003;
                            }
                            workBook.SaveAs(stream);
                        }

                        //Message box confirmation to view the created spreadsheet.
                        if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                            MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                        {
                            //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
                            Open(sfd.FileName);
                        }
                    }
                }
                else
                {
                    var options = new PdfExportingOptions();
                    options.ExportAllPages = true;
                    var document = dataGrid.ExportToPdf(options);

                    SaveFileDialog sfd = new SaveFileDialog
                    {
                        Filter   = "PDF Files(*.pdf)|*.pdf",
                        FileName = "document1"
                    };

                    if (sfd.ShowDialog() == true)
                    {
                        using (Stream stream = sfd.OpenFile())
                        {
                            document.Save(stream);
                        }

                        //Message box confirmation to view the created Pdf file.
                        if (MessageBox.Show("Do you want to view the Pdf file?", "Pdf file has been created",
                                            MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                        {
                            //Launching the Pdf file using the default Application.
                            System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(sfd.FileName);
                            info.UseShellExecute = true;
                            System.Diagnostics.Process.Start(info);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 53
0
        private void BuildConfig(
            string projectName,
            string projectFolder,
            System.Guid projectGuid,
            string output,
            string outputFolder,
            Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Settings settings,
            Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Config config,
            List <Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Reference> references,
            List <Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.ProjectReference> projectReferences,
            List <Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Item> items,
            ProjectBuildTracker projectBuildTracker)
        {
            this._output.Add(new Output("Begin Build " + projectName));
            this._output.Add(new Output(""));



            System.IO.DirectoryInfo directoryInfo = new System.IO.FileInfo(output).Directory;
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }



            Bamboo.CSharp.Compilers.CompilerParameters compilerParameters = new Bamboo.CSharp.Compilers.CompilerParameters();

            if (settings.ApplicationIcon.Length > 0)
            {
                compilerParameters.ApplicationIcon = projectFolder + System.IO.Path.DirectorySeparatorChar + settings.ApplicationIcon;
            }

            compilerParameters.Assembly = output;

            compilerParameters.Target = settings.OutputType.ToLower();

            compilerParameters.Define = config.DefineConstants;
            if (config.DebugSymbols.Length == 0)
            {
                compilerParameters.Debug = false;
            }
            else
            {
                compilerParameters.Debug = System.Boolean.Parse(config.DebugSymbols);
            }
            foreach (Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Reference reference in references)
            {
                if (ProjectReferenceRules.IsFrameworkReference(reference))
                {
                    //
                    // Framework reference.
                    //
                    string frameworkPath = this._compiler.GetFrameworkPath();
                    string referencePath = frameworkPath + reference.Include + ".dll";

                    if (!System.IO.File.Exists(referencePath))
                    {
                    }
                    else
                    {
                        compilerParameters.References.Add(referencePath);
                    }
                }
                else if (ProjectReferenceRules.IsAssemblyFolderReference(reference))
                {
                    //
                    // AssemblyFolder reference.
                    //
                    string referencePath = ProjectReferenceRules.GetReferencePath(projectFolder, reference.HintPath, this._compiler);
                    if (referencePath != null)
                    {
                        if (System.IO.File.Exists(referencePath))
                        {
                            compilerParameters.References.Add(referencePath);
                        }
                        else if (System.IO.File.Exists(referencePath + ".dll"))
                        {
                            compilerParameters.References.Add(referencePath + ".dll");
                        }
                        else
                        {
                        }
                    }
                }
                else
                {
                    //
                    // File reference.
                    //
                    string referencePath = ProjectReferenceRules.GetReferencePath(projectFolder, reference.HintPath, this._compiler);
                    if (referencePath != null)
                    {
                        string output_folder = new System.IO.FileInfo(output).DirectoryName;
                        if (!output_folder.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                        {
                            output_folder += System.IO.Path.DirectorySeparatorChar;
                        }
                        string target = output_folder + new System.IO.FileInfo(referencePath).Name;
                        if (!target.Equals(referencePath))
                        {
                            System.IO.File.Copy(referencePath, target, true);

                            while (!System.IO.File.Exists(target))
                            {
                                System.Threading.Thread.Sleep(500);
                            }
                        }

                        compilerParameters.References.Add(referencePath);
                    }
                }
            }
            foreach (Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.ProjectReference projectReference in projectReferences)
            {
                //
                // Project reference.
                //
                string projectReferencePath = projectBuildTracker.GetPath(new System.Guid(projectReference.Project));

                if (projectReferencePath != null)
                {
                    string output_folder = new System.IO.FileInfo(output).DirectoryName;
                    if (!output_folder.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                    {
                        output_folder += System.IO.Path.DirectorySeparatorChar;
                    }
                    string target = output_folder + new System.IO.FileInfo(projectReferencePath).Name;
                    if (!target.Equals(projectReferencePath))
                    {
                        System.IO.File.Copy(projectReferencePath, target, true);

                        while (!System.IO.File.Exists(target))
                        {
                            System.Threading.Thread.Sleep(500);
                        }
                    }
                    compilerParameters.References.Add(target);
                }
            }
            foreach (Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Item item in items)
            {
                if (item.Type == "Compile")
                {
                    compilerParameters.Sources.Add(projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include);
                }
                else if (item.Type == "Content")
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(outputFolder + item.Include);
                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }
                    System.IO.File.Copy(projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include, outputFolder + item.Include, true);
                }
                else if (item.Type == "None" && item.Include.Equals("App.config"))
                {
                    System.IO.File.Copy(projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include, output + ".config");
                }
                else if (item.Type == "EmbeddedResource")
                {
                    if (item.Include.ToLower().EndsWith(".resx"))
                    {
                        string RESGEN_EXE = Bamboo.CSharp.FrameworkDetector.GetSDKInstallRoot("v" + this._compiler.GetFrameworkVersion()) + "Bin\\resgen.exe";
                        //TODO OLD string RESGEN_EXE = @"C:\Program Files\Swampware\SDK\NET_2.0\resgen.exe";

                        System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
                        processStartInfo.FileName = RESGEN_EXE;
                        processStartInfo.RedirectStandardOutput = true;
                        processStartInfo.UseShellExecute        = false;
                        processStartInfo.CreateNoWindow         = true;
                        processStartInfo.WorkingDirectory       = System.Environment.CurrentDirectory;

                        string arguments = "\"" + projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include + "\"";

                        string resourceFile  = item.Include.Substring(0, item.Include.Length - 5) + ".resources";
                        string resource_name = settings.RootNamespace + "." + resourceFile.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), ".");
                        string resource_path = "\"" + projectFolder + System.IO.Path.DirectorySeparatorChar + "obj" + System.IO.Path.DirectorySeparatorChar + "res" + System.IO.Path.DirectorySeparatorChar + resource_name + "\"";
                        arguments += " " + resource_path;

                        if (!System.IO.Directory.Exists(projectFolder + System.IO.Path.DirectorySeparatorChar + "obj" + System.IO.Path.DirectorySeparatorChar + "res"))
                        {
                            System.IO.Directory.CreateDirectory(projectFolder + System.IO.Path.DirectorySeparatorChar + "obj" + System.IO.Path.DirectorySeparatorChar + "res");
                        }

                        processStartInfo.Arguments = arguments;
                        System.Diagnostics.Process process = System.Diagnostics.Process.Start(processStartInfo);

                        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
                        while (!process.HasExited)
                        {
                            stringWriter.Write(process.StandardOutput.ReadToEnd());
                            process.WaitForExit(50);
                        }
                        stringWriter.Write(process.StandardOutput.ReadToEnd());
                        process.Close();
                        process.Dispose();

                        this._output.Add(new Output(stringWriter.ToString()));



                        this._output.Add(new Output("Converting " + item.Include + " to " + resourceFile + ""));

                        compilerParameters.Resources.Add(resource_path);
                    }
                    else
                    {
                        string resource_name = settings.RootNamespace + "." + item.Include.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), ".");

                        compilerParameters.Resources.Add("\"" + projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include + "\"" + "," + resource_name);
                    }
                }
            }


            this._compiler.Compile(compilerParameters);



            //
            // Output
            //
            foreach (string line in compilerParameters.Output)
            {
                this._output.Add(new Output(line));
            }

            //
            // Errors
            //
            bool hasErrors = false;

            foreach (Bamboo.CSharp.Compilers.Error error in compilerParameters.Errors)
            {
                if (!error.IsWarning)
                {
                    hasErrors = true;
                }
                this._errors.Add(new Error(error.IsWarning, error.File, error.Line, error.Column, error.Code, error.Description, error.Text));
            }



            if (hasErrors)
            {
                this._succeeded = false;
                this._output.Add(new Output(""));
                this._output.Add(new Output("Build Failed " + projectName));
            }
            else
            {
                this._succeeded = true;
                this._assembly  = compilerParameters.Assembly;
                this._output.Add(new Output(""));
                this._output.Add(new Output("Build Succeeded " + projectName));

                projectBuildTracker.Add(projectGuid, compilerParameters.Assembly);
            }
        }
Ejemplo n.º 54
0
        private bool Install()
        {
            if (System.IO.Directory.Exists(m_InstallDirectory) == true)
            {
                var files = System.IO.Directory.GetFiles(m_InstallDirectory);

                bool launcherInDirectory = false;
                foreach (var file in files)
                {
                    if (file.ToLower().Contains("vf_wowlauncher.exe") == true || file.ToLower().Contains("wyupdate.exe") == true)
                    {
                        launcherInDirectory = true;
                    }
                }
                if (launcherInDirectory == true)
                {
                    var dialogResult = MessageBox.Show("The installer has detected that VF_WowLauncher was already installed. Do you want to delete all the old settings and replace the other installation?", "Delete all old settings?", MessageBoxButtons.YesNo);
                    if (dialogResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        try
                        {
                            VF.Utility.DeleteDirectory(m_InstallDirectory);
                        }
                        catch (Exception ex)
                        { }
                        if (System.IO.Directory.Exists(m_InstallDirectory) == true)
                        {
                            VF.Utility.SoftThreadSleep(5000);
                            if (System.IO.Directory.Exists(m_InstallDirectory) == true)
                            {
                                MessageBox.Show("Could not delete the old installation, try restart the computer or install to another path");
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (files.Length > 0 || System.IO.Directory.GetDirectories(m_InstallDirectory).Length > 0)
                {
                    MessageBox.Show("The installer has detected that there were files in the folder selected as install directory. Please chose another directory or delete the directory and try install again");
                    return(false);
                }
                else
                {
                    VF.Utility.DeleteDirectory(m_InstallDirectory);
                }
            }

            //At this stage m_InstallDirectory should not exist!
            if (System.IO.Directory.Exists(m_InstallDirectory) == true)
            {
                throw new Exception("Unexpected: Installation Directory should not exist at this point!");
            }

            System.IO.Directory.CreateDirectory(m_InstallDirectory);

            System.IO.File.WriteAllBytes(m_InstallDirectory + "wyUpdate.exe", Properties.Resources.wyUpdate);
            System.IO.File.WriteAllBytes(m_InstallDirectory + "client.wyc", Properties.Resources.client);

            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName               = m_InstallDirectory + "wyUpdate.exe";
            startInfo.Arguments              = "/skipinfo";
            startInfo.UseShellExecute        = false;
            startInfo.RedirectStandardOutput = true;
            var wyUpdateProcess = System.Diagnostics.Process.Start(startInfo);

            string data = "";

            while (wyUpdateProcess.HasExited == false)
            {
                VF.Utility.SoftThreadSleep(100);
                data += wyUpdateProcess.StandardOutput.ReadToEnd();
            }

            data += wyUpdateProcess.StandardOutput.ReadToEnd();
            int exitCode = wyUpdateProcess.ExitCode;

            if (exitCode == 1)
            {
                return(false);
            }

            if (System.IO.File.Exists(m_InstallDirectory + "VF_WowLauncher.exe") == false)
            {
                return(false);
            }

            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            if (System.IO.File.Exists(desktopPath + "\\VF_WoWLauncher.lnk") == true)
            {
                VF.Utility.DeleteFile(desktopPath + "\\VF_WoWLauncher.lnk");
            }
            VF.Utility.SoftThreadSleep(100);
            CreateShortcut(desktopPath + "\\VF_WoWLauncher"
                           , m_InstallDirectory + "VF_WowLauncher.exe", "VF_WoWLauncher", m_InstallDirectory + "VF_WowLauncher.exe");

            return(true);
        }
Ejemplo n.º 55
0
 private static void Open(string fileName)
 {
     System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(fileName);
     info.UseShellExecute = true;
     System.Diagnostics.Process.Start(info);
 }
Ejemplo n.º 56
0
        void LoadFile(string filepath, bool isReloading)
        {
            // Convert file
            var ext         = System.IO.Path.GetExtension(filepath).ToLower().Replace(".", "");
            var newFilepath = System.IO.Path.ChangeExtension(filepath, ".efkmodel");

            Effekseer.Utl.ModelInformation modelInfo = new Utl.ModelInformation();
            if (modelInfo.Load(newFilepath))
            {
                if (!isReloading)
                {
                    binding.SetAbsolutePath(filepath);
                    System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));
                    return;
                }
            }
            else
            {
                // Remove invalid file
                if (System.IO.File.Exists(newFilepath))
                {
                    try
                    {
                        System.IO.File.Delete(newFilepath);
                    }
                    catch
                    {
                    }
                }
            }

            Dialog.OpenModel omd = new Dialog.OpenModel(modelInfo.Scale);

            if (ext == "fbx" || ext == "mqo")
            {
                omd.Show("");
            }
            else
            {
                binding.SetAbsolutePath(filepath);

                System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));

                Manager.Viewer.Reload(true);
            }

            omd.OnOK = () =>
            {
                if (ext == "fbx")
                {
                    var  oldFilepath = filepath;
                    bool doGenerate  = false;

                    if (!System.IO.File.Exists(newFilepath) ||
                        System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                        modelInfo.Scale != omd.Magnification)
                    {
                        doGenerate = true;
                    }

                    if (doGenerate)
                    {
                        string converterPath = Manager.GetEntryDirectory() + "/tools/fbxToEffekseerModelConverter";

                        // japanese file path is not supported.
                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Copy(oldFilepath, tempFilePath);
                            oldFilepath = tempFilePath;
                        }
                        catch
                        {
                        }


                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

                        var os = System.Environment.OSVersion;
                        if (os.Platform == PlatformID.Win32NT ||
                            os.Platform == PlatformID.Win32S ||
                            os.Platform == PlatformID.Win32Windows ||
                            os.Platform == PlatformID.WinCE)
                        {
                            converterPath += ".exe";
                        }

                        if (os.Platform == PlatformID.Unix && os.Platform != PlatformID.MacOSX)
                        {
                            string pathvar = System.Environment.GetEnvironmentVariable("LD_LIBRARY_PATH");
                            info.EnvironmentVariables["LD_LIBRARY_PATH"] = pathvar + ";" + Manager.GetEntryDirectory() + "/tools/";
                        }

                        info.FileName = converterPath;

                        info.Arguments = "\"" + oldFilepath + "\" \"" + newFilepath + "\" -scale " + omd.Magnification.ToString();

                        if (!System.IO.File.Exists(oldFilepath))
                        {
                            var msg = oldFilepath + " is not found.";

                            swig.GUIManager.show(msg, "Error", swig.DialogStyle.Error, swig.DialogButtons.OK);
                            return;
                        }

                        if (!System.IO.File.Exists(converterPath))
                        {
                            var msg = converterPath + " is not found.";

                            swig.GUIManager.show(msg, "Error", swig.DialogStyle.Error, swig.DialogButtons.OK);
                            return;
                        }

                        info.UseShellExecute        = false;
                        info.RedirectStandardOutput = true;
                        info.RedirectStandardInput  = false;
                        info.CreateNoWindow         = true;

                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);

                        string outputs = p.StandardOutput.ReadToEnd();

                        p.WaitForExit();
                        p.Dispose();


                        if (System.IO.File.Exists(newFilepath))
                        {
                            System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                        }
                        else
                        {
                            var msg = " Failed to load. \n" + outputs;

                            swig.GUIManager.show(msg, "Error", swig.DialogStyle.Error, swig.DialogButtons.OK);
                        }

                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Delete(tempFilePath);
                        }
                        catch
                        {
                        }
                    }
                }

                if (ext == "mqo")
                {
                    var oldFilepath = filepath;

                    bool doGenerate = false;

                    if (!System.IO.File.Exists(newFilepath) ||
                        System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                        modelInfo.Scale != omd.Magnification)
                    {
                        doGenerate = true;
                    }

                    if (doGenerate)
                    {
                        string converterPath = Manager.GetEntryDirectory() + "/tools/mqoToEffekseerModelConverter";

                        // japanese file path is not supported.
                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Copy(oldFilepath, tempFilePath);
                            oldFilepath = tempFilePath;
                        }
                        catch
                        {
                        }

                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

                        var os = System.Environment.OSVersion;
                        if (os.Platform == PlatformID.Win32NT ||
                            os.Platform == PlatformID.Win32S ||
                            os.Platform == PlatformID.Win32Windows ||
                            os.Platform == PlatformID.WinCE)
                        {
                            converterPath += ".exe";
                        }

                        try
                        {
                            mqoToEffekseerModelConverter.Program.Call(new[] { oldFilepath, newFilepath, "-scale", omd.Magnification.ToString() });
                        }
                        catch
                        {
                        }

                        if (System.IO.File.Exists(newFilepath))
                        {
                            System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                        }

                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Delete(tempFilePath);
                        }
                        catch
                        {
                        }
                    }
                }

                binding.SetAbsolutePath(filepath);

                System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));

                Manager.Viewer.Reload(true);

                Read();
            };
        }
Ejemplo n.º 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();
                    }
                }
            }
        }
Ejemplo n.º 58
0
        void StartExternalServer(bool admin)
        {
//return;
            m_log.Info("StartExternalServer");
            TextAsset serverData = LoadTextAsset("HFTOSXServer");
            TextAsset shaData    = LoadTextAsset("HFTOSXServer.sha256");

            if (serverData == null || shaData == null)
            {
                return;
            }

            string serverPath = Application.persistentDataPath + "/hft-server";
            string shaPath    = Application.persistentDataPath + "/hft-server.sha";

            m_log.Info("Checking: " + serverPath);
            if (!FileExistsAndSame(serverPath, shaPath, shaData.text))
            {
                HFTUtil.WriteBytes(serverPath, serverData.bytes);
                HFTUtil.WriteText(shaPath, shaData.text);
                m_log.Info("wrote new webserver: " + serverPath + ", size: " + serverData.bytes.Length);
            }

            string cmdString = @"-e '
set myFile to quoted form of ""%(serverPath)s""
do shell script ""chmod -R 700 "" & myFile
do shell script myFile %(admin)s
'";
            Dictionary <string, string> dict = new Dictionary <string, string>();

            dict["serverPath"] = serverPath;
            dict["admin"]      = admin ? "with administrator privileges" : "";
            string script = HFTUtil.ReplaceParamsFlat(cmdString, dict);

            System.Diagnostics.Process          p   = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo psi = p.StartInfo;
            psi.EnvironmentVariables.Add("HFT_ARGS", Serializer.Serialize(m_options));
            psi.UseShellExecute        = false;
            psi.FileName               = "/usr/bin/osascript";
            psi.Arguments              = script;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            p.ErrorDataReceived       += new System.Diagnostics.DataReceivedEventHandler((sender, e) => {
                if (m_listening && !String.IsNullOrEmpty(e.Data))
                {
                    m_log.Tell("webserver: stderr: " + e.Data);
                }
            });
            p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler((sender, e) => {
                if (m_listening && !String.IsNullOrEmpty(e.Data))
                {
                    m_log.Info("webserver: stdout: " + e.Data);
                }
            });
            m_log.Info("StartExternalServer: start");
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            if (p.WaitForExit(2000))
            {
                // If it exited there was an error
                m_log.Tell("error starting webserver: exit code = " + p.ExitCode);
            }
            else
            {
                m_webServerProcess = p;
                m_log.Info("StartExternalServer: started");
            }
        }
Ejemplo n.º 59
0
 public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo startInfo)
 {
     return(default(System.Diagnostics.Process));
 }
Ejemplo n.º 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;
        }