private static void run_shell_script()
 {
     System.Diagnostics.Process proc = new System.Diagnostics.Process();
     proc.EnableRaisingEvents = false;
     proc.StartInfo.FileName = "run.sh";
     proc.Start();
 }
        //-------------------------------------------------------------------//
        //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]);
            }
        }
        public void start()
        {
            try
            {
                geoDatabaseUtility geoUtil = new geoDatabaseUtility();
                System.Diagnostics.Process pr = new System.Diagnostics.Process();
                geoUtil.check_dir(rmrsDir);
                string hFl = rmrsDir + "\\" + HelpFileName;
                pr.StartInfo.FileName = hFl;

                if (System.IO.File.Exists(hFl))
                {
                    pr.Start();
                }
                else
                {
                    update up = new update();
                    try
                    {
                        System.Windows.Forms.MessageBox.Show("Can't find help files. Trying to download from the internet.");
                        string cuSet = up.UpdateCheck;
                        if (cuSet.ToLower() != "yes")
                        {
                            up.UpdateCheck = "yes";

                        }
                        Properties.Settings.Default.HelpVersion = "unknown";
                        Properties.Settings.Default.Save();
                        if (up.updateHelp())
                        {
                            pr.Start();
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show("Can't find help files on the internet. Try again later.");
                        }
                        up.UpdateCheck = cuSet;
                    }
                    catch
                    {
                        System.Windows.Forms.MessageBox.Show("Error in updating help. Try again later.");
                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {

            }
        }
Exemple #4
0
        public static void SaveScreenShot(string path, string filename,string savepath)
        {
            //string result = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = path + "\\adb.exe";
            //要执行的程序名称
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            //可能接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;
            //由调用程序获取输出信息
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.Arguments = "pull /sdcard/"+filename+" " + savepath + "\\" + filename;
            //不显示程序窗口
            p.Start();

            //result += p.StandardOutput.ReadToEnd();
            //p.BeginOutputReadLine();
            p.WaitForExit();
            while (p.ExitCode != 0)
            {
                //result += p.StandardOutput.ReadToEnd();
                //Thread.Sleep(200);
            }
            Thread.Sleep(500);
            p.Close();
            return;
        }
        public override object Invoke(object[] args)
        {
            if (_dbsh == null) return args[0];
            if (args[0] == null) return null;

            try
            {
                var process = new System.Diagnostics.Process();
                process.StartInfo.FileName = _dbsh.Program;
                process.StartInfo.Arguments = _dbsh.Arguments;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                process.Start();

                process.StandardInput.Write(args[0].SafeToString() ?? "");
                process.StandardInput.Close();

                string output = process.StandardOutput.ReadToEnd();
                return output;
            }
            catch (Exception err)
            {
                return args[0];
            }
        }
 private void iv_MouseClick(object sender, MouseEventArgs e)
 {
     string filename = ((ImageViewerControl)(sender)).FileName;
     System.Diagnostics.Process process = new System.Diagnostics.Process();
     process.StartInfo = new System.Diagnostics.ProcessStartInfo(filename);
     process.Start();
 }      
Exemple #7
0
        public static void Run(string cmd, string arguments)
        {
            try
            {
                //process used to execute external commands
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.ErrorDialog = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                process.StartInfo.StandardErrorEncoding = Encoding.UTF8;

                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = cmd;
                process.StartInfo.Arguments = arguments;
                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                process.StartInfo.LoadUserProfile = true;

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

            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry! Error occured during starting glassfish starting.");
            }
            finally
            {
                this.Close();
                this.Dispose(true);
            }
        }
Exemple #9
0
        public GUI()
        {
            InitializeComponent();
            

            #region Timers
            // Manages gui updates
            guiUpdateTimer.Interval = 100;
            guiUpdateTimer.Tick += new EventHandler(guiUpdateTimer_Tick);
            guiUpdateTimer.Start();

            #endregion Timers

            #region OpenGL
            //Start OpenGLViewer, listen for it to exit and setup remoting
            openGLApp = new System.Diagnostics.Process();
            openGLApp.StartInfo.FileName = "OpenGLViewer.exe";
            openGLApp.EnableRaisingEvents = true;
            openGLApp.Start();
            openGLApp.Exited += new EventHandler(openGLApp_Exited);

            openGLViewerRemoteControl = (OpenGLViewer.OpenGLViewerRemoteControl)Activator.GetObject(typeof(OpenGLViewer.OpenGLViewerRemoteControl), "tcp://127.0.0.1:8008/Remote");
              

            #endregion OpenGL 

            //Build the GUI for the trackables and joints definied in the member variables
            BuildGUI();

            //connect to the server
            connect_Click(null, EventArgs.Empty);
        }
Exemple #10
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
            }
        }
Exemple #11
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;
        }
        public void Command(String Action, String Data)
        {
            iHandle = Win32.FindWindow("WMPlayerApp", "Windows Media Player");

            switch (Action)
            {
                case "Play":
                    {
                        if (iHandle == 0)
                        {
                            string FileName = @"wmplayer.exe";
                            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
                            myProcess.StartInfo.FileName = FileName;
                            myProcess.Start();
                        }

                        Win32.SendMessage(iHandle, Win32.WM_COMMAND, 0x00004978, 0x00000000);
                        break;
                    }
                case "Stop":
                    {
                        if (iHandle == 0)
                            return;
                        Win32.SendMessage(iHandle, Win32.WM_COMMAND, 0x00004979, 0x00000000);
                        break;
                    }

            }
        }
Exemple #13
0
        public static string GetDevice(string path)
        {
            string result = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = path + "\\adb.exe";
            //要执行的程序名称
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            //可能接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;
            //由调用程序获取输出信息
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.Arguments = "devices";
            //不显示程序窗口
            p.Start();

            result += p.StandardOutput.ReadToEnd();
            //p.BeginOutputReadLine();
            p.WaitForExit();
            while (p.ExitCode != 0)
            {
                result += p.StandardOutput.ReadToEnd();
                Thread.Sleep(200);
            }
            p.Close();
            return result;
        }
Exemple #14
0
 private void BtnScreenKeyboard_Click(object sender, RoutedEventArgs e)
 {
     var p = new System.Diagnostics.Process();
     p.StartInfo.FileName = "osk.exe";
     p.StartInfo.UseShellExecute = true;
     p.Start();
 }
        //CheckEpubを実施、Output/Errorを表示する
        public void CheckEpub()
        {
            //EPUBチェック実施中パネルを表示する
            var checkingDlg = new EpubCheckingDialog();
            checkingDlg.Show();

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

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

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

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

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

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

            p.Start();

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

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

            var resultDlg = new EpubCheckResultDialog();

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

            //Errorをコピーする
            if (errorLines.Count> 1)
            {
                foreach (var error in errorLines)
                {
                    resultDlg.errorTextBox.Text += (error + "\n");
                }
            }
            else
            {
                resultDlg.errorTextBox.Text = "エラーはありませんでした。";
            }
            checkingDlg.Close();
            resultDlg.ShowDialog();
        }
Exemple #16
0
 public static void Chmod(string Filename, int Chmod)
 {
     string exec = "chmod "+ Chmod.ToString() +" \""+ Filename +"\"";
     System.Diagnostics.Process process = new System.Diagnostics.Process();
     process.StartInfo.FileName = exec;
     process.Start();
 }
Exemple #17
0
        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();

            if(!UpdateSpec())
            {
                MessageBox.Show("error");
                return;
            }

            string path = Environment.CurrentDirectory.ToString() + "\\nuget.exe";

            if (!System.IO.File.Exists(directory + "\\nuget.exe"))
                System.IO.File.Copy(path, directory + "\\nuget.exe");

            System.Diagnostics.Process nuget = new System.Diagnostics.Process();
            nuget.StartInfo.FileName = directory + "\\nuget.exe";
            nuget.StartInfo.RedirectStandardOutput = true;
            nuget.StartInfo.UseShellExecute = false;
            nuget.StartInfo.WorkingDirectory = directory;
            nuget.StartInfo.Arguments = "pack ";//+ System.IO.Path.GetFileName(txtCsproj.Text);
            nuget.Start();

            var aa = nuget.StandardOutput.ReadToEnd();
            listBox1.Items.Add(nuget.StandardOutput.ReadToEnd());
        }
Exemple #18
0
        public override void Uninstall(IDictionary state)
        {
            //UninstallFirewallRule(state);
            /*
            bool rebootRequired;
            Interop.DriverPackageUninstallW(
                Context.Parameters["TARGETDIR"] + @"\ytdrv.inf",
                0,
                IntPtr.Zero,
                out rebootRequired
                );
            */
            // Удаляем драйвер.
            System.Diagnostics.Process infSetup =
                new System.Diagnostics.Process();

            infSetup.StartInfo.FileName = "rundll32";
            infSetup.StartInfo.Arguments =
                "advpack.dll, LaunchINFSection .\\ytdrv.inf,Uninstall.NT";
            infSetup.StartInfo.CreateNoWindow = true;
            infSetup.StartInfo.UseShellExecute = true;
            infSetup.StartInfo.WorkingDirectory = Context.Parameters["INSTDIR"];

            infSetup.Start();

            base.Uninstall(state);
        }
        public static void runningBalkCopy(string dbName, string path, BCPDirection direction, string option, string remoteDb)
        {
            //ディレクション
            string strDirection = "in";
            if (direction == BCPDirection.BCP_OUT)
            {
                strDirection = "out";
            }
            else
            {
                strDirection = "in";
            }

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

            using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
            {
                proc.StartInfo.FileName = "bcp";
                proc.StartInfo.Arguments = dbName + " " + strDirection + " \"" + path + "\" " + option + strRemoteDb;
                proc.Start();
                proc.WaitForExit();
            }
        }
 private void stackpanel_MouseDown(object sender, MouseButtonEventArgs e)
 {
     string filename = (string)((StackPanel)(sender)).ToolTip;
     System.Diagnostics.Process process = new System.Diagnostics.Process();
     process.StartInfo = new System.Diagnostics.ProcessStartInfo(filename);
     process.Start();
 }
Exemple #21
0
        public override void Install(IDictionary state)
        {
            // Устанавливаем драйвер.
            System.Diagnostics.Process infSetup =
                new System.Diagnostics.Process();

            infSetup.StartInfo.FileName = "rundll32";
            infSetup.StartInfo.Arguments = "syssetup,SetupInfObjectInstallAction DefaultInstall 128 .\\ytdrv.inf";
            infSetup.StartInfo.CreateNoWindow = true;
            infSetup.StartInfo.UseShellExecute = false;
            infSetup.StartInfo.WorkingDirectory = Context.Parameters["INSTDIR"];

            infSetup.Start();

            base.Install(state);
            /*
            bool rebootRequired;
            int result = Interop.DriverPackageInstallW(
                Context.Parameters["INSTDIR"] + "ytdrv.inf",
                Interop.DRIVER_PACKAGE_LEGACY_MODE,
                IntPtr.Zero,
                out rebootRequired
                );

            MessageBox.Show(result.ToString("X"));
            //InstallFirewallRule(state);
             */
        }
Exemple #22
0
        static void device_OnPaketArrival(object sender, CaptureEventArgs e)
        {
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
              var tcpPacket = TcpPacket.GetEncapsulated(packet);
            //  TcpPacket tcpPacket = packet.Extract(typeof(TcpPacket)) as TcpPacket;
              //string KeyWord = "qwe";
              if (tcpPacket != null) {
                  String SPort = tcpPacket.SourcePort.ToString();
                  var DPort = tcpPacket.DestinationPort.ToString();
                  var Data = Encoding.Unicode.GetString(tcpPacket.PayloadData); //Encoding.ASCII.GetString(tcpPacket.PayloadData).ToString();

                  if (OptionTCP.UnsafeCompareByte(tcpPacket.PayloadData, KeyWord))
                  {  //if  if (OptionTCP.UnsafeCompareByte(tcpPacket.PayloadData, KeyWord) && SPort = tcpPacket.SourcePort.ToString() == 1768)
                    Console.WriteLine("eeeeeeeess");
                    try
                    {
                        System.Diagnostics.Process proc = new System.Diagnostics.Process();
                        proc.StartInfo.FileName = "dropTcpPacket.exe";
                        proc.StartInfo.Arguments = StegWord;
                        proc.Start();
                    }
                    catch (Exception exp) {
                        Console.WriteLine("errro .. {0}", exp.ToString());
                    }
                  }
                  else Console.WriteLine("nnnnnnnnoo: {0}", Encoding.Unicode.GetString(KeyWord));

                  Console.WriteLine("Sport: {0},  DPort: {1}, Data: {2}", SPort, DPort, Data);
                  Console.WriteLine("==========================================================");

              }
        }
Exemple #23
0
        public void SpeakAsync(string text)
        {
            if (MONO)
            {
                //if (_speechlinux == null)
                {
                    _state = SynthesizerState.Speaking;
                    _speechlinux = new System.Diagnostics.Process();
                    _speechlinux.StartInfo.RedirectStandardInput = true;
                    _speechlinux.StartInfo.UseShellExecute = false;
                    _speechlinux.StartInfo.FileName = "festival";
                    _speechlinux.Start();
                    _speechlinux.Exited += new EventHandler(_speechlinux_Exited);

                    log.Info("TTS: start " + _speechlinux.StartTime);

                }

                _state = SynthesizerState.Speaking;
                _speechlinux.StandardInput.WriteLine("(SayText \"" + text + "\")");
                _speechlinux.StandardInput.WriteLine("(quit)");

                _speechlinux.Close();

                _state = SynthesizerState.Ready;
            }
            else
            {
                _speechwindows.SpeakAsync(text);
            }

            log.Info("TTS: say " + text);
        }
Exemple #24
0
 //function to run an exe with a given set of arguments 
 public static bool Execute(string executable, string[] args)
 {
   
   System.Diagnostics.Process proc = new System.Diagnostics.Process();
   proc.StartInfo.WorkingDirectory = ".";
   proc.StartInfo.UseShellExecute = false;
   proc.StartInfo.FileName = executable;
   //convert string[] to string for the process
   string arg = "";
   if((args != null) && args.Length >= 1)
   arg =  args[0];    
   for (int i = 1; i < args.Length; i++)
     arg = arg + " " + args[i];
   proc.StartInfo.Arguments = arg;
   bool ret = false;
   try
   {
    ret   = proc.Start();
   }
   catch (Exception ex)
   {
     Console.WriteLine(ex.Message);
     throw ex;
   }
   return ret;
 }
