private static void run_shell_script()
 {
     System.Diagnostics.Process proc = new System.Diagnostics.Process();
     proc.EnableRaisingEvents = false;
     proc.StartInfo.FileName = "run.sh";
     proc.Start();
 }
 private void Help_Click(object sender, RoutedEventArgs e)
 {
     var help = new System.Diagnostics.Process();
     help.StartInfo.FileName = @"Archiver Revolution.chm";
     help.StartInfo.UseShellExecute = true;
     help.Start();
 }
Exemple #3
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 #4
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 #5
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;
            }
        }
Exemple #6
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;
        }
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
        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;
        }
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);
        }
        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];
            }
        }
Exemple #11
0
        public ElginTrackerForm()
        {
            InitializeComponent();
            openLogs = new Dictionary<RunLog, RunLogExplorerForm>();

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

            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                columnVisibility.Items.Add(new DataGridColumnWrapper(col));
                columnVisibility.SetItemChecked(columnVisibility.Items.Count - 1, col.Visible);
            }

            variableColumns = new List<DataGridViewColumn>();
            variableColumns.Add(VarA);
            variableColumns.Add(VarB);
            variableColumns.Add(VarC);
            variableColumns.Add(VarD);
            variableColumns.Add(VarE);
            variableColumns.Add(VarF);
            variableColumns.Add(VarG);

            variableSelections = new Dictionary<DataGridViewColumn, ColumnVariableSelection>();
        }
Exemple #12
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 #13
0
        private void playitems()
        {
            foreach (ListViewItem item in Playlist.Items)
            {
                // now spawn mplayer sessions for the playlist...
                string strCmdLine;
                strCmdLine = "-fs " + item.ImageKey;
                string originalName = item.Name;
                item.Name = item.Name + " [now playing]";

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

                //Do not receive an event when the process exits.
                mplayerprocess.EnableRaisingEvents = false;

                mplayerprocess = System.Diagnostics.Process.Start("mplayer.exe", strCmdLine);

                while (!mplayerprocess.HasExited)
                {
                    if (!PlaylistManager.play) break;
                    System.Threading.Thread.Sleep(10);
                }

                mplayerprocess.Close();

                item.Name = originalName;
            }
        }
Exemple #14
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
            }
        }
        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 #16
0
        protected override void Dispose(bool disposing)
        {
            if (m_p != null)
            {
                m_basestream.Close();

                if (!m_t.Join(5000))
                    throw new System.Security.Cryptography.CryptographicException(Strings.GPGStreamWrapper.GPGFlushError);

                if (!m_p.WaitForExit(5000))
                    throw new System.Security.Cryptography.CryptographicException(Strings.GPGStreamWrapper.GPGTerminateError);

                if (!m_p.StandardError.EndOfStream)
                {
                    string errmsg = m_p.StandardError.ReadToEnd();
                    if (errmsg.Contains("decryption failed:"))
                        throw new System.Security.Cryptography.CryptographicException(string.Format(Strings.GPGStreamWrapper.DecryptionError, errmsg));
                }

                m_p.Dispose();
                m_p = null;

                m_t = null;
            }

            base.Dispose(disposing);
        }
Exemple #17
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);
        }
        //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 #19
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 #20
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 #21
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);
        }
 void run()
 {
     System.Diagnostics.Process proc = new System.Diagnostics.Process();
     string strCmdLine="dir";
     //strCmdLine = "/C regenresx " + textBox1.Text + " " + textBox2.Text;
     System.Diagnostics.Process.Start("CMD.exe", strCmdLine);
 }
 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 #24
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("==========================================================");

              }
        }
		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);
			}
		}
        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();
            }
        }
Exemple #27
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 #28
0
                public static void Reboot()
                {
                        if (Lfx.Workspace.Master != null) {
                                Lfx.Workspace.Master.Disposing = true;
                                Lfx.Workspace.Master.Dispose();
                        }

                        string[] ParametrosAPasar = System.Environment.GetCommandLineArgs();
                        ParametrosAPasar[0] = "";
                        string Params = string.Join(" ", ParametrosAPasar).Trim();

                        string ExeName;
                        if (System.IO.File.Exists(Lfx.Environment.Folders.ApplicationFolder + "ActualizadorLazaro.exe"))
                                ExeName = Lfx.Environment.Folders.ApplicationFolder + "ActualizadorLazaro.exe";
                        else
                                ExeName = Lfx.Environment.Folders.ApplicationFolder + "Lazaro.exe";

                        System.Diagnostics.Process NuevoProceso = new System.Diagnostics.Process();
                        if (Lfx.Environment.SystemInformation.RunTime == Lfx.Environment.SystemInformation.RunTimes.DotNet) {
                                NuevoProceso.StartInfo = new System.Diagnostics.ProcessStartInfo(ExeName, Params);
                        } else {
                                string MonoName = Lfx.Environment.SystemInformation.Platform == SystemInformation.Platforms.Windows ? "mono.exe" : "/usr/bin/mono";
                                NuevoProceso.StartInfo = new System.Diagnostics.ProcessStartInfo(MonoName, @"""" + ExeName + @""" " + Params);
                        }

                        NuevoProceso.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                        NuevoProceso.StartInfo.UseShellExecute = false;
                        NuevoProceso.Start();

                        System.Environment.Exit(0);
                }
Exemple #29
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            List <BuiltInCategory> builtInFilter = new List <BuiltInCategory>();

            builtInFilter.Add(BuiltInCategory.OST_RevisionClouds);
            //builtInFilter.Add(BuiltInCategory.OST_RevisionCloudTags);


            ElementMulticategoryFilter filterRevision = new ElementMulticategoryFilter(builtInFilter);

            //ICollection<Element> fec = new FilteredElementCollector(doc).WherePasses(filterRevision).WhereElementIsNotElementType().ToElements();

            ICollection <ElementId> fec = uidoc.Selection.GetElementIds();

            string outputFile = @"C:\Temp\reportUprev.csv";

            StringBuilder sb = new StringBuilder();

            StringBuilder result = new StringBuilder();

            try
            {
                File.WriteAllText(outputFile,
                                  "Sheet Number," +
                                  "Sheet Name," +
                                  "Sheet Revision," +
                                  "Cloud Id," +
                                  "Is Hidden," +
                                  "Current Revision," +
                                  "Error" + Environment.NewLine
                                  );
            }
            catch
            {
                TaskDialog.Show("Error", "Opertion cancelled. Please close the log file.");
                return(Result.Failed);
            }

            int hiddenClouds     = 0;
            int changedClouds    = 0;
            int cloudsNotOnSheet = 0;
            int errors           = 0;

            using (Transaction t = new Transaction(doc, "Reset revision cloud color"))
            {
                t.Start();

                foreach (ElementId revId in fec)
                {
                    Element rev             = doc.GetElement(revId);
                    View    v               = doc.GetElement(rev.OwnerViewId) as View;
                    string  fixedName       = v.Name.Replace(',', '-');
                    string  currentRevision = "N/A";
                    string  sheetNumber     = "N/A";

                    if (rev.IsHidden(v))
                    {
                        hiddenClouds += 1;
                    }

                    try
                    {
                        if (v is ViewSheet)
                        {
                            ViewSheet sheetView = doc.GetElement(rev.OwnerViewId) as ViewSheet;
                            sheetNumber = sheetView.SheetNumber;


                            Parameter sheetRevision = sheetView.get_Parameter("TB_Revision");
                            Parameter p             = rev.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);

                            if (!rev.IsHidden(v))
                            {
                                Parameter revision = rev.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);

                                Parameter version = rev.get_Parameter(BuiltInParameter.DOOR_NUMBER);

                                if (revision != null)
                                {
                                    currentRevision = revision.AsString();
                                }

                                if (currentRevision != null)
                                {
                                    int last = Int32.Parse(sheetRevision.AsString()); //sheet revision, not cloud revision
                                    revision.Set("00" + last.ToString());
                                    version.Set("01");
                                }
                                changedClouds += 1;
                                sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}",
                                                            sheetNumber,
                                                            fixedName,
                                                            sheetRevision.AsString(),
                                                            rev.Id,
                                                            rev.IsHidden(v),
                                                            rev.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString(),
                                                            "No"
                                                            ));
                            }
                        }
                        else
                        {
                            cloudsNotOnSheet += 1;
                            sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}",
                                                        sheetNumber,
                                                        fixedName,
                                                        "N/A",
                                                        rev.Id,
                                                        rev.IsHidden(v),
                                                        currentRevision,
                                                        "N/A"
                                                        ));
                        }
                    }
                    catch (Exception ex)
                    {
                        errors += 1;
                        string str = ex.Message;
                        str = str.Replace("\n", String.Empty);
                        str = str.Replace("\r", String.Empty);
                        str = str.Replace("\t", String.Empty);

                        sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}",
                                                    sheetNumber,
                                                    fixedName,
                                                    "N/A",
                                                    rev.Id,
                                                    rev.IsHidden(v),
                                                    currentRevision,
                                                    str
                                                    ));
                    }
                }

                t.Commit();
            }

            File.AppendAllText(outputFile, sb.ToString());



            TaskDialog myDialog = new TaskDialog("Summary");

            myDialog.MainIcon = TaskDialogIcon.TaskDialogIconNone;
            //myDialog.MainContent = String.Format("Rev Clouds: {0} \nClouds not on sheets: {1}\nClouds hidden (not uprev): {2} \nErrors: {3}", fec.Count, cloudsNotOnSheet, hiddenClouds, errors);
            myDialog.MainContent = String.Format("Rev Clouds updated: {0}", fec.Count);

            myDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink4, $"Open Log File {outputFile}", "");

            TaskDialogResult res = myDialog.Show();

            if (TaskDialogResult.CommandLink4 == res)

            {
                System.Diagnostics.Process process =

                    new System.Diagnostics.Process();

                process.StartInfo.FileName = outputFile;

                process.Start();
            }

            return(Result.Succeeded);
        }
