Inheritance: System.ComponentModel.Component
Example #1
22
        private Dictionary<int, ThreadInfo> processThreads; //has relating thread id to its threadInfo object

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructor for ProcessInfo
        /// </summary>
        /// <param name="procID">The id of the process</param>
        /// <param name="debugger">The debugger</param>
        public ProcessInfo(Process process, CorDebugger debug)
        {
            if (debug == null)
            {
                throw new ArgumentException("Null Debugger Exception");
            }

            processThreads = new Dictionary<int, ThreadInfo>();
            processCorThreads = new List<CorThread>();
            generalThreadInfos = new Dictionary<int, ProcessThread>();

            attachedCompletedProcessEvent = new ManualResetEvent(false);
            debugger = debug;
            processId = process.Id;
            generalProcessInfo = Process.GetProcessById(processId);

            //CorPublish cp = new CorPublish();
            //cpp = cp.GetProcess(processId);
            processFullName = process.MainModule.FileName;
            processShortName = System.IO.Path.GetFileName(process.MainModule.FileName);
            FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(processFullName);
            description = fileInfo.FileDescription;
            company = fileInfo.CompanyName;

            //debuggerProcessInfo will be set when the updateInfo function is called
            //the reason for this is that the process must be stopped for this to take place
            //this happen only when we want it to
        }
Example #2
12
        public String cmd(String cnd)
        {

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

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

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

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

            }
            return output;
        } // end cmd 
Example #3
2
        void Button1Click(object sender, EventArgs e)
        {
            Process myProcess = new Process();

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

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

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

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

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

            //listBox1.Text = output;

            // 프로그램이 종료되면
            //System.Console.WriteLine( "ExitCode is " + myProcess.ExitCode );
            myProcess.WaitForExit();
            myProcess.Close();
        }
Example #4
1
        public static string AssembleFile(string ilFile, string outFile, bool debug)
        {
            if (!File.Exists(ilFile))
            {
                throw new FileNotFoundException("IL file \"" + ilFile + "\" not found.");
            }

            File.Delete(outFile);

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

            if (!File.Exists(outFile))
            {
                throw new Exception("File \"" + ilFile + "\" could not be assembled.");
            }
            return stdout;
        }
Example #5
1
 public static void HandleRunningInstance(Process instance,int showType)
 {
     //ȷ������û�б���С�������
     ShowWindowAsync(instance.MainWindowHandle, showType);
     //������ʵ����Ϊforeground window
     SetForegroundWindow(instance.MainWindowHandle);
 }
Example #6
1
        public string Runcmd()
        {
            Process myProcess = new Process();
            myProcess.StartInfo.FileName = "cmd.exe";
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.StartInfo.RedirectStandardError = true;
            myProcess.StartInfo.RedirectStandardInput = true;
            myProcess.StartInfo.RedirectStandardOutput = true;
            try
            {
                myProcess.Start();
            }
            catch (Exception)
            {

                throw;
            }
            try
            {
                foreach (var item in Cmds)
                {
                    myProcess.StandardInput.WriteLine(item);
                }

            }
            catch (Exception)
            {

                throw;
            }
            myProcess.StandardInput.WriteLine("exit");
            return myProcess.StandardOutput.ReadToEnd();
        }
Example #7
1
 private void _load(Process proc) {
     File = new FileInfo(ProcessExecutablePath(proc));
     Name = proc.ProcessName;
     Id = proc.Id;
     Thread = new Thread(Monitor);
     Thread.Start(this);
 }
Example #8
1
 private void ayudaToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Process pr = new Process();
     pr.StartInfo.WorkingDirectory = @"C:\Users\Wilfredo\Desktop\admin\admin\admin";
     pr.StartInfo.FileName = "SofTool Systems help.htm";
     pr.Start();
 }
Example #9
1
        public bool StartSteamAccount(SteamAccount a)
        {
            bool finished = false;

            if(IsSteamRunning())
            {
                KillSteam();
            }

            while (finished == false)
            {
                if (IsSteamRunning() == false)
                {
                    Process p = new Process();
                    if (File.Exists(installDir))
                    {
                        p.StartInfo = new ProcessStartInfo(installDir, a.getStartParameters());
                        p.Start();
                        finished = true;
                        return true;
                    }
                }
            }
            return false;
        }
Example #10
1
        public void Pack_Works()
        {
            string pathToNuGet = MakeAbsolute(@".nuget\NuGet.exe");
            string pathToNuSpec = MakeAbsolute(@"src\app\SharpRaven\SharpRaven.nuspec");

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

            using (var process = new Process())
            {
                process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
                process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
                process.StartInfo = start;
                Assert.That(process.Start(), Is.True, "The NuGet process couldn't start.");
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit(3000);
                Assert.That(process.ExitCode, Is.EqualTo(0), "The NuGet process exited with an unexpected code.");
            }
        }
Example #11
1
        private MemoryStream GetThumbnailFromProcess(Process p, ref int width, ref int height)
        {
            Debug("Starting ffmpeg");
              using (var thumb = new MemoryStream()) {
            var pump = new StreamPump(p.StandardOutput.BaseStream, thumb, null, 4096);
            if (!p.WaitForExit(20000)) {
              p.Kill();
              throw new ArgumentException("ffmpeg timed out");
            }
            if (p.ExitCode != 0) {
              throw new ArgumentException("ffmpeg does not understand the stream");
            }
            Debug("Done ffmpeg");
            if (!pump.Wait(2000)) {
              throw new ArgumentException("stream reading timed out");
            }
            if (thumb.Length == 0) {
              throw new ArgumentException("ffmpeg did not produce a result");
            }

            using (var img = Image.FromStream(thumb)) {
              using (var scaled = ThumbnailMaker.ResizeImage(img, ref width, ref height)) {
            var rv = new MemoryStream();
            try {
              scaled.Save(rv, ImageFormat.Jpeg);
              return rv;
            }
            catch (Exception) {
              rv.Dispose();
              throw;
            }
              }
            }
              }
        }
Example #12
1
 public static string Run(string path, string args, out string error)
 {
     try
     {
         using (Process process = new Process())
         {
             process.StartInfo.FileName = path;
             process.StartInfo.Arguments = args;
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.RedirectStandardError = true;
             process.Start();
             process.WaitForExit();
             error = process.StandardError.ReadToEnd();
             if (process.ExitCode != 0)
             {
                 return string.Empty;
             }
             return process.StandardOutput.ReadToEnd().Trim().Replace(@"\\", @"\");
         }
     }
     catch (Exception exception)
     {
         error = string.Format("Calling {0} caused an exception: {1}.", path, exception.Message);
         return string.Empty;
     }
 }
Example #13
1
        private void B_start_Click(object sender, EventArgs e)
        {
            AccountCacher = new Process();
            AccountCacher.StartInfo.FileName = "AccountCacher.exe";
            AccountCacher.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            AccountCacher.Start();

            Thread.Sleep(500);

            LauncherServer = new Process();
            LauncherServer.StartInfo.FileName = "LauncherServer.exe";
            LauncherServer.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            LauncherServer.Start();

            Thread.Sleep(500);

            LobbyServer = new Process();
            LobbyServer.StartInfo.FileName = "LobbyServer.exe";
            LobbyServer.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            LobbyServer.Start();

            Thread.Sleep(500);

            WorldServer = new Process();
            WorldServer.StartInfo.FileName = "WorldServer.exe";
            WorldServer.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            WorldServer.Start();
        }
Example #14
1
        public Snes()
        {
            mProcess = SearchProcess("snes9x.exe");
            mProcessPtr = OpenProcess(ProcessAccessFlags.PROCESS_VM_READ, false, mProcess.Id);

            updateMemory();
        }
Example #15
1
        /// <summary>
        /// Generate a keypair
        /// </summary>
        public static void generateKeypair()
        {
            // We need both, the Public and Private Key
            // Public Key to send to Gitlab
            // Private Key to connect to Gitlab later
            if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa.pub") &&
                File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa"))
            {
                return;
            }

            try {
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh");
            } catch (Exception) {}
            Process p = new Process();
            p.StartInfo.FileName = "ssh-keygen";
            p.StartInfo.Arguments = "-t rsa -f \"" + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\.ssh\\id_rsa\" -N \"\"";
            p.Start();
            Console.WriteLine();
            Console.WriteLine("Waiting for SSH Key to be generated ...");
            p.WaitForExit();
            while (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa.pub") &&
                   !File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ssh\id_rsa"))
            {
                Thread.Sleep(1000);
            }
            Console.WriteLine("SSH Key generated successfully!");
        }
Example #16
1
        static void Main(string[] args)
        {
            List<string> start_for = new List<string>();

            start_for.Add(@"C:\\xampp\\mysql\\bin\\mysqld.exe");//mysql路徑
            start_for.Add(@"C:\\xampp\\apache\\bin\\httpd.exe");//apache路徑
            start_for.Add("netsh wlan stop hostednetwork");//wifi stop
            start_for.Add("netsh wlan set hostednetwork mode=allow ssid=Apple-steven-wifi key=0000000000123");//wifi set
            start_for.Add("netsh wlan start hostednetwork");//cmd 指令

            //Process p = new Process();
            //p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            int i = 0;
            foreach (string C_val in start_for)
            {
                Process SomeProgram = new Process();

                SomeProgram.StartInfo.FileName = (i == 2 || i == 3 || i == 4) ? "cmd.exe" : C_val;
                SomeProgram.StartInfo.Arguments = @"/c " + C_val;
                //p.StartInfo.Arguments = "/c " + command;
                SomeProgram.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//不要有視窗
                SomeProgram.Start();
                i++;
            }
        }
Example #17
1
        void ExecuteUtilityAsync(string args, Action<string> parseOutput, Action onComplete)
        {
            Process p = new Process();
            p.StartInfo.FileName = Utility;
            p.StartInfo.Arguments = args;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();

            var t = new Thread( _ =>
            {
                using (var reader = p.StandardOutput)
                {
                    // This is wrong, chrisf knows why
                    while (!p.HasExited)
                    {
                        string s = reader.ReadLine();
                        if (string.IsNullOrEmpty(s)) continue;
                        parseOutput(s);
                    }
                }
                onComplete();
            }) { IsBackground = true };
            t.Start();
        }
Example #18
1
 public static void AddSimpleRectoSvn(string inputDir)
 {
     try {
         Process p = new Process();
         p.StartInfo.FileName = "svn";
         p.StartInfo.Arguments = "add -N " + inputDir + @"\*";
         p.StartInfo.UseShellExecute = false;
         p.StartInfo.RedirectStandardOutput = true;
         p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
         p.StartInfo.CreateNoWindow = false;
         p.Start();
         string output = p.StartInfo.Arguments + "\r\n";
         output = output + p.StandardOutput.ReadToEnd();
         p.WaitForExit();
         p = new Process();
         p.StartInfo.FileName = "svn";
         p.StartInfo.Arguments = "commit " + inputDir + "\\* -m\"addedFiles\"";
         p.StartInfo.UseShellExecute = false;
         p.StartInfo.RedirectStandardOutput = true;
         p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
         p.StartInfo.CreateNoWindow = false;
         p.Start();
         p.WaitForExit();
     } catch (Exception ex) {
         MessageBox.Show(ex.Message, "SVN checkout issue");
     }
 }
Example #19
1
 internal void AbortedShutdown()
 {
     if(_ShutdownProcess != null && !_ShutdownProcess.HasExited)
         _ShutdownProcess.Kill();
     _ShutdownProcess = null;
     _Main.StopTimer();
 }
        public static int BuildPSAttack(Attack attack, GeneratedStrings generatedStrings)
        {
            //DateTime now = DateTime.Now;
            //string buildDate = String.Format("{0:MMMM dd yyyy} at {0:hh:mm:ss tt}", now);
            //using (StreamWriter buildDateFile = new StreamWriter(Path.Combine(attack.resources_dir, "attackDate.txt")))
            //{
            //    buildDateFile.Write(buildDate);
            //}
            string dotNetDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
            string msbuildPath = Path.Combine(dotNetDir, "msbuild.exe");
            if (File.Exists(msbuildPath))
            {
                Process msbuild = new Process();
                msbuild.StartInfo.FileName = msbuildPath;
                msbuild.StartInfo.Arguments = attack.build_args(Path.Combine(Strings.obfuscatedSourceDir, generatedStrings.Store["psaReplacement"] + ".sln"));
                msbuild.StartInfo.UseShellExecute = false;
                msbuild.StartInfo.RedirectStandardOutput = true;
                msbuild.StartInfo.RedirectStandardError = true;

                Console.WriteLine("Running build with this command: {0} {1}", msbuild.StartInfo.FileName, msbuild.StartInfo.Arguments);

                msbuild.Start();
                string output = msbuild.StandardOutput.ReadToEnd();
                Console.WriteLine(output);
                string err = msbuild.StandardError.ReadToEnd();
                Console.WriteLine(err);
                msbuild.WaitForExit();
                int exitCode = msbuild.ExitCode;
                msbuild.Close();
                return exitCode;
            }
            return 999;
        }
Example #21
1
		private string RunProcess(string commandName, string arguments, bool useShell)
		{
			System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
			System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

			Process p = new Process();
			p.StartInfo.CreateNoWindow  = !useShell;
			p.StartInfo.UseShellExecute = useShell;
			p.StartInfo.Arguments = arguments;
			p.StartInfo.RedirectStandardOutput = !useShell;
			p.StartInfo.RedirectStandardError = !useShell;
			p.StartInfo.FileName = commandName;
			p.Start();
			if(!useShell)
			{
				string output = p.StandardOutput.ReadToEnd();
				string error = p.StandardError.ReadToEnd();
				p.WaitForExit();
				WriteToConsole(error);
				WriteToConsole(output);
				System.Windows.Forms.Cursor.Current =  oldCursor;
				return output;
			}
			return "";
		}
Example #22
1
        public void aa()
        {
            //实例化一个进程类
            cmd = new Process();

            //获得系统信息,使用的是 systeminfo.exe 这个控制台程序
            cmd.StartInfo.FileName = "cmd.exe";

            //将cmd的标准输入和输出全部重定向到.NET的程序里

            cmd.StartInfo.UseShellExecute = false; //此处必须为false否则引发异常

            cmd.StartInfo.RedirectStandardInput = true; //标准输入
            cmd.StartInfo.RedirectStandardOutput = true; //标准输出
            cmd.StartInfo.RedirectStandardError = true;

            //不显示命令行窗口界面
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            cmd.Start(); //启动进程
            cmd.StandardInput.WriteLine("jdf b");
            //cmd.StandardInput.WriteLine("exit");

            //获取输出
            //需要说明的:此处是指明开始获取,要获取的内容,
            //<span style="color: #FF0000;">只有等进程退出后才能真正拿到</span>

            //cmd.WaitForExit();//等待控制台程序执行完成
            //cmd.Close();//关闭该进程

            Thread oThread1 = new Thread(new ThreadStart(bb));
            oThread1.Start();
        }
        public void ExecuteSync(string fileName, string arguments, string workingDirectory)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                throw new ArgumentException("fileName");

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

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

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

                process.WaitForExit();
            } catch (Win32Exception) {
                throw new ExecuteFileNotFoundException(fileName);
            }
        }