Exemple #25
0
        private static string ExecuteCommand(string fileName, string arguments)
        {
            try
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();

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

                process.Start();

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

                return error;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
        public static string GetMacAddress(string ipAddress)
        {
            string macAddress = string.Empty;
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = "arp";
            pProcess.StartInfo.Arguments = "-a " + ipAddress;
            pProcess.StartInfo.UseShellExecute = false;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow = true;
            pProcess.Start();
            string strOutput = pProcess.StandardOutput.ReadToEnd();
            string[] substrings = strOutput.Split('-');
            if (substrings.Length >= 8)
            {
                macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2))
                         + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6]
                         + "-" + substrings[7] + "-"
                         + substrings[8].Substring(0, 2);
                return macAddress;
            }

            else
            {
                return "not found";
            }
        }
Exemple #27
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;
         }
     }
 }
		public static void Launch(Account account, String url) {

			if (account == null || account.Browser == null) {

				var action = new Action(() => System.Diagnostics.Process.Start(url));

				if (Program.MainForm.InvokeRequired) {
					Program.MainForm.Invoke(action);
				}
				else {
					action();
				}

				return;
			}

			Boolean poop = false;
			System.Diagnostics.Process browser = new System.Diagnostics.Process();

			browser.StartInfo.Arguments = url;
			browser.StartInfo.FileName = account.Browser.Path;

			try {
				browser.Start();
			}
			catch (InvalidOperationException) { poop = true; }
			catch (System.ComponentModel.Win32Exception) { poop = true; }

			if (poop) {
				System.Windows.Forms.Help.ShowHelp(Program.MainForm, url);
			}
		}