Exemple #30
0
 private void button1_Click(object sender, EventArgs e)
 {
     System.Diagnostics.Process process = new System.Diagnostics.Process();
     if (checkBox1.Checked == true)
     {
         process.StartInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
         process.StartInfo.FileName        = "cmd.exe";
         process.StartInfo.UseShellExecute = true;
         process.StartInfo.Verb            = "runas";
         process.StartInfo.Arguments       = "/C choco install firefox -y";
         try
         {
             process.Start();
         }
         catch (Exception)
         {
             Console.WriteLine("USER CANCLED ERROR");
         }
     }
     if (checkBox2.Checked == true)
     {
         process.StartInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
         process.StartInfo.FileName        = "cmd.exe";
         process.StartInfo.UseShellExecute = true;
         process.StartInfo.Verb            = "runas";
         process.StartInfo.Arguments       = "/C start C:\\Users\\%USERNAME%\\Desktop\\PAT\\Backups\\Download2.bat";
         try
         {
             process.Start();
         }
         catch (Exception)
         {
             Console.WriteLine("USER CANCLED ERROR");
         }
     }
     if (checkBox3.Checked == true)
     {
         process.StartInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
         process.StartInfo.FileName        = "cmd.exe";
         process.StartInfo.UseShellExecute = true;
         process.StartInfo.Verb            = "runas";
         process.StartInfo.Arguments       = "/C start C:\\Users\\%USERNAME%\\Desktop\\PAT\\Backups\\Download3.bat";
         try
         {
             process.Start();
         }
         catch (Exception)
         {
             Console.WriteLine("USER CANCLED ERROR");
         }
     }
     if (checkBox4.Checked == true)
     {
         process.StartInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
         process.StartInfo.FileName        = "cmd.exe";
         process.StartInfo.UseShellExecute = true;
         process.StartInfo.Verb            = "runas";
         process.StartInfo.Arguments       = "/C start C:\\Users\\%USERNAME%\\Desktop\\PAT\\Backups\\Download4.bat";
         try
         {
             process.Start();
         }
         catch (Exception)
         {
             Console.WriteLine("USER CANCLED ERROR");
         }
     }
 }
Exemple #31
0
        public void Init()
        {
            var fuctory = new ModelFuctory();

            //プロクシ処理用クラス初期化
            try
            {
                DatProxy = new DatProxy(Appkey, HMkey, UserAgent1, UserAgent0, UserAgent2, RouninID, RouninPW, ProxyAddress)
                {
                    APIMediator   = fuctory.CreateAPIMediator(),
                    HtmlConverter = fuctory.CreateHtmlConverter()
                };
            }
            catch (System.IO.FileLoadException)
            {
                using (TaskTrayIcon)
                {
                    System.Windows.MessageBox.Show("FiddlerCore4.dllのバージョンが違うか必要なdllが無いようです。zipファイルに同梱のすべてのdllを上書きコピーしてください。", "dll読み込みエラー");
                    Microsoft.Win32.SystemEvents.PowerModeChanged -= new Microsoft.Win32.PowerModeChangedEventHandler(PowermodeChanged);
                    System.Windows.Application.Current.Shutdown();
                    return;
                }
            }
            //書き込みヘッダ定義ファイルの読み込み
            Dictionary <String, String> header = new Dictionary <string, string>();

            if (File.Exists("./WriteRequestHeader.txt"))
            {
                using (StreamReader sr = new StreamReader("./WriteRequestHeader.txt", System.Text.Encoding.UTF8))
                {
                    while (sr.EndOfStream == false)
                    {
                        try
                        {
                            string line = sr.ReadLine();
                            if (line.IndexOf("//") == 0 || string.IsNullOrEmpty(line) == true)
                            {
                                continue;
                            }
                            var pair = line.Split(':');
                            if (pair.Length == 0)
                            {
                                continue;
                            }
                            if (pair.Length == 1)
                            {
                                header.Add(pair[0], "");
                            }
                            else
                            {
                                header.Add(pair[0], pair[1]);
                            }
                        }
                        catch (Exception err)
                        {
                            System.Diagnostics.Debug.WriteLine("●ヘッダ定義の読み込み中のエラー\n" + err.ToString());
                        }
                    }
                }
            }
            DatProxy.WriteHeader = header;
            if (header.Count == 0)
            {
                this.SystemLog = "書き込み時には内部定義ヘッダを使用します";
            }
            else
            {
                this.SystemLog = "書き込み時には外部定義ヘッダを使用します";
            }

            //外部コードのコンパイル
            if (CEExternalRead)
            {
                CEResultView = DatProxy.HtmlConverter.Compile(CESrcfilePath);
            }

            //設定の適用、プロクシクラス
            DatProxy.AllowWANAccese  = WANAccess;
            DatProxy.user            = WANID;
            DatProxy.pw              = WANPW;
            DatProxy.WriteUA         = UserAgent3;
            DatProxy.GetHTML         = KakotoHTML;
            DatProxy.OfflawRokkaPerm = OfflawRokkaPermutation;
            DatProxy.CangeUARetry    = ChangeUARetry;
            DatProxy.SocksPoxy       = Socks4aProxy;
            DatProxy.gZipRes         = gZipResponse;
            DatProxy.ChunkRes        = ChunkedResponse;
            DatProxy.OnlyORPerm      = OnlyORPerm;
            DatProxy.CRReplace       = CRReplace;
            DatProxy.KakolinkPerm    = KakolinkPermutation;
            DatProxy.AllUAReplace    = (UserAgent3 == "") ? (false) : (AllUAReplace);
            DatProxy.BeLogin         = BeLogin;

            //設定の適用、APIアクセスクラス
            DatProxy.APIMediator.AppKey       = this.Appkey;
            DatProxy.APIMediator.HMKey        = this.HMkey;
            DatProxy.APIMediator.SidUA        = this.UserAgent0;
            DatProxy.APIMediator.X2chUA       = this.UserAgent1;
            DatProxy.APIMediator.DatUA        = this.UserAgent2;
            DatProxy.APIMediator.RouninID     = this.RouninID;
            DatProxy.APIMediator.RouninPW     = this.RouninPW;
            DatProxy.APIMediator.ProxyAddress = this.ProxyAddress;
            DatProxy.UpdateAsync();

            //設定の適用、html変換クラス
            DatProxy.HtmlConverter.UserAgent              = _UserAgent4;
            DatProxy.HtmlConverter.ProxyAddress           = _ProxyAddress;
            DatProxy.HtmlConverter.IsDifferenceDetect     = !_AllReturn;
            DatProxy.HtmlConverter.IsAliveCheckSkip       = _SkipAliveCheck;
            DatProxy.HtmlConverter.Is5chURIReplace        = _Replace5chURI;
            DatProxy.HtmlConverter.IsHttpsReplace         = _ReplaceHttpsLink;
            DatProxy.HtmlConverter.IsExternalConverterUse = _CEExternalRead;

            //エラー通知用コールバック登録
            DatProxy.APIMediator.PropertyChanged += (sender, e) =>
            {
                if (e.PropertyName == nameof(DatProxy.APIMediator.CurrentError))
                {
                    //ここで取得しておく
                    string error = DatProxy.APIMediator.CurrentError;

                    App.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        this.SystemLog = error;
                    }));
                }
            };

            DatProxy.HtmlConverter.PropertyChanged += (sender, e) =>
            {
                if (e.PropertyName == nameof(DatProxy.HtmlConverter.CurrentError))
                {
                    //ここで取得しておく
                    string error = DatProxy.HtmlConverter.CurrentError;

                    App.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        this.SystemLog = error;
                    }));
                }
            };

            //自動開始処理
            if (Setting.AutoStart)
            {
                int pnum = (Setting.AutoSelect) ? (0) : (Setting.PortNumber);
                pnum = DatProxy.Start(pnum);
                if (pnum != 0)
                {
                    SystemLog  = "開始、ポート番号:" + pnum;
                    NowStart   = true;
                    PortNumber = pnum;
                }
                else
                {
                    SystemLog = "既に使用中のポートみたいです、別のポートを指定して下さい。";
                    DatProxy.End();
                }
            }
            //同時起動と終了を設定
            if (!String.IsNullOrEmpty(Setting.SenburaPath))
            {
                bool kage = true;
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = Setting.SenburaPath;
                if (System.IO.Path.GetFileName(Setting.SenburaPath) != "kage.exe")
                {
                    kage = false;
                    p.EnableRaisingEvents = true;
                    p.Exited += (sender, e) =>
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() => { if (Setting.SyncEnd)
                                                                            {
                                                                                BeforeShutdown();
                                                                            }
                                                                    }), null);
                    };
                }
                try
                {
                    p.Start();
                    m_SenburaPID = p.Id;
                    SystemLog    = Setting.SenburaPath + " を起動";
                    m_SyncStart  = true;
                    //かちゅ~しゃの場合の終了同期処理の追加
                    if (kage)
                    {
                        System.Diagnostics.Process[] plist = null;
                        for (int i = 0; i < 50; ++i)
                        {
                            plist = System.Diagnostics.Process.GetProcessesByName("Katjusha");
                            if (plist.Length != 0)
                            {
                                break;
                            }
                            System.Threading.Thread.Sleep(100);
                        }
                        plist[0].EnableRaisingEvents = true;
                        plist[0].Exited += (sender, e) =>
                        {
                            App.Current.Dispatcher.BeginInvoke((Action)(() => { if (Setting.SyncEnd)
                                                                                {
                                                                                    BeforeShutdown();
                                                                                }
                                                                        }), null);
                        };
                        m_SenburaPID = plist[0].Id;
                    }
                }
                catch (Exception err)
                {
                    SystemLog = Setting.SenburaPath + " の起動に失敗\n" + err.ToString();
                }
            }
            Setting.change = false;
            //プロセス間通信のサーバ登録
            try
            {
                IpcServerChannel server = new IpcServerChannel("2chApiProxyIPC");
                ChannelServices.RegisterChannel(server, true);
                RemoteObject         = new SendObject();
                SendObject.OnTrance += new SendObject.CallEventHandler((e) =>
                {
                    if (RemoteObject.first)
                    {
                        RemoteObject.first = false;
                        App.Current.Dispatcher.BeginInvoke((Action)(() => { if (e)
                                                                            {
                                                                                ActivateWindow();
                                                                            }
                                                                    }));
                    }
                    else
                    {
                        RemoteObject.first = true;
                    }
                });
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(SendObject), "ShowWindow", WellKnownObjectMode.Singleton);
            }
            catch (Exception) { }
            SystemLog = "2chAPIProxy起動";
        }