Example #24
1
        void tcpRouteStart()
        {
            tcpRoute = new Process();
            tcpRoute.StartInfo.FileName = "TcpRoute2.exe";
            tcpRoute.StartInfo.WorkingDirectory = ".";
            tcpRoute.StartInfo.Arguments = "";
            tcpRoute.StartInfo.CreateNoWindow = true;
            // tcpRoute.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            tcpRoute.StartInfo.UseShellExecute = false;
            tcpRoute.StartInfo.RedirectStandardOutput = true;
            tcpRoute.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            tcpRoute.StartInfo.StandardErrorEncoding = Encoding.UTF8;
            tcpRoute.StartInfo.RedirectStandardError = true;

            // 注册关闭事件
            tcpRoute.EnableRaisingEvents = true;
            tcpRoute.SynchronizingObject = this;
            tcpRoute.Exited += new EventHandler(TcpRouteExit);


            tcpRoute.OutputDataReceived += new DataReceivedEventHandler(process1_ErrorDataReceived);
            tcpRoute.ErrorDataReceived += new DataReceivedEventHandler(process1_ErrorDataReceived);

            tcpRoute.Start();

            tcpRoute.BeginOutputReadLine();
            tcpRoute.BeginErrorReadLine();

            //   tcpRoute.WaitForExit();
        }
Example #25
1
		static public bool RunProgam(String asFile, String asArgs)
		{
			Process myProcess = new Process();
            
			try
			{
				myProcess.StartInfo.FileName = asFile; 
				myProcess.StartInfo.Arguments = asArgs;
				myProcess.Start();
			}
			catch (Win32Exception e)
			{
				if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
				{
					return false;
				} 

				else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
				{
					return false;
				}
			}

			return true;
		}
Example #26
0
		public BitcoinQProcess(Process process)
		{
			this._Process = process;

			WqlObjectQuery wqlQuery =
			new WqlObjectQuery("Select * from Win32_Process where Handle=\"" + process.Id + "\"");
			ManagementObjectSearcher searcher =
				new ManagementObjectSearcher(wqlQuery);
			var result = searcher.Get().OfType<ManagementObject>().FirstOrDefault();

			if(result != null)
			{
				_CommandLine = result["CommandLine"].ToString();
				var configurationFile = GetConfigurationFile();
				if(configurationFile != null && File.Exists(configurationFile))
				{
					_Configuration = File.ReadAllText(configurationFile);
					_Configuration = Regex.Replace(_Configuration, "(#.*)", "");

					ParseConfigurationFile();
				}

				ParseCommandLine();
				FillWithDefault();
			}
		}
Example #27
0
 bool runLoginScript()
 {
     using (Process p = new Process())
     {
         ProcessStartInfo info = new ProcessStartInfo(@"ruby");
         info.Arguments = "C:\\Users\\Saulo\\Documents\\RPGVXAce\\projectNOMAD\\Scripts\\login.rb" +" "+ username + " " + password; // set args
         info.RedirectStandardInput = true;
         info.RedirectStandardOutput = true;
         info.UseShellExecute = false;
         p.StartInfo = info;
         p.Start();
         String output = p.StandardOutput.ReadToEnd();
         // process output
         if (output == "0")
         {
             MessageBox.Show("Incorrect password or username");
             return false;
         }
         else
         {
             MessageBox.Show("Welcome!");
             return true;
         }
     }
 }
        protected override void OnStop()
        {
            this.eventLog.WriteEntry("Squid is stopping...", EventLogEntryType.Information);

            if (timer != null)
            {
                timer.Dispose();
                timer = null;
            }

            if (updateTimer != null)
            {
                updateTimer.Dispose();
                updateTimer = null;
            }

            lock(this.locker)
            {
                this.Kill(this.squid);
                this.squid = null;
            }

            var processes = Process.GetProcessesByName("squid");
            foreach (var p in processes)
            {
                this.Kill(p);
            }

            this.eventLog.WriteEntry("Squid stopped.", EventLogEntryType.Information);
        }
        /// <summary>
        /// Execute a general git command
        /// </summary>
        /// <param name="args">The command arguments</param>
        /// <returns>A list of strings with the command output</returns>
        public List<string> ExecCommand(string args)
        {
            //Console.WriteLine("gitPath = "+GitPath);
            //Console.WriteLine("args = " + args);

            ProcessStartInfo psinfo = new ProcessStartInfo
            {
                FileName = GitPath,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };

            Stdout = new List<string>();// clear the buffer.
            Stderr = new List<string>();

            using (Process gitProcess = new Process())
            {
                gitProcess.StartInfo = psinfo;
                gitProcess.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);

                bool started = gitProcess.Start();

                gitProcess.BeginOutputReadLine();
                gitProcess.WaitForExit();
                gitProcess.Close();

                return Stdout;
            };
        }
Example #30
0
        public Boolean Start()
        {
            //FileInfo commandFile = new FileInfo(_commandFullPath);
            //if(commandFile.Exists == false) throw new FileNotFoundException();

            Boolean result = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        if (!File.Exists(outputDbPath))
                        {
                            throw new BuildFailedException(string.Format(
                                                               "Failed to generate image database. Output from arcoreimg:\n\nstdout:\n{0}\n====\n\nstderr:\n{1}\n====",
                                                               stdout.ToString(),
                                                               stderr.ToString()));
                        }
                    }
                    catch
                    {
                        Debug.LogErrorFormat("Failed to generated ARCore reference image library '{0}'", imageLib.name);
                        throw;
                    }
                    finally
                    {
                        Directory.Delete(tempDirectory, true);
                    }
                }
            }
            catch
            {
                RemoveGeneratedStreamingAssets();
                throw;
            }
        }
        /// <summary>
        /// Launches a program
        /// </summary>
        /// <param name="ProgramFile">Path to the program to run</param>
        /// <param name="Arguments">Command-line arguments</param>
        /// <param name="OnExit">Optional callback whent he program exits</param>
        /// <param name="OutputHandler">If supplied, std-out and std-error will be redirected to this function and no shell window will be created</param>
        /// <returns>The newly-created process, or null if it wasn't able to start.  Exceptions are swallowed, but a debug output string is emitted on errors</returns>
        public System.Diagnostics.Process LaunchProgram(string ProgramFile, string Arguments, EventHandler OnExit = null, DataReceivedEventHandler OutputHandler = null, bool bWaitForCompletion = false)
        {
            // Create the action's process.
            ProcessStartInfo ActionStartInfo = new ProcessStartInfo();

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

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

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

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


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

            System.Diagnostics.Process ActionProcess;

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

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

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

                // Launch the program
                ActionProcess.Start();

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

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

            return(ActionProcess);
        }
Example #33
0
        /// <summary>
        /// run the task
        /// </summary>
        protected override void ExecuteTask()
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.EnableRaisingEvents = false;
            process.StartInfo.FileName  = FMysqlExecutable;

            if (FSQLCommand.Length > 0)
            {
                process.StartInfo.RedirectStandardInput = true;
                Log(Level.Info, FSQLCommand);
            }
            else if (FSQLFile.Length > 0)
            {
                process.StartInfo.RedirectStandardInput = true;
                Log(Level.Info, "Load sql commands from file: " + FSQLFile);
            }

            // add -v before -u if you want to see the sql commands...

            if (FPassword.Length > 0)
            {
                process.StartInfo.Arguments += " --password="******" --user="******" --database=" + FDatabase;
            }

            process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.EnableRaisingEvents = true;

            try
            {
                if (!process.Start())
                {
                    throw new Exception("cannot start " + process.StartInfo.FileName);
                }
            }
            catch (Exception exp)
            {
                throw new Exception("cannot start " + process.StartInfo.FileName + Environment.NewLine + exp.Message);
            }

            if ((FSQLCommand.Length > 0) && (process.StandardInput != null))
            {
                process.StandardInput.WriteLine(FSQLCommand);
                process.StandardInput.Close();
            }
            else if (FSQLFile.Length > 0)
            {
                StreamReader sr = new StreamReader(FSQLFile);
                process.StandardInput.Write(sr.ReadToEnd());
                process.StandardInput.Close();
                sr.Close();
            }

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

            // TODO: what about error output?
            // see also http://csharptest.net/?p=321 about how to use Process class

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

            foreach (string line in output)
            {
                if (!(line.Trim().StartsWith("INSERT") || line.Trim().StartsWith("GRANT") || line.Trim().StartsWith("COPY") ||
                      line.Trim().StartsWith("DELETE")))
                {
                    Console.WriteLine(line);
                }
            }

            if (FOutputFile.Length > 0)
            {
                StreamWriter sw = new StreamWriter(FOutputFile);

                foreach (string line in output)
                {
                    sw.WriteLine(line);
                }

                sw.Close();
            }

            if (FailOnError && (process.ExitCode != 0))
            {
                throw new Exception("Exit Code " + process.ExitCode.ToString() + " shows that something went wrong");
            }
        }
Example #34
0
 // Open Calculator
 private void calculator_button_Click(object sender, EventArgs e) //Start Calculator
 {
     System.Diagnostics.Process calculatorProcess = System.Diagnostics.Process.Start("calc.exe");
 }