Exemple #29
0
        private void PWork_DoWork(object sender, DoWorkEventArgs e)
        {
            //pProgressFrm.TopMost = true;
            pProgressFrm.ShowDialog();
            WorkArgument pWorkArgument = e.Argument as WorkArgument;


            string ExcelPath = pWorkArgument.ExcelPath;

            string ExcelName = System.IO.Path.GetFileNameWithoutExtension(ExcelPath);
            //string ProjectName = pWorkArgument.ProjectName;

            string DwgPath = pWorkArgument.DwgSavePath;

            SysDBUnitiy.MDBPath = Path.GetDirectoryName(DwgPath) + string.Format("\\{0}.db", Path.GetFileNameWithoutExtension(DwgPath));

            string          TemplateDwg = SysDBUnitiy.RootDir + "\\Template\\template.dwg";
            string          TemplateMdb = SysDBUnitiy.RootDir + "\\Template\\Template.db";
            AcadApplication AcadApp     = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");

            pWork.ReportProgress(0, "正在创建数据文件");
            if (File.Exists(SysDBUnitiy.MDBPath))
            {
                File.Delete(SysDBUnitiy.MDBPath);
            }
            if (!File.Exists(SysDBUnitiy.MDBPath))
            {
                File.Copy(TemplateMdb, SysDBUnitiy.MDBPath, false);
            }

            if (File.Exists(DwgPath))
            {
                try
                {
                    File.Delete(DwgPath);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("删除旧dwg文件失败,请检查该文件是否被占用");
                    return;
                }
            }
            if (!File.Exists(DwgPath))
            {
                File.Copy(TemplateDwg, DwgPath, false);
            }


            //List<TableConfig> LineTableName = new List<TableConfig>();
            //List<TableConfig> PointTableName = new List<TableConfig>();
            pWork.ReportProgress(0, "正在准备写入dwg文件数据");
            Autodesk.AutoCAD.Interop.AcadDocument AcadDoc = AcadApp.Documents.Open(DwgPath);
            double MinX, MinY, MaxX, MaxY;

            //string[] MinPoint = System.Configuration.ConfigurationSettings.AppSettings["MinPoint"].Split(',');

            MinX = double.Parse(CIni.ReadINI("XYExtent", "MinX"));
            MinY = double.Parse(CIni.ReadINI("XYExtent", "MinY"));

            //string[] MaxPoint = System.Configuration.ConfigurationSettings.AppSettings["MaxPoint"].Split(',');
            MaxX = double.Parse(CIni.ReadINI("XYExtent", "MaxX"));
            MaxY = double.Parse(CIni.ReadINI("XYExtent", "MaxY"));
            pWork.ReportProgress(0, "正在读取表格数据");
            DataTable PCTable    = ExcelClass.ReadExcelFile(ExcelPath);
            DataTable CoordTable = ExcelClass.ReadExcelFile(pWorkArgument.CoordExcelpath);

            CoordTable.Columns[0].ColumnName = "ID";
            //CoordTable.PrimaryKey = new DataColumn[] { CoordTable.Columns[0] };
            DataRow FirstRow     = CoordTable.Rows[0];

            for (int j = 1; j < FirstRow.ItemArray.Length; j++)
            {
                string value = FirstRow.ItemArray[j].ToString();
                double V_num = 0;
                if (double.TryParse(value, out V_num))
                {
                    if (V_num > MinX && V_num < MaxX)
                    {
                        CoordTable.Columns[j].ColumnName = "CO_X";
                    }
                    else if (V_num > MinY && V_num < MaxY)
                    {
                        CoordTable.Columns[j].ColumnName = "CO_Y";
                    }
                    else
                    {
                        CoordTable.Columns[j].ColumnName = "CO_Z";
                    }
                }
            }
            Dictionary <string, DataRow> CoordBHTable = new Dictionary <string, DataRow>();

            foreach (DataRow pCoordRow in CoordTable.Rows)
            {
                string key = pCoordRow["ID"].ToString();
                if (!CoordBHTable.ContainsKey(key))
                {
                    CoordBHTable.Add(key, pCoordRow);
                }
            }
            DataTable ErrorTable = PCTable.Clone();

            if (!ErrorTable.Columns.Contains("错误消息"))
            {
                ErrorTable.Columns.Add("错误消息");
            }
            #region 循环遍历表
            //int SumCount = PCTable.Rows.Count;
            //int CurNum =0;
            DataTable PCTab2 = PCTable.Copy();
            for (int i = 0; i < PCTable.Rows.Count; i++)
            {
                //CurNum++;
                DataRow pDataRow = PCTable.Rows[i];
                try
                {
                    pWork.ReportProgress(i * 100 / PCTable.Rows.Count, string.Format("正在导入第: {0}/{1}条", i + 1, PCTable.Rows.Count));

                    string ErrorMsg = string.Empty;

                    string SPointID = GetValue(pDataRow, "起点点号");
                    if (string.IsNullOrEmpty(SPointID))
                    {
                        ErrorMsg += "起点号不能为空;";
                    }
                    IPipePoint SPoint    = null;
                    DataRow    SPointRow = IsExistSURVEYID(SPointID);
                    if (SPointRow == null)
                    {
                        if (!CoordBHTable.ContainsKey(SPointID))
                        {
                            ErrorMsg += "起点对应的坐标不存在;";
                        }

                        if (ErrorMsg != string.Empty)
                        {
                            goto a1;
                        }
                        //DataRow pCoordRow = CoordBHTable[SPointID];
                        SPoint = GetPipePoint(SPointID, pDataRow, CoordBHTable[SPointID]);
                        SPoint.AddNew();
                        SPoint.DrawCADObject(AcadDoc);
                        //CoordBHTable.ContainsKey(SPointID)
                        CoordBHTable.Remove(SPointID);
                    }
                    else
                    {
                        //string ClassName = SPointRow["ClassName"].ToString();
                        //string ID = SPointRow["ID"].ToString();
                        SPoint = new PCPoint();
                        //string sql = string.Format("select * from Points where ID='{0}'" , ID);

                        //DataTable pTable = SysDBUnitiy.OleDataBase.ExecuteQuery(sql).Tables[0];

                        //if (pTable.Rows.Count > 0)
                        //{
                        SPoint.FillValueByRow(SPointRow);
                        //}
                    }
                    string EPointID = GetValue(pDataRow, "终点点号");
                    if (EPointID == string.Empty)
                    {
                        goto a1;
                    }
                    IPipePoint EPoint    = null;
                    DataRow    EPointRow = IsExistSURVEYID(EPointID);

                    if (EPointRow == null)
                    {
                        EPointRow = FindRow(PCTable, EPointID, i + 1);
                        if (EPointRow == null)
                        {
                            ErrorMsg += "终点对应的信息不存在;";
                            goto a1;
                        }
                        //   DataRow[] ECoordRows = CoordTable.Select(string.Format("ID='{0}'", EPointID));
                        if (!CoordBHTable.ContainsKey(EPointID))
                        {
                            ErrorMsg += "终点对应的坐标不存在;";
                            goto a1;
                        }

                        /*   string EPointType = GetValue(EPointRow, "起点类型");
                         * if (EPointType == string.Empty)
                         * {
                         *     ErrorMsg += "终点类型不能为空";
                         * }
                         * string ClassName = GetTrueType(EPointType);
                         * if (ClassName == string.Empty)
                         * {
                         *     ErrorMsg += "终点类型无法识别";
                         *
                         * } */
                        if (ErrorMsg != string.Empty)
                        {
                            goto a1;
                        }
                        EPoint = GetPipePoint(EPointID, EPointRow, CoordBHTable[EPointID]);
                        EPoint.AddNew();
                        EPoint.DrawCADObject(AcadDoc);
                        CoordBHTable.Remove(EPointID);
                    }
                    else
                    {
                        //string ClassName = EPointRow["ClassName"].ToString();
                        //string ID = EPointRow["ID"].ToString();
                        EPoint = new PCPoint();
                        //string sql = string.Format("select * from Points where ID='{0}'", ID);

                        //DataTable pTable = SysDBUnitiy.OleDataBase.ExecuteQuery(sql).Tables[0];

                        //if (pTable.Rows.Count > 0)
                        //{
                        EPoint.FillValueByRow(EPointRow);
                        //}
                    }
                    string    GJ        = GetValue(pDataRow, "管径");
                    IPIPELine pPIPELine = new PIPELineClass();
                    if (!pPIPELine.isExistSURVEY_ID(SPointID, EPointID))
                    {
                        pPIPELine.Width        = GJ;
                        pPIPELine.US_SURVEY_ID = SPointID;
                        pPIPELine.DS_SURVEY_ID = EPointID;
                        //pPIPELine.ID = pPIPELine.GetHead() + SPointID.Substring(2, 3) + pPIPELine.GetNextNO();
                        pPIPELine.ID           = Guid.NewGuid().ToString("N");
                        pPIPELine.US_OBJECT_ID = SPoint.ID;
                        pPIPELine.DS_OBJECT_ID = EPoint.ID;
                        //pPIPELine.SYSTEM_TYPE = SPoint.SYSTEM_TYPE;

                        double D_X = double.Parse(EPoint.X) - double.Parse(SPoint.X);
                        double D_Y = double.Parse(EPoint.Y) - double.Parse(EPoint.Y);
                        double Len = Math.Round(Math.Sqrt(D_X * D_X + D_Y * D_Y), 2);

                        pPIPELine.Pipe_Length = Len.ToString();
                        //pPIPELine.US_POINT_INVERT_LEVEL = SPoint.INVERT_LEVEL;

                        /* string US_NS = GetValue(pDataRow, "起点管口泥深");
                         * if (US_NS != string.Empty)
                         *   pPIPELine.US_INVERT_LEVEL = (double.Parse(SPoint.GROUND_LEVEL) - double.Parse(US_NS)/100).ToString("0.00");
                         * string DS_NS = GetValue(pDataRow, "终点管口泥深");
                         * if (DS_NS != string.Empty)
                         *   pPIPELine.DS_INVERT_LEVEL = (double.Parse(EPoint.GROUND_LEVEL) - double.Parse(DS_NS)/100).ToString("0.00");
                         */
                        pPIPELine.SEDIMENT_DEPTH = GetValue(pDataRow, "泥深");
                        pPIPELine.MATERIAL       = GetValue(pDataRow, "材质");
                        pPIPELine.PRESSURE       = GetValue(pDataRow, "管道形式");
                        pPIPELine.STATE          = GetValue(pDataRow, "设施状态");
                        pPIPELine.ROAD_NAME      = GetValue(pDataRow, "所在道路");
                        pPIPELine.Remark         = GetValue(pDataRow, "线备注");

                        pPIPELine.WATER_LEVEL   = GetValue(pDataRow, "泥深");
                        pPIPELine.WATER_QUALITY = GetValue(pDataRow, "水质");
                        pPIPELine.WATER_State   = GetValue(pDataRow, "水体状态");
                        pPIPELine.Dirtcion      = GetValue(pDataRow, "流向");

                        pPIPELine.AddNew();
                        pPIPELine.DrawCADObject(AcadDoc);
                    }
a1:
                    if (ErrorMsg != string.Empty)
                    {
                        DataRow ErrorRow = ErrorTable.NewRow();

                        List <object> ItemList = new List <object>();

                        if (pDataRow.Table.Columns.Contains("错误消息"))
                        {
                            pDataRow["错误消息"] = ErrorMsg;
                            ItemList.AddRange(pDataRow.ItemArray);
                        }
                        else
                        {
                            ItemList.AddRange(pDataRow.ItemArray);
                            ItemList.Add(ErrorMsg);
                        }

                        ErrorRow.ItemArray = ItemList.ToArray();
                        ErrorTable.Rows.Add(ErrorRow);
                    }
                    //PCTable.Rows.RemoveAt(i);
                }
                catch (System.Exception ex)
                {
                    DataRow ErrorRow = ErrorTable.NewRow();

                    List <object> ItemList = new List <object>();

                    if (pDataRow.Table.Columns.Contains("错误消息"))
                    {
                        pDataRow["错误消息"] = ex.Message;
                        ItemList.AddRange(pDataRow.ItemArray);
                    }
                    else
                    {
                        ItemList.AddRange(pDataRow.ItemArray);
                        ItemList.Add(ex.Message);
                    }

                    ErrorRow.ItemArray = ItemList.ToArray();
                    ErrorTable.Rows.Add(ErrorRow);
                }
                pWork.ReportProgress((i + 1) * 100 / PCTable.Rows.Count);
            }
            int n = 0;
            //pProgressFrm.SafeCallDisplayProgress(0);

            foreach (KeyValuePair <string, DataRow> CoordBH in CoordBHTable)
            {
                pWork.ReportProgress(n * 100 / CoordBHTable.Count, string.Format("正在导入第: {0}/{1}个多余点", n, CoordBHTable.Count));
                n++;

                //   pProgressFrm.SafeCallDisplayText(string.Format("正在导入第: {0}/{1}个多余点", n, CoordBHTable.Count));

                IPCPoint pPCPoint = new PCPoint();
                if (IsExistSURVEYID(CoordBH.Key) == null)
                {
                    try
                    {
                        pPCPoint.ID           = Guid.NewGuid().ToString("N");
                        pPCPoint.SURVEY_ID    = CoordBH.Key;
                        pPCPoint.X            = CoordBH.Value["CO_X"].ToString();
                        pPCPoint.Y            = CoordBH.Value["CO_Y"].ToString();
                        pPCPoint.GROUND_LEVEL = CoordBH.Value["CO_Z"].ToString();
                        pPCPoint.AddNew();
                        pPCPoint.DrawCADObject(AcadDoc);
                    }
                    catch (System.Exception ex)
                    {
                    }
                }
                pWork.ReportProgress(n * 100 / CoordBHTable.Count);
                // pProgressFrm.SafeCallDisplayProgress(n * 100 / CoordBHTable.Count);
            }
            //pProgressFrm.SafeCallCloseDialog();
            MessageBox.Show(string.Format("总共导入{0}条管线数据,{3}个多余点,其中成功{1}条,失败{2}条。",
                                          PCTab2.Rows.Count, PCTab2.Rows.Count - ErrorTable.Rows.Count, ErrorTable.Rows.Count, CoordBHTable.Count
                                          ), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            if (ErrorTable.Rows.Count > 0)
            {
                string ReportXls = System.IO.Path.GetDirectoryName(pWorkArgument.DwgSavePath) + string.Format("\\未导入{0}.xls", DateTime.Now.ToString("MMddHHmm"));
                ExcelClass.ExpReport(ErrorTable, ReportXls);
                if (MessageBox.Show("已导出失败记录到输出目录,是否查看", "提示",
                                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    System.Diagnostics.Process pExecuteEXE = new System.Diagnostics.Process();
                    pExecuteEXE.StartInfo.FileName = ReportXls;
                    pExecuteEXE.Start();
                }
            }
            #endregion
        }
Exemple #30
0
        private void btnCode_Click(object sender, EventArgs e)
        {
            string code = txtCode.Text;

            string code1 = "" + code[0] + code[1] + code[2];
            string code2 = "" + code[3] + code[4] + code[5];


            if (File.Exists("batch2.bat"))
            {
                File.Delete("batch2.bat");
            }

            using (StreamWriter sw = File.CreateText("batch2.bat"))
            {
                sw.WriteLine("cd yowsup-master");
                sw.WriteLine("py yowsup-cli registration --register " + code1 + "-" + code2 + " --phone " + from + " -C 20");
            }

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError  = true;
            proc.StartInfo.FileName = "batch2.bat";
            proc.Start();

            proc.WaitForExit();

            StringBuilder response = new StringBuilder();

            using (StreamReader sr = proc.StandardOutput)
            {
                response.Append(sr.ReadToEnd());
            }
            using (StreamReader sr2 = proc.StandardError)
            {
                response.Append(sr2.ReadToEnd());
            }

            proc.WaitForExit();

            password = getBetween(response.ToString(), "pw: b'", "'");

            grp3.Enabled = true;

            if (File.Exists("number.txt"))
            {
                File.Delete("number.txt");
            }
            if (File.Exists("pass.txt"))
            {
                File.Delete("pass.txt");
            }

            using (StreamWriter sw = File.CreateText("number.txt"))
            {
                sw.Write(from);
            }
            using (StreamWriter sw = File.CreateText("pass.txt"))
            {
                sw.Write(password);
            }


            MessageBox.Show("Registered Successfully !");
        }
        ///////////////////////////////////////////////////////////////////////
        public static string run_svn(string args_without_password, string repo)
        {
            // run "svn.exe" and capture its output

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            string filename = Util.get_setting("SubversionPathToSvn", "svn");

            p.StartInfo.FileName = filename;

            configure_startinfo(p.StartInfo);

            args_without_password += " --non-interactive";

            string more_args = Util.get_setting("SubversionAdditionalArgs", "");

            if (more_args != "")
            {
                args_without_password += " " + more_args;
            }

            Util.write_to_log(filename + " " + args_without_password);

            string args_with_password = args_without_password;

            // add a username and password to the args
            string username_and_password_and_websvn = Util.get_setting(repo, "");

            string[] parts = btnet.Util.rePipes.Split(username_and_password_and_websvn);
            if (parts.Length > 1)
            {
                if (parts[0] != "" && parts[1] != "")
                {
                    args_with_password += " --username ";
                    args_with_password += parts[0];
                    args_with_password += " --password ";
                    args_with_password += parts[1];
                }
            }

            p.StartInfo.Arguments = args_with_password;
            p.Start();
            string stdout = p.StandardOutput.ReadToEnd();

            p.WaitForExit();
            stdout += p.StandardOutput.ReadToEnd();

            string error = p.StandardError.ReadToEnd();

            if (error != "")
            {
                Util.write_to_log("stderr:" + error);
                Util.write_to_log("stdout:" + stdout);
            }

            if (error != "")
            {
                string msg = "<div style='color:red; font-weight: bold; font-size: 10pt;'>";
                msg += "<br>Error executing svn command:";
                msg += "<br>Error: " + error;
                msg += "<br>Command: " + filename + " " + args_without_password;
                if (error.Contains("File not found"))
                {
                    msg += "<br><br>***** Has this file been deleted or renamed? See the following links:";
                    msg += "<br><a href=http://svn.apache.org/repos/asf/subversion/trunk/doc/user/svn-best-practices.html>";
                    msg += "http://svn.apache.org/repos/asf/subversion/trunk/doc/user/svn-best-practices.html</a>";
                    msg += "</div>";
                }
                HttpContext.Current.Response.Write(msg);
                HttpContext.Current.Response.End();
                return(msg);
            }
            else
            {
                Util.write_to_log("stdout:" + stdout);
                return(stdout);
            }
        }
Exemple #32
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                //Getting Image files path.
                string dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\..\Common\images\DocIO\";

                //A new document is created.
                WordDocument document = new WordDocument();
                //Adding a new section to the document.
                WSection section = document.AddSection() as WSection;
                //Set Margin of the section
                section.PageSetup.Margins.All = 72;
                //Set page size of the section
                section.PageSetup.PageSize = new SizeF(612, 792);
                //Create Paragraph styles
                WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle;
                style.CharacterFormat.FontName      = "Calibri";
                style.CharacterFormat.FontSize      = 11f;
                style.ParagraphFormat.BeforeSpacing = 0;
                style.ParagraphFormat.AfterSpacing  = 8;
                style.ParagraphFormat.LineSpacing   = 13.8f;

                style = document.AddParagraphStyle("Heading 1") as WParagraphStyle;
                style.ApplyBaseStyle("Normal");
                style.CharacterFormat.FontName      = "Calibri Light";
                style.CharacterFormat.FontSize      = 16f;
                style.CharacterFormat.TextColor     = Color.FromArgb(46, 116, 181);
                style.ParagraphFormat.BeforeSpacing = 12;
                style.ParagraphFormat.AfterSpacing  = 0;
                style.ParagraphFormat.Keep          = true;
                style.ParagraphFormat.KeepFollow    = true;
                style.ParagraphFormat.OutlineLevel  = OutlineLevel.Level1;
                IWParagraph paragraph = section.HeadersFooters.Header.AddParagraph();

                WPicture picture = paragraph.AppendPicture(Image.FromFile(dataPath + "AdventureCycle.jpg")) as WPicture;
                picture.TextWrappingStyle  = TextWrappingStyle.InFrontOfText;
                picture.VerticalOrigin     = VerticalOrigin.Margin;
                picture.VerticalPosition   = -45;
                picture.HorizontalOrigin   = HorizontalOrigin.Column;
                picture.HorizontalPosition = 263.5f;
                picture.WidthScale         = 20;
                picture.HeightScale        = 15;

                paragraph.ApplyStyle("Normal");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
                WTextRange textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange;
                textRange.CharacterFormat.FontSize  = 12f;
                textRange.CharacterFormat.FontName  = "Calibri";
                textRange.CharacterFormat.TextColor = Color.Red;

                //Appends paragraph.
                paragraph = section.AddParagraph();
                paragraph.ApplyStyle("Heading 1");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
                textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange;
                textRange.CharacterFormat.FontSize = 18f;
                textRange.CharacterFormat.FontName = "Calibri";


                //Appends paragraph.
                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.FirstLineIndent = 36;
                paragraph.BreakCharacterFormat.FontSize   = 12f;
                textRange = paragraph.AppendText("Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;

                paragraph = section.AddParagraph();
                paragraph.ParagraphFormat.FirstLineIndent = 36;
                paragraph.BreakCharacterFormat.FontSize   = 12f;
                textRange = paragraph.AppendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;

                paragraph = section.AddParagraph();
                paragraph.ApplyStyle("Heading 1");
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
                textRange = paragraph.AppendText("Product Overview") as WTextRange;
                textRange.CharacterFormat.FontSize = 16f;
                textRange.CharacterFormat.FontName = "Calibri";


                //Appends table.
                IWTable table = section.AddTable();
                table.ResetCells(3, 2);
                table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
                table.TableFormat.IsAutoResized      = true;

                //Appends paragraph.
                paragraph = table[0, 0].AddParagraph();
                paragraph.ParagraphFormat.AfterSpacing  = 0;
                paragraph.BreakCharacterFormat.FontSize = 12f;
                //Appends picture to the paragraph.
                picture = paragraph.AppendPicture(Image.FromFile(dataPath + "Mountain-200.jpg")) as WPicture;
                picture.TextWrappingStyle  = TextWrappingStyle.TopAndBottom;
                picture.VerticalOrigin     = VerticalOrigin.Paragraph;
                picture.VerticalPosition   = 4.5f;
                picture.HorizontalOrigin   = HorizontalOrigin.Column;
                picture.HorizontalPosition = -2.15f;
                picture.WidthScale         = 79;
                picture.HeightScale        = 79;

                //Appends paragraph.
                paragraph = table[0, 1].AddParagraph();
                paragraph.ApplyStyle("Heading 1");
                paragraph.ParagraphFormat.AfterSpacing = 0;
                paragraph.ParagraphFormat.LineSpacing  = 12f;
                paragraph.AppendText("Mountain-200");
                //Appends paragraph.
                paragraph = table[0, 1].AddParagraph();
                paragraph.ParagraphFormat.AfterSpacing  = 0;
                paragraph.ParagraphFormat.LineSpacing   = 12f;
                paragraph.BreakCharacterFormat.FontSize = 12f;
                paragraph.BreakCharacterFormat.FontName = "Times New Roman";

                textRange = paragraph.AppendText("Product No: BK-M68B-38\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Size: 38\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Weight: 25\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Price: $2,294.99\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";

                //Appends paragraph.
                paragraph = table[0, 1].AddParagraph();
                paragraph.ParagraphFormat.AfterSpacing  = 0;
                paragraph.ParagraphFormat.LineSpacing   = 12f;
                paragraph.BreakCharacterFormat.FontSize = 12f;

                //Appends paragraph.
                paragraph = table[1, 0].AddParagraph();
                paragraph.ApplyStyle("Heading 1");
                paragraph.ParagraphFormat.AfterSpacing = 0;
                paragraph.ParagraphFormat.LineSpacing  = 12f;
                paragraph.AppendText("Mountain-300 ");
                //Appends paragraph.
                paragraph = table[1, 0].AddParagraph();
                paragraph.ParagraphFormat.AfterSpacing  = 0;
                paragraph.ParagraphFormat.LineSpacing   = 12f;
                paragraph.BreakCharacterFormat.FontSize = 12f;
                paragraph.BreakCharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Product No: BK-M47B-38\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Size: 35\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Weight: 22\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Price: $1,079.99\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";

                //Appends paragraph.
                paragraph = table[1, 0].AddParagraph();
                paragraph.ParagraphFormat.AfterSpacing  = 0;
                paragraph.ParagraphFormat.LineSpacing   = 12f;
                paragraph.BreakCharacterFormat.FontSize = 12f;

                //Appends paragraph.
                paragraph = table[1, 1].AddParagraph();
                paragraph.ApplyStyle("Heading 1");
                paragraph.ParagraphFormat.LineSpacing = 12f;
                //Appends picture to the paragraph.
                picture = paragraph.AppendPicture(Image.FromFile(dataPath + "Mountain-300.jpg")) as WPicture;
                picture.TextWrappingStyle  = TextWrappingStyle.TopAndBottom;
                picture.VerticalOrigin     = VerticalOrigin.Paragraph;
                picture.VerticalPosition   = 8.2f;
                picture.HorizontalOrigin   = HorizontalOrigin.Column;
                picture.HorizontalPosition = -14.95f;
                picture.WidthScale         = 75;
                picture.HeightScale        = 75;

                //Appends paragraph.
                paragraph = table[2, 0].AddParagraph();
                paragraph.ApplyStyle("Heading 1");
                paragraph.ParagraphFormat.LineSpacing = 12f;
                //Appends picture to the paragraph.
                picture = paragraph.AppendPicture(Image.FromFile(dataPath + "Road-550-W.jpg")) as WPicture;
                picture.TextWrappingStyle  = TextWrappingStyle.TopAndBottom;
                picture.VerticalOrigin     = VerticalOrigin.Paragraph;
                picture.VerticalPosition   = 3.75f;
                picture.HorizontalOrigin   = HorizontalOrigin.Column;
                picture.HorizontalPosition = -5f;
                picture.WidthScale         = 92;
                picture.HeightScale        = 92;

                //Appends paragraph.
                paragraph = table[2, 1].AddParagraph();
                paragraph.ApplyStyle("Heading 1");
                paragraph.ParagraphFormat.AfterSpacing = 0;
                paragraph.ParagraphFormat.LineSpacing  = 12f;
                paragraph.AppendText("Road-150 ");
                //Appends paragraph.
                paragraph = table[2, 1].AddParagraph();
                paragraph.ParagraphFormat.AfterSpacing  = 0;
                paragraph.ParagraphFormat.LineSpacing   = 12f;
                paragraph.BreakCharacterFormat.FontSize = 12f;
                paragraph.BreakCharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Product No: BK-R93R-44\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Size: 44\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Weight: 14\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                textRange = paragraph.AppendText("Price: $3,578.27\r") as WTextRange;
                textRange.CharacterFormat.FontSize = 12f;
                textRange.CharacterFormat.FontName = "Times New Roman";
                //Appends paragraph.

                section.AddParagraph();
                //Save as doc format
                if (wordDocRadioBtn.Checked)
                {
                    //Saving the document to disk.
                    document.Save("Sample.doc");

                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.doc")
                        {
                            UseShellExecute = true
                        };
                        process.Start();
#else
                        System.Diagnostics.Process.Start("Sample.doc");
#endif
                        //Exit
                        this.Close();
                    }
                }
                //Save as docx format
                else if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Sample.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.docx")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Sample.docx");
#endif
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    //Save the pdf file
                    pdfDoc.Save("Sample.pdf");
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Sample.pdf");
#endif

                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Exemple #33
0
        public void build()
        {
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = variables.pathforit + @"\xeBuild\xeBuild.exe";
            string arguments = "";

            arguments  = "-t " + _ttype;
            arguments += " -c " + _ctype.XeBuild;
            foreach (String patch in _patches)
            {
                arguments += " " + patch;
            }
            if (variables.debugme)
            {
                arguments += " -v";
            }
            arguments += " -noenter";
            arguments += " -f " + _dash;
            arguments += " -d data";
            arguments += " \"" + variables.xefolder + "\\" + variables.nandflash + "\" ";

            RegexOptions options = RegexOptions.None;
            Regex        regex   = new Regex(@"[ ]{2,}", options);

            arguments = regex.Replace(arguments, @" ");

            if (variables.debugme)
            {
                Console.WriteLine(variables.pathforit);
            }
            if (variables.debugme)
            {
                Console.WriteLine("---" + variables.pathforit + @"\xeBuild\xeBuild.exe");
            }
            if (variables.debugme)
            {
                Console.WriteLine(arguments);
            }
            pProcess.StartInfo.Arguments              = arguments;
            pProcess.StartInfo.UseShellExecute        = false;
            pProcess.StartInfo.WorkingDirectory       = variables.pathforit;
            pProcess.StartInfo.RedirectStandardInput  = true;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow         = true;
            pProcess.Exited += new EventHandler(xeExit);
            //pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(DataReceived);
            //pProcess.Exited += new EventHandler(xe_Exited);
            //pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
            try
            {
                AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
                pProcess.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        Console.WriteLine(e.Data);
                        if (e.Data != null && e.Data.Contains("image built"))
                        {
                            variables.xefinished = true;
                        }
                    }
                };
                pProcess.Start();
                pProcess.BeginOutputReadLine();
                pProcess.StandardInput.WriteLine("enter");
                pProcess.WaitForExit();

                if (pProcess.HasExited)
                {
                    pProcess.CancelOutputRead();
                }
            }
            catch (Exception objException)
            {
                Console.WriteLine(objException.Message);
            }
        }