Exemple #32
0
        /// <summary>
        /// Method for sending an email message with an attachment.
        /// </summary>
        /// <param name="sender">Originator email address.</param>
        /// <param name="recipient">Recipient email address.</param>
        /// <param name="subject">Subject of the email message.</param>
        /// <param name="message">Email message body.</param>
        /// <param name="attachment">Attachment file name.</param>
        public void Send(string sender, string recipient, string subject,
                         string message, string attachment)
        {
            using (var mail = new System.Diagnostics.Process())
            {
                // Validate parameters

                if (sender.IndexOf("\"") != -1)
                {
                    throw new Exception(" sender argument contains a double quote character.");
                }

                if ((sender.Length > 0) && (sender.Length < 6))
                {
                    throw new Exception("sender argument is too short.");
                }

                if (recipient.IndexOf("\"") != -1)
                {
                    throw new Exception("recipient argument contains a double quote character.");
                }

                if (recipient.Length < 6)
                {
                    throw new Exception("recipient argument is too short.");
                }

                if (subject.IndexOf("\"") != -1)
                {
                    throw new Exception("subject argument contains a double quote character.");
                }

                if (attachment.IndexOf("\"") != -1)
                {
                    throw new Exception("attachment argument contains a double quote character.");
                }

                if ((attachment.Length > 0) && !System.IO.File.Exists(attachment))
                {
                    throw new Exception("attachment file cannot be read.");
                }

                // Assemble command line arguments

                string args = "";
                if (sender != "")
                {
                    args += "-r " + Quote(sender) + " ";
                }
                if (subject != "")
                {
                    args += "-s " + Quote(subject) + " ";
                }
                if (attachment != "")
                {
                    args += "-A " + Quote(attachment) + " ";
                }
                args += recipient;

                // Set the rest of the process start settings

                mail.StartInfo.FileName               = "/usr/bin/mail";
                mail.StartInfo.Arguments              = args;
                mail.StartInfo.CreateNoWindow         = true;
                mail.StartInfo.UseShellExecute        = false;
                mail.StartInfo.RedirectStandardInput  = true;
                mail.StartInfo.RedirectStandardOutput = false;
                mail.StartInfo.RedirectStandardError  = false;

                // Dispatch the message

                mail.Start();
                mail.StandardInput.WriteLine(message);
                mail.StandardInput.Close();
                mail.WaitForExit(5000);
            }
        }
Exemple #33
0
        public static bool ReceiveTransmission(Windows.MainWindow window, IntPtr remoteWindow, System.Diagnostics.Process remoteProcess, Windows.COPYDATASTRUCT cds)
        {
            Session session = Sessions.FirstOrDefault(q => q.RemoteWindow == remoteWindow && q.Process.Id == remoteProcess.Id);

            if (session == null)
            {
                session = new Session(remoteWindow, remoteProcess);
                Sessions.Add(session);
            }

            switch ((long)cds.dwData)
            {
            case 10:
                if (!App.Settings.HasPasswordMasterKey)
                {
                    return(false);
                }
                session.ReceivePublicKeyTransmission(cds);
                session.TransmitPublicKey(window, false);
                session.TransmitEncryptedMasterKey(window);
                return(true);

            case 11:
                session.ReceiveEncryptedMasterKeyTransmission(cds);
                return(true);

            case 12:
                session.ReceivePublicKeyTransmission(cds);
                return(true);
            }

            return(false);
        }