Example #35
0
        private async void StartSITL(string exepath, string model, string homelocation, string extraargs = "", int speedup = 1)
        {
            if (String.IsNullOrEmpty(homelocation))
            {
                CustomMessageBox.Show(Strings.Invalid_home_location, Strings.ERROR);
                return;
            }

            if (!File.Exists(exepath))
            {
                CustomMessageBox.Show(Strings.Failed_to_download_the_SITL_image, Strings.ERROR);
                return;
            }

            // kill old session
            try
            {
                if (simulator != null)
                {
                    simulator.Kill();
                }
            }
            catch
            {
            }

            // override default model
            if (cmb_model.Text != "")
            {
                model = cmb_model.Text;
            }

            var config = await GetDefaultConfig(model);

            if (!string.IsNullOrEmpty(config))
            {
                extraargs += @" --defaults """ + config + @"""";
            }

            extraargs += " " + txt_cmdline.Text + " ";

            if (chk_wipe.Checked)
            {
                extraargs += " --wipe ";
            }

            string simdir = sitldirectory + model + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(simdir);

            string path = Environment.GetEnvironmentVariable("PATH");

            Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path, EnvironmentVariableTarget.Process);

            Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

            ProcessStartInfo exestart = new ProcessStartInfo();

            exestart.FileName         = exepath;
            exestart.Arguments        = String.Format("-M{0} -O{1} -s{2} --uartA tcp:0 {3}", model, homelocation, speedup, extraargs);
            exestart.WorkingDirectory = simdir;
            exestart.WindowStyle      = ProcessWindowStyle.Minimized;
            exestart.UseShellExecute  = true;

            try
            {
                simulator = System.Diagnostics.Process.Start(exestart);
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show("Failed to start the simulator\n" + ex.ToString(), Strings.ERROR);
                return;
            }

            System.Threading.Thread.Sleep(2000);

            MainV2.View.ShowScreen(MainV2.View.screens[0].Name);

            var client = new Comms.TcpSerial();

            try
            {
                client.client = new TcpClient("127.0.0.1", 5760);

                MainV2.comPort.BaseStream = client;

                SITLSEND = new UdpClient("127.0.0.1", 5501);

                Thread.Sleep(200);

                MainV2.instance.doConnect(MainV2.comPort, "preset", "5760");
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
Example #36
0
        private void DoUpdate()
        {
            // Create FreshClam.Conf File

            // Get location of current config file
            FileInfo configFile        = new FileInfo(ClamAVConfig.ClamConfigFile);
            string   freshClamConfFile = configFile.DirectoryName + "\\FreshClam.conf";

            // Delete config if it already exists
            if (File.Exists(freshClamConfFile))
            {
                File.Delete(freshClamConfFile);
            }

            // Use the path of the config file for the location of FreshClam.conf
            using (TextWriter freshClamConf = new StreamWriter(freshClamConfFile))
            {
                freshClamConf.WriteLine("# FreshClam.conf file created by ClamAV WHS Add-in " + DateTime.Now.ToString());
                freshClamConf.WriteLine("#");
                freshClamConf.WriteLine("DatabaseMirror " + ClamAVConfig.ReadClamConfigKey("dbmirror"));
                freshClamConf.WriteLine("#");
                freshClamConf.WriteLine("MaxAttempts 3");
                freshClamConf.WriteLine("#");

                // Direct to log file
                freshClamConf.WriteLine("UpdateLogFile " + ClamAVConfig.ReadClamConfigKey("dbupdatelogfile"));
                freshClamConf.WriteLine("#");

                // Setup proxy if required
                if (!string.IsNullOrEmpty(ClamAVConfig.ReadClamConfigKey("host")))
                {
                    freshClamConf.WriteLine("HTTPProxyServer " + ClamAVConfig.ReadClamConfigKey("host"));
                    if (!string.IsNullOrEmpty(ClamAVConfig.ReadClamConfigKey("port")))
                    {
                        freshClamConf.WriteLine("HTTPProxyPort " + ClamAVConfig.ReadClamConfigKey("port"));
                    }
                    if (!string.IsNullOrEmpty(ClamAVConfig.ReadClamConfigKey("user")))
                    {
                        freshClamConf.WriteLine("HTTPProxyUsername " + ClamAVConfig.ReadClamConfigKey("user"));
                    }
                    if (!string.IsNullOrEmpty(ClamAVConfig.ReadClamConfigKey("password")))
                    {
                        freshClamConf.WriteLine("HTTPProxyPassword " + ClamAVConfig.ReadClamConfigKey("password"));
                    }
                }
                freshClamConf.WriteLine("# End");
                // Write and Close compelted by end of using
            }

            // Run Fresh Clam

            // Update status

            string command = ClamAVConfig.ReadClamConfigKey("freshclam");
            string args    = "--config-file=\"" + freshClamConfFile + "\"";

            args += " --datadir=\"" + ClamAVConfig.ReadClamConfigKey("database") + "\"";

            System.Diagnostics.Process freshClam = new System.Diagnostics.Process();
            freshClam.StartInfo.FileName  = command;
            freshClam.StartInfo.Arguments = args;
            freshClam.Exited             += new EventHandler(freshClam_Exited);
            freshClam.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(freshClam_OutputDataReceived);
            freshClam.ErrorDataReceived  += new System.Diagnostics.DataReceivedEventHandler(freshClam_ErrorDataReceived);
            freshClam.EnableRaisingEvents = true;
            freshClam.Start();

            switch (ClamAVConfig.ReadClamConfigKey("priority"))
            {
            case "Low":
                freshClam.PriorityClass = System.Diagnostics.ProcessPriorityClass.BelowNormal;
                break;

            case "Med":
                freshClam.PriorityClass = System.Diagnostics.ProcessPriorityClass.Normal;
                break;

            case "High":
                freshClam.PriorityClass = System.Diagnostics.ProcessPriorityClass.AboveNormal;
                break;

            default:
                freshClam.PriorityClass = System.Diagnostics.ProcessPriorityClass.Normal;
                break;
            }
        }
Example #37
0
        /// <summary>
        /// </summary>
        /// <param name = "command">OsCommand to be executed</param>
        /// <param name = "wait">wait property</param>
        /// <param name = "show">show property</param>
        /// <param name = "errMsg">hold error message string, if command execution fails.</param>
        /// <param name = "exitCode">exit code returned by process</param>
        /// <returns>this returns errcode, if command fails to execute. </returns>
        public static int InvokeOS(String command, bool wait, CallOsShow show, ref String errMsg, ref int exitCode)
        {
            String[] commands = null;
            int      retcode  = -1;

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

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

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

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

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

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

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

            return(retcode);
        }
Example #38
0
        private void btnCreate_Click(object sender, System.EventArgs e)
        {
            #region Workbook Initialize
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            //Set the Default version as Excel 97to2003
            if (this.rdbExcel97.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel97to2003;
                fileName = "InteractiveFeatures.xls";
            }
            //Set the Default version as Excel 2007
            else if (this.rdbExcel2007.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2007;
                fileName = "InteractiveFeatures.xlsx";
            }
            //Set the Default version as Excel 2010
            else if (this.rdbExcel2010.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2010;
                fileName = "InteractiveFeatures.xlsx";
            }
            //Set the Default version as Excel 2013
            else if (this.rdbExcel2013.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2013;
                fileName = "InteractiveFeatures.xlsx";
            }
            //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
            //The new workbook will have 3 worksheets
            IWorkbook workbook = application.Workbooks.Create(3);
            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];
            #endregion

            sheet.IsGridLinesVisible = false;

            sheet.Range["B2"].Text = "Interactive features";
            sheet.Range["B2"].CellStyle.Font.Bold = true;
            sheet.Range["B2"].CellStyle.Font.Size = 14;

            sheet.Range["A4"].Text = "Some Useful links";
            sheet.Range["A4"].CellStyle.Font.Bold = true;
            sheet.Range["A4"].CellStyle.Font.Size = 12;

            sheet.Range["A20"].Text = "Comments";
            sheet.Range["A20"].CellStyle.Font.Bold = true;
            sheet.Range["A20"].CellStyle.Font.Size = 12;

            sheet.Range["B5"].Text  = "Feature page";
            sheet.Range["B7"].Text  = "Support Email Id";
            sheet.Range["B9"].Text  = "Samples";
            sheet.Range["B11"].Text = "Read the comment about XlsIO";
            sheet.Range["B13"].Text = "Read the Comment about Interactive features";
            sheet.Range["B20"].Text = "XlsIO";
            sheet.Range["B22"].Text = "Interactive features";

            #region Hyperlink
            //Creating Hyperlink for a Website
            IHyperLink hyperlink = sheet.HyperLinks.Add(sheet.Range["C5"]);
            hyperlink.Type      = ExcelHyperLinkType.Url;
            hyperlink.Address   = "http://www.syncfusion.com/products/windows-forms/xlsio";
            hyperlink.ScreenTip = "To know more About XlsIO go through this link";

            //Creating Hyperlink for e-mail
            IHyperLink hyperlink1 = sheet.HyperLinks.Add(sheet.Range["C7"]);
            hyperlink1.Type      = ExcelHyperLinkType.Url;
            hyperlink1.Address   = "mailto:[email protected]";
            hyperlink1.ScreenTip = "Send Mail to this id for your queries";

            //Creating Hyperlink for Opening Files using type as  File
            IHyperLink hyperlink2 = sheet.HyperLinks.Add(sheet.Range["C9"]);
            hyperlink2.Type = ExcelHyperLinkType.File;

            hyperlink2.Address       = "../../../";
            hyperlink2.ScreenTip     = "File path";
            hyperlink2.TextToDisplay = "Hyperlink for files using File as type";

            //Creating Hyperlink to another cell using type as Workbook
            IHyperLink hyperlink4 = sheet.HyperLinks.Add(sheet.Range["C11"]);
            hyperlink4.Type          = ExcelHyperLinkType.Workbook;
            hyperlink4.Address       = "Sheet1!B20";
            hyperlink4.ScreenTip     = "Click here";
            hyperlink4.TextToDisplay = "Click here to move to the cell with Comments about XlsIO";

            IHyperLink hyperlink5 = sheet.HyperLinks.Add(sheet.Range["C13"]);
            hyperlink5.Type          = ExcelHyperLinkType.Workbook;
            hyperlink5.Address       = "Sheet1!B22";
            hyperlink5.ScreenTip     = "Click here";
            hyperlink5.TextToDisplay = "Click here to move to the cell with Comments about this sample";

            #endregion

            #region Comments

            //Insert Comments
            //Adding comments to a cell.
            sheet.Range["B20"].AddComment().Text = "XlsIO is a Backoffice product with high performance!";

            //Add RichText Comments
            IRange range = sheet.Range["B22"];
            range.AddComment().RichText.Text = "Great Sample!";
            IRichTextString rtf = range.Comment.RichText;

            //Formatting first 4 characters
            IFont greyFont = workbook.CreateFont();
            greyFont.Bold     = true;
            greyFont.Italic   = true;
            greyFont.RGBColor = Color.FromArgb(333365);
            rtf.SetFont(0, 3, greyFont);

            //Formatting last 4 characters
            IFont greenFont = workbook.CreateFont();
            greenFont.Bold     = true;
            greenFont.Italic   = true;
            greenFont.RGBColor = Color.Green;
            rtf.SetFont(4, 7, greenFont);

            //Set column width
            sheet.Columns[0].ColumnWidth = 30;

            #endregion

            #region Autofit the UsedRanges
            sheet.UsedRange.AutofitRows();
            sheet.UsedRange.AutofitColumns();
            #endregion

            #region Save the Workbook
            //Saving the workbook to disk.
            workbook.SaveAs(fileName);
            #endregion

            #region Workbook Close and Dispose
            //Close the workbook.
            workbook.Close();

            //No exception will be thrown if there are unsaved workbooks.
            excelEngine.ThrowNotSavedOnDestroy = false;
            excelEngine.Dispose();
            #endregion

            #region View the Workbook
            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo(fileName)
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                Process.Start(fileName);
#endif
                //Exit
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
            #endregion
        }
Example #39
0
        private void CommandExec(CommandModel cmd)
        {
            Trace.Call(cmd);

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

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

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

            string file;
            string args = null;

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

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

                try {
                    process.Start();
                    process.StandardInput.Close();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    process.WaitForExit();
                } catch (Exception ex) {
#if LOG4NET
                    f_Logger.Error(ex);
#endif
                    var command = info.FileName;
                    if (!String.IsNullOrEmpty(info.Arguments))
                    {
                        command += " " + info.Arguments;
                    }
                    var msg = new MessageBuilder().
                              AppendErrorText("Executing '{0}' failed with: {1}",
                                              command, ex.Message).
                              ToMessage();
                    AddMessageToFrontend(cmd, msg);
                }
            }
        }
        public void ReportePDF()
        {
            DateTime fecha = DT_fecha.Value;

            try {
                Document doc      = new Document(PageSize.A4);
                string   filename = "ResumenSaldo\\ResumenSaldo" + fecha.ToString("dd-MM-yyyy") + "_" + suc + ".pdf";

                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@filename, FileMode.Create));

                writer.PageEvent = new HeaderFooter();

                doc.AddTitle("Reporte de saldos de proveedor");
                doc.AddCreator("RoyP3r3z");


                // Abrimos el archivo
                doc.Open();

                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);



                Paragraph paragraph = new Paragraph("");
                doc.Add(paragraph);

                //Este codigo agrega una imagen al pdf
                string imageURL           = "imagenes/logo.png";
                iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);

                ////Resize image depend upon your need
                jpg.ScaleToFit(140f, 120f);

                ////Give space before image
                jpg.SpacingBefore = 10f;

                ////Give some space after the image
                jpg.SpacingAfter = 10f;
                jpg.Alignment    = Element.ALIGN_CENTER;
                doc.Add(jpg);
                ////fin del codigo de la imagen


                Paragraph parrafoEnc = new Paragraph();
                parrafoEnc.Add("");
                doc.Add(parrafoEnc);
                parrafoEnc.Clear();

                doc.Add(Chunk.NEWLINE);



                //Creamos nuestra tabla
                PdfPTable table = new PdfPTable(DG_reporte.Columns.Count);


                table.WidthPercentage = 100;
                float[] widths = new float[] { 40f, 110f, 30f, 45f };
                table.SetWidths(widths);
                table.SkipLastFooter = true;
                table.SpacingAfter   = 50;

                //Encabezados
                for (int j = 0; j < DG_reporte.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(DG_reporte.Columns[j].HeaderText));
                }

                //flag the first row as a header
                table.HeaderRows = 1;


                for (int i = 0; i < DG_reporte.Rows.Count; i++)
                {
                    for (int k = 0; k < DG_reporte.Columns.Count; k++)
                    {
                        if (DG_reporte[k, i].Value != null)
                        {
                            table.AddCell(new Phrase(DG_reporte[k, i].Value.ToString()));
                        }
                    }
                }

                doc.Add(table);


                doc.Close();
                writer.Close();

                Process prc = new System.Diagnostics.Process();
                prc.StartInfo.FileName = filename;
                prc.Start();
            }catch (Exception ex)
            {
                MessageBox.Show("Error al crear PDF" + ex);
            }
        }
Example #41
0
 private ProcessContext(System.Diagnostics.Process p, IValue encoding)
 {
     _p = p;
     _outputEncoding = encoding;
 }
Example #42
0
 public ProcessContext(System.Diagnostics.Process p) : this(p, ValueFactory.Create())
 {
 }
Example #43
0
        public static (int exitCode, string output, bool timedOut) ExecuteBlockingWithOutputs(this System.Diagnostics.Process p,
                                                                                              int timeout =
                                                                                              int.MaxValue,
                                                                                              bool kill = true)
        {
            StringBuilder outputBuilder = new StringBuilder();

            void OutputDataReceived(object sender,
                                    DataReceivedEventArgs e)
            {
                lock (outputBuilder)
                    outputBuilder.Append(e.Data + "\n");
            }

            p.EnableRaisingEvents = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.OutputDataReceived += OutputDataReceived;
            p.ErrorDataReceived  += OutputDataReceived;

            try
            {
                p.Start();

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

                if (!p.WaitForExit(timeout))
                {
                    if (kill)
                    {
                        p.Kill();
                    }

                    return(-1, null, true);
                }

                p.WaitForExit();

                return(p.ExitCode, outputBuilder.ToString(), false);
            }
            finally
            {
                p.Dispose();
            }
        }
Example #44
0
 public Process()
 {
     _process = new System.Diagnostics.Process();
     _process.ErrorDataReceived  += (sender, args) => ErrorDataReceived.Invoke(sender, args);
     _process.OutputDataReceived += (sender, args) => OutputDataReceived.Invoke(sender, args);
 }
Example #45
0
        /// <summary>
        /// Create Pivot Table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2016;
            // Accessing workbook
            string    inputPath = GetFullTemplatePath("PivotLayout.xlsx");
            IWorkbook workbook  = application.Workbooks.Open(inputPath);

            CreatePivotTable(workbook);
            IPivotTable pivotTable = workbook.Worksheets[1].PivotTables[0];

            pivotTable.Layout();

            //To view the pivot table inline formatting in MS Excel, we have to set the IsRefreshOnLoad property as true.
            (workbook.PivotCaches[pivotTable.CacheIndex] as PivotCacheImpl).IsRefreshOnLoad = true;

            //Save the document as Excel
            string outputFileName = "PivotLayoutCompact.xlsx";

            if (rdBtnOutline.Checked)
            {
                outputFileName = "PivotLayoutOutline.xlsx";
            }
            else if (rdBtnTabular.Checked)
            {
                outputFileName = "PivotLayoutTabular.xlsx";
            }
            try
            {
                workbook.SaveAs(outputFileName);

                //Close the workbook.
                workbook.Close();

                //No exception will be thrown if there are unsaved workbooks.
                excelEngine.ThrowNotSavedOnDestroy = false;
                excelEngine.Dispose();

                //Message box confirmation to view the created spreadsheet.
                if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    try
                    {
                        //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo = new System.Diagnostics.ProcessStartInfo(outputFileName)
                        {
                            UseShellExecute = true
                        };
                        process.Start();
#else
                        Process.Start(outputFileName);
#endif
                    }
                    catch (Win32Exception ex)
                    {
                        MessageBox.Show("Excel 2007 is not installed in this system");
                        Console.WriteLine(ex.ToString());
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch
            {
                MessageBox.Show("Sorry, Excel can't open two workbooks with the same name at the same time.\nPlease close the workbook and try again.", "File is already open", MessageBoxButtons.OK);
            }
        }
Example #46
0
        /// <summary>
        /// Convert To PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConvert_Click(object sender, EventArgs e)
        {
            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2016;
            // Accessing workbook
            string    inputPath = GetFullTemplatePath("PivotLayout.xlsx");
            IWorkbook workbook  = application.Workbooks.Open(inputPath);

            CreatePivotTable(workbook);
            //Intialize the ExcelToPdfConverter class
            ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);
            //Intialize the ExcelToPdfConverterSettings class
            ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings();

            //Set the Layout Options for the output Pdf page.
            settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage;
            //Convert the Excel document to PDF
            PdfDocument pdfDoc = converter.Convert(settings);
            //Save the document as PDF
            string outputFileName = "PivotLayoutCompact.pdf";

            if (rdBtnOutline.Checked)
            {
                outputFileName = "PivotLayoutOutline.pdf";
            }
            else if (rdBtnTabular.Checked)
            {
                outputFileName = "PivotLayoutTabular.pdf";
            }
            try
            {
                pdfDoc.Save(outputFileName);

                pdfDoc.Close();
                converter.Dispose();
                //Close the workbook.
                workbook.Close();

                //No exception will be thrown if there are unsaved workbooks.
                excelEngine.ThrowNotSavedOnDestroy = false;
                excelEngine.Dispose();

                //Message box confirmation to view the created spreadsheet.
                if (MessageBox.Show("Do you want to view the PDF?", "PDF has been created",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    try
                    {
                        //Launching the PDF file using the default Application.
#if NETCORE
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo = new System.Diagnostics.ProcessStartInfo(outputFileName)
                        {
                            UseShellExecute = true
                        };
                        process.Start();
#else
                        Process.Start(outputFileName);
#endif
                    }
                    catch (Win32Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch
            {
                MessageBox.Show("Sorry, PDF can't opened", "File is already open", MessageBoxButtons.OK);
            }

            workbook.Close();
            excelEngine.Dispose();
        }
Example #47
0
        private void ConvertSFD()
        {
            Process pProcess;
            string  strOutput;

            if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, "system")))
            {
                WriteLog("Could not locate the system folder.");
                MessageBox.Show("Unable to locate SADX system folder at: " + Path.Combine(Environment.CurrentDirectory, "system") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: system folder not found", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }
            // Convert all SA* SFDs to MPG
            if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA1.SFD")))
            {
                pProcess = new System.Diagnostics.Process();
                pProcess.StartInfo.FileName               = "sfd2mpg.exe";
                pProcess.StartInfo.Arguments              = "-c \"..\\lame --silent\" sa1.sfd sa2.sfd sa3.sfd sa4.sfd sa5.sfd sa6.sfd sa7.sfd sa8.sfd";
                pProcess.StartInfo.UseShellExecute        = false;
                pProcess.StartInfo.RedirectStandardOutput = true;
                pProcess.StartInfo.WorkingDirectory       = Path.Combine(Environment.CurrentDirectory, "system");
                pProcess.StartInfo.CreateNoWindow         = true;
                pProcess.Start();
                strOutput = pProcess.StandardOutput.ReadToEnd();
                WriteLog(strOutput);
                pProcess.WaitForExit();
                bool mpgcheck = false;
                progressBar1.Value += 40;
                // Convert SA* MPGs using FFMPEG
                for (int u = 1; u < 9; u++)
                {
                    progressBar1.Value += 20;
                    WriteLog("Converting SA" + u.ToString() + ".MPG...");
                    pProcess.StartInfo.FileName              = "ffmpeg.exe";
                    pProcess.StartInfo.Arguments             = "-y -hide_banner -loglevel error -f mpeg -r 29.97 -i sa" + u.ToString() + ".mpg -vcodec mpeg1video -s 640x480 -aspect 4/3 -acodec mp2 -b:v 3000000 SA" + u.ToString() + ".MPEG";
                    pProcess.StartInfo.UseShellExecute       = false;
                    pProcess.StartInfo.RedirectStandardError = true;
                    pProcess.StartInfo.WorkingDirectory      = Path.Combine(Environment.CurrentDirectory, "system");
                    pProcess.StartInfo.CreateNoWindow        = true;
                    pProcess.Start();
                    strOutput = pProcess.StandardError.ReadToEnd();
                    WriteLog(strOutput);
                    pProcess.WaitForExit();
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPEG")))
                    {
                        if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPG")))
                        {
                            File.Replace(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPEG"), Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".MPG"), Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + "_bk.MPEG"));
                        }
                        File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + "_bk.MPEG"));
                        if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".SFD")))
                        {
                            File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "SA" + u.ToString() + ".SFD"));
                        }
                    }
                    else
                    {
                        WriteLog("Error converting file SA" + u.ToString() + ".MPG.");
                    }
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "tmp.mp2")))
                    {
                        File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "tmp.mp2"));
                    }
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "tmp.wav")))
                    {
                        File.Delete(Path.Combine(Environment.CurrentDirectory, "system", "tmp.wav"));
                    }
                }
                for (int o = 1; o < 9; o++)
                {
                    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + o.ToString() + ".MPG")))
                    {
                        mpgcheck = true;
                    }
                }
                if (mpgcheck)
                {
                    MessageBox.Show("sfd2mpg failed to convert some or all SADX videos to 2004 format. Verify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }
            }
            else
            {
                WriteLog("SA* SFD files not found, skipping conversion.");
                bool mpgcheck = false;
                for (int o = 1; o < 9; o++)
                {
                    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "SA" + o.ToString() + ".MPG")))
                    {
                        mpgcheck = true;
                    }
                }
                if (mpgcheck)
                {
                    MessageBox.Show("sfd2mpg failed to convert some or all SADX videos to 2004 format. Verify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }
                else
                {
                    WriteLog("SA* MPG files already exist.");
                }
            }
            // Convert US intro using FFMPEG
            if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG")))
            {
                if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, "DLC")))
                {
                    WriteLog("Could not locate the DLC folder.");
                    MessageBox.Show("Could not locate the DLC folder at " + Path.Combine(Environment.CurrentDirectory, "DLC") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    return;
                }
                else
                {
                    pProcess = new System.Diagnostics.Process();
                    WriteLog("Converting RE-US.MPG...");
                    pProcess.StartInfo.FileName              = "ffmpeg.exe";
                    pProcess.StartInfo.Arguments             = "-y -hide_banner -loglevel error -f mpeg -r 29.97 -i re-us2.sfd -vcodec mpeg1video -aspect 4/3 -acodec mp2 -b:v 5800000 RE-US.MPG";
                    pProcess.StartInfo.UseShellExecute       = false;
                    pProcess.StartInfo.RedirectStandardError = true;
                    pProcess.StartInfo.WorkingDirectory      = Path.Combine(Environment.CurrentDirectory, "DLC");
                    pProcess.StartInfo.CreateNoWindow        = true;
                    pProcess.Start();
                    strOutput = pProcess.StandardError.ReadToEnd();
                    WriteLog(strOutput);
                    pProcess.WaitForExit();
                    if (File.Exists(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-US.MPG")))
                    {
                        File.Move(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-US.MPG"), Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG"));
                    }
                    else
                    {
                        WriteLog("Error converting RE-US.MPG.");
                    }
                    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG")))
                    {
                        MessageBox.Show("Intro file conversion failed: " + Path.Combine(Environment.CurrentDirectory, "system", "RE-US.MPG") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    }
                }
            }
            else
            {
                WriteLog("File RE-US.MPG already exists.");
            }
            // Convert JP intro using FFMPEG
            if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG")))
            {
                pProcess = new System.Diagnostics.Process();
                WriteLog("Converting RE-JP.MPG");
                pProcess.StartInfo.FileName              = "ffmpeg.exe";
                pProcess.StartInfo.Arguments             = "-y -hide_banner -loglevel error -f mpeg -r 29.97 -i re-jp2.sfd -vcodec mpeg1video -aspect 4/3 -acodec mp2 -b:v 5800000 RE-JP.MPG";
                pProcess.StartInfo.UseShellExecute       = false;
                pProcess.StartInfo.RedirectStandardError = true;
                pProcess.StartInfo.WorkingDirectory      = Path.Combine(Environment.CurrentDirectory, "DLC");
                pProcess.StartInfo.CreateNoWindow        = true;
                pProcess.Start();
                strOutput = pProcess.StandardError.ReadToEnd();
                WriteLog(strOutput);
                pProcess.WaitForExit();
                if (File.Exists(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-JP.MPG")))
                {
                    File.Move(Path.Combine(Environment.CurrentDirectory, "DLC", "RE-JP.MPG"), Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG"));
                }
                else
                {
                    WriteLog("Error converting RE-JP.MPG.");
                }
                if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG")))
                {
                    MessageBox.Show("Intro file conversion failed: " + Path.Combine(Environment.CurrentDirectory, "system", "RE-JP.MPG") + ".\nVerify integrity of your SADX installation and run the installer again.", "Error: FMV conversion failed", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }
            }
            else
            {
                WriteLog("File RE-JP.MPG already exists.");
            }
        }
Example #48
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            // The instantiation process consists of two steps.

            // Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            // Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2007;

            // An existing workbook is opened.
#if NETCORE
            IWorkbook workbook = application.Workbooks.Open(@"..\..\..\..\..\..\..\Common\Data\XlsIO\WorkSheetToImage.xlsx");
#else
            IWorkbook workbook = application.Workbooks.Open(@"..\..\..\..\..\..\Common\Data\XlsIO\WorkSheetToImage.xlsx");
#endif

            // The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets["Pivot Table"];

            sheet.UsedRangeIncludesFormatting = false;
            int lastRow    = sheet.UsedRange.LastRow + 1;
            int lastColumn = sheet.UsedRange.LastColumn + 1;


            // Save the image.
            if (this.rBtnBitmap.IsChecked.Value)
            {
                // Convert the worksheet to image
                System.Drawing.Image img = sheet.ConvertToImage(1, 1, lastRow, lastColumn, ImageType.Bitmap, null);

                fileName = "Sample.png";
                img.Save(fileName, ImageFormat.Png);
            }
            else
            {
                // Convert the worksheet to image
                System.Drawing.Image img = sheet.ConvertToImage(1, 1, lastRow, lastColumn, ImageType.Metafile, null);

                fileName = "Sample.emf";
                img.Save(fileName, ImageFormat.Emf);
            }

            //Close the workbook.
            workbook.Close();
            excelEngine.Dispose();

            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the image?", "Image has been created",
                                MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                try
                {
                    //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo = new System.Diagnostics.ProcessStartInfo(fileName)
                    {
                        UseShellExecute = true
                    };
                    process.Start();
#else
                    Process.Start(fileName);
#endif

                    //Exit
                    this.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {
                // Exit
                this.Close();
            }
        }
Example #49
0
        public void reply(string question)
        {
            check = true;
            speech.Speak(question);

            if (result.Length > 1 && check == true)
            {
                for (int i = 0; i < result.Length; i++)
                {
                    if (question.Contains(result[i]))
                    {
                        check = false;
                        Process.Start(@result[i + 1]);
                    }
                }

                if (question.Contains("what are you doing"))
                {
                    // Reply1.Text = Reply1.Text + " I am fine";
                    speech.Speak(" I am fine");
                }

                else if (question.Contains("how are you"))
                {
                    // Reply.Text = Reply.Text + " Answering your questions";
                    //speech.Speak(" Answering your questions");

                    //DateTime date = new DateTime();
                    string custom = DateTime.Now.ToLongTimeString();
                    //MessageBox.Show(custom);
                    // Reply1.Text = Reply1.Text + "Its " + custom;
                    speech.Speak("Its " + custom);
                }

                else if (question.Contains("what is time"))
                {
                    //DateTime date = new DateTime();
                    string custom = DateTime.Now.ToLongTimeString();
                    //MessageBox.Show(custom);
                    //Reply.Text = Reply.Text + "Its " + custom;
                    speech.Speak("Its " + custom);
                }
                else if (question.Contains("shutdown"))
                {
                    Process.Start("shutdown", "/s /t 0"); Process.Start("Shutdown", "-s -t 10");
                }
                else if (question.Contains("Facebook"))
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;

                    System.Diagnostics.Process.Start("http://www.facebook.com");
                }
                else if (question.Contains("facebook"))
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;

                    System.Diagnostics.Process.Start("http://www.facebook.com");
                }
                else if (question.Contains("open Google"))
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;

                    System.Diagnostics.Process.Start("http://www.google.com");
                }
                else if (question.Contains("open google"))
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;

                    System.Diagnostics.Process.Start("http://www.google.com");
                }
                else if (question.Contains("open Gmail"))
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;

                    System.Diagnostics.Process.Start("http://www.gmail.com");
                }
                else if (question.Contains("open e"))
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;
                    process = Process.Start("explorer.exe", @"E:\");
                }

                else if (question.Contains("open paint"))
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;
                    process = Process.Start("explorer.exe", @"C:\Windows\system32\mspaint.exe");
                }

                else if (question.Contains("screenshot"))
                {
                    Bitmap   printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
                    Graphics graphics    = Graphics.FromImage(printscreen as Image);
                    graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
                    printscreen.Save(@"C:\Temp\printscreen.jpg", ImageFormat.Jpeg);

                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.UseShellExecute = true;
                    process = Process.Start("explorer.exe", @"C:\Temp\printscreen.jpg");
                }

                else if (question.Contains("open snipping tool"))
                {
                    if (!Environment.Is64BitProcess)
                    {
                        System.Diagnostics.Process.Start("C:\\Windows\\sysnative\\SnippingTool.exe");
                    }
                    else
                    {
                        System.Diagnostics.Process.Start("C:\\Windows\\system32\\SnippingTool.exe");
                    }
                }


                else if (question.Contains("Exit"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Take Care"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Ok take care"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Ok good by"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Ok thats it"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Ok thats enough"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Good by"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Thats it"))
                {
                    Application.Exit();
                }
                else if (question.Contains("Thats enough"))
                {
                    Application.Exit();
                }
            }
        }
Example #50
0
        /// <summary>
        /// Opens the Uri. System's default application will be used
        /// to show the uri.
        /// </summary>
        /// <param name="uriToLaunch"></param>
        private void LaunchOnlineHelp(Uri uriToLaunch)
        {
            Diagnostics.Assert(null != uriToLaunch, "uriToLaunch should not be null");

            if (!uriToLaunch.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
                !uriToLaunch.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw PSTraceSource.NewInvalidOperationException(HelpErrors.ProtocolNotSupported,
                                                                 uriToLaunch.ToString(),
                                                                 "http",
                                                                 "https");
            }

            // we use this test hook is to avoid actually calling out to another process
            if (InternalTestHooks.BypassOnlineHelpRetrieval)
            {
                this.WriteObject(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                return;
            }

            Exception exception           = null;
            bool      wrapCaughtException = true;

            try
            {
                this.WriteVerbose(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                System.Diagnostics.Process browserProcess = new System.Diagnostics.Process();
#if UNIX
                browserProcess.StartInfo.FileName  = Platform.IsLinux ? "xdg-open" : /* macOS */ "open";
                browserProcess.StartInfo.Arguments = uriToLaunch.OriginalString;
                browserProcess.Start();
#else
                if (Platform.IsNanoServer || Platform.IsIoT)
                {
                    // We cannot open the URL in browser on headless SKUs.
                    wrapCaughtException = false;
                    exception           = PSTraceSource.NewInvalidOperationException(HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    // We can call ShellExecute directly on Full Windows.
                    browserProcess.StartInfo.FileName        = uriToLaunch.OriginalString;
                    browserProcess.StartInfo.UseShellExecute = true;
                    browserProcess.Start();
                }
#endif
            }
            catch (InvalidOperationException ioe)
            {
                exception = ioe;
            }
            catch (System.ComponentModel.Win32Exception we)
            {
                exception = we;
            }

            if (null != exception)
            {
                if (wrapCaughtException)
                {
                    throw PSTraceSource.NewInvalidOperationException(exception, HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    throw exception;
                }
            }
        }
Example #51
0
 // Open Paint
 private void open_paint_button_Click(object sender, EventArgs e)
 {
     System.Diagnostics.Process paintProcess = System.Diagnostics.Process.Start("mspaint.exe");
 }
Example #52
0
        private void Completed(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                DLSystem.Dispose();
                MessageBox.Show("Download aborted.\n\nPress OK to close the download window.", "OmniConverter - Download aborted", MessageBoxButtons.OK, MessageBoxIcon.Warning, DriverReinstall ? MessageBoxDefaultButton.Button1 : 0, DriverReinstall ? MessageBoxOptions.DefaultDesktopOnly : 0);
                DialogResult = DialogResult.No;
                Close();
            }
            else if (e.Error != null)
            {
                DLSystem.Dispose();
                MessageBox.Show("The configurator is unable to download the latest version.\nIt might not be available yet, or you might not be connected to the Internet.\n\nIf your connection is working, wait a few minutes for the update to appear online.\nIf your connection is malfunctioning or is not working at all, check your network connection, or contact your system administrator or network service provider.", "OmniConverter - Connection error", MessageBoxButtons.OK, MessageBoxIcon.Warning, DriverReinstall ? MessageBoxDefaultButton.Button1 : 0, DriverReinstall ? MessageBoxOptions.DefaultDesktopOnly : 0);
                DialogResult = DialogResult.No;

                if (DriverReinstall && InstallMode == UpdateSystem.WIPE_SETTINGS)
                {
                    var p = new System.Diagnostics.Process();
                    p.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.CreateNoWindow         = true;
                    p.Start();
                    Application.ExitThread();
                }

                Close();
            }
            else
            {
                if (InstallMode == UpdateSystem.NORMAL || InstallMode == UpdateSystem.WIPE_SETTINGS)
                {
                    try
                    {
                        byte[] fileData = e.Result;

                        using (FileStream fileStream = new FileStream(String.Format("OmniConverterSetup.exe", Path.GetTempPath()), FileMode.Create))
                            fileStream.Write(fileData, 0, fileData.Length);

                        DLSystem.Dispose();

                        MessageBox.Show("The update for the converter is ready to be installed.\n\nClick OK when you're ready.", "OmniConverter - Update warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, DriverReinstall ? MessageBoxDefaultButton.Button1 : 0, DriverReinstall ? MessageBoxOptions.DefaultDesktopOnly : 0);
                        Process.Start(String.Format("{0}{1}", Path.GetTempPath(), "OmniConverterSetup.exe"), "/SILENT /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS /NOCANCEL /SP-");

                        DialogResult = DialogResult.OK;
                        Application.ExitThread();
                    }
                    catch (Exception ex)
                    {
                        if (ex.GetBaseException() is InvalidOperationException)
                        {
                            MessageBox.Show("Unable to locate the setup!\n\nThe file is missing from your storage or it's not even present in GitHub's servers.\n\nThis usually indicates an issue with your connection, or a problem at GitHub.", "OmniConverter - Update error", MessageBoxButtons.OK, MessageBoxIcon.Error, DriverReinstall ? MessageBoxDefaultButton.Button1 : 0, DriverReinstall ? MessageBoxOptions.DefaultDesktopOnly : 0);
                        }
                        else if (ex.GetBaseException() is Win32Exception)
                        {
                            MessageBox.Show("Can not open the setup!\n\nThe file is probably damaged, or its missing the Win32PE header.\n\nThis usually indicates an issue with your connection.", "OmniConverter - Update error", MessageBoxButtons.OK, MessageBoxIcon.Error, DriverReinstall ? MessageBoxDefaultButton.Button1 : 0, DriverReinstall ? MessageBoxOptions.DefaultDesktopOnly : 0);
                        }
                        else if (ex.GetBaseException() is ObjectDisposedException)
                        {
                            MessageBox.Show("The process object has already been disposed.", "OmniConverter - Update error", MessageBoxButtons.OK, MessageBoxIcon.Error, DriverReinstall ? MessageBoxDefaultButton.Button1 : 0, DriverReinstall ? MessageBoxOptions.DefaultDesktopOnly : 0);
                        }
                        else
                        {
                            MessageBox.Show("Unknown error.", "OmniConverter - Update error", MessageBoxButtons.OK, MessageBoxIcon.Error, DriverReinstall ? MessageBoxDefaultButton.Button1 : 0, DriverReinstall ? MessageBoxOptions.DefaultDesktopOnly : 0);
                        }

                        DialogResult = DialogResult.No;
                        Close();
                    }
                }
                else
                {
                    byte[] fileData = e.Result;

                    using (FileStream fileStream = new FileStream(String.Format("{0}\\{1}", DestinationPath, FullURL.Split('/').Last()), FileMode.Create))
                        fileStream.Write(fileData, 0, fileData.Length);

                    DLSystem.Dispose();

                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
        }
Example #53
0
        static void Main()
        {
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Utils.ReleaseMemory(true);
            using (Mutex mutex = new Mutex(false, "Global\\Shadowsocks_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.ApplicationExit   += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.ApplicationExit += (sender, args) => HotKeys.Destroy();

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" +
                                    I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                    return;
                }

                /**
                 * 当前用户是管理员的时候,直接启动应用程序
                 * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
                 */
                //获得当前登录的Windows用户标示
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                //判断当前登录用户是否为管理员
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    var process  = System.Diagnostics.Process.GetCurrentProcess();
                    var filename = process.MainModule.FileName;
                    //创建启动对象
                    var p = new System.Diagnostics.Process();
                    p.StartInfo.UseShellExecute  = true;
                    p.StartInfo.WorkingDirectory = new FileInfo(filename).DirectoryName;
                    p.StartInfo.FileName         = filename;
                    //设置启动动作,确保以管理员身份运行
                    p.StartInfo.Verb = "runas";
                    try { p.Start(); } catch { }
                    //退出
                    Environment.Exit(0);
                }

                Directory.SetCurrentDirectory(Application.StartupPath);
#if DEBUG
                Logging.OpenLogFile();

                // truncate privoxy log file while debugging
                string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                if (File.Exists(privoxyLogFilename))
                {
                    using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                }
#else
                Logging.OpenLogFile();
#endif
                _controller     = new NewShadowsocksController();
                _viewController = new NewMenuViewController(_controller);
                HotKeys.Init();
                _controller.Start();
                Application.Run();
            }
        }
Example #54
0
        private void btnExport_Click(object sender, System.EventArgs e)
        {
            //Exports the DataTable to a spreadsheet.

            #region Workbook Initialize
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            //Set the Workbook version as Excel 97to2003
            if (this.rdbSaveXls.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel97to2003;
                fileName = "ExportToExcel.xls";
            }
            //Set the Workbook version as Excel 2007
            else if (this.rdbSaveXlsx.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2007;
                fileName = "ExportToExcel.xlsx";
            }
            //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
            //The new workbook will have 3 worksheets
            IWorkbook workbook = application.Workbooks.Create(1);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet worksheet = workbook.Worksheets[0];
            #endregion

            #region Export DataTable to Excel
            //Export DataTable.
            if (this.dataGridView1.DataSource != null)
            {
                worksheet.ImportDataTable((DataTable)this.dataGridView1.DataSource, true, 3, 1, -1, -1);
            }
            else
            {
                MessageBox.Show("There is no datatable to export, Please import a datatable first", "Error");

                //Close the workbook.
                workbook.Close();
                return;
            }
            #endregion

            #region Formatting the Report
            //Formatting the Report

            #region Applying Body Stlye
            //Body Style
            IStyle bodyStyle = workbook.Styles.Add("BodyStyle");
            bodyStyle.BeginUpdate();

            //Add custom colors to the palette.
            workbook.SetPaletteColor(9, Color.FromArgb(239, 242, 247));
            bodyStyle.Color = Color.FromArgb(239, 243, 247);
            bodyStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle  = ExcelLineStyle.Thin;
            bodyStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin;

            //Apply Style
            worksheet.UsedRange.CellStyleName = "BodyStyle";
            bodyStyle.EndUpdate();
            #endregion

            #region Applying Header Style
            //Header Style
            IStyle headerStyle = workbook.Styles.Add("HeaderStyle");
            headerStyle.BeginUpdate();

            //Add custom colors to the palette.
            workbook.SetPaletteColor(8, Color.FromArgb(182, 189, 218));
            headerStyle.Color     = Color.FromArgb(182, 189, 218);
            headerStyle.Font.Bold = true;
            headerStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle   = ExcelLineStyle.Thin;
            headerStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle  = ExcelLineStyle.Thin;
            headerStyle.Borders[ExcelBordersIndex.EdgeTop].LineStyle    = ExcelLineStyle.Thin;
            headerStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin;

            //Apply Style
            worksheet.Range["A1:K3"].CellStyleName = "HeaderStyle";
            headerStyle.EndUpdate();
            #endregion

            //Remove grid lines in the worksheet.
            worksheet.IsGridLinesVisible = false;

            //Autofit Rows and Columns
            worksheet.UsedRange.AutofitRows();
            worksheet.UsedRange.AutofitColumns();

            //Adjust Row Height.
            worksheet.Rows[1].RowHeight = 25;

            //Freeze header row.
            worksheet.Range["A4"].FreezePanes();

            worksheet.Range["C2"].Text = "Customer Details";
            worksheet.Range["C2:D2"].Merge();
            worksheet.Range["C2"].CellStyle.Font.Size           = 14;
            worksheet.Range["C2"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter;
            #endregion

            #region Workbook Save and Close
            //Saving the workbook to disk.
            workbook.SaveAs(fileName);
            workbook.Close();
            //No exception will be thrown if there are unsaved workbooks.
            excelEngine.ThrowNotSavedOnDestroy = false;
            excelEngine.Dispose();
            #endregion

            #region View the Workbook
            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo(fileName)
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                Process.Start(fileName);
#endif
            }
            #endregion
        }
Example #55
0
 private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
 {
     if (listView1.SelectedItems.Count == 0)
     {
         return;
     }
     //обработка двойного нажатия по папке или файла в ListView
     if (listView1.SelectedItems[0].Text.IndexOf('.') == -1)
     {
         //обработка нажатия на папку
         Addresses.Add(listView1.SelectedItems[0].Name);
         currIndex++;
         currListViewAddress = ((string)Addresses[currIndex]);
         if (currIndex + 1 == Addresses.Count)
         {
             button2.Enabled = false;
         }
         else
         {
             button2.Enabled = true;
         }
         if (currIndex - 1 == -1)
         {
             button1.Enabled = false;
         }
         else
         {
             button1.Enabled = true;
         }
         currListViewAddress = listView1.SelectedItems[0].Name;
         textBox1.Text       = currListViewAddress;
         FileInfo f    = new FileInfo(@listView1.SelectedItems[0].Name);
         string   t    = "";
         string[] str2 = Directory.GetDirectories(@listView1.SelectedItems[0].Name);
         string[] str3 = Directory.GetFiles(@listView1.SelectedItems[0].Name);
         listView1.Items.Clear();
         ListViewItem lw = new ListViewItem();
         if (listView1.View == View.Details)
         {
             foreach (string s2 in str2)
             {
                 f = new FileInfo(@s2);
                 string type = "Папка";
                 t       = s2.Substring(s2.LastIndexOf('\\') + 1);
                 lw      = new ListViewItem(new string[] { t, "", type, f.LastWriteTime.ToString() }, 0);
                 lw.Name = s2;
                 listView1.Items.Add(lw);
             }
             foreach (string s2 in str3)
             {
                 f = new FileInfo(@s2);
                 string type = "Файл";
                 t       = s2.Substring(s2.LastIndexOf('\\') + 1);
                 lw      = new ListViewItem(new string[] { t, f.Length.ToString() + " байт", type, f.LastWriteTime.ToString() }, 1);
                 lw.Name = s2;
                 listView1.Items.Add(lw);
             }
         }
         else
         {
             foreach (string s2 in str2)
             {
                 f       = new FileInfo(@s2);
                 t       = s2.Substring(s2.LastIndexOf('\\') + 1);
                 lw      = new ListViewItem(new string[] { t }, 0);
                 lw.Name = s2;
                 listView1.Items.Add(lw);
             }
             foreach (string s2 in str3)
             {
                 f       = new FileInfo(@s2);
                 t       = s2.Substring(s2.LastIndexOf('\\') + 1);
                 lw      = new ListViewItem(new string[] { t }, 1);
                 lw.Name = s2;
                 listView1.Items.Add(lw);
             }
         }
     }
     else
     {
         //обработка нажатия на файл(его запуска)
         System.Diagnostics.Process MyProc = new System.Diagnostics.Process();
         MyProc.StartInfo.FileName = @listView1.SelectedItems[0].Name;
         MyProc.Start();
     }
 }
Example #56
0
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            this._syncObject = new object();
            string pSExePath = PSExePath;

            if (useWow64)
            {
                string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
                if (!string.IsNullOrEmpty(environmentVariable) && (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    pSExePath = PSExePath.ToLowerInvariant().Replace(@"\system32\", @"\syswow64\");
                    if (!System.IO.File.Exists(pSExePath))
                    {
                        throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.IPCWowComponentNotPresent, new object[] { pSExePath }));
                    }
                }
            }
            string  str4    = string.Empty;
            Version version = powerShellVersion ?? PSVersionInfo.PSVersion;

            if (null == version)
            {
                version = new Version(3, 0);
            }
            str4 = string.Format(CultureInfo.InvariantCulture, "-Version {0}", new object[] { new Version(version.Major, version.Minor) });
            str4 = string.Format(CultureInfo.InvariantCulture, "{0} -s -NoLogo -NoProfile", new object[] { str4 });
            if (initializationScript != null)
            {
                string str5 = initializationScript.ToString();
                if (!string.IsNullOrEmpty(str5))
                {
                    string str6 = Convert.ToBase64String(Encoding.Unicode.GetBytes(str5));
                    str4 = string.Format(CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", new object[] { str4, str6 });
                }
            }
            ProcessStartInfo info = new ProcessStartInfo {
                FileName               = useWow64 ? pSExePath : PSExePath,
                Arguments              = str4,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                WindowStyle            = ProcessWindowStyle.Hidden,
                CreateNoWindow         = true,
                LoadUserProfile        = true
            };

            this._startInfo = info;
            if (credential != null)
            {
                NetworkCredential networkCredential = credential.GetNetworkCredential();
                this._startInfo.UserName = networkCredential.UserName;
                this._startInfo.Domain   = string.IsNullOrEmpty(networkCredential.Domain) ? "." : networkCredential.Domain;
                this._startInfo.Password = credential.Password;
            }
            System.Diagnostics.Process process = new System.Diagnostics.Process {
                StartInfo           = this._startInfo,
                EnableRaisingEvents = true
            };
            this._process = process;
        }
Example #57
0
        static void Main(string[] args)
        {
            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool             hasAdministrativeRight = principal.IsInRole(WindowsBuiltInRole.Administrator);

            if (!hasAdministrativeRight)
            {
                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.Verb     = "runas";
                processInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
                if (args.Length > 0)
                {
                    processInfo.Arguments = args.ToString();
                }
                try
                {
                    Process.Start(processInfo);
                }
                catch
                {
                    Environment.Exit(0);
                }
                Environment.Exit(0);
            }

            Console.WriteLine("This program will remove Yet Another Minecraft Server. Use only if the uninstaller has failed.");
            Console.WriteLine("This will not delete database file or individual server files, allowing re-install.");
            Console.WriteLine("If you don't plan to re-install you can safely delete all the instalation folder once this process is complete.");
            Console.WriteLine("Continue? (y/n)");

            string strResponse = Console.ReadLine();

            if (strResponse.ToUpper().Equals("Y"))
            {
                Console.WriteLine("Remove Service? (y/n)");
                strResponse = Console.ReadLine();
                if (strResponse.ToUpper().Equals("Y"))
                {
                    //Try and stop the service nicely
                    Console.WriteLine("Stopping service....");
                    try
                    {
                        ServiceController svcYAMS = new ServiceController("YAMS_Service");
                        while (true)
                        {
                            if (svcYAMS.Status.Equals(ServiceControllerStatus.Stopped))
                            {
                                Console.WriteLine("Service not running");
                                break;
                            }
                            else if (svcYAMS.Status.Equals(ServiceControllerStatus.StartPending))
                            {
                                System.Threading.Thread.Sleep(1000);
                            }
                            else
                            {
                                svcYAMS.Stop();
                                Console.WriteLine("Service stopped");
                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception: {1}", e.Message);
                    }

                    //Check if the process has really gone away, if not kill it.
                    Process[] processes = Process.GetProcessesByName("YAMS-Service.exe");
                    if (processes.Length > 0)
                    {
                        Console.WriteLine("Killing process...");
                        processes[0].Close();
                    }

                    //Now try and remove
                    Console.WriteLine("Removing service....");
                    Console.WriteLine("Trying \"sc delete YAMS_Service\"");
                    try
                    {
                        System.Diagnostics.ProcessStartInfo procStartInfo =
                            new System.Diagnostics.ProcessStartInfo("cmd", "/c sc delete YAMS_Service");

                        procStartInfo.RedirectStandardOutput = true;
                        procStartInfo.UseShellExecute        = false;
                        procStartInfo.CreateNoWindow         = true;
                        System.Diagnostics.Process proc = new System.Diagnostics.Process();
                        proc.StartInfo = procStartInfo;
                        proc.Start();
                        string result = proc.StandardOutput.ReadToEnd();
                        Console.WriteLine(result);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception: {1}", e.Message);
                    }

                    Console.WriteLine("Checking Registry...");
                    string keyName = @"SYSTEM\CurrentControlSet\Services";
                    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName, true))
                    {
                        try
                        {
                            key.DeleteSubKeyTree("YAMS_Service");
                            Console.WriteLine("Registry key deleted");
                        }
                        catch (KeyNotFoundException e)
                        {
                            Console.WriteLine("Registry key already deleted");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Exception: {1}", e.Message);
                        }
                    }
                }

                Console.WriteLine("Remove Program files? (y/n)");
                strResponse = Console.ReadLine();
                if (strResponse.ToUpper().Equals("Y"))
                {
                    //SYSTEM\CurrentControlSet\Services\YAMS_Service\ImagePath
                }

                Console.WriteLine("Remove add/remove programs entry? (y/n)");
                strResponse = Console.ReadLine();
                if (strResponse.ToUpper().Equals("Y"))
                {
                }
            }
        }
Example #58
0
        private void button1_Click(object sender, EventArgs e)
        {
            object filename1 = Application.StartupPath + "\\bin\\" + Global.templateName;

            object G_Missing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    wordDoc;
            wordDoc = wordApp.Documents.Open(filename1);
            wordDoc.ActiveWindow.Visible = false;//打开word

            Microsoft.Office.Interop.Word.Range myRange = wordDoc.Range();

            Microsoft.Office.Interop.Word.Find f = myRange.Find;
            f.Text = "布点数量:";
            f.ClearFormatting();

            bool finded = f.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                    ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                    ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                    ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                    );

            myRange      = wordDoc.Range(myRange.End, myRange.End + 6);
            myRange.Text = textBox1.Text;

            Microsoft.Office.Interop.Word.Range myRange1 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f1       = myRange1.Find;
            f1.Text = "仪表编号:";
            f1.ClearFormatting();

            bool finded1 = f1.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange1      = wordDoc.Range(myRange1.End, myRange1.End + 9);
            myRange1.Text = textBox2.Text;

            Microsoft.Office.Interop.Word.Range myRange2 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f2       = myRange2.Find;
            f2.Text = "测量点数量:";
            f2.ClearFormatting();

            bool finded2 = f2.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange2      = wordDoc.Range(myRange2.End, myRange2.End + 6);
            myRange2.Text = textBox6.Text;

            Microsoft.Office.Interop.Word.Range myRange3 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f3       = myRange3.Find;
            f3.Text = "仪表编号: ";
            f3.ClearFormatting();

            bool finded3 = f3.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange3      = wordDoc.Range(myRange3.End, myRange3.End + 8);
            myRange3.Text = textBox5.Text;

            Microsoft.Office.Interop.Word.Range myRange4 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f4       = myRange4.Find;
            f4.Text = "测量点数量: ";
            f4.ClearFormatting();

            bool finded4 = f4.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange4      = wordDoc.Range(myRange4.End, myRange4.End + 5);
            myRange4.Text = textBox9.Text;

            Microsoft.Office.Interop.Word.Range myRange5 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f5       = myRange5.Find;
            f5.Text = "仪表编号:  ";
            f5.ClearFormatting();

            bool finded5 = f5.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange5      = wordDoc.Range(myRange5.End, myRange5.End + 7);
            myRange5.Text = textBox8.Text;

            Microsoft.Office.Interop.Word.Range myRange6 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f6       = myRange6.Find;
            f6.Text = "测量点数量:  ";
            f6.ClearFormatting();

            bool finded6 = f6.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange6      = wordDoc.Range(myRange6.End, myRange6.End + 4);
            myRange6.Text = textBox12.Text;

            Microsoft.Office.Interop.Word.Range myRange7 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f7       = myRange7.Find;
            f7.Text = "仪表编号:   ";
            f7.ClearFormatting();

            bool finded7 = f7.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange7      = wordDoc.Range(myRange7.End, myRange7.End + 6);
            myRange7.Text = textBox11.Text;

            Microsoft.Office.Interop.Word.Range myRange8 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f8       = myRange8.Find;
            f8.Text = "测量点数量:   ";
            f8.ClearFormatting();

            bool finded8 = f8.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange8      = wordDoc.Range(myRange8.End, myRange8.End + 3);
            myRange8.Text = textBox15.Text;

            Microsoft.Office.Interop.Word.Range myRange9 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f9       = myRange9.Find;
            f9.Text = "仪表编号:    ";
            f9.ClearFormatting();

            bool finded9 = f9.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                      ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                      );

            myRange9      = wordDoc.Range(myRange9.End, myRange9.End + 5);
            myRange9.Text = textBox14.Text;

            Microsoft.Office.Interop.Word.Range myRange10 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f10       = myRange10.Find;
            f10.Text = "测量点数量:    ";
            f10.ClearFormatting();

            bool finded10 = f10.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                        );

            myRange10      = wordDoc.Range(myRange10.End, myRange10.End + 2);
            myRange10.Text = textBox18.Text;

            Microsoft.Office.Interop.Word.Range myRange11 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f11       = myRange11.Find;
            f11.Text = "仪表编号:     ";
            f11.ClearFormatting();

            bool finded11 = f11.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                        );

            myRange11      = wordDoc.Range(myRange11.End, myRange11.End + 4);
            myRange11.Text = textBox17.Text;

            Microsoft.Office.Interop.Word.Range myRange12 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f12       = myRange12.Find;
            f12.Text = "测量点数量:     ";
            f12.ClearFormatting();

            bool finded12 = f12.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                        );

            myRange12      = wordDoc.Range(myRange12.End, myRange12.End + 1);
            myRange12.Text = textBox21.Text;

            Microsoft.Office.Interop.Word.Range myRange13 = wordDoc.Range();
            Microsoft.Office.Interop.Word.Find  f13       = myRange13.Find;
            f13.Text = "仪表编号:      ";
            f13.ClearFormatting();

            bool finded13 = f13.Execute(ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
                                        ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing
                                        );

            myRange13      = wordDoc.Range(myRange13.End, myRange13.End + 3);
            myRange13.Text = textBox20.Text;


            wordDoc.Save();
            wordDoc.Close();
            wordApp.Quit();
            wordApp = null;



            string ImagePath     = pictureBox1.ImageLocation;
            string strKey        = "示意图:(上层,中层,下层)";
            object MissingValue  = Type.Missing;
            bool   isFindSealLoc = false;

            Microsoft.Office.Interop.Word.Application wp = null;
            Microsoft.Office.Interop.Word.Document    wd = null;
            try
            {
                wp = new Microsoft.Office.Interop.Word.Application();
                wd = wp.Documents.Open(ref filename1, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue);
                wp.Selection.Find.ClearFormatting();
                wp.Selection.Find.Replacement.ClearFormatting();
                wp.Selection.Find.Text = strKey;
                object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref objReplace, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor           = wp.Selection.Range;
                    object LinkToFile       = false;
                    object SaveWithDocument = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape = wp.Selection.InlineShapes.AddPicture(
                        ImagePath, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                    Inlineshape.Select();
                    Microsoft.Office.Interop.Word.Shape shape = Inlineshape.ConvertToShape();
                    shape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd != null)
                {
                    wd.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd);
                    wd = null;
                }
                if (wp != null)
                {
                    wp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp);
                    wp = null;
                }
            }

            string ImagePath1     = pictureBox2.ImageLocation;
            string strKey1        = "6.1.2风机出风口布点";
            object MissingValue1  = Type.Missing;
            bool   isFindSealLoc1 = false;

            Microsoft.Office.Interop.Word.Application wp1 = null;
            Microsoft.Office.Interop.Word.Document    wd1 = null;
            try
            {
                wp1 = new Microsoft.Office.Interop.Word.Application();
                wd1 = wp1.Documents.Open(ref filename1, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue);
                wp1.Selection.Find.ClearFormatting();
                wp1.Selection.Find.Replacement.ClearFormatting();
                wp1.Selection.Find.Text = strKey1;
                object objReplace1 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp1.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref objReplace1, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor1           = wp1.Selection.Range;
                    object LinkToFile1       = false;
                    object SaveWithDocument1 = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape1 = wp1.Selection.InlineShapes.AddPicture(
                        ImagePath1, ref LinkToFile1, ref SaveWithDocument1, ref Anchor1);
                    Inlineshape1.Select();
                    Microsoft.Office.Interop.Word.Shape shape1 = Inlineshape1.ConvertToShape();
                    shape1.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc1 = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd1 != null)
                {
                    wd1.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd1);
                    wd1 = null;
                }
                if (wp1 != null)
                {
                    wp1.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp1);
                    wp1 = null;
                }
            }

            string ImagePath2     = pictureBox3.ImageLocation;
            string strKey2        = "6.1.3出入口布点";
            object MissingValue2  = Type.Missing;
            bool   isFindSealLoc2 = false;

            Microsoft.Office.Interop.Word.Application wp2 = null;
            Microsoft.Office.Interop.Word.Document    wd2 = null;
            try
            {
                wp2 = new Microsoft.Office.Interop.Word.Application();
                wd2 = wp2.Documents.Open(ref filename1, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue);
                wp2.Selection.Find.ClearFormatting();
                wp2.Selection.Find.Replacement.ClearFormatting();
                wp2.Selection.Find.Text = strKey2;
                object objReplace2 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp2.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref objReplace2, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor2           = wp2.Selection.Range;
                    object LinkToFile2       = false;
                    object SaveWithDocument2 = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape2 = wp2.Selection.InlineShapes.AddPicture(
                        ImagePath2, ref LinkToFile2, ref SaveWithDocument2, ref Anchor2);
                    Inlineshape2.Select();
                    Microsoft.Office.Interop.Word.Shape shape2 = Inlineshape2.ConvertToShape();
                    shape2.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc2 = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd2 != null)
                {
                    wd2.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd2);
                    wd2 = null;
                }
                if (wp2 != null)
                {
                    wp2.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp2);
                    wp2 = null;
                }
            }

            string ImagePath3     = pictureBox4.ImageLocation;
            string strKey3        = "6.1.4死角布点";
            object MissingValue3  = Type.Missing;
            bool   isFindSealLoc3 = false;

            Microsoft.Office.Interop.Word.Application wp3 = null;
            Microsoft.Office.Interop.Word.Document    wd3 = null;
            try
            {
                wp3 = new Microsoft.Office.Interop.Word.Application();
                wd3 = wp3.Documents.Open(ref filename1, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue);
                wp3.Selection.Find.ClearFormatting();
                wp3.Selection.Find.Replacement.ClearFormatting();
                wp3.Selection.Find.Text = strKey3;
                object objReplace3 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp3.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref objReplace3, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor3           = wp3.Selection.Range;
                    object LinkToFile3       = false;
                    object SaveWithDocument3 = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape3 = wp3.Selection.InlineShapes.AddPicture(
                        ImagePath3, ref LinkToFile3, ref SaveWithDocument3, ref Anchor3);
                    Inlineshape3.Select();
                    Microsoft.Office.Interop.Word.Shape shape3 = Inlineshape3.ConvertToShape();
                    shape3.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc3 = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd3 != null)
                {
                    wd3.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd3);
                    wd3 = null;
                }
                if (wp3 != null)
                {
                    wp3.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp3);
                    wp3 = null;
                }
            }

            string ImagePath4     = pictureBox5.ImageLocation;
            string strKey4        = "6.1.5死角布点";
            object MissingValue4  = Type.Missing;
            bool   isFindSealLoc4 = false;

            Microsoft.Office.Interop.Word.Application wp4 = null;
            Microsoft.Office.Interop.Word.Document    wd4 = null;
            try
            {
                wp4 = new Microsoft.Office.Interop.Word.Application();
                wd4 = wp4.Documents.Open(ref filename1, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue);
                wp4.Selection.Find.ClearFormatting();
                wp4.Selection.Find.Replacement.ClearFormatting();
                wp4.Selection.Find.Text = strKey4;
                object objReplace4 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp4.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref objReplace4, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor4           = wp4.Selection.Range;
                    object LinkToFile4       = false;
                    object SaveWithDocument4 = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape4 = wp4.Selection.InlineShapes.AddPicture(
                        ImagePath4, ref LinkToFile4, ref SaveWithDocument4, ref Anchor4);
                    Inlineshape4.Select();
                    Microsoft.Office.Interop.Word.Shape shape4 = Inlineshape4.ConvertToShape();
                    shape4.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc4 = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd4 != null)
                {
                    wd4.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd4);
                    wd4 = null;
                }
                if (wp4 != null)
                {
                    wp4.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp4);
                    wp4 = null;
                }
            }

            string ImagePath5     = pictureBox6.ImageLocation;
            string strKey5        = "6.1.6货架布点";
            object MissingValue5  = Type.Missing;
            bool   isFindSealLoc5 = false;

            Microsoft.Office.Interop.Word.Application wp5 = null;
            Microsoft.Office.Interop.Word.Document    wd5 = null;
            try
            {
                wp5 = new Microsoft.Office.Interop.Word.Application();
                wd5 = wp5.Documents.Open(ref filename1, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue);
                wp5.Selection.Find.ClearFormatting();
                wp5.Selection.Find.Replacement.ClearFormatting();
                wp5.Selection.Find.Text = strKey5;
                object objReplace5 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp5.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref objReplace5, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor5           = wp5.Selection.Range;
                    object LinkToFile5       = false;
                    object SaveWithDocument5 = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape5 = wp5.Selection.InlineShapes.AddPicture(
                        ImagePath5, ref LinkToFile5, ref SaveWithDocument5, ref Anchor5);
                    Inlineshape5.Select();
                    Microsoft.Office.Interop.Word.Shape shape5 = Inlineshape5.ConvertToShape();
                    shape5.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc5 = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd5 != null)
                {
                    wd5.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd5);
                    wd5 = null;
                }
                if (wp5 != null)
                {
                    wp5.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp5);
                    wp5 = null;
                }
            }

            string ImagePath6     = pictureBox7.ImageLocation;
            string strKey6        = "6.1.7监控系统探头及验证环境布点";
            object MissingValue6  = Type.Missing;
            bool   isFindSealLoc6 = false;

            Microsoft.Office.Interop.Word.Application wp6 = null;
            Microsoft.Office.Interop.Word.Document    wd6 = null;
            try
            {
                wp6 = new Microsoft.Office.Interop.Word.Application();
                wd6 = wp6.Documents.Open(ref filename1, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue,
                                         ref MissingValue, ref MissingValue);
                wp6.Selection.Find.ClearFormatting();
                wp6.Selection.Find.Replacement.ClearFormatting();
                wp6.Selection.Find.Text = strKey6;
                object objReplace6 = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp6.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue,
                                               ref MissingValue, ref objReplace6, ref MissingValue,
                                               ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor6           = wp6.Selection.Range;
                    object LinkToFile6       = false;
                    object SaveWithDocument6 = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape6 = wp6.Selection.InlineShapes.AddPicture(
                        ImagePath6, ref LinkToFile6, ref SaveWithDocument6, ref Anchor6);
                    Inlineshape6.Select();
                    Microsoft.Office.Interop.Word.Shape shape6 = Inlineshape6.ConvertToShape();
                    shape6.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc6 = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd6 != null)
                {
                    wd6.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd6);
                    wd6 = null;
                }
                if (wp6 != null)
                {
                    wp6.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp6);
                    wp6 = null;
                }
                MessageBox.Show("导入成功!");
            }


            #region  除后台word占用。
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();
            //得到所有打开的进程
            try
            {
                foreach (Process thisproc in Process.GetProcessesByName("WINWORD"))
                {
                    if (!thisproc.CloseMainWindow())
                    {
                        thisproc.Kill();
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("杀死" + "WINWORD" + "失败!");
            }
            #endregion


            string             filename = Environment.CurrentDirectory.ToString() + "\\bin\\" + Global.templateName + ".doc";
            Spire.Doc.Document document = new Spire.Doc.Document(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox   = document.TextBoxes[2];
            Spire.Doc.Documents.Paragraph paragraph = textBox.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange = paragraph.AppendText(textBox3.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox111 = document.TextBoxes[3];
            Spire.Doc.Documents.Paragraph paragraph1 = textBox111.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange1 = paragraph1.AppendText(textBox4.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox22  = document.TextBoxes[4];
            Spire.Doc.Documents.Paragraph paragraph2 = textBox22.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange2 = paragraph2.AppendText(textBox7.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox33   = document.TextBoxes[5];
            Spire.Doc.Documents.Paragraph paragraph33 = textBox33.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange33 = paragraph33.AppendText(textBox10.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox55  = document.TextBoxes[6];
            Spire.Doc.Documents.Paragraph paragraph5 = textBox55.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange5 = paragraph5.AppendText(textBox13.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox66  = document.TextBoxes[7];
            Spire.Doc.Documents.Paragraph paragraph6 = textBox66.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange6 = paragraph6.AppendText(textBox16.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox88  = document.TextBoxes[8];
            Spire.Doc.Documents.Paragraph paragraph8 = textBox88.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange8 = paragraph8.AppendText(textBox19.Text);
            document.SaveToFile(filename, FileFormat.Docx);

            MessageBox.Show("导入成功!");
            this.Close();
        }
Example #59
0
        public override void Execute()
        {
            dte = GetService<DTE>(true);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                //add log file to the parent folder
                if (File.Exists(tempLogFilePath))
                {
                    targetFolder.ProjectItems.AddFromFileCopy(tempLogFilePath);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        private void event_其他程式啟動_選單(List <data_開啟程式> ar)
        {
            M.but_用外部程式開啟.Click += (sender, e) => {
                u_menu_用外部程式開啟.func_open(M.but_用外部程式開啟);
            };



            u_menu_用外部程式開啟.func_add_menu("檔案右鍵選單", null, () => {
                fun_顯示原生右鍵選單(false);
            });

            u_menu_用外部程式開啟.func_add_menu("開啟檔案位置", null, () => {
                M.fun_用檔案總管開啟目前圖片();
            });

            u_menu_用外部程式開啟.func_add_menu("列印", null, () => {
                try {
                    var pr = new System.Diagnostics.Process();
                    pr.StartInfo.FileName       = M.ar_path[M.int_目前圖片位置];//文件全稱-包括文件後綴
                    pr.StartInfo.CreateNoWindow = true;
                    pr.StartInfo.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Hidden;
                    pr.StartInfo.Verb           = "Print";
                    pr.Start();
                } catch (Exception e2) {
                    MessageBox.Show("找不到對應開啟的程式:\n" + e2.ToString(), "列印失敗");
                }
            });

            u_menu_用外部程式開啟.func_add_menu("設成桌布", null, () => {
                if (File.Exists(M.ar_path[M.int_目前圖片位置]))   //判別檔案是否存在於對應的路徑
                {
                    try {
                        SystemParametersInfo(20, 1, M.ar_path[M.int_目前圖片位置], 0x1 | 0x2);  //存在成立,修改桌布  (uActuin 20 參數為修改wallpaper
                    } catch (Exception e2) {
                        MessageBox.Show("設定桌布失敗:\n" + e2.ToString(), "失敗");
                    }
                }
            });

            u_menu_用外部程式開啟.func_add_menu("選擇其他程式", null, () => {
                if (File.Exists(M.ar_path[M.int_目前圖片位置]))   //判別檔案是否存在於對應的路徑
                {
                    try {
                        String _path = M.ar_path[M.int_目前圖片位置];
                        Process.Start(new ProcessStartInfo("rundll32.exe")
                        {
                            Arguments        = $"shell32.dll,OpenAs_RunDLL {_path}",
                            WorkingDirectory = Path.GetDirectoryName(_path)
                        });
                    } catch (Exception e2) {
                        MessageBox.Show(e2.ToString(), "Error");
                    }
                }
            });



            u_menu_用外部程式開啟.func_add_水平線();

            if (C_window_AERO.IsWindows10())
            {
                // 3D小畫家
                String s_Paint3D = M.fun_執行檔路徑() + "/data/imgs/icon-Paint3D.png";
                u_menu_用外部程式開啟.func_add_menu_imgPath("3D小畫家", s_Paint3D, () => {
                    if (File.Exists(M.ar_path[M.int_目前圖片位置]))   //判別檔案是否存在於對應的路徑
                    {
                        try {
                            System.Diagnostics.Process.Start("mspaint", '"' + M.ar_path[M.int_目前圖片位置] + '"' + " /ForceBootstrapPaint3D");
                        } catch (Exception e2) {
                            MessageBox.Show(e2.ToString(), "失敗");
                        }
                    }
                });

                // win10相片 APP
                String s_photos = M.fun_執行檔路徑() + "/data/imgs/icon-photos.png";
                u_menu_用外部程式開啟.func_add_menu_imgPath("相片 APP", s_photos, () => {
                    if (File.Exists(M.ar_path[M.int_目前圖片位置]))   //判別檔案是否存在於對應的路徑
                    {
                        try {
                            String url_path = Uri.EscapeDataString(M.ar_path[M.int_目前圖片位置]);
                            System.Diagnostics.Process.Start("ms-photos:viewer?fileName=" + url_path);
                        } catch (Exception e2) {
                            MessageBox.Show(e2.ToString(), "失敗");
                        }
                    }
                });
            }



            //使用者自定的名單
            for (int i = 0; i < ar.Count; i++)
            {
                int          xx  = i;
                BitmapSource img = null;
                try {
                    img = M.c_影像.BitmapToBitmapSource(ar[i].img);
                } catch { }

                u_menu_用外部程式開啟.func_add_menu(ar[i].name, img, () => {
                    try {
                        System.Diagnostics.Process.Start(ar[xx].path, "\"" + M.ar_path[M.int_目前圖片位置] + "\"");
                    } catch (Exception e2) {
                        MessageBox.Show(e2.ToString());
                    }
                });
            }//for
        }