Exemple #34
0
        /// <summary>
        /// Asynchronous RunScript method. Instead of blocking until the script is finished, this method
        /// takes three methods that are called with the output of the script as it's being read as well
        /// as one with the exit code once the script has finished.
        /// </summary>
        /// <param name="startInfo">Process start configuration (note that UseShellExecute, RedirectStandardOutput and RedirectStandardError will be overwritten)</param>
        /// <param name="input">Input written to the script's standard input (or null)</param>
        /// <param name="onOutput">Method called with each output line</param>
        /// <param name="onError">Method called with each error line</param>
        /// <param name="onExit">Method called with the exit code</param>
        /// <returns>A callback that can be used to stop the script (parameter: false = terminate, true = kill)</returns>
        public static Action <bool> RunScriptAsnyc(System.Diagnostics.ProcessStartInfo startInfo, string input, Action <string> onOutput, Action <string> onError, Action <int> onExit)
        {
            var scriptName = Path.GetFileName(startInfo.FileName);

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

            script.StartInfo = startInfo;
            script.StartInfo.UseShellExecute        = false;
            script.StartInfo.RedirectStandardOutput = true;
            script.StartInfo.RedirectStandardError  = true;
            script.EnableRaisingEvents = true;

            if (!string.IsNullOrEmpty(input))
            {
                script.StartInfo.RedirectStandardInput = true;
            }

            script.OutputDataReceived += (s, a) => {
                if (onOutput != null)
                {
                    onOutput(a.Data);
                }
            };
            script.ErrorDataReceived += (s, a) => {
                if (onError != null)
                {
                    onError(a.Data);
                }
            };
            script.Exited += (s, a) => {
                if (onExit != null)
                {
                    // Wait for stdout and stderr to flush
                    script.WaitForExit();
                    onExit(script.ExitCode);
                }
            };

            try {
                script.Start();

                script.BeginOutputReadLine();
                script.BeginErrorReadLine();

                if (!string.IsNullOrEmpty(input))
                {
                    // Unity's old Mono runtime writes a BOM to the input stream,
                    // tripping up the command. Create a new writer with an encoding
                    // that has BOM disabled.
                    var writer = new StreamWriter(script.StandardInput.BaseStream, new System.Text.UTF8Encoding(false));
                    writer.Write(input);
                    writer.Close();
                }
            } catch (Exception e) {
                if (onError != null)
                {
                    onError("RunScript: Exception running " + scriptName + ": " + e.Message);
                }
                return(null);
            }

            return((kill) => {
                if (script.HasExited)
                {
                    return;
                }
                if (kill)
                {
                    script.Kill();
                }
                else
                {
                    script.CloseMainWindow();
                }
            });
        }
Exemple #35
0
        /// <summary>
        /// Run an external process/script with given arguments, write the given input
        /// to its standard input, wait for it to exit and capture its output and/or errors.
        /// </summary>
        /// <param name="path">Path to the script (absolute, relative to project directory or on the PATH)</param>
        /// <param name="arguments">Arguments to pass to the script</param>
        /// <param name="input">Input written to the script's standard input (or null)</param>
        /// <param name="output">The standard output of the script</param>
        /// <param name="error">The standard error of the script</param>
        /// <returns>The exit code of the script.</returns>
        public static int RunScript(string path, string arguments, string input, out string output, out string error)
        {
            output = null;

            if (string.IsNullOrEmpty(path))
            {
                error = "RunScript: path null or empty";
                return(127);
            }

            var scriptName = Path.GetFileName(path);
            var script     = new System.Diagnostics.Process();

            script.StartInfo.UseShellExecute        = false;
            script.StartInfo.RedirectStandardOutput = true;
            script.StartInfo.RedirectStandardError  = true;
            script.StartInfo.FileName  = path;
            script.StartInfo.Arguments = arguments;

            if (!string.IsNullOrEmpty(input))
            {
                script.StartInfo.RedirectStandardInput = true;
            }

            var outputBuilder = new StringBuilder();

            script.OutputDataReceived += (s, a) => {
                outputBuilder.AppendLine(a.Data);
            };
            var errorBuilder = new StringBuilder();

            script.ErrorDataReceived += (s, a) => {
                errorBuilder.AppendLine(a.Data);
            };

            try {
                script.Start();

                script.BeginOutputReadLine();
                script.BeginErrorReadLine();

                if (!string.IsNullOrEmpty(input))
                {
                    // Unity's old Mono runtime writes a BOM to the input stream,
                    // tripping up the command. Create a new writer with an encoding
                    // that has BOM disabled.
                    var writer = new StreamWriter(script.StandardInput.BaseStream, new System.Text.UTF8Encoding(false));
                    writer.Write(input);
                    writer.Close();
                }

                script.WaitForExit();
            } catch (Exception e) {
                error = "RunScript: Exception running " + scriptName + ": " + e.Message;
                return(-1);
            }

            output = outputBuilder.ToString();
            error  = errorBuilder.ToString();

            return(script.ExitCode);
        }
Exemple #36
0
        /// <summary>
        /// Runs the given text through clang-format and returns the replacements as XML.
        ///
        /// Formats the text range starting at offset of the given length.
        /// </summary>
        private static string RunClangFormat(string text, int offset, int length, string path, string filePath, OptionPageGrid options)
        {
            string vsixPath = Path.GetDirectoryName(
                typeof(ClangFormatPackage).Assembly.Location);

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.FileName        = vsixPath + "\\clang-format.exe";
            // Poor man's escaping - this will not work when quotes are already escaped
            // in the input (but we don't need more).
            string style         = options.Style.Replace("\"", "\\\"");
            string fallbackStyle = options.FallbackStyle.Replace("\"", "\\\"");

            process.StartInfo.Arguments = " -offset " + offset +
                                          " -length " + length +
                                          " -output-replacements-xml " +
                                          " -style \"" + style + "\"" +
                                          " -fallback-style \"" + fallbackStyle + "\"";
            if (options.SortIncludes)
            {
                process.StartInfo.Arguments += " -sort-includes ";
            }
            string assumeFilename = options.AssumeFilename;

            if (string.IsNullOrEmpty(assumeFilename))
            {
                assumeFilename = filePath;
            }
            if (!string.IsNullOrEmpty(assumeFilename))
            {
                process.StartInfo.Arguments += " -assume-filename \"" + assumeFilename + "\"";
            }
            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.RedirectStandardInput  = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            if (path != null)
            {
                process.StartInfo.WorkingDirectory = path;
            }
            // We have to be careful when communicating via standard input / output,
            // as writes to the buffers will block until they are read from the other side.
            // Thus, we:
            // 1. Start the process - clang-format.exe will start to read the input from the
            //    standard input.
            try
            {
                process.Start();
            }
            catch (Exception e)
            {
                throw new Exception(
                          "Cannot execute " + process.StartInfo.FileName + ".\n\"" +
                          e.Message + "\".\nPlease make sure it is on the PATH.");
            }
            // 2. We write everything to the standard output - this cannot block, as clang-format
            //    reads the full standard input before analyzing it without writing anything to the
            //    standard output.
            process.StandardInput.Write(text);
            // 3. We notify clang-format that the input is done - after this point clang-format
            //    will start analyzing the input and eventually write the output.
            process.StandardInput.Close();
            // 4. We must read clang-format's output before waiting for it to exit; clang-format
            //    will close the channel by exiting.
            string output = process.StandardOutput.ReadToEnd();

            // 5. clang-format is done, wait until it is fully shut down.
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                // FIXME: If clang-format writes enough to the standard error stream to block,
                // we will never reach this point; instead, read the standard error asynchronously.
                throw new Exception(process.StandardError.ReadToEnd());
            }
            return(output);
        }
Exemple #37
0
        static void Main(string[] args)
        {
            SupportedMods = new List <string>();
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/AutoSpeed/AutoSpeed-Source/AutoSpeed");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/Billboard_Anywhere/BillboardAnywhere/BillboardAnywhere");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/BuildEndurance/BuildEndurance/BuildEndurance");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/BuildHealth/BuildHealth/BuildHealth");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/BuyBackCollectables/BuyBackCollectables-Source/BuyBackCollectables");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/CurrentLocationPopUp/CurrentLocationPopUp");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/DailyQuest_Anywhere/DailyQuest Anywhere");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/Fall28SnowDay/Fall28SnowDay/Fall28SnowDay");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/HappyBirthday/HappyBirthday");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/MoreRain/Stardew_More_Rain/Stardew_More_Rain");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/Museum_Rearrange/Museum_Rearranger/Museum_Rearranger");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/NightOwl/Stardew_NightOwl/Stardew_NightOwl");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/NoMorePets/NoMorePets/NoMorePets");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/Save_Anywhere_V2/Save_Anywhere_V2");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/Stardew_Save_Backup/Stardew_Save_Backup/Stardew_Save_Backup");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/StardewSymphony/StardewSymphony/StardewSymphony");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/GeneralMods/TimeFreeze/TimeFreeze/TimeFreeze");

            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/OmegasisCore/OmegasisCore");
            SupportedMods.Add("C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/Revitalize/Revitalize/Revitalize");
            foreach (var v in SupportedMods)
            {
                string ModVersion = "";
                string APIVersion = "";
                string ModName    = "";

                string ModMajorVersion = "";
                string ModMinorVersion = "";
                string ModPatchVersion = "";
                string ModBuildVersion = "";

                string APIMajorVersion = "";
                string APIMinorVersion = "";
                string APIPatchVersion = "";

                if (Directory.Exists(v))
                {
                    ModName = getModName(v);
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Processing data for mod: " + ModName);
                    Console.ResetColor();

                    string modInfoFile  = (Path.Combine(v, "ModInfo.txt"));
                    string ManifestFile = (Path.Combine(v, "Manifest.json"));
                    if (!File.Exists(modInfoFile))
                    {
                        createModInfoFile(modInfoFile, ModName, ManifestFile);
                    }
                    else
                    {
                        //File Exists.
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine(ModName + ": ModInfo already exists.");
                        readModInfoFile(modInfoFile, ModName);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine("Edit the ModInfo file?");

                        string input = Console.ReadLine();
                        bool   exit  = false;
                        while (exit == false)
                        {
                            if (input == "y" || input == "Y")
                            {
                                File.Delete(modInfoFile);
                                createModInfoFile(modInfoFile, ModName, ManifestFile);
                                exit = true;
                            }
                            else if (input == "n" || input == "N")
                            {
                                exit = true;
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("ERROR: Invaild input. Input either Y/y/N/n to continue.");
                                Console.ForegroundColor = ConsoleColor.White;
                                input = Console.ReadLine();
                            }
                        }
                        //Output some stuff to the console here and prompt to update the mod info file.
                    }
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Done Writing ModInfo.txt file for: " + ModName);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Invalid mod project directory @ " + v + "\nPlease make sure the directory is a valid one.");
                }
                //Console.WriteLine(v);
                Console.ResetColor();
            }
            Console.WriteLine("Done Processing all Mods. Please press any key to now compile all of the mods.");
            Console.ReadKey();

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName         = "C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods/ModUpdater.bat";
            proc.StartInfo.WorkingDirectory = "C:/Users/owner/Documents/Visual Studio 2015/Projects/github/StardewValleyMods";
            proc.Start();
            Console.WriteLine("All done! Press any key to close this.");
            Console.ReadKey();
        }
Exemple #38
0
        public static int Start(string app, string args, Options options = Options.RedirectOutput | Options.RedirectErrors, StringBuilder output = null)
        {
            if (output == null)
            {
                output = new StringBuilder();
            }
            var p = new System.Diagnostics.Process();

            p.StartInfo.FileName        = app;
            p.StartInfo.Arguments       = args;
            p.StartInfo.UseShellExecute = false;
#if WIN
            p.StartInfo.CreateNoWindow   = true;
            p.StartInfo.WorkingDirectory = Path.GetDirectoryName(app);
            int cp = System.Text.Encoding.Default.CodePage;
            if (cp == 1251)
            {
                cp = 866;
            }
            p.StartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(cp);
            p.StartInfo.StandardErrorEncoding  = System.Text.Encoding.GetEncoding(cp);
#else
            p.StartInfo.StandardOutputEncoding = System.Text.Encoding.Default;
            p.StartInfo.StandardErrorEncoding  = System.Text.Encoding.Default;
            p.StartInfo.EnvironmentVariables.Clear();
            p.StartInfo.EnvironmentVariables.Add("PATH", "/bin:/usr/bin");
#endif
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            var logger = new System.Text.StringBuilder();
            if ((options & Options.RedirectOutput) != 0)
            {
                p.OutputDataReceived += (sender, e) => {
                    lock (logger) {
                        if (e.Data != null)
                        {
                            logger.AppendLine(e.Data);
                            output.AppendLine(e.Data);
                        }
                    }
                };
            }
            if ((options & Options.RedirectErrors) != 0)
            {
                p.ErrorDataReceived += (sender, e) => {
                    lock (logger) {
                        if (e.Data != null)
                        {
                            logger.AppendLine(e.Data);
                            output.AppendLine(e.Data);
                        }
                    }
                };
            }
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            while (!p.HasExited)
            {
                p.WaitForExit(50);
                lock (logger) {
                    if (logger.Length > 0)
                    {
                        Console.Write(logger.ToString());
                        logger.Clear();
                    }
                }
                The.UI.ProcessPendingEvents();
            }
            Console.Write(logger.ToString());
            return(p.ExitCode);
        }