Exemple #34
0
        /// <summary>
        /// Request Master Key from Master Instance
        /// </summary>
        /// <param name="window"></param>
        /// <param name="remoteWindow"></param>
        /// <param name="remoteProcess"></param>
        public static void RequestMasterKey(Windows.MainWindow window, IntPtr remoteWindow, System.Diagnostics.Process remoteProcess)
        {
            Session session = Sessions.FirstOrDefault(q => q.RemoteWindow == remoteWindow && q.Process.Id == remoteProcess.Id);

            if (session == null)
            {
                session = new Session(remoteWindow, remoteProcess);
                Sessions.Add(session);
            }

            session.TransmitPublicKey(window, true);
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                //Get Template document and database path.
                string         dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\common\Data\DocIO\";
                WordDocument   document;
                ProtectionType protectionType;

                //Loads the template document.
                if (comboBox1.SelectedIndex == 0)
                {
                    document = new WordDocument(Path.Combine(dataPath, @"TemplateFormFields.doc"));
                    // Sets the protection type as allow only Form Fields.
                    protectionType = ProtectionType.AllowOnlyFormFields;
                }
                else if (comboBox1.SelectedIndex == 1)
                {
                    document = new WordDocument(Path.Combine(dataPath, @"TemplateComments.doc"));
                    // Sets the protection type as allow only Comments.
                    protectionType = ProtectionType.AllowOnlyComments;
                }
                else if (comboBox1.SelectedIndex == 2)
                {
                    document = new WordDocument(Path.Combine(dataPath, @"TemplateRevisions.doc"));
                    // Enables track changes in the document.
                    document.TrackChanges = true;
                    // Sets the protection type as allow only Revisions.
                    protectionType = ProtectionType.AllowOnlyRevisions;
                }
                else
                {
                    document = new WordDocument(Path.Combine(dataPath, @"Essential DocIO.doc"));
                    // Sets the protection type as allow only Reading.
                    protectionType = ProtectionType.AllowOnlyReading;
                }

                // Enforces protection of the document.
                if (string.IsNullOrEmpty(textBox1.Text))
                {
                    document.Protect(protectionType);
                }
                else
                {
                    document.Protect(protectionType, textBox1.Text);
                }

                //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());
                        }
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Exemple #36
0
        public static string generateTestGridString(string fileName)
        {
            string restr = null;
            var    t1    = cTi("A");
            var    t2    = cTi("B");
            var    t3    = cTi("Z");
            var    t4    = cTi("AA");
            var    t5    = cTi("AZ");
            var    t6    = cTi("ZZ");
            var    t7    = cTi("AAA");
            var    t8    = cTi("ZZZ");

            string targetFile = fileName;

            //string targetFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), @"20180605検査員の作業範囲.xlsx");

            Excel.Application xlApp = new Excel.Application();

            var workbook = xlApp.Workbooks.Open(targetFile, ReadOnly: true);

            foreach (Excel.Worksheet sheet in workbook.Worksheets)
            {
                var range = sheet.UsedRange;
                int col   = range.Columns.Count;
                int row   = range.Rows.Count;

                if (sheet.Name == "print")
                {
                    Border[,] rawborder = new Border[row + 1, col + 1];

                    if (col >= 1 && row >= 1)
                    {
                        for (int i = 1; i <= row + 1; i++)
                        {
                            for (int j = 1; j <= col + 1; j++)
                            {
                                var rg = sheet.Cells[i, j] as Excel.Range;
                                readBorderInfo(rg, i, j, rawborder);
                            }
                        }
                    }

                    Dictionary <Tuple <int, int>, List <Border> > res = new Dictionary <Tuple <int, int>, List <Border> >();

                    for (int i = 0; i < rawborder.GetLength(0); i++)
                    {
                        for (int j = 0; j < rawborder.GetLength(1); j++)
                        {
                            //Console.Write(rawborder[i, j].ToString() + " ");

                            findMap(i, j, rawborder, res);
                        }
                        //Console.WriteLine();
                    }

                    if (res.Count > 0)
                    {
                        var filter1 = res.Values.Where(r => r.Count >= 5 && r[0].Equals(r[r.Count - 1]));

                        if (filter1.Count() > 0)
                        {
                            var max    = filter1.Select(r => r.Count).Max();
                            var target = filter1.FirstOrDefault(r => r.Count == max);

                            var leftmost   = target.Select(r => r.Y).Min();
                            var rightmost  = target.Select(r => r.Y).Max();
                            var topmost    = target.Select(r => r.X).Min();
                            var bottommost = target.Select(r => r.X).Max();

                            string defaultGrid = createDefaultGrid(leftmost, topmost, rightmost, bottommost);

                            string defaultGridWithMergedSupported = createDefaultGridSupportingMerged(leftmost, topmost, rightmost, bottommost, rawborder);

                            restr = defaultGridWithMergedSupported;
                            //Console.WriteLine(String.Join(" ", target.Select(r => r.Position())));

                            //Console.WriteLine(leftmost + " " + rightmost + " " + topmost + " " + bottommost);
                            //Console.WriteLine(defaultGridWithMergedSupported);
                        }
                    }
                }
            }

            xlApp.Quit();

            if (xlApp != null)
            {
                int excelProcessId = -1;
                GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out excelProcessId);

                System.Diagnostics.Process ExcelProc = System.Diagnostics.Process.GetProcessById(excelProcessId);
                if (ExcelProc != null)
                {
                    ExcelProc.Kill();
                }
            }

            //Console.ReadKey();
            return(restr);
        }
 /// <summary>
 /// Constructor.  Creates Named Pipe based on process object.
 /// </summary>
 /// <param name="process">Target process object for pipe.</param>
 /// <param name="appDomainName">AppDomain name or null for default AppDomain</param>
 public RemoteSessionNamedPipeClient(
     System.Diagnostics.Process process, string appDomainName) :
     this(NamedPipeUtils.CreateProcessPipeName(process, appDomainName))
 {
 }
 /// <summary>
 /// Create a pipe name based on process information.
 /// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
 /// </summary>
 /// <param name="proc">Process object</param>
 /// <returns>Pipe name</returns>
 internal static string CreateProcessPipeName(
     System.Diagnostics.Process proc)
 {
     return(CreateProcessPipeName(proc, DefaultAppDomainName));
 }
        public override object Process(XapProjectFile input, ContentProcessorContext context)
        {
            var location = Path.GetFullPath(GetType().Assembly.Location);

            if (string.IsNullOrEmpty(WineInstall))
            {
                WineInstall = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".wine");
            }
            // execute the XActBld3.exe.
            var isWindows    = Environment.OSVersion.Platform != PlatformID.Unix;
            var programFiles = isWindows ? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) :
                               Path.Combine(WineInstall, "drive_c", "Program Files (x86)");
            var xnaPath      = Path.Combine(programFiles, "Microsoft XNA", "XNA Game Studio", "v4.0");
            var XactBld3Tool = Path.Combine("Tools", "XactBld3.exe");
            var toolPath     = Path.Combine(xnaPath, XactBld3Tool);

            if (!isWindows)
            {
                // extract wine and install XNA
                if (!File.Exists(toolPath))
                {
                    throw new InvalidProgramException($"Could not locate {XactBld3Tool}. You need to install Wine and XNA Tooling. See https://github.com/infinitespace-studios/InfinitespaceStudios.Pipeline/wiki for more details.");
                }
            }

            if (isWindows && !File.Exists(toolPath))
            {
                toolPath = Path.Combine(Environment.GetEnvironmentVariable("XNAGSv4"), XactBld3Tool);
                if (!File.Exists(toolPath))
                {
                    toolPath = Path.Combine(location, XactBld3Tool);
                    if (!File.Exists(toolPath))
                    {
                        throw new InvalidProgramException($"Could not locate {XactBld3Tool}");
                    }
                }
            }

            var outputPath = Path.GetDirectoryName(context.OutputFilename);

            Directory.CreateDirectory(outputPath);
            var inputPath = input.FileName;

            if (!isWindows)
            {
                outputPath = "Z:" + outputPath.Replace("/", "\\");
                if (outputPath.EndsWith("\\"))
                {
                    outputPath = outputPath.Substring(0, outputPath.Length - 1);
                }
                inputPath = "Z:" + inputPath.Replace("/", "\\");
            }

            var stdout_completed = new ManualResetEvent(false);
            var stderr_completed = new ManualResetEvent(false);
            var psi = new System.Diagnostics.ProcessStartInfo()
            {
                FileName               = isWindows ? toolPath : WineExe,
                Arguments              = (!isWindows ? $"\"{toolPath}\" " : String.Empty) + $"/WINDOWS \"{inputPath}\" \"{outputPath}\"",
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
                WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden,
            };

            context.Logger.LogImportantMessage($"Running: {psi.FileName} {psi.Arguments}");

            using (var proc = new System.Diagnostics.Process())
            {
                proc.OutputDataReceived += (o, e) =>
                {
                    if (e.Data == null)
                    {
                        stdout_completed.Set();
                        return;
                    }
                    //context.Logger.LogImportantMessage($"{e.Data}");
                };
                proc.ErrorDataReceived += (o, e) =>
                {
                    if (e.Data == null)
                    {
                        stderr_completed.Set();
                        return;
                    }
                    //context.Logger.LogImportantMessage($"{e.Data}");
                };
                proc.StartInfo = psi;
                proc.Start();
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();
                if (psi.RedirectStandardError)
                {
                    stderr_completed.WaitOne(TimeSpan.FromSeconds(30));
                }
                if (psi.RedirectStandardOutput)
                {
                    stdout_completed.WaitOne(TimeSpan.FromSeconds(30));
                }
                if (proc.ExitCode != 0)
                {
                    throw new InvalidContentException();
                }
                foreach (var file in Directory.GetFiles(Path.GetDirectoryName(context.OutputFilename), "*.xgs", SearchOption.TopDirectoryOnly))
                {
                    context.AddOutputFile(file);
                }
                foreach (var file in Directory.GetFiles(Path.GetDirectoryName(context.OutputFilename), "*.xsb", SearchOption.TopDirectoryOnly))
                {
                    context.AddOutputFile(file);
                }
                foreach (var file in Directory.GetFiles(Path.GetDirectoryName(context.OutputFilename), "*.xwb", SearchOption.TopDirectoryOnly))
                {
                    context.AddOutputFile(file);
                }
            }
            return(null);
        }
        /// <summary>
        /// Copy the selected db to C:\EnablerdB, check backup and restore the db then adding user role
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRestore_Click(object sender, EventArgs e)
        {
            string filePath = string.Empty;

            // open a dialog for selecting the database
            using (var files = new OpenFileDialog())
            {
                files.Filter           = "Enabler Database File |*.*|*.dmp";
                files.Title            = "Select a Enabler Database";
                files.InitialDirectory = this.targetFolder;
                DialogResult result = files.ShowDialog();

                if (result == DialogResult.OK)
                {
                    filePath = files.FileName;
                }
            }

            // copy the database and add the rename mapping into a text file
            if (File.Exists(filePath))
            {
                // Copy to EnablerDB folder with adding Date and time as suffix
                string fileNewName = string.Format("{0}_EnablerDB_{1}.dmp", FileOperator.CaseNumber, DateTime.Now.Ticks);

                string JIRAMappingPath = Path.Combine(LocalFilePath.EnablerDBPath, LocalFilePath.JIRAMappingFileName);
                if (!File.Exists(JIRAMappingPath))
                {
                    File.Create(JIRAMappingPath).Close();
                }

                // move other db files into DB Backup folder with replacement
                string[] dmpFiles = Directory.GetFiles(LocalFilePath.EnablerDBPath, "*.dmp");
                if (dmpFiles.Length > 0)
                {
                    //move them to DB backup folder
                    foreach (string fileName in dmpFiles)
                    {
                        string tempFileName = Path.Combine(Path.Combine(LocalFilePath.EnablerDBPath, "DB backup"), Path.GetFileName(fileName));

                        if (File.Exists(tempFileName))
                        {
                            // TODO: check the target folder, if the file is the same and already in the target folder, delete it from the source path
                            continue;
                        }

                        try
                        {
                            File.Move(fileName, tempFileName);
                            UpdateActivityMessage(string.Format("Moved {0} to db backup folder", fileName));
                        }
                        catch (Exception ex)
                        {
                            UpdateActivityMessage(string.Format("Unable to moved {0} to db backup folder: {1}", fileName, ex.Message));
                        }
                    }
                }

                Task copyToPath = CopyTask(filePath, Path.Combine(LocalFilePath.EnablerDBPath, fileNewName));

                copyToPath.ContinueWith((task) =>
                {
                    UpdateActivityMessage("Copying...");
                    if (task.IsCompleted && !task.IsFaulted && !task.IsCanceled)
                    {
                        UpdateActivityMessage(String.Format("DB file {0} copied to Enablerdb folder", filePath));

                        #region Pending Section

                        // open and add the mapping entry
                        using (StreamWriter writer = new StreamWriter(JIRAMappingPath, true))
                        {
                            writer.WriteLine(string.Format("Ori File: {0} - New File: {1}", filePath, fileNewName));
                        }

                        // TODO: The batch is not running as expected, need to check why.
                        // restore the database
                        using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                        {
                            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                            //process.StartInfo = new System.Diagnostics.ProcessStartInfo()
                            //process.StartInfo.WorkingDirectory = @"C:\Enabler";
                            process.StartInfo.FileName = @"C:\\Enabler\\EnablerRestore.bat";
                            //process.StartInfo.Arguments = string.Format("{0}", "C:\\Enabler\\EnablerRestore.bat");
                            //process.StartInfo.FileName = "C:\\Enabler\\EnablerRestore.bat";
                            process.StartInfo.Arguments              = fileNewName;
                            process.StartInfo.RedirectStandardInput  = false;
                            process.StartInfo.RedirectStandardOutput = false;
                            process.StartInfo.UseShellExecute        = false;
                            process.Start();
                            process.WaitForExit();

                            UpdateActivityMessage("Enabler Database restored");
                        }

                        // System.Diagnostics.Process.Start("C:\\Enabler\\EnablerRestore.bat");

                        // insert user role
                        using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection())
                        {
                            conn.ConnectionString = @"Data Source=.;Database=EnablerDB;Trusted_Connection=True;";
                            conn.Open();
                            string commandText = @"UPDATE USERS set Login_Name='admin', Password='******', Role_ID = 1 where User_ID =1;";
                            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(commandText, conn))
                            {
                                command.ExecuteNonQuery();
                            }
                            UpdateActivityMessage("Admin role added into the restored database");
                        }

                        #endregion
                    }
                    else
                    {
                        UpdateActivityMessage("Copy failed");
                    }
                });
            }
        }
Exemple #41
0
 private static String describe(System.Diagnostics.Process process)
 {
     return(String.Format("{0}({1}), ID: {2} ", process.ProcessName, process.MainWindowTitle, process.Id));
 }
Exemple #42
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 #43
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        private static async Task Main(string[] args)
        {
            var url = "http://localhost:8787/";

            if (args.Length > 0)
            {
                url = args[0];
            }

            AppDbContext.InitDatabase();

            var ctSource = new CancellationTokenSource();

            ctSource.Token.Register(() => "Shutting down".Info());

            // Set a task waiting for press key to exit
#pragma warning disable 4014
            Task.Run(() =>
#pragma warning restore 4014
            {
                // Wait for any key to be pressed before disposing of our web server.
                Console.ReadLine();

                ctSource.Cancel();
            }, ctSource.Token);


            // Our web server is disposable.
            using (var server = new WebServer(url))
            {
                // First, we will configure our web server by adding Modules.
                // Please note that order DOES matter.
                // ================================================================================================
                // If we want to enable sessions, we simply register the LocalSessionModule
                // Beware that this is an in-memory session storage mechanism so, avoid storing very large objects.
                // You can use the server.GetSession() method to get the SessionInfo object and manupulate it.
                server.RegisterModule(new LocalSessionModule());

                // Set the CORS Rules
                server.RegisterModule(new CorsModule(
                                          // Origins, separated by comma without last slash
                                          "http://unosquare.github.io,http://run.plnkr.co",
                                          // Allowed headers
                                          "content-type, accept",
                                          // Allowed methods
                                          "post"));

                // Register the static files server. See the html folder of this project. Also notice that
                // the files under the html folder have Copy To Output Folder = Copy if Newer
                StaticFilesSample.Setup(server, useGzip: Runtime.IsUsingMonoRuntime == false);

                // Register the Web Api Module. See the Setup method to find out how to do it
                // It registers the WebApiModule and registers the controller(s) -- that's all.
                server.WithWebApiController <PeopleController>();

                // Register the WebSockets module. See the Setup method to find out how to do it
                // It registers the WebSocketsModule and registers the server for the given paths(s)
                WebSocketsSample.Setup(server);

                server.RegisterModule(new FallbackModule((ctx, ct) => ctx.JsonResponse(new { Message = "Error " })));

                // Fire up the browser to show the content!
                var browser = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo(url.Replace("*", "localhost"))
                    {
                        UseShellExecute = true
                    }
                };

                browser.Start();

                // Once we've registered our modules and configured them, we call the RunAsync() method.
                if (!ctSource.IsCancellationRequested)
                {
                    await server.RunAsync(ctSource.Token);
                }

                "Bye".Info();
            }
        }
        private void setupPortForwarding(int port)
        {
#if !UNITY_WEBPLAYER
            string adbCommand = string.Format("adb forward tcp:{0} tcp:{0}", port);
            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
            string processFilename;
            string processArguments;
            int    kExitCodeCommandNotFound;

            if (Application.platform == RuntimePlatform.WindowsEditor ||
                Application.platform == RuntimePlatform.WindowsPlayer)
            {
                processFilename  = "CMD.exe";
                processArguments = @"/k " + adbCommand + " & exit";
                // See "Common Error Lookup Tool" (https://www.microsoft.com/en-us/download/details.aspx?id=985)
                // MSG_DIR_BAD_COMMAND_OR_FILE (cmdmsg.h)
                kExitCodeCommandNotFound = 9009; // 0x2331
            }
            else // Unix
            {
                processFilename  = "bash";
                processArguments = string.Format("-l -c \"{0}\"", adbCommand);
                // "command not found" (see http://tldp.org/LDP/abs/html/exitcodes.html)
                kExitCodeCommandNotFound = 127;
            }

            System.Diagnostics.ProcessStartInfo myProcessStartInfo =
                new System.Diagnostics.ProcessStartInfo(processFilename, processArguments);
            myProcessStartInfo.UseShellExecute       = false;
            myProcessStartInfo.RedirectStandardError = true;
            myProcessStartInfo.CreateNoWindow        = true;
            myProcess.StartInfo = myProcessStartInfo;
            myProcess.Start();
            myProcess.WaitForExit();
            // Also wait for HasExited here, to avoid ExitCode access below occasionally throwing InvalidOperationException
            while (!myProcess.HasExited)
            {
                Thread.Sleep(1);
            }
            int    exitCode      = myProcess.ExitCode;
            string standardError = myProcess.StandardError.ReadToEnd();
            myProcess.Close();

            if (exitCode == 0)
            {
                // Port forwarding setup successfully.
                return;
            }

            if (exitCode == kExitCodeCommandNotFound)
            {
                // Caught by phoneEventSocketLoop.
                throw new Exception(
                          "Android Debug Bridge (`adb`) command not found." +
                          "\nVerify that the Android SDK is installed and that the directory containing" +
                          " `adb` is included in your PATH environment variable.");
            }
            // Caught by phoneEventSocketLoop.
            throw new Exception(
                      string.Format(
                          "Failed to setup port forwarding." +
                          " Exit code {0} returned by process: {1} {2}\n{3}",
                          exitCode, processFilename, processArguments, standardError));
#endif  // !UNITY_WEBPLAYER
        }
 public static bool Peek(System.Diagnostics.Process proc, int target, byte[] data)
 {
     return(ReadProcessMemory(proc.Handle, new IntPtr(target), data, new UIntPtr((uint)data.Length), new IntPtr(0)));
 }
Exemple #46
0
        private string ProcessInfo()
        {
            System.Diagnostics.Process oProc = System.Diagnostics.Process.GetCurrentProcess();

            StringBuilder oSB = new StringBuilder();

            oSB.AppendLine("Process Information: ");
            oSB.AppendLine("  MachineName: " + oProc.MachineName);
            oSB.AppendLine("  ProcessName: " + oProc.ProcessName);
            oSB.AppendLine("  ID: " + oProc.Id.ToString());
            oSB.AppendLine("  StartTime: " + oProc.StartTime.ToString());
            oSB.AppendLine("  TotalProcessorTime: " + oProc.TotalProcessorTime.ToString());
            oSB.AppendLine("  UserProcessorTime: " + oProc.UserProcessorTime.ToString());
            //oSB.AppendLine("  VirtualMemorySize: " + oProc.VirtualMemorySize.ToString());
            oSB.AppendLine("  VirtualMemorySize64: " + oProc.VirtualMemorySize64.ToString());
            //oSB.AppendLine("  WorkingSet: " + oProc.WorkingSet.ToString());
            oSB.AppendLine("  WorkingSet64: " + oProc.WorkingSet64.ToString());
            oSB.AppendLine("  UserName: "******"  .NET version currently used: " + Environment.Version);
            oSB.AppendLine("  Is64BitOperatingSystem: " + Environment.Is64BitOperatingSystem);
            oSB.AppendLine("  Is64BitProcess: " + Environment.Is64BitProcess);
            oSB.AppendLine("  OSVersion: " + Environment.OSVersion.VersionString);
            oSB.AppendLine("  ProcessorCount: " + Environment.ProcessorCount.ToString());
            oSB.AppendLine("  WorkingSet (Memory mapped to this process context): " + Environment.WorkingSet.ToString());
            oSB.AppendLine("  SystemPageSize: " + Environment.SystemPageSize);
            oSB.AppendLine("  SystemDirectory: " + Environment.SystemDirectory);
            oSB.AppendLine("  CurrentDirectory: " + Environment.CurrentDirectory);
            oSB.AppendLine("  CommandLine: " + Environment.CommandLine);
            oSB.AppendLine("  MainModule: ");
            oSB.AppendLine("    FileName: " + oProc.MainModule.FileName);
            oSB.AppendLine("    FileVersionInfo: ");
            oSB.AppendLine("      InternalName: " + oProc.MainModule.FileVersionInfo.InternalName);
            oSB.AppendLine("      OriginalFilename: " + oProc.MainModule.FileVersionInfo.OriginalFilename);
            oSB.AppendLine("      FileVersion: " + oProc.MainModule.FileVersionInfo.FileVersion);
            oSB.AppendLine("      FileDescription: " + oProc.MainModule.FileVersionInfo.FileDescription);
            oSB.AppendLine("      Product: " + oProc.MainModule.FileVersionInfo.ProductName);
            oSB.AppendLine("      ProductVersion: " + oProc.MainModule.FileVersionInfo.ProductVersion);
            oSB.AppendLine("      IsPatched: " + oProc.MainModule.FileVersionInfo.IsPatched.ToString());
            oSB.AppendLine("      InternalName: " + oProc.MainModule.FileVersionInfo.InternalName);
            oSB.AppendLine("      IsPreRelease: " + oProc.MainModule.FileVersionInfo.IsPreRelease.ToString());
            oSB.AppendLine("      PrivateBuild: " + oProc.MainModule.FileVersionInfo.PrivateBuild);
            oSB.AppendLine("      SpecialBuild: " + oProc.MainModule.FileVersionInfo.SpecialBuild);
            oSB.AppendLine("      Language: " + oProc.MainModule.FileVersionInfo.Language);
            oSB.AppendLine("    ModuleName: " + oProc.MainModule.ModuleName.ToString());
            oSB.AppendLine("    ModuleMemorySize: " + oProc.MainModule.ModuleMemorySize.ToString());
            if (oProc.MainModule.Site != null)
            {
                oSB.AppendLine("    Site:");
                oSB.AppendLine("      Name: " + oProc.MainModule.Site.Name);
            }
            oSB.AppendLine("  StartInfo: ");
            oSB.AppendLine("    Arguments: " + oProc.StartInfo.Arguments);
            oSB.AppendLine("    Domain: " + oProc.StartInfo.Domain);
            oSB.AppendLine("    FileName: " + oProc.StartInfo.FileName);
            oSB.AppendLine("    LoadUserProfile: " + oProc.StartInfo.LoadUserProfile.ToString());
            oSB.AppendLine("    UserName: "******"    Verb: " + oProc.StartInfo.Verb);
            oSB.AppendLine("    WorkingDirectory: " + oProc.StartInfo.WorkingDirectory);


            return(oSB.ToString());
        }