Exemple #39
0
 public static void StopRecording()
 {
     if (null != capture)
     {
         //no need to ckeck, capture.Stop() will work anyway
         if (true == capture.Capturing)
         {
             capture.Stop();
             capture.Dispose();
             if ("" != sCurrentRecordingFileName)
             {
                 //////////////// CONVERT & UPLOAD .FLV
                 string sFlvOutputName = sCurrentRecordingFileName.Substring(0, sCurrentRecordingFileName.LastIndexOf(".")) + ".flv";
                 System.Diagnostics.Process convertFlv = new System.Diagnostics.Process();
                 convertFlv.StartInfo
                     = new System.Diagnostics.ProcessStartInfo
                           (@"c:\Program Files\WinFF\ffmpeg.exe", " -i "
                           + "\"" + sCurrentRecordingFileName + "\""
                           + " -ar 44100 "
                           + " -b 1250k "
                           + " -r 25 "
                           + " -ab 128k "
                           + " -y "
                           + "\"" + sFlvOutputName + "\"");
                 convertFlv.EnableRaisingEvents = true;
                 convertFlv.Exited += new EventHandler(delegate(object sender, EventArgs e)
                 {
                     if (convertFlv.ExitCode != 0)
                     {
                         //if ffmpeg failed, then there will be no flv/jpg and we won't delete avi or try to upload flv/jpeg
                         Console.WriteLine("Konvertirebisas moxda shecdoma {0}.", convertFlv.ExitCode);
                         return;
                     }
                     else
                     {
                         Console.WriteLine("Konvertireba dasrulda shedegit {0}.", convertFlv.ExitCode);
                     }
                     //droebit, vtvirtavt FLV-s chaceris morchenistanave
                     FTPUploader uplFlv = new FTPUploader(sFlvOutputName);
                     uplFlv.UploadFileToFTP();
                     //Thread thrUpload = new Thread(new ThreadStart(upl.UploadFileToFTP));
                     //thrUpload.SetApartmentState(ApartmentState.STA);
                     //thrUpload.Start();
                     //////////////// CONVERT & UPLOAD .JPG WHEN .FLV is done
                     string sJpegOutputName = sCurrentRecordingFileName.Substring(0, sCurrentRecordingFileName.LastIndexOf(".")) + ".jpg";
                     System.Diagnostics.Process convertJpeg = new System.Diagnostics.Process();
                     convertJpeg.StartInfo
                         = new System.Diagnostics.ProcessStartInfo
                               (@"c:\Program Files\WinFF\ffmpeg.exe", " -i "
                               + "\"" + sFlvOutputName + "\""
                               + " -vframes 1 "
                               + " -ss 00:00:06 "
                               + " -f image2 "
                               + "\"" + sJpegOutputName + "\"");
                     convertJpeg.EnableRaisingEvents = true;
                     convertJpeg.Exited += new EventHandler(delegate(object senderJpeg, EventArgs eJpeg)
                     {
                         //droebit, vtvirtavt JPG-s chaceris morchenistanave
                         FTPUploader uplJpeg = new FTPUploader(sJpegOutputName);
                         uplJpeg.UploadFileToFTP();
                     });
                     //
                     convertJpeg.Start();
                 });
                 convertFlv.Start();
                 //end
             }
             //
         }
     }
     //
 }
Exemple #40
0
        /// <summary>
        /// Determine what port Unity is listening for on Windows
        /// </summary>
        static int GetDebugPort()
        {
#if UNITY_EDITOR_WIN
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "netstat";
            process.StartInfo.Arguments              = "-a -n -o -p TCP";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

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

            process.WaitForExit();

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

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

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

            process.WaitForExit();

            foreach (string line in lines)
            {
                int port = -1;
                if (line.StartsWith("Unity"))
                {
                    string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None);
                    if (portions.Length >= 2)
                    {
                        Regex  digitsOnly = new Regex(@"[^\d]");
                        string cleanPort  = digitsOnly.Replace(portions[1], "");
                        if (int.TryParse(cleanPort, out port))
                        {
                            if (port > -1)
                            {
                                return(port);
                            }
                        }
                    }
                }
            }
#endif
            return(-1);
        }
Exemple #41
0
 private void run(Object obj)
 {
     System.Diagnostics.Process ps = new System.Diagnostics.Process();
     ps.StartInfo.FileName = obj.ToString();
     ps.Start();
 }
Exemple #42
0
 public static void GotoUrl(string url)
 {
     System.Diagnostics.Process process = new System.Diagnostics.Process();
     process.StartInfo.FileName = url;
     process.Start();
 }
        private void btnReport_Click(object sender, RoutedEventArgs e)
        {
            QuoteIllustration qi = new QuoteIllustration();

            //qi.CreateQuoteIllustrationReport(Convert.ToInt16(App.Current.Properties["StlmtBrokerID"].ToString())
            //    , App.Current.Properties["AnnuitantName"].ToString()
            //    , App.Current.Properties["GenderAgeLabel"].ToString()
            //    , App.Current.Properties["GenderAge"].ToString()
            //    , Convert.ToDateTime(txtQuoteDate.Text)
            //    , Convert.ToDateTime(txtPurchaseDate.Text)
            //    , txtRateVersion.Text
            //    , dgBenefits);

            qi.CreateSettlementReport(Convert.ToInt16(App.Current.Properties["StlmtBrokerID"].ToString())
                                      , App.Current.Properties["AnnuitantName"].ToString()
                                      , App.Current.Properties["GenderAgeLabel"].ToString()
                                      , App.Current.Properties["GenderAge"].ToString()
                                      , Convert.ToDateTime(txtQuoteDate.Text)
                                      , Convert.ToDateTime(txtPurchaseDate.Text)
                                      , txtRateVersion.Text
                                      , dgBenefits
                                      , Convert.ToInt16(App.Current.Properties["QuoteID"]));

            //try
            //{
            //    System.Diagnostics.Process process = new System.Diagnostics.Process();

            //    Uri pdf = new Uri(qi.IllustrationReportName, UriKind.RelativeOrAbsolute);
            //    process.StartInfo.FileName = pdf.LocalPath;
            //    process.Start();
            //    //process.WaitForExit();
            //}
            //catch (Exception error)
            //{
            //    MessageBox.Show("Could not open the report.", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            //    MessageBox.Show(error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            //}

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

                Uri pdf = new Uri(qi.SettlementReportName, UriKind.RelativeOrAbsolute);
                process.StartInfo.FileName = pdf.LocalPath;
                process.Start();
                //process.WaitForExit();
            }
            catch (Exception error)
            {
                MessageBox.Show("Could not open the report.", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                MessageBox.Show(error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            //string fileName = thisFileName;
            ////finalDoc.Save(Server.MapPath(thisFileName));
            ////string fileName = Server.MapPath(thisFileName);

            //FileInfo fileInfo = new FileInfo(fileName);

            //string responseHeader = "attachment; filename=" + fileInfo.Name;

            //Response.ContentType = "Application/pdf";
            //Response.AppendHeader("Content-Disposition", responseHeader);
            //Response.TransmitFile(fileName);
            //Response.End();
        }
Exemple #44
0
        public static bool BuildAppxFromSolution(string productName, string msBuildVersion, bool forceRebuildAppx, string buildConfig, string buildDirectory, bool incrementVersion)
        {
            // Get 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);
            }

            // Get 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;
            pinfo.RedirectStandardOutput = 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);
            }
        }
        public ConsoleApp(string[] args, ManualResetEvent wait)
        {
            this.OutputPath = Directory.GetCurrentDirectory();
            string args0 = args[0].Trim().ToLower();

            if (args[0] == "?" || args0 == "--help" || args0 == "-help")
            {
                var bgcolor = Console.BackgroundColor;
                var fgcolor = Console.ForegroundColor;

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#######################################");
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                       ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.Write("    .NETCore 2.1 + SQLServer 生成器    ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                       ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#######################################");
                Console.Write("##");

                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write(@"

用于快速创建和更新 .NETCore 2.1 + SQLServer 项目,非常合适敏捷开发;
Github: https://github.com/2881099/dotnetgen_sqlserver

");
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write("Example:");
                Console.ForegroundColor = fgcolor;
                Console.WriteLine(@"

	> GenMs 127.0.0.1 -U sa -P 123456 -D dyschool -N dyschool -S -A -R
	> GenMs 127.0.0.1 -D dyschool -N dyschool -S -A -R //使用windows登陆

		-U	SQLServer账号
		-P	SQLServer密码
		-D	需要生成的数据库

		-N	字符串,生成代码的解决方案名和命名空间
		-S	生成解决方案,在项目第一次生成时使用
		-A	生成后台管理
		-R	下载资源
		
		-O	输出路径(默认:当前目录)"            );
                wait.Set();
                return;
            }
            this.Server = args[0];
            for (int a = 1; a < args.Length; a++)
            {
                switch (args[a])
                {
                case "-U":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-U 参数错误");
                    }
                    else
                    {
                        this.Username = args[a + 1];
                    }
                    a++;
                    break;

                case "-P":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-P 参数错误");
                    }
                    else
                    {
                        this.Password = args[a + 1];
                    }
                    a++;
                    break;

                case "-D":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-D 参数错误");
                    }
                    else
                    {
                        this.Database = args[a + 1];
                    }
                    a++;
                    break;

                case "-N":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-N 参数错误");
                    }
                    else
                    {
                        this.SolutionName = args[a + 1];
                    }
                    a++;
                    break;

                case "-O":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-O 参数错误");
                    }
                    else
                    {
                        this.OutputPath = args[a + 1];
                    }
                    a++;
                    break;

                case "-S":
                    this.IsMakeSolution = true;
                    break;

                case "-A":
                    this.IsMakeWebAdmin = true;
                    break;

                case "-R":
                    this.IsDownloadRes = true;
                    break;
                }
            }
            this._client = new ClientInfo(this.Server, this.Username, this.Password);
            StreamReader sr     = new StreamReader(System.Net.WebRequest.Create("https://files.cnblogs.com/files/kellynic/GenMs_server.css").GetResponse().GetResponseStream(), Encoding.UTF8);
            string       server = sr.ReadToEnd()?.Trim();
            //server = "127.0.0.1:29918";
            Uri uri = new Uri("tcp://" + server + "/");

            this._socket          = new ClientSocket();
            this._socket.Error   += Socket_OnError;
            this._socket.Receive += Socket_OnReceive;
            this._socket.Connect(uri.Host, uri.Port);
            Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
            if (this._socket.Running == false)
            {
                wait.Set();
                return;
            }

            WriteLine("正在生成,稍候 …", ConsoleColor.DarkGreen);

            SocketMessager messager = new SocketMessager("GetDatabases", this._client);

            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                List <DatabaseInfo> dbs = e2.Messager.Arg as List <DatabaseInfo>;
            });
            this._client.Database = this.Database;
            List <TableInfo> tables = null;

            messager = new SocketMessager("GetTablesByDatabase", this._client.Database);
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                tables = e2.Messager.Arg as List <TableInfo>;
            });
            if (tables == null)
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] 无法读取表");
                this._socket.Close();
                this._socket.Dispose();

                wait.Set();
                return;
            }
            tables.ForEach(a => a.IsOutput = true);
            List <BuildInfo> bs = null;

            messager = new SocketMessager("Build", new object[] {
                SolutionName,
                IsMakeSolution,
                string.Join("", tables.ConvertAll <string>(delegate(TableInfo table){
                    return(string.Concat(table.IsOutput ? 1 : 0));
                }).ToArray()),
                IsMakeWebAdmin,
                IsDownloadRes
            });
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                bs = e2.Messager.Arg as List <BuildInfo>;
                if (e2.Messager.Arg is Exception)
                {
                    throw e2.Messager.Arg as Exception;
                }
            }, TimeSpan.FromSeconds(60 * 5));
            if (bs != null)
            {
                foreach (BuildInfo b in bs)
                {
                    string path = Path.Combine(OutputPath, b.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    string   fileName = Path.GetFileName(b.Path);
                    string   ext      = Path.GetExtension(b.Path);
                    Encoding encode   = Encoding.UTF8;

                    if (fileName.EndsWith(".rar") || fileName.EndsWith(".zip") || fileName.EndsWith(".dll"))
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                            fs.Write(b.Data, 0, b.Data.Length);
                            fs.Close();
                        }
                        continue;
                    }

                    byte[] data    = Deflate.Decompress(b.Data);
                    string content = Encoding.UTF8.GetString(data);

                    if (string.Compare(fileName, "web.config") == 0)
                    {
                        string place = System.Web.HttpUtility.HtmlEncode(this.ConnectionString);
                        content = content.Replace("{connectionString}", place);
                    }
                    if (fileName.EndsWith(".json"))
                    {
                        content = content.Replace("{connectionString}", this.ConnectionString);
                    }
                    if (string.Compare(ext, ".refresh") == 0)
                    {
                        encode = Encoding.Unicode;
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, encode)) {
                        sw.Write(content);
                        sw.Close();
                    }
                }
                var appsettingsPath        = Path.Combine(OutputPath, "appsettings.json");
                var appsettingsPathWebHost = Path.Combine(OutputPath, @"src\WebHost\appsettings.json");
                var htmZipPath             = Path.Combine(OutputPath, "htm.zip");
                //解压htm.zip
                if (this.IsDownloadRes && File.Exists(htmZipPath))
                {
                    try {
                        System.IO.Compression.ZipFile.ExtractToDirectory(htmZipPath, OutputPath, Encoding.UTF8, true);
                    } catch (Exception ex) {
                        var color = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"解压 htm.zip 失败:{ex.Message}");
                        Console.ForegroundColor = color;
                    }
                }
                if (this.IsMakeSolution)
                {
                    WriteLine("代码已生成完毕!使用 -S 生成完整项目,正在建立脚手架,大约需要10秒 …", ConsoleColor.DarkGreen);

                    var shellret = ShellRun(OutputPath, "gulp -v");

                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine("");
                        WriteLine(@"正在安装gulp-cli …", ConsoleColor.DarkGreen);
                        shellret = ShellRun(OutputPath, "npm install --global gulp-cli");
                        if (!string.IsNullOrEmpty(shellret.err))
                        {
                            WriteLine(shellret.err, ConsoleColor.Red);
                        }
                        if (!string.IsNullOrEmpty(shellret.warn))
                        {
                            WriteLine(shellret.warn, ConsoleColor.Yellow);
                        }
                        if (!string.IsNullOrEmpty(shellret.info))
                        {
                            WriteLine(shellret.info, ConsoleColor.DarkGray);
                        }
                    }

                    //WriteLine("");
                    //WriteLine("正在还原项目 …", ConsoleColor.DarkGreen);
                    //shellret = ShellRun(OutputPath, "dotnet1 restore");
                    //if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red);
                    //if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow);
                    //if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray);

                    WriteLine("");
                    WriteLine(@"正在编译Module\Test …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Test"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine(@"正在编译Module\Admin …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Admin"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine("正在安装npm包 …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "npm install");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine("正在编译WebHost …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine($"脚手架建立完成。", ConsoleColor.DarkGreen);

                    //WriteLine("");
                    //Write($"项目运行依赖 ", ConsoleColor.DarkYellow);
                    //Write($"redis-server", ConsoleColor.Green);
                    //Write($",安装地址:", ConsoleColor.DarkYellow);
                    //Write("https://files.cnblogs.com/files/kellynic/Redis-x64-2.8.2402.zip", ConsoleColor.Blue);
                    //WriteLine($",或前往官方下载", ConsoleColor.DarkYellow);

                    WriteLine($"{Path.Combine(OutputPath, @"src\WebHost")} 目执行 dotnet run", ConsoleColor.DarkYellow);
                    WriteLine("");
                    //Console.WriteLine(ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet run"));

                    var pro = new System.Diagnostics.Process();
                    pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "run --urls=http://0.0.0.0:5000")
                    {
                        WorkingDirectory     = Path.Combine(OutputPath, @"src\WebHost"),
                        EnvironmentVariables = { ["ASPNETCORE_ENVIRONMENT"] = "Development" }
                    };
                    pro.Start();
                    pro.WaitForExit();
                }
                //如果三个选项为false,并且 src\WebHost\appsettings.json 不存在,则在当前目录使用 appsettings.json
                if (this.IsDownloadRes == false && this.IsMakeSolution == false && this.IsMakeWebAdmin == false && File.Exists(appsettingsPathWebHost) == false)
                {
                    var appsettings = Newtonsoft.Json.JsonConvert.DeserializeObject(File.Exists(appsettingsPath) ? File.ReadAllText(appsettingsPath) : "{}") as JToken;
                    var oldtxt      = appsettings.ToString();
                    if (appsettings["ConnectionStrings"] == null)
                    {
                        appsettings["ConnectionStrings"] = new JObject();
                    }
                    if (appsettings["ConnectionStrings"][$"{this.SolutionName}_mssql"] == null)
                    {
                        appsettings["ConnectionStrings"][$"{this.SolutionName}_mssql"] = this.ConnectionString + "Pooling=true;Max Pool Size=100";
                    }
                    if (appsettings["ConnectionStrings"]["redis1"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis1"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings["ConnectionStrings"]["redis2"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis2"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] == null)
                    {
                        appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] = JToken.FromObject(new {
                            Timeout = 180
                        });
                    }
                    if (appsettings["Logging"] == null)
                    {
                        appsettings["Logging"] = new JObject();
                    }
                    if (appsettings["Logging"]["IncludeScopes"] == null)
                    {
                        appsettings["Logging"]["IncludeScopes"] = false;
                    }
                    if (appsettings["Logging"]["LogLevel"] == null)
                    {
                        appsettings["Logging"]["LogLevel"] = new JObject();
                    }
                    if (appsettings["Logging"]["LogLevel"]["Default"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Default"] = "Debug";
                    }
                    if (appsettings["Logging"]["LogLevel"]["System"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["System"] = "Information";
                    }
                    if (appsettings["Logging"]["LogLevel"]["Microsoft"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Microsoft"] = "Information";
                    }
                    var newtxt = appsettings.ToString();
                    if (newtxt != oldtxt)
                    {
                        File.WriteAllText(appsettingsPath, newtxt, Encoding.UTF8);
                    }
                    //增加当前目录 .csproj nuguet 引用 <PackageReference Include="dng.Mssql" Version="" />
                    string csprojPath = Directory.GetFiles(OutputPath, "*.csproj").FirstOrDefault();
                    if (!string.IsNullOrEmpty(csprojPath) && File.Exists(csprojPath))
                    {
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"dng\.Mssql""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package dng.Mssql")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"CSRedisCore""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package CSRedisCore")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                    }
                    //向startup.cs注入代码
                    string startupPath = Path.Combine(OutputPath, "Startup.cs");
                    if (!string.IsNullOrEmpty(startupPath) && File.Exists(startupPath))
                    {
                        //web项目才需要 Caching.CSRedis
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"Caching.CSRedis""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package Caching.CSRedis")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }

                        bool isChanged   = false;
                        var  startupCode = File.ReadAllText(startupPath);
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Caching\.Distributed;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Caching.Distributed;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Logging;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Logging;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Configuration;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Configuration;\r\n" + startupCode;
                        }

                        var servicesName = "services";
                        if (startupCode.IndexOf("RedisHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;

                                var connStr1 = @"Configuration[""ConnectionStrings:redis2""]";
                                var connStr2 = @"Configuration[""ConnectionStrings:redis1""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr1 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                    connStr2 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                }

                                return(m.Groups[0].Value + $@"


			//单redis节点模式,如需开启集群负载,请将注释去掉并做相应配置
			RedisHelper.Initialization(
				csredis: new CSRedis.CSRedisClient(//null,
					//{connStr1},
					{connStr2}),
				serialize: value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
				deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type));
			{servicesName = m.Groups[1].Value}.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));