Exemple #47
0
 public static void openXmlFile(string fileName)
 {
     System.Diagnostics.Process openingTxtFile = new System.Diagnostics.Process();
     openingTxtFile.StartInfo.FileName = fileName;
     openingTxtFile.Start();
 }
        public static bool Poke(System.Diagnostics.Process proc, int target, byte[] data)
        {
            IntPtr bytesWritten = new IntPtr(0);

            return(WriteProcessMemory(proc.Handle, new IntPtr(target), data, new UIntPtr((uint)data.Length), out bytesWritten));
        }
Exemple #49
0
        static void JoinVideoSegments(DirectoryInfo segmentsFolder, FileInfo outputVideoFile)
        {
            if (segmentsFolder == null)
            {
                Console.WriteLine("The segments folder must be a folder path.");
                return;
            }

            if (outputVideoFile == null)
            {
                Console.WriteLine("The output video file must be a file path.");
                return;
            }

            try {
                if (!Directory.Exists(segmentsFolder.FullName))
                {
                    throw new Exception("Video segments folder must exist");
                }

                if (File.Exists(outputVideoFile.FullName))
                {
                    throw new Exception("Output video file must not exist.");
                }

                var files = Directory
                            .GetFiles(segmentsFolder.FullName, "*.mp4")
                            .Select(fileName => "file '" + Path.GetFileName(fileName) + "'")
                            .ToList();

                files.Sort();

                var listFileName = Path.Join(segmentsFolder.FullName, "list.txt");

                System.IO.File.WriteAllText(
                    listFileName,
                    String.Join(Environment.NewLine, files)
                    );

                var ffmpegArgs = new string[] {
                    "-f",
                    "concat",
                    "-i",
                    listFileName,
                    "-c",
                    "copy",
                    outputVideoFile.FullName,
                };

                using (var process = new System.Diagnostics.Process()) {
                    process.StartInfo.FileName  = Path.Join(Environment.CurrentDirectory, "ffmpeg");
                    process.StartInfo.Arguments = String.Join(" ", ffmpegArgs);
                    // process.StartInfo.RedirectStandardError = true;
                    // process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler((sender, e) => {
                    //  Log.Error(e.Data);
                    // });

                    process.Start();
                    process.WaitForExit();
                }
            } catch (Exception exc) {
                Log.Error(exc.Message);
                Console.WriteLine("Error while trying to join video segments into a single video. Please review the logs.");
            }
        }
Exemple #50
0
        /// <summary>
        /// Run specified EXE with given arguments
        /// </summary>
        private void RunProcess(string exeFilename, string[] args, string workingDir,
                                TextWriter standardOutputWriter = null, TextWriter standardErrorWriter = null)
        {
            var p = new System.Diagnostics.Process
            {
                StartInfo =
                {
                    UseShellExecute = false,
                    CreateNoWindow  = true,
                    FileName        = exeFilename,
                    Arguments       = (args == null ? "" : string.Join(" ", args)),
                }
            };

            if (workingDir != null)
            {
                p.StartInfo.WorkingDirectory = workingDir;
            }

            if (standardOutputWriter != null)
            {
                p.StartInfo.RedirectStandardOutput = true;
                p.OutputDataReceived += (s, a) => { if (a.Data != null)
                                                    {
                                                        standardOutputWriter.WriteLine(a.Data);
                                                    }
                };
            }

            if (standardErrorWriter != null)
            {
                p.StartInfo.RedirectStandardError = true;
                p.ErrorDataReceived += (s, a) => { if (a.Data != null)
                                                   {
                                                       standardErrorWriter.WriteLine(a.Data);
                                                   }
                };
            }

            p.Start();
            //p.EnableRaisingEvents = true; // REVIEW: Why would you claim you wanted to
            // use the async exit handler, only to just use WaitForExit downstream?
            if (standardOutputWriter != null)
            {
                p.BeginOutputReadLine();
            }
            if (standardErrorWriter != null)
            {
                p.BeginErrorReadLine();
            }
            p.WaitForExit();

            if (standardOutputWriter != null)
            {
                standardOutputWriter.Flush();
                standardOutputWriter.Close();
            }

            if (standardErrorWriter != null)
            {
                standardErrorWriter.Flush();
                standardErrorWriter.Close();
            }
        }
Exemple #51
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;


            string outputFile = @"C:\Temp\report.csv";

            StringBuilder sb = new StringBuilder();

            StringBuilder result = new StringBuilder();

            try
            {
                File.WriteAllText(outputFile,
                                  "Sheet Number," +
                                  "Sheet Name," +
                                  "Sheet Revision," +
                                  "Cloud Id," +
                                  "Is Hidden," +
                                  "Is Element Color Override," +
                                  "Is Category Color Override," +
                                  "Revision," +
                                  "Mark" + Environment.NewLine
                                  );
            }
            catch
            {
                TaskDialog.Show("Error", "Opertion cancelled. Please close the log file.");
                return(Result.Failed);
            }


            ICollection <Element> allClouds = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RevisionClouds).WhereElementIsNotElementType().ToElements();

            int cloudsOnSheets = 0;

            foreach (Element rev in allClouds)
            {
                Parameter p           = rev.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);
                View      currentView = doc.GetElement(rev.OwnerViewId) as View;

                Parameter revision = rev.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
                Parameter version  = rev.get_Parameter(BuiltInParameter.DOOR_NUMBER);

                try
                {
                    if (currentView is ViewSheet)
                    {
                        ViewSheet sheetView = doc.GetElement(rev.OwnerViewId) as ViewSheet;

                        Parameter sheetRevision = sheetView.get_Parameter("TB_Revision");

                        OverrideGraphicSettings og = sheetView.GetElementOverrides(rev.Id);

                        Category revCloudsCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_RevisionClouds);

                        OverrideGraphicSettings ogc = sheetView.GetCategoryOverrides(revCloudsCategory.Id);

                        string isElementOverriden  = "";
                        string isCategoryOverriden = "";

                        if (null != og)
                        {
                            if (og.IsValidObject)
                            {
                                if (og.ProjectionLineColor.IsValid)
                                {
                                    isElementOverriden = $"{og.ProjectionLineColor.Red.ToString()} {og.ProjectionLineColor.Green.ToString()} {og.ProjectionLineColor.Blue.ToString()}";
                                }
                                else
                                {
                                    isElementOverriden = "N/A";
                                }
                            }
                            else
                            {
                                isElementOverriden = "N/A";
                            }
                        }

                        if (null != ogc)
                        {
                            if (ogc.IsValidObject)
                            {
                                if (ogc.ProjectionLineColor.IsValid)
                                {
                                    isCategoryOverriden = $"{ogc.ProjectionLineColor.Red.ToString()} {ogc.ProjectionLineColor.Green.ToString()} {ogc.ProjectionLineColor.Blue.ToString()}";
                                }
                                else
                                {
                                    isCategoryOverriden = "N/A";
                                }
                            }
                        }
                        else
                        {
                            isCategoryOverriden = "N/A";
                        }


                        string fixedName = sheetView.Name.Replace(',', '-');

                        sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}",
                                                    sheetView.SheetNumber,
                                                    fixedName,
                                                    sheetRevision.AsString(),
                                                    rev.Id,
                                                    rev.IsHidden(sheetView),
                                                    isElementOverriden,
                                                    isCategoryOverriden,
                                                    revision.AsString(),
                                                    version.AsString()));
                        cloudsOnSheets += 1;
                    }
                    else
                    {
                        string fixedName = currentView.Name.Replace(',', '-');

                        sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}",
                                                    "N/A",
                                                    fixedName,
                                                    "N/A",
                                                    rev.Id,
                                                    rev.IsHidden(currentView),
                                                    "N/A",
                                                    "N/A",
                                                    revision.AsString(),
                                                    version.AsString()));
                    }
                }
                catch (Exception ex)
                {
                    result.AppendLine(String.Format("Element {0} \nError Message: {1}", rev.Id, ex.Message));
                }
            }
            File.AppendAllText(outputFile, sb.ToString());



            TaskDialog myDialog = new TaskDialog("Summary");

            myDialog.MainIcon    = TaskDialogIcon.TaskDialogIconNone;
            myDialog.MainContent = String.Format("Total Rev Clouds: {0} \nClouds not on Sheets: {1} \nErrors: {2}",

                                                 allClouds.Count, allClouds.Count - cloudsOnSheets, result.ToString());

            myDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink4, $"Open Log File {outputFile}", "");

            TaskDialogResult res = myDialog.Show();

            if (TaskDialogResult.CommandLink4 == res)

            {
                System.Diagnostics.Process process =

                    new System.Diagnostics.Process();

                process.StartInfo.FileName = outputFile;

                process.Start();
            }

            return(Result.Succeeded);
        }
Exemple #52
0
        private void OnProcessRequest(object sender, CfxProcessRequestEventArgs e)
        {
            var request = e.Request;

            var uri = new Uri(request.Url);

            var headers = request.GetHeaderMap().Select(x => new { Key = x[0], Value = x[1] }).ToList();

            var contentRange = headers.FirstOrDefault(x => x.Key.ToLower() == "range");

            if (contentRange != null)
            {
                var group = System.Text.RegularExpressions.Regex.Match(contentRange.Value, @"(?<start>\d+)-(?<end>\d*)").Groups;
                if (group != null)
                {
                    int startPos, endPos;
                    if (!string.IsNullOrEmpty(group["start"].Value) && int.TryParse(group["start"].Value, out startPos))
                    {
                        buffStartPostition = startPos;
                    }

                    if (!string.IsNullOrEmpty(group["end"].Value) && int.TryParse(group["end"].Value, out endPos))
                    {
                        buffEndPostition = endPos;
                    }
                }
                isPartContent = true;
            }

            readResponseStreamOffset = 0;

            if (buffStartPostition.HasValue)
            {
                readResponseStreamOffset = buffStartPostition.Value;
            }

            var filePath = Uri.UnescapeDataString(uri.AbsolutePath);

            if (string.IsNullOrEmpty(CgiResource.Domain))
            {
                filePath = string.Format("{0}{1}", uri.Authority, filePath);
            }
            filePath = filePath.Trim('/');

            var scriptName   = filePath;
            var physicalPath = System.IO.Path.Combine(documentRoot, filePath);

            if (!System.IO.File.Exists(physicalPath))
            {
                scriptName   = "";
                physicalPath = documentRoot;
                string[] splitPath = filePath.Split('/');
                foreach (string fileName in splitPath)
                {
                    var realPath = System.IO.Path.Combine(physicalPath, fileName);
                    if (!System.IO.Directory.Exists(realPath) && !System.IO.File.Exists(realPath))
                    {
                        break;
                    }
                    scriptName  += "/" + fileName;
                    physicalPath = realPath;
                }
            }

            if (System.IO.Directory.Exists(physicalPath))
            {
                var realPath = System.IO.Path.Combine(physicalPath, scriptIndex);
                if (System.IO.File.Exists(realPath))
                {
                    scriptName  += "/" + scriptIndex;
                    physicalPath = realPath;
                }
            }

            if (System.IO.File.Exists(physicalPath))
            {
                var fileExt = System.IO.Path.GetExtension(physicalPath);
                if (fileExt == scriptExt)
                {
                    var process = new System.Diagnostics.Process();
                    process.StartInfo.Arguments              = physicalPath;
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.CreateNoWindow         = true;
                    process.StartInfo.FileName               = execgiPath;
                    process.StartInfo.RedirectStandardInput  = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.StartInfo.WorkingDirectory       = documentRoot;

                    process.StartInfo.EnvironmentVariables.Add("SERVER_SOFTWARE", "PhpWin");
                    process.StartInfo.EnvironmentVariables.Add("SERVER_NAME", uri.Host);
                    process.StartInfo.EnvironmentVariables.Add("SERVER_PORT", uri.Port.ToString());
                    process.StartInfo.EnvironmentVariables.Add("SERVER_PROTOCOL", "HTTP/1.1");
                    process.StartInfo.EnvironmentVariables.Add("HTTP_HOST", uri.Host);
                    process.StartInfo.EnvironmentVariables.Add("GATEWAY_INTERFACE", "CGI/1.1");
                    process.StartInfo.EnvironmentVariables.Add("REQUEST_METHOD", request.Method);
                    if (uri.Query.Length > 1)
                    {
                        process.StartInfo.EnvironmentVariables.Add("QUERY_STRING", uri.Query.Substring(1));
                    }
                    process.StartInfo.EnvironmentVariables.Add("REQUEST_URI", string.Format("/{0}{1}", filePath, uri.Query));
                    if (filePath.Length > scriptName.Length)
                    {
                        process.StartInfo.EnvironmentVariables.Add("PATH_INFO", filePath.Substring(scriptName.Length - 1));
                    }
                    process.StartInfo.EnvironmentVariables.Add("SCRIPT_NAME", scriptName);
                    process.StartInfo.EnvironmentVariables.Add("DOCUMENT_URI", "/" + filePath);
                    process.StartInfo.EnvironmentVariables.Add("DOCUMENT_ROOT", documentRoot);
                    process.StartInfo.EnvironmentVariables.Add("SCRIPT_FILENAME", physicalPath);
                    process.StartInfo.EnvironmentVariables.Add("REDIRECT_STATUS", "200");

                    foreach (var item in headers)
                    {
                        if (item.Key == "PROXY")
                        {
                            continue;
                        }
                        if (item.Key.ToUpper() == "CONTENT-TYPE")
                        {
                            process.StartInfo.EnvironmentVariables.Add("CONTENT_TYPE", item.Value);
                        }
                        else
                        {
                            process.StartInfo.EnvironmentVariables.Add("HTTP_" + item.Key.Replace("-", "_").ToUpper(), item.Value);
                        }
                    }

                    ulong contentLength = 0;
                    if (request.PostData != null)
                    {
                        foreach (var element in request.PostData.Elements)
                        {
                            if (element.Type == CfxPostdataElementType.Bytes)
                            {
                                contentLength += element.BytesCount;
                            }
                            else if (element.Type == CfxPostdataElementType.File)
                            {
                                var fileInfo = new System.IO.FileInfo(element.File);
                                contentLength += Convert.ToUInt64(fileInfo.Length);
                            }
                        }
                    }

                    process.StartInfo.EnvironmentVariables.Add("CONTENT_LENGTH", contentLength.ToString());

                    if (process.Start())
                    {
                        if (request.PostData != null && contentLength > 0)
                        {
                            foreach (var element in request.PostData.Elements)
                            {
                                if (element.Type == CfxPostdataElementType.Bytes)
                                {
                                    var      buffer  = new byte[element.BytesCount];
                                    GCHandle hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                                    IntPtr   pBuffer = hBuffer.AddrOfPinnedObject();

                                    var count = element.GetBytes(element.BytesCount, pBuffer);
                                    process.StandardInput.Write(Encoding.ASCII.GetChars(buffer, 0, Convert.ToInt32(count)));

                                    if (hBuffer.IsAllocated)
                                    {
                                        hBuffer.Free();
                                    }
                                }
                                else if (element.Type == CfxPostdataElementType.File)
                                {
                                    try
                                    {
                                        var buffer = System.IO.File.ReadAllBytes(element.File);
                                        process.StandardInput.BaseStream.Write(buffer, 0, Convert.ToInt32(buffer.Length));
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                        e.Callback.Dispose();
                                        e.SetReturnValue(false);
                                        return;
                                    }
                                }
                            }
                        }
                    }

                    using (var output = new System.IO.MemoryStream())
                    {
                        int    read;
                        byte[] buffer = new byte[16 * 1024];
                        var    stream = process.StandardOutput.BaseStream;
                        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            output.Write(buffer, 0, read);
                        }
                        output.Seek(0, System.IO.SeekOrigin.Begin);

                        var offset = 0;
                        var reader = new System.IO.StreamReader(output);
                        while (!reader.EndOfStream)
                        {
                            var readline = reader.ReadLine();
                            offset += readline.Length + 2;
                            if (readline.Equals(""))
                            {
                                break;
                            }
                            var header = readline.Split(':');
                            if (header.Length < 2)
                            {
                                break;
                            }
                            header[1] = header[1].Trim();
                            if (header[0].ToUpper() == "CONTENT-TYPE")
                            {
                                mimeType = header[1].Split(';')[0].Trim();
                            }
                            else if (header[0].ToUpper() == "STATUS")
                            {
                                httpStatus = int.Parse(header[1].Split(' ')[0]);
                            }
                            else if (header[0].ToUpper() == "LOCATION")
                            {
                                if (header[1].StartsWith("/"))
                                {
                                    redirectUrl = CgiResource.GetFullUrl(header[1]);
                                }
                                else
                                {
                                    redirectUrl = header[1];
                                }
                            }
                            scriptHeaders.Add(header);
                        }

                        var count = output.Length - offset;
                        data = new byte[count];
                        output.Seek(offset, System.IO.SeekOrigin.Begin);
                        output.Read(data, 0, Convert.ToInt32(count));
                    }
                }
                else
                {
                    data     = System.IO.File.ReadAllBytes(physicalPath);
                    mimeType = CfxRuntime.GetMimeType(fileExt.TrimStart('.'));
                }

                e.Callback.Continue();
                e.SetReturnValue(true);
            }
            else
            {
                e.Callback.Continue();
                e.SetReturnValue(false);
            }
        }
Exemple #53
0
 public void setCurrentProcess(int processId)
 {
     CurrentProcess = System.Diagnostics.Process.GetProcessById(processId);
 }
 void sfDataGrid1_CurrentCellBeginEdit(object sender, CurrentCellBeginEditEventArgs e)
 {
     process = System.Diagnostics.Process.Start("Osk.exe");
 }
Exemple #55
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
#if NETCORE
                string dataPath = @"..\..\..\..\..\..\..\..\Common\Data\DocIO\";
#else
                string dataPath = @"..\..\..\..\..\..\..\Common\Data\DocIO\";