");
                            }, RegexOptions.Multiline);
                        }
                        if (Regex.IsMatch(startupCode, @"\s+IConfiguration(Root)?\s+Configuration(;|\s+\{)") == false)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;
                                return($@"
		public IConfiguration Configuration {{ get; set; }}
{m.Groups[0].Value}

			Configuration = {servicesName = m.Groups[1].Value}.BuildServiceProvider().GetService<IConfiguration>();"            );
                            }, RegexOptions.Multiline);
                        }
                        if (startupCode.IndexOf(this.SolutionName + ".BLL.SqlHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"([\t ]+public\s+void\s+Configure\s*\()([^\{]+)\{", m => {
                                isChanged         = true;
                                var str1          = m.Groups[1].Value;
                                var str2          = m.Groups[2].Value;
                                var loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                if (loggerFactory.Success == false)
                                {
                                    str2 = "ILoggerFactory loggerFactory, " + str2;
                                }
                                loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                var appName   = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");
                                if (appName.Success == false)
                                {
                                    str2 = "IApplicationBuilder app, " + str2;
                                }
                                appName = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");

                                var connStr = $@"Configuration[""ConnectionStrings:{this.SolutionName}_mssql""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr = $"{this.ConnectionString};Pooling=true;Maximum Pool Size=100";
                                }

                                return(str1 + str2 + $@"{{

			
			{this.SolutionName}.BLL.SqlHelper.Initialization({appName.Groups[1].Value}.ApplicationServices.GetService<IDistributedCache>(), Configuration.GetSection(""{this.SolutionName}_BLL_ITEM_CACHE""),
				{connStr}, /* 此参数可以配置【从数据库】 */ null, {loggerFactory.Groups[1].Value}.CreateLogger(""{this.SolutionName}_DAL_sqlhelper""));


");
                            }, RegexOptions.Multiline);
                        }
                        if (isChanged)
                        {
                            File.WriteAllText(startupPath, startupCode);
                        }
                    }
                }
                if (File.Exists(Path.Combine(OutputPath, "GenMs只更新db.bat")) == false)
                {
                    var batPath = Path.Combine(OutputPath, $"GenMs_{this.SolutionName}_{this.Server}_{this.Database}.bat");
                    if (File.Exists(batPath) == false)
                    {
                        if (string.IsNullOrEmpty(this.Username))
                        {
                            File.WriteAllText(batPath, $@"
GenMs {this.Server} -D {this.Database} -N {this.SolutionName}");
                        }
                        else
                        {
                            File.WriteAllText(batPath, $@"
GenMs {this.Server} -U {this.Username} -P {this.Password} -D {this.Database} -N {this.SolutionName}");
                        }
                    }
                }
            }
            this._socket.Close();
            this._socket.Dispose();
            GC.Collect();

            ConsoleColor fc = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] The code files be maked in \"" + OutputPath + "\", please check.");
            Console.ForegroundColor = fc;
            wait.Set();
        }
Exemple #46
0
        public async Task <IActionResult> Upload(IFormCollection paras)
        {
            var auth = await HttpContext.AuthenticateAsync();

            if (!auth.Succeeded)
            {
                return(BadRequest(new { status = "not login" }));
            }

            var claim = User.FindFirstValue("User");
            int usid;

            if (!Int32.TryParse(claim, out usid))
            {
                return(BadRequest(new { status = "validation failed" }));
            }

            string pathToSave;
            string coverFileName = Guid.NewGuid().ToString() + '.' + paras.Files["cover"].FileName.Split('.').Last();
            string videoFileName = Guid.NewGuid().ToString() + '.' + paras.Files["video"].FileName.Split('.').Last();

            pathToSave = "wwwroot/images" + "/" + coverFileName;
            using (var stream = System.IO.File.Create(pathToSave))
            {
                await paras.Files["cover"].CopyToAsync(stream);
            }

            pathToSave = "wwwroot/videos" + "/" + videoFileName;
            using (var stream = System.IO.File.Create(pathToSave))
            {
                await paras.Files["video"].CopyToAsync(stream);
            }

            var videoPO = new Video();

            videoPO.Usid        = usid;
            videoPO.Cover       = coverFileName;
            videoPO.Path        = videoFileName;
            videoPO.Title       = paras["title"];
            videoPO.Description = paras["desc"];
            videoPO.CreateTime  = DateTime.Now;

            try
            {
                using (System.Diagnostics.Process pro = new System.Diagnostics.Process())
                {
                    pro.StartInfo.UseShellExecute       = false;
                    pro.StartInfo.ErrorDialog           = false;
                    pro.StartInfo.RedirectStandardError = true;

                    pro.StartInfo.FileName  = "../ffmpeg/tools/ffmpeg/bin/ffmpeg.exe";
                    pro.StartInfo.Arguments = " -i " + pathToSave;

                    pro.Start();
                    System.IO.StreamReader errorreader = pro.StandardError;
                    pro.WaitForExit(1000);

                    string result = errorreader.ReadToEnd();
                    if (!string.IsNullOrEmpty(result))
                    {
                        result = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);
                        var v = result.Split(':');
                        int t = Convert.ToInt32(v[0]) * 3600 + Convert.ToInt32(v[1]) * 60 + Convert.ToInt32(v[2]);
                        videoPO.Time = t;
                    }
                }
            }
            catch { }

            try
            {
                await _context.Video.AddAsync(videoPO);

                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                return(BadRequest(new
                {
                    status = "Create failed.",
                    data = e.ToString()
                }));
            }

            try
            {
                foreach (var v in paras["tags"])
                {
                    var tag = await _context.Tag.FirstOrDefaultAsync(x => x.Name == v);

                    if (tag == null)
                    {
                        tag      = new Tag();
                        tag.Name = v;
                        await _context.Tag.AddAsync(tag);
                    }
                    var vt = new Videotag();
                    vt.TagId = tag.TagId;
                    vt.Vid   = videoPO.Vid;
                    await _context.Videotag.AddAsync(vt);
                }
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                return(BadRequest(new
                {
                    status = "Create tag failed.",
                    data = e.ToString()
                }));
            }

            try
            {
                foreach (var v in paras["catags"])
                {
                    var tag = await _context.Tag.FirstOrDefaultAsync(x => x.Name == v);

                    if (tag == null)
                    {
                        tag      = new Tag();
                        tag.Name = v;
                        await _context.Tag.AddAsync(tag);
                    }

                    if (tag.CatId == null)
                    {
                        var ncat = new Cat();
                        ncat.Name = v;
                        await _context.Cat.AddAsync(ncat);

                        tag.CatId = ncat.CatId;
                    }

                    var vt = new Videotag();
                    vt.TagId = tag.TagId;
                    vt.Vid   = videoPO.Vid;
                    await _context.Videotag.AddAsync(vt);
                }
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                return(BadRequest(new
                {
                    status = "Create catag failed.",
                    data = e.ToString()
                }));
            }

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

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


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


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


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


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

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

                try {
                    process?.Start();

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

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

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

            return(items);
        }