#endif
                // Creating a new document.
                WordDocument document = new WordDocument();
                //Adds section with one empty paragraph to the Word document
                document.EnsureMinimal();
                //sets the page margins
                document.LastSection.PageSetup.Margins.All = 72f;
                //Appends bookmark to the paragraph
                document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
                document.LastParagraph.AppendText("Northwind database with normalization concept");
                document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
                // Open an existing template document with single section to get Northwind.information
                WordDocument nwdInformation = new WordDocument(dataPath + "Bookmark_Template.doc");
                // Open an existing template document with multiple section to get Northwind data.
                WordDocument templateDocument = new WordDocument(dataPath + "BkmkDocumentPart_Template.doc");
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the template document.
                BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
                // Move to the NorthWind bookmark in template document
                bk.MoveToBookmark("NorthWind");
                //Gets the bookmark content as WordDocumentPart
                WordDocumentPart documentPart = bk.GetContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the Northwind information document.
                bk = new BookmarksNavigator(nwdInformation);
                // Move to the information bookmark
                bk.MoveToBookmark("Information");
                // Get the content of information bookmark.
                TextBodyPart bodyPart = bk.GetBookmarkContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the destination document.
                bk = new BookmarksNavigator(document);
                // Move to the NorthWind database in the destination document
                bk.MoveToBookmark("NorthwindDatabase");
                //Replace the bookmark content using word document parts
                bk.ReplaceContent(documentPart);
                // Move to the Northwind_Information in the destination document
                bk.MoveToBookmark("Northwind_Information");
                // Replacing content of Northwind_Information bookmark.
                bk.ReplaceBookmarkContent(bodyPart);
                // Move to the text bookmark
                bk.MoveToBookmark("Text");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting text inside the bookmark. This will preserve the source formatting
                bk.InsertText("Northwind Database contains the following table:");
                #region tableinsertion
                WTable tbl = new WTable(document);
                tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
                tbl.TableFormat.IsAutoResized      = true;
                tbl.ResetCells(8, 2);
                IWParagraph paragraph;
                tbl.Rows[0].IsHeader = true;
                paragraph            = tbl[0, 0].AddParagraph();
                paragraph.AppendText("Suppliers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[0, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 0].AddParagraph();
                paragraph.AppendText("Customers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 0].AddParagraph();
                paragraph.AppendText("Employees");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 0].AddParagraph();
                paragraph.AppendText("Products");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 0].AddParagraph();
                paragraph.AppendText("Inventory");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 1].AddParagraph();
                paragraph.AppendText("2");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 0].AddParagraph();
                paragraph.AppendText("Shippers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 0].AddParagraph();
                paragraph.AppendText("PO Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 0].AddParagraph();
                paragraph.AppendText("Sales Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 1].AddParagraph();
                paragraph.AppendText("7");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;


                bk.InsertTable(tbl);
                #endregion
                //Move to image bookmark
                bk.MoveToBookmark("Image");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting image to the bookmark.
                IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
#if NETCORE
                pic.LoadImage(System.Drawing.Image.FromFile(@"..\..\..\..\..\..\..\..\Common\images\DocIO\Northwind.png"));
#else
                pic.LoadImage(System.Drawing.Image.FromFile(@"..\..\..\..\..\..\..\Common\images\DocIO\Northwind.png"));
#endif
                pic.WidthScale  = 50f; // It reduces the image size because it doesnot fit
                pic.HeightScale = 75f; // in document page.
                bodyPart.Close();
                documentPart.Close();
                #region save document
                //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());
                        }
                    }
                }
                #endregion
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Exemple #56
0
        public static void OnGUI(UnityModManager.ModEntry modEntry)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label("每个存档槽最大保留备份数量(0-1000):");

            if (int.TryParse(GUILayout.TextField(settings.maxBackupsToKeep.ToString()),
                             out int maxBackupsToKeep))
            {
                if (maxBackupsToKeep <= 1000 && maxBackupsToKeep >= 0)
                {
                    settings.maxBackupsToKeep = maxBackupsToKeep;
                }
            }

            GUILayout.Label("读档列表的最大存档数(0表示不受限制)");
            if (int.TryParse(GUILayout.TextField(settings.maxBackupToLoad.ToString()),
                             out int maxBackupToLoad))
            {
                if (maxBackupToLoad >= 0)
                {
                    settings.maxBackupToLoad = maxBackupToLoad;
                }
            }

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("禁用游戏换季存档", GUILayout.Width(250));
            settings.blockAutoSave = GUILayout.SelectionGrid(settings.blockAutoSave ? 1 : 0,
                                                             Off_And_On, 2, GUILayout.Width(150)) == 1;
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("讀檔後重置亂數種子", GUILayout.Width(250));
            settings.regenerateRandomSeedAfterLoad = GUILayout.SelectionGrid(settings.regenerateRandomSeedAfterLoad ? 1 : 0,
                                                                             Off_And_On, 2, GUILayout.Width(150)) == 1;
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            HyperQuickLoad.InitClass.OnGUI(modEntry);


            GUILayout.BeginHorizontal();
            if (GUILayout.Button("打印log", GUILayout.Width(100)))
            {
                Log();
            }

            if (GUILayout.Button("显示log路径", GUILayout.Width(100)))
            {
                if (logPath != null && File.Exists(logPath))
                {
                    var p = new System.Diagnostics.Process();
                    p.StartInfo.FileName  = "explorer.exe";
                    p.StartInfo.Arguments = "/e,/select,\"" + logPath + "\"";
                    p.Start();
                }
            }

            GUILayout.EndHorizontal();
        }
        private void button8_Click(object sender, EventArgs e)
        {
            NSISScript = "!include \"MUI.nsh\"\n" + "!define MUI_ABORTWARNING\n";
            String[] output1;
            output1 = Regex.Split(Licenses, "SPLITT");
            foreach (String licenses in output1)
            {
                if (String.IsNullOrEmpty(licenses))
                {
                }
                else
                {
                    NSISScript = NSISScript + "!insertmacro MUI_PAGE_LICENSE \"" + licenses + "\"\n";
                }
            }
            NSISScript = NSISScript + "!insertmacro MUI_PAGE_COMPONENTS\n!define MUI_TEXT_LICENSE_TITLE \"License Agreement\"\n!insertmacro MUI_LANGUAGE \"English\"\n";
            NSISScript = NSISScript + "Name \"" + textBox1.Text + "\"\nCaption \"" + textBox2.Text + "\"\nIcon \"" + IconPath + "\"\nOutFile \"" + OutputPath + "\"\n";
            NSISScript = NSISScript + "SetDateSave on\nSetDatablockOptimize on\nCRCCheck on\nSilentInstall normal\n";
            NSISScript = NSISScript + "InstallDir \"" + MainInstallDir + textBox3.Text + "\"\n" + "RequestExecutionLevel " + UseAdmin + "\nManifestSupportedOS all\n";
            NSISScript = NSISScript + "Page directory\nPage instfiles\nUninstPage uninstConfirm\nUninstPage instfiles\nAutoCloseWindow false\nShowInstDetails show\n";
            NSISScript = NSISScript + "Section \"\"\nSetOutPath $INSTDIR\nFile /nonfatal /a /r \"" + folderPath + "\\\"\n" + "SectionEnd\n";
            if (checkedListBox1.GetItemCheckState(1) == CheckState.Checked)
            {
                NSISScript = NSISScript + "Section \"Install Source Code\"\nSetOutPath \"$INSTDIR\\Source\"\n" + "File /nonfatal /a /r \"" + SourcePath + "\\\"\nSectionEnd\n";
            }
            if (checkedListBox1.GetItemCheckState(3) == CheckState.Checked)
            {
                if (EXEPath.Contains(folderPath))
                {
                    String[] output2;
                    String[] output22;
                    String[] output23;
                    String[] output24;
                    String   temp1;
                    String   temp2;
                    String   temp3;
                    temp1 = "";
                    temp2 = "";
                    temp3 = "";
                    Char Splitter = '\\';
                    output22 = folderPath.Split(Splitter);
                    for (int count = 0; count < output22.Length + 1; count++)
                    {
                        if (count == output22.Length)
                        {
                            temp1 = output22[count - 1];
                        }
                    }
                    //        output23 = folderPath.Split(Splitter);
                    //      foreach(String tempstring in output23)
                    //    {
                    //      temp2 = temp2 + "\\\\" + tempstring;
                    //   }
                    output23 = Regex.Split(EXEPath, temp1);
                    for (int count = 0; count < output23.Length + 1; count++)
                    {
                        if (count == output23.Length)
                        {
                            temp2 = output23[count - 1];
                        }
                    }
                    output24 = Regex.Split(ShortcutIconPath, temp1);
                    for (int count = 0; count < output24.Length + 1; count++)
                    {
                        if (count == output24.Length)
                        {
                            temp3 = output24[count - 1];
                        }
                    }
                    //       temp1.TrimStart(Splitter);
                    //     temp2.TrimStart(Splitter);
                    //               output2 = Regex.Split(temp1, temp2);
                    //             output24 = ShortcutIconPath.Split(Splitter);
                    //           foreach(String tempstring in output24)
                    //         {
                    //           temp3 = temp3 + "\\\\" + tempstring;
                    //     }
                    //   temp3.TrimStart(Splitter);

                    if (ShortcutIconPath.Contains(folderPath))
                    {
                        //    String[] output3;
                        //  output3 = Regex.Split(temp3, temp2);
                        NSISScript = NSISScript + "Section \"Create Shortcut on Desktop\"\nCreateShortCut \"$DESKTOP\\" + textBox1.Text + ".lnk\" \"$INSTDIR\\" + temp2 + "\" \"\" \"$INSTDIR\\" + temp3 + "\" 0 SW_SHOWNORMAL ALT|CONTROL|SHIFT|F4 \"" + textBox1.Text + "\"\nSectionEnd";
                    }
                }
            }
            StreamWriter WriteToNSI;

            WriteToNSI = new StreamWriter(Application.StartupPath + "\\" + "temp.nsi");
            WriteToNSI.Write(NSISScript);
            WriteToNSI.Close();
            System.Diagnostics.Process          CompileNSI     = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo CompileNSIInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\" + "makensis.exe");
            CompileNSIInfo.Arguments      = "temp.nsi";
            CompileNSIInfo.CreateNoWindow = true;
            CompileNSIInfo.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Hidden;
            CompileNSI.StartInfo          = CompileNSIInfo;
            CompileNSI.Start();
            CompileNSI.WaitForExit();
            CompileNSI.Close();
            MessageBox.Show("Completed");
        }
Exemple #58
0
 private static Boolean validProcess(System.Diagnostics.Process process)
 {
     return(process.SessionId == currentSessionId && process.ProcessName.Contains("T1.Tb"));
 }
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;
        }