Exemple #48
0
        void t_Tick(object sender, EventArgs e)
        {
            ((Timer)sender).Stop();
            this.Text += " v" + Application.ProductVersion;

            DFC.coreTest();
            if (Directory.Exists(@"..\..\tools\"))
            {
                if (DialogResult.Yes == MessageBox.Show(
                        "make .dfc (decent file container) ?\r\n\r\nhint: rename the tools folder\r\n         if you don't wanna see this",
                        "new embedded archive",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question))
                {
                    splash.vis();
                    new DFC().make(splash.pb);
                    Program.kill();
                }
            }
            if (!Program.DO_IT)
            {
                MessageBox.Show("This program should be run by Loopstream!\n\nStop doing that.");
                Program.kill();
            }
            if (!Directory.Exists(Program.tools))
            {
                //MessageBox.Show(Program.tools);
                MessageBox.Show("Could not find LoopstreamTools directory.\n\nWhat the f**k.");
                Program.kill();
            }
            System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("traktor2loopstream");
            if (procs.Length > 0)
            {
                Program.kill();
            }

            string basedir = Program.tools + "ice";

            if (Directory.Exists(basedir))
            {
                bool ok = false;
                try
                {
                    var txt = File.ReadAllText(Path.Combine(basedir, "web", "statuls.xsl"), Encoding.UTF8);
                    ok = txt.Contains("artist\" /> - </xsl:if><xsl");
                }
                catch { }

                if (!ok)
                {
                    for (int a = 0; a < 3; a++)
                    {
                        try
                        {
                            Directory.Delete(basedir, true);
                            Application.DoEvents();
                            System.Threading.Thread.Sleep(500); // mkdir fails otherwise, ok yes good
                            break;
                        }
                        catch
                        {
                            Application.DoEvents();
                            System.Threading.Thread.Sleep(250);
                        }
                    }
                }
            }

            if (!Directory.Exists(basedir))
            {
                splash.vis();
                new DFC().extract(splash.pb);

                if (DialogResult.Yes == MessageBox.Show(
                        "Would you like me to perform the necessary\n" +
                        "changes to the Traktor configuration files?",
                        "Automatic Install Prompt",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question))
                {
                    configure_traktor();
                }

                if (DialogResult.Yes == MessageBox.Show(
                        "Would you like me to perform the necessary\n" +
                        "changes to the Virtualdj configuration files?",
                        "Automatic Install Prompt",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question))
                {
                    configure_virtualdj();
                }
            }
            splash.unvis();
            splash.fx = false;
            splash.gtfo();

            System.Diagnostics.Process proc;
            proc           = new System.Diagnostics.Process();
            proc.StartInfo = new System.Diagnostics.ProcessStartInfo(
                "bin\\traktor2loopstream.exe",
                "-c icecast.xml");
            proc.StartInfo.WindowStyle      = System.Diagnostics.ProcessWindowStyle.Hidden;
            proc.StartInfo.WorkingDirectory = Program.tools + "ice";
            proc.Start();
            for (int a = 0; a < 20; a++)
            {
                try
                {
                    string str = new System.Net.WebClient().DownloadString("http://127.0.0.1:42069/statuls.xsl");
                    if (str.Contains("<pre>"))
                    {
                        break;
                    }
                }
                catch { }
                if (a == 19)
                {
                    MessageBox.Show("the Traktor plugin failed to start ;_;");
                    break;
                }
                Application.DoEvents();
                System.Threading.Thread.Sleep(500);
            }
            Application.DoEvents();
            Program.kill();
        }
Exemple #49
0
        public AppFinder(Platform p)
        {
            platform = p;
            if (p == Platform.MacOS)
            {
                ValkyrieDebug.Log("Attempting to locate AppId " + AppId() + " on MacOS.");
                System.Diagnostics.ProcessStartInfo processStartInfo;
                System.Diagnostics.Process          process;

                StringBuilder outputBuilder = new StringBuilder();

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

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


                string output = outputBuilder.ToString();

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

            if (location == null || location.Length == 0)
            {
                string[] args = Environment.GetCommandLineArgs();
                for (int i = 0; i < (args.Length - 1); i++)
                {
                    if (args[i] == "-import")
                    {
                        location = args[i + 1];
                        if (location.Length > 0)
                        {
                            if (location[location.Length - 1] == '/' || location[location.Length - 1] == '\\')
                            {
                                location = location.Substring(0, location.Length - 1);
                            }
                        }
                        ValkyrieDebug.Log("Using import flag location: " + location);
                    }
                }
            }
            exeLocation += location + "/" + Executable();
            location    += DataDirectory();
            ValkyrieDebug.Log("Asset location: " + location);
        }
Exemple #50
0
        private static void Main()
        {
            OperatingSystem os = Environment.OSVersion;

            Console.WriteLine(os.VersionString.ToString());

            if (os.VersionString.ToString().ToUpper().Contains("UNIX"))
            {
                MAC = true;
            }

            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            // give 4 seconds grace
            System.Threading.Thread.Sleep(5000);

            //UpdateFiles(path);

            if (!UpdateFiles(path))
            {
                Console.WriteLine("Update failed, please try it later.");
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey();
            }
            else
            {
                try
                {
                    Directory.GetFiles(path, "*.old").ForEach(a =>
                    {
                        try
                        {
                            File.SetAttributes(a, FileAttributes.Normal);
                            File.Delete(a);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    });

                    System.Diagnostics.Process P = new System.Diagnostics.Process();
                    if (MAC)
                    {
                        P.StartInfo.WorkingDirectory = path;
                        P.StartInfo.FileName         = "mono";
                        P.StartInfo.Arguments        =
                            " \"" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) +
                            Path.DirectorySeparatorChar + "MissionPlanner.exe\"";
                    }
                    else
                    {
                        P.StartInfo.WorkingDirectory = path;
                        P.StartInfo.FileName         = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) +
                                                       Path.DirectorySeparatorChar + "MissionPlanner.exe";
                        P.StartInfo.Arguments = "";
                    }

                    Console.WriteLine("Start " + P.StartInfo.FileName + " with " + P.StartInfo.Arguments);
                    P.Start();
                }
                catch
                {
                } // likely file didnt exist
            }
        }
        // ******************************** Center System Dialogs

        #region Center System Dialogs

        internal static bool CenterSystemDialog(string fileName, string arguments, Form baseForm) //Rectangle itemBounds)
        {
            bool result = true;

            try
            {
                IntPtr hWndCurrent = GetForegroundWindow();

                System.Diagnostics.Process showControlPanel = new System.Diagnostics.Process
                {
                    StartInfo = { FileName = fileName, Arguments = arguments }
                };
                showControlPanel.Start();
                showControlPanel.Dispose();

                if (baseForm != null)
                {
                    int    i    = 0;
                    IntPtr hWnd = GetForegroundWindow();
                    while (i < 100 && hWnd == hWndCurrent)
                    {
                        ++i;
                        System.Threading.Thread.Sleep(10);
                        hWnd = GetForegroundWindow();
                    }

                    if (hWnd != hWndCurrent)
                    {
                        Rectangle r1 = new Rectangle();
                        Rectangle r2 = Screen.GetWorkingArea(baseForm);
                        Rect      r3;

                        GetWindowRect(hWnd, out r3);

                        r1.Width  = r3.Right - r3.Left + 1;
                        r1.Height = r3.Bottom - r3.Top + 1;

                        r1.X = baseForm.Bounds.Left + (baseForm.Bounds.Width - r1.Width) / 2;
                        if (r1.X < r2.X)
                        {
                            r1.X = r2.X + 2;
                        }
                        else if (r1.X + r1.Width > r2.Width)
                        {
                            r1.X = r2.Width - r1.Width - 2;
                        }

                        r1.Y = baseForm.Bounds.Top + (baseForm.Bounds.Height - r1.Height) / 2;
                        if (r1.Y < r2.Y)
                        {
                            r1.Y = r2.Y + 2;
                        }
                        else if (r1.Y + r1.Height > r2.Height)
                        {
                            r1.Y = r2.Height - r1.Height - 2;
                        }

                        SetWindowPos(hWnd, IntPtr.Zero, r1.X, r1.Y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW);
                    }
                }
            }
            catch { result = false; }
            return(result);
        }
        /// <summary>
        /// Task Dialog - create an instance of task dialog gives you more options.
        /// cf. Developer guide, Figure 223 (on pp 405) has a image of all the components visible.
        /// This function is to visulize what kind of contents you can add with TaskDialog.
        /// Note: actual interpretation of
        /// </summary>
        public void ShowTaskDialogInstance(bool stepByStep)
        {
            // (0) create an instance of task dialog to set more options.
            TaskDialog myDialog = new TaskDialog("Revit UI Labs - Task Dialog Options");

            if (stepByStep)
            {
                myDialog.Show();
            }

            // (1) set the main area. these appear at the upper portion of the dialog.

            myDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
            // or TaskDialogIcon.TaskDialogIconNone.
            if (stepByStep)
            {
                myDialog.Show();
            }

            myDialog.MainInstruction = "Main instruction: This is Revit UI Lab 3 Task Dialog";
            if (stepByStep)
            {
                myDialog.Show();
            }

            myDialog.MainContent = "Main content: You can add detailed description here.";
            if (stepByStep)
            {
                myDialog.Show();
            }

            // (2) set the bottom area

            myDialog.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel;
            myDialog.DefaultButton = TaskDialogResult.Yes;
            if (stepByStep)
            {
                myDialog.Show();
            }

            myDialog.ExpandedContent = "Expanded content: the visibility of this portion is controled by Show/Hide button.";
            if (stepByStep)
            {
                myDialog.Show();
            }

            myDialog.VerificationText = "Verification: Do not show this message again comes here";
            if (stepByStep)
            {
                myDialog.Show();
            }

            myDialog.FooterText = "Footer: <a href=\"http://www.autodesk.com/developrevit\">Revit Developer Center</a>";
            if (stepByStep)
            {
                myDialog.Show();
            }

            // (4) add command links. you can add up to four links

            myDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Command Link 1", "description 1");
            if (stepByStep)
            {
                myDialog.Show();
            }
            myDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Command Link 2", "description 2");
            if (stepByStep)
            {
                myDialog.Show();
            }
            myDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Command Link 3", "you can add up to four command links");
            if (stepByStep)
            {
                myDialog.Show();
            }
            myDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink4, "Command Link 4", "Can also have URLs e.g. Revit Product Online Help");
            //if (stepByStep) myDialog.Show();

            // Show it.
            TaskDialogResult res = myDialog.Show();

            if (TaskDialogResult.CommandLink4 == res)
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                // process.StartInfo.FileName = "http://docs.autodesk.com/REVIT/2011/ENU/landing.html";
                //process.StartInfo.FileName = "http://wikihelp.autodesk.com/Revit/enu/2012";
                process.StartInfo.FileName = "http://wikihelp.autodesk.com/Revit/enu/2013";
                process.Start();
            }

            TaskDialog.Show("Show task dialog", "The last action was: " + res.ToString());
        }
Exemple #53
0
        private void btnToEPub_Click(object sender, RoutedEventArgs e)
        {
            if (this.textBox1.Text != String.Empty && fullPath != string.Empty)
            {
                if (!this.textBox1.Text.EndsWith(".doc") && !this.textBox1.Text.EndsWith(".docx") &&
                    !this.textBox1.Text.EndsWith(".rtf") && !this.textBox1.Text.EndsWith(".docm") &&
                    !this.textBox1.Text.EndsWith(".dotx") && !this.textBox1.Text.EndsWith(".dotm") &&
                    !this.textBox1.Text.EndsWith(".dot") && !this.textBox1.Text.EndsWith(".txt"))
                {
                    MessageBox.Show("Browse a Word document to convert to EPub", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (fullPath.EndsWith("\\"))
                {
                    fullPath += this.textBox1.Text;
                }
                if (File.Exists(fullPath))
                {
                    try
                    {
                        WordDocument document = new WordDocument(fullPath);

                        document.SaveOptions.EPubExportFont = this.chkBox1.IsChecked.Value;

                        document.Save("Sample.epub", FormatType.EPub);
                        document.Close();

                        //Message box confirmation to view the created document.
                        if (MessageBox.Show("Conversion Successful. Do you want to view the EPub File?", "Status", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            try
                            {
#if NETCORE
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.epub")
                                {
                                    UseShellExecute = true
                                };
                                process.Start();
#else
                                System.Diagnostics.Process process = System.Diagnostics.Process.Start("Sample.epub");
                                if (process != null && process.ProcessName != null && process.ProcessName.ToLower() == "rundll32")
                                {
                                    process.Kill();
                                    MessageBox.Show("EPub viewer is not installed in this system!", "Status");
                                }
#endif
                                this.Close();
                            }
                            catch (System.ComponentModel.Win32Exception)
                            {
                                MessageBox.Show("EPub viewer is not installed in this system!", "Status");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is IOException)
                        {
                            MessageBox.Show("Please close the file (" + Directory.GetCurrentDirectory() + "\\Sample.epub" + ") then try generating the document.", "File is already open",
                                            MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        else
                        {
                            MessageBox.Show("Document could not be generated, Could you please email the error details with along input document to [email protected] for trouble shooting" + "\r\n" + ex.ToString(), "Error",
                                            MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("File doesn’t exist");
                }
            }
            else
            {
                MessageBox.Show("Browse a Word document to convert to EPub", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #54
0
        public static String UpdateServiceStop(UpdateGA update, ProcedureSchedule procedureschedule, int serviceId)
        {
            Models.GAContext           context   = new Models.GAContext();
            GALibrary.Models.Parameter parameter = context.Parameter.FirstOrDefault();

            Service service = context.Service.First(x => x.Id == serviceId);
            Server  server  = context.Server.Include(x => x.ServerUser).First(x => x.Id == service.ServerId);
            OS      os      = context.OS.First(x => x.Id == server.OSId);

            String result          = "";
            String comandoCompleto = os.AccessCommand;

            comandoCompleto = comandoCompleto.Replace("nomeDoServidor", server.Name);
            comandoCompleto = comandoCompleto.Replace("usuarioDeAcesso", GALibrary.GACrypto.Base64Decode(server.ServerUser.ServerUsername));
            comandoCompleto = comandoCompleto.Replace("senhaDeAcesso", GALibrary.GACrypto.Base64Decode(server.ServerUser.ServerPassword));
            comandoCompleto = comandoCompleto.Replace("comandoParaExecutar", service.CommandStop);

            try
            {
                if (update != null)
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop", "Procedimento - " + service.Name, 2, parameter);
                }
                else
                {
                    GALibrary.GALogs.SaveLogProcedure(procedureschedule, "ServiceStop - " + service.Name, "Parando servico", 2, parameter);
                }

                System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + comandoCompleto);
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.CreateNoWindow         = true;
                procStartInfo.UseShellExecute        = false;
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();

                result = proc.StandardOutput.ReadToEnd();

                if (update != null)
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop - " + service.Name, "Retorno: " + result, 2, parameter);
                }
                else
                {
                    GALibrary.GALogs.SaveLogProcedure(procedureschedule, "ServiceStop - " + service.Name, "Retorno: " + result, 2, parameter);
                }
            }
            catch (Exception error)
            {
                if (update != null)
                {
                    GALibrary.GALogs.SaveLogUpdate(update, "ServiceStop  - " + service.Name, error.ToString(), 1, parameter);
                }
                else
                {
                    GALibrary.GALogs.SaveLogProcedure(procedureschedule, "ServiceStop  - " + service.Name, error.ToString(), 1, parameter);
                }
                return(error.ToString());
            }

            return(result);
        }
Exemple #55
0
        /// <summary>
        /// Runs iwyu. Blocks until finished.
        /// </summary>
        static public async Task <string> RunIncludeWhatYouUse(string fullFileName, EnvDTE.Project project, IncludeWhatYouUseOptionsPage settings)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            string preprocessorDefintions;

            try
            {
                preprocessorDefintions = VSUtils.VCUtils.GetCompilerSetting_PreprocessorDefinitions(project);
            }
            catch (VCQueryFailure e)
            {
                await Output.Instance.ErrorMsg("Can't run IWYU: {0}", e.Message);

                return(null);
            }

            string output = "";

            using (var process = new System.Diagnostics.Process())
            {
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.FileName = settings.ExecutablePath;

                // Clang options
                var clangOptionList = new List <string>();
                // Disable all diagnostics
                clangOptionList.Add("-w");
                // ... despite of that "invalid token paste" comes through a lot. Disable it.
                clangOptionList.Add("-Wno-invalid-token-paste");
                // Assume C++14
                clangOptionList.Add("-std=c++14");
                // MSVC specific. See https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
                clangOptionList.Add("-fms-compatibility -fms-extensions -fdelayed-template-parsing");
                clangOptionList.Add($"-fmsc-version={VSUtils.GetMSCVerString()}");
                // Architecture
                try
                {
                    switch (VSUtils.VCUtils.GetLinkerSetting_TargetMachine(project))
                    {
                    // Most targets give an error of this form:
                    // "error: unknown target CPU 'x86'"
                    // It seems iwyu is only really fine with x86-64

                    /*case VCProjectUtils.Base.TargetMachineType.X86:
                     *  clangOptions.Add("-march=x86");
                     *  break;*/
                    case VCHelper.TargetMachineType.AMD64:
                        clangOptionList.Add("-march=x86-64");
                        break;

                        /*case VCProjectUtils.Base.TargetMachineType.ARM:
                         *  clangOptions.Add("-march=arm");
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.MIPS:
                         *  clangOptions.Add(""-march=mips");
                         *  break;
                         * case VCProjectUtils.Base.TargetMachineType.THUMB:
                         *  clangOptions.Add(""-march=thumb");
                         *  break;*/
                    }
                }
                catch (VCQueryFailure e)
                {
                    await Output.Instance.ErrorMsg($"Failed to query for target machine: {e.Message}");
                }

                // icwyu options
                var iwyuOptionList = new List <string>();
                iwyuOptionList.Add("--verbose=" + settings.LogVerbosity);
                for (int i = 0; i < settings.MappingFiles.Length; ++i)
                {
                    iwyuOptionList.Add("--mapping_file=\"" + settings.MappingFiles[i] + "\"");
                }
                if (settings.NoDefaultMappings)
                {
                    iwyuOptionList.Add("--no_default_mappings");
                }
                if (settings.PCHInCode)
                {
                    iwyuOptionList.Add("--pch_in_code");
                }
                switch (settings.PrefixHeaderIncludes)
                {
                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Add:
                    iwyuOptionList.Add("--prefix_header_includes=add");
                    break;

                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Remove:
                    iwyuOptionList.Add("--prefix_header_includes=remove");
                    break;

                case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Keep:
                    iwyuOptionList.Add("--prefix_header_includes=keep");
                    break;
                }
                if (settings.TransitiveIncludesOnly)
                {
                    iwyuOptionList.Add("--transitive_includes_only");
                }

                // Set max line length so something large so we don't loose comment information.
                // Documentation:
                // --max_line_length: maximum line length for includes. Note that this only affects comments and alignment thereof,
                // the maximum line length can still be exceeded with long file names(default: 80).
                iwyuOptionList.Add("--max_line_length=1024");

                /// write support file with includes, defines and the targetgile. Long argument lists lead to an error. Support files are the solution here.
                /// https://github.com/Wumpf/IncludeToolbox/issues/36
                // Include-paths and Preprocessor.
                var includes        = string.Join(" ", VSUtils.GetProjectIncludeDirectories(project, false).Select(x => "-I \"" + x.Replace("\\", "\\\\") + "\""));
                var defines         = preprocessorDefintions.Length == 0 ? "" : string.Join(" ", preprocessorDefintions.Split(';').Select(x => "-D" + x));
                var filename        = "\"" + fullFileName.Replace("\\", "\\\\") + "\"";
                var supportFilePath = Path.GetTempFileName();
                File.WriteAllText(supportFilePath, includes + " " + defines + " " + filename);

                var clangOptions = string.Join(" ", clangOptionList);
                // each include-what-you-use parameter has an -Xiwyu prefix
                var iwyuOptions = string.Join(" ", iwyuOptionList.Select(x => " -Xiwyu " + x));
                process.StartInfo.Arguments = $"{clangOptions} {iwyuOptions} {settings.AdditionalParameters} \"@{supportFilePath}\"";

                Output.Instance.Write("Running command '{0}' with following arguments:\n{1}\n\n", process.StartInfo.FileName, process.StartInfo.Arguments);

                // Start the child process.
                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.ErrorDataReceived += (s, args) =>
                {
                    Output.Instance.WriteLine(args.Data);
                    output += args.Data + "\n";
                };
                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.CancelOutputRead();
                process.CancelErrorRead();
            }

            return(output);
        }
Exemple #56
0
        private void btnPDFForm_Click(object sender, System.EventArgs e)
        {
            //Load the template document
#if NETCORE
            PdfLoadedDocument doc = new PdfLoadedDocument(@"..\..\..\..\..\..\..\..\Common\Data\PDF\Form.pdf");
#else
            PdfLoadedDocument doc = new PdfLoadedDocument(@"..\..\..\..\..\..\..\Common\Data\PDF\Form.pdf");
#endif

            PdfLoadedForm form = doc.Form;

            // fill the fields from the first page
            (form.Fields["f1-1"] as PdfLoadedTextBoxField).Text  = "1";
            (form.Fields["f1-2"] as PdfLoadedTextBoxField).Text  = "1";
            (form.Fields["f1-3"] as PdfLoadedTextBoxField).Text  = "1";
            (form.Fields["f1-4"] as PdfLoadedTextBoxField).Text  = "3";
            (form.Fields["f1-5"] as PdfLoadedTextBoxField).Text  = "1";
            (form.Fields["f1-6"] as PdfLoadedTextBoxField).Text  = "1";
            (form.Fields["f1-7"] as PdfLoadedTextBoxField).Text  = "22";
            (form.Fields["f1-8"] as PdfLoadedTextBoxField).Text  = "30";
            (form.Fields["f1-9"] as PdfLoadedTextBoxField).Text  = "John";
            (form.Fields["f1-10"] as PdfLoadedTextBoxField).Text = "Doe";
            (form.Fields["f1-11"] as PdfLoadedTextBoxField).Text = "3233 Spring Rd.";
            (form.Fields["f1-12"] as PdfLoadedTextBoxField).Text = "Atlanta, GA 30339";
            (form.Fields["f1-13"] as PdfLoadedTextBoxField).Text = "332";
            (form.Fields["f1-14"] as PdfLoadedTextBoxField).Text = "43";
            (form.Fields["f1-15"] as PdfLoadedTextBoxField).Text = "4556";
            (form.Fields["f1-16"] as PdfLoadedTextBoxField).Text = "3";
            (form.Fields["f1-17"] as PdfLoadedTextBoxField).Text = "2000";
            (form.Fields["f1-18"] as PdfLoadedTextBoxField).Text = "Exempt";
            (form.Fields["f1-19"] as PdfLoadedTextBoxField).Text = "Syncfusion, Inc.";
            (form.Fields["f1-20"] as PdfLoadedTextBoxField).Text = "200";
            (form.Fields["f1-21"] as PdfLoadedTextBoxField).Text = "22";
            (form.Fields["f1-22"] as PdfLoadedTextBoxField).Text = "56654";
            (form.Fields["c1-1[0]"] as PdfLoadedCheckBoxField).Items[0].Checked = true;
            (form.Fields["c1-1[1]"] as PdfLoadedCheckBoxField).Items[0].Checked = true;

            // fill the fields from the second page
            (form.Fields["f2-1"] as PdfLoadedTextBoxField).Text  = "3200";
            (form.Fields["f2-2"] as PdfLoadedTextBoxField).Text  = "4850";
            (form.Fields["f2-3"] as PdfLoadedTextBoxField).Text  = "0";
            (form.Fields["f2-4"] as PdfLoadedTextBoxField).Text  = "500";
            (form.Fields["f2-5"] as PdfLoadedTextBoxField).Text  = "500";
            (form.Fields["f2-6"] as PdfLoadedTextBoxField).Text  = "800";
            (form.Fields["f2-7"] as PdfLoadedTextBoxField).Text  = "0";
            (form.Fields["f2-8"] as PdfLoadedTextBoxField).Text  = "0";
            (form.Fields["f2-9"] as PdfLoadedTextBoxField).Text  = "3";
            (form.Fields["f2-10"] as PdfLoadedTextBoxField).Text = "3";
            (form.Fields["f2-11"] as PdfLoadedTextBoxField).Text = "3";
            (form.Fields["f2-12"] as PdfLoadedTextBoxField).Text = "2";
            (form.Fields["f2-13"] as PdfLoadedTextBoxField).Text = "3";
            (form.Fields["f2-14"] as PdfLoadedTextBoxField).Text = "3";
            (form.Fields["f2-15"] as PdfLoadedTextBoxField).Text = "2";
            (form.Fields["f2-16"] as PdfLoadedTextBoxField).Text = "1";
            (form.Fields["f2-17"] as PdfLoadedTextBoxField).Text = "200";
            (form.Fields["f2-18"] as PdfLoadedTextBoxField).Text = "600";
            (form.Fields["f2-19"] as PdfLoadedTextBoxField).Text = "250";

            doc.Save("sample.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                System.Diagnostics.Process.Start("Sample.pdf");
#endif
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
        static void Main(string[] args)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "ipconfig";
            process.StartInfo.Arguments              = "/all";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.Start(); //start process

            // Read the output (or the error)
            string output = process.StandardOutput.ReadToEnd(); //normal output

            Console.WriteLine(output);
            string err = process.StandardError.ReadToEnd(); //error output (if any)

            Console.WriteLine(err);
            //Continue
            Console.WriteLine("Klaar");

            Console.ReadLine();
            Console.Clear();

            process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "hostname";
            process.StartInfo.Arguments              = "";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.Start(); //start process

            // Read the output (or the error)
            output = process.StandardOutput.ReadToEnd(); //normal output
            Console.WriteLine(output);
            err = process.StandardError.ReadToEnd();     //error output (if any)
            Console.WriteLine(err);
            //Continue
            Console.WriteLine("Klaar");

            Console.ReadLine();
            Console.Clear();

            process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "arp";
            process.StartInfo.Arguments              = "-a";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.Start(); //start process

            // Read the output (or the error)
            output = process.StandardOutput.ReadToEnd(); //normal output
            Console.WriteLine(output);
            err = process.StandardError.ReadToEnd();     //error output (if any)
            Console.WriteLine(err);
            //Continue
            Console.WriteLine("Klaar");

            Console.ReadLine();
            Console.Clear();

            process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "getmac";
            process.StartInfo.Arguments              = "";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.Start(); //start process

            // Read the output (or the error)
            output = process.StandardOutput.ReadToEnd(); //normal output
            Console.WriteLine(output);
            err = process.StandardError.ReadToEnd();     //error output (if any)
            Console.WriteLine(err);
            //Continue
            Console.WriteLine("Klaar");

            Console.ReadLine();
            Console.Clear();

            process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "nslookup";
            process.StartInfo.Arguments              = "google.com";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.Start(); //start process

            // Read the output (or the error)
            output = process.StandardOutput.ReadToEnd(); //normal output
            Console.WriteLine(output);
            err = process.StandardError.ReadToEnd();     //error output (if any)
            Console.WriteLine(err);
            //Continue
            Console.WriteLine("Klaar");

            Console.ReadLine();
            Console.Clear();

            process = new System.Diagnostics.Process();
            process.StartInfo.FileName               = "notepad";
            process.StartInfo.Arguments              = "mytest.txt";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.Start(); //start process

            // Read the output (or the error)
            output = process.StandardOutput.ReadToEnd(); //normal output
            Console.WriteLine(output);
            err = process.StandardError.ReadToEnd();     //error output (if any)
            Console.WriteLine(err);
            //Continue
            Console.WriteLine("Klaar");

            Console.ReadLine();
            Console.Clear();
        }
Exemple #58
0
        private void GerarArquivoComparacaoSQL(string nomeBaseFonte, string nomeBaseAlvo, string xmlOutPutFile, string connectionStringBasesLegadas)
        {
            if (File.Exists(xmlOutPutFile))
            {
                return;
            }
            string diretorioDACPACs = configuration.GetSection("DirectoryDACPAC").Value;

            new DACPACGerador(configuration).GerarArquivoDacPacDeBase(nomeBaseFonte, connectionStringBasesLegadas);
            new DACPACGerador(configuration).GerarArquivoDacPacDeBase(nomeBaseAlvo, connectionStringBasesLegadas);
            var startInfo = new System.Diagnostics.ProcessStartInfo();

            startInfo.FileName        = $"{configuration.GetSection("MSBuildExeFile").Value}";
            startInfo.Arguments       = $"{configuration.GetSection("SchemaCompareProjectCSProjFile").Value} /t:SqlSchemaCompare /p:CmdLineInMemoryStorage=TRUE /p:source=\"{diretorioDACPACs}{nomeBaseFonte}.dacpac\" /p:target=\"{diretorioDACPACs}{nomeBaseAlvo}.dacpac\" /p:xmlOutput=\"{xmlOutPutFile}\" /p:Deploy=false /p:CmdLineInMemoryStorage=TRUE /t:Build  /p:DropObjectsNotInSource=True /p:DropIndexesNotInSource=True /p:TreatVerificationErrorsAsWarnings=true /p:IgnoreExtendedProperties=true /p:IgnoreColumnCollation=true /p:IgnoreColumnOrder=true /p:IgnoreComments=true /p:IgnoreIncrement=true /p:IgnoreTableOptions=true /p:IgnoreUserSettingsObjects=true /p:AllowDropBlockingAssemblies=false /p:IgnoreIndexOptions=true /p:ExcludeObjectType=ServerTriggers /p:ExcludeObjectType=Users /p:ExcludeObjectType=Views /p:ExcludeObjectType=Logins /p:ExcludeObjectType=StoredProcedures /p:ExcludeObjectType=DatabaseTriggers /p:ExcludeObjectType=Assemblies /p:ExcludeObjectType=Permissions /p:ExcludeObjectType=Queues /p:ExcludeObjectType=XmlSchemaCollections /p:ExcludeObjectType=Trigger";
            startInfo.UseShellExecute = false;
            //WARNING!!! If the powershell script outputs lots of data, this code could hang
            //You will need to output using a stream reader and purge the contents from time to time
            startInfo.RedirectStandardOutput = !startInfo.UseShellExecute;
            startInfo.RedirectStandardError  = !startInfo.UseShellExecute;
            var process = new System.Diagnostics.Process();

            process.StartInfo = startInfo;
            var output  = new StringBuilder();
            var error   = new StringBuilder();
            int timeout = 300000;

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

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

            if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout))
            {
                // Process completed. Check process.ExitCode here.
                if (process.ExitCode == 1)
                {
                    throw new Exception($"Falha ao executar a comparação (build) das bases. Mensagem: \n{error}");
                }
            }
            else
            {
                // Timed out.
            }
        }
Exemple #59
-1
 private void CMD(string str)
 {
     //process用于调用外部程序
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     //调用cmd.exe
     p.StartInfo.FileName = "cmd.exe";
     //是否指定操作系统外壳进程启动程序
     p.StartInfo.UseShellExecute = false;
     //可能接受来自调用程序的输入信息
     //重定向标准输入
     p.StartInfo.RedirectStandardInput = true;
     //重定向标准输出
     p.StartInfo.RedirectStandardOutput = true;
     //重定向错误输出
     p.StartInfo.RedirectStandardError = true;
     //不显示程序窗口
     p.StartInfo.CreateNoWindow = true;
     //启动程序
     p.Start();
     //睡眠1s。
     System.Threading.Thread.Sleep(1000);
     //输入命令
     p.StandardInput.WriteLine(str);
     skinTextBox1.Text += p.StandardOutput.ReadToEnd() + "\r\n";
     //一定要关闭。
     p.StandardInput.WriteLine("exit");
 }
Exemple #60
-2
        //CMD Funtion For Global
        static string CMD(string args)
        {
            string cmdbat = "cd " + Application.StartupPath.Replace("\\", "/") + "\r\n";
            cmdbat += args + " >> out.txt\r\n";
            cmdbat += "exit\r\n";
            File.WriteAllText(Application.StartupPath + "\\cmd.bat", cmdbat);

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

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

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