Exemple #1
0
 internal static bool runShellCommand(string command) {
     System.Diagnostics.Process p = new System.Diagnostics.Process {
         StartInfo = new System.Diagnostics.ProcessStartInfo {
             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
             FileName = "cmd.exe",
             Arguments = (@"CMD /C " + command)
         }
     };
     p.Start();
     p.WaitForExit(5000);
     if (p.HasExited == false) { //Check to see if the process is still running.
         if (p.Responding) {//Test to see if the process is hung up.
             p.CloseMainWindow();//Process was responding; close the main window.
             return false;
         } else {
             p.Kill(); //Process was not responding; force the process to close.
             return false;
         }
     }
     return true;
 }
Exemple #2
0
        private void ConvertToStream(string fileUrl)
        {
            try
            {
                Thread waitThread = new Thread(() =>
                {
                    PleaseWaitWindow wait = new PleaseWaitWindow();

                    wait.ShowDialog();
                    // wait.LoadingAdorner.IsAdornerVisible = true;
                    wait.Close();
                });
                waitThread.SetApartmentState(ApartmentState.STA);
                waitThread.Start();
            }

            catch
            {
            }

            System.Threading.Thread.Sleep(2000);

            try
            {
                //  ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(fileUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();



                var    theStream = new object();
                string fileName  = AppDomain.CurrentDomain.BaseDirectory + "Printings" + @"\toPrint.pdf";


                using (var stream = File.Create(fileName))
                {
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    response.GetResponseStream().CopyTo(stream);
                }

                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(fileName);
                int numberOfPages = pdfReader.NumberOfPages;

                if (GlobalCounters.numberOfCurrentPrintings + numberOfPages <= Convert.ToInt32("6"))
                {
                    try
                    {
                        // this.log.Info("Invoking Action: ViewPrintRequested " + numberOfPages.ToString() + " pages.");
                    }
                    catch
                    { }

                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                    info.UseShellExecute = true;
                    info.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
                    info.Verb            = "print";
                    info.FileName        = fileName;
                    info.CreateNoWindow  = true;


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

                    p.WaitForInputIdle();
                    p.CloseMainWindow();

                    /*  if (numberOfPages < Int32.Parse(this.numberOfAvailabelPagesToPrint))
                     * {
                     *    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(numberOfPages));
                     * }
                     * else
                     * {
                     *    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
                     * }*/
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(6));

                    if (false == p.CloseMainWindow())
                    {
                        try
                        {
                            p.Kill();
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            p.Kill();
                        }
                        catch { }
                    }

                    try
                    {
                        //  this.sender.SendAction("Printed " + numberOfPages + " pages.");
                    }
                    catch { }
                    GlobalCounters.numberOfCurrentPrintings += numberOfPages;
                }

                else
                {
                    System.Windows.MessageBox.Show("Unfortunately, you can not print so many pages! Please press OK to continue.");
                }
            }
            catch
            {
            }
            finally
            {
                //response.Close();
            }
        }
Exemple #3
0
 public void Close()
 {
     _proc.CloseMainWindow();
 }
Exemple #4
0
        private void ConvertToStream(string fileUrl)
        {
            try
            {
                this.events.PublishOnUIThread(new ViewStartPrintProgressCommand());
            }

            catch (Exception ex)
            {
                this.log.Info("InvokingAction: ViewException " + ex.ToString());
            }

            System.Threading.Thread.Sleep(3000);

            try {
                ServicePointManager
                .ServerCertificateValidationCallback +=
                    (sender, cert, chain, sslPolicyErrors) => true;

                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(fileUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();



                var    theStream = new object();
                string fileName  = AppDomain.CurrentDomain.BaseDirectory + "Printings" + @"\toPrint.pdf";


                using (var stream = File.Create(fileName))
                {
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    response.GetResponseStream().CopyTo(stream);
                }

                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(fileName);
                int numberOfPages = pdfReader.NumberOfPages;

                if (GlobalCounters.numberOfCurrentPrintings + numberOfPages <= Convert.ToInt32(this.numberOfAvailabelPagesToPrint))
                {
                    try
                    {
                        this.log.Info("Invoking Action: ViewPrintRequested " + numberOfPages.ToString() + " pages.");
                    }
                    catch
                    { }

                    try
                    {
                        TaskbarManager.HideTaskbar();
                    }
                    catch { }

                    try
                    {
                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                        info.UseShellExecute = true;
                        info.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
                        info.Verb            = "print";
                        info.FileName        = fileName;
                        info.CreateNoWindow  = true;


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

                        p.WaitForExit();
                        p.CloseMainWindow();


                        if (false == p.CloseMainWindow())
                        {
                            try
                            {
                                p.Kill();
                            }
                            catch { }
                        }
                        else
                        {
                            try
                            {
                                p.Kill();
                            }
                            catch { }
                        }
                    }
                    catch { }

                    GlobalCounters.numberOfCurrentPrintings += numberOfPages;

                    try
                    {
                        TaskbarManager.HideTaskbar();
                    }
                    catch { }

                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(6));

                    try
                    {
                        TaskbarManager.HideTaskbar();
                    }
                    catch { }



                    try
                    {
                        this.sender.SendAction("Printed " + numberOfPages + " pages.");
                    }
                    catch { }
                }

                else
                {
                    System.Windows.MessageBox.Show("Unfortunately, you can not print so many pages! Please press OK to continue.");
                }
            }
            catch (Exception ex)
            {
                this.log.Info("InvokingAction: ViewException " + ex.ToString());
            }
            finally
            {
            }
        }
Exemple #5
0
        /// <summary>
        /// Asynchronous RunScript method. Instead of blocking until the script is finished, this method
        /// takes three methods that are called with the output of the script as it's being read as well
        /// as one with the exit code once the script has finished.
        /// </summary>
        /// <param name="startInfo">Process start configuration (note that UseShellExecute, RedirectStandardOutput and RedirectStandardError will be overwritten)</param>
        /// <param name="input">Input written to the script's standard input (or null)</param>
        /// <param name="onOutput">Method called with each output line</param>
        /// <param name="onError">Method called with each error line</param>
        /// <param name="onExit">Method called with the exit code</param>
        /// <returns>A callback that can be used to stop the script (parameter: false = terminate, true = kill)</returns>
        public static Action <bool> RunScriptAsnyc(System.Diagnostics.ProcessStartInfo startInfo, string input, Action <string> onOutput, Action <string> onError, Action <int> onExit)
        {
            var scriptName = Path.GetFileName(startInfo.FileName);

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

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

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

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

            try {
                script.Start();

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

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

            return((kill) => {
                if (script.HasExited)
                {
                    return;
                }
                if (kill)
                {
                    script.Kill();
                }
                else
                {
                    script.CloseMainWindow();
                }
            });
        }
Exemple #6
0
        /// <summary>
        /// Instantiate a new process to execute the application in the given path.
        /// This is used primary to install/uninstall individual keyboard msi builds.
        /// </summary>
        /// <param name="path">The path to the application to install</param>
        /// <param name="arg">Arguments to pass to the application</param>
        /// <param name="wait">Wait for the process to complete before returning.</param>
        private void ExecProc(string path, string arg, bool wait)
        {
            //create the process instance to execute the application.
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = true;
            proc.Exited += new EventHandler(proc_Exited);
            proc.StartInfo.FileName = path;
            proc.StartInfo.Arguments = arg;
            proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            this.WindowState = FormWindowState.Minimized;
            proc.Start();

            //wait for the process to finish.
            if (wait == true)
            {
                proc.WaitForExit();
                if (proc.HasExited == false)
                    proc.CloseMainWindow();
            }
        }
        public async Task RunAsync(string url)
        {
            var querystringData = new Dictionary <string, string>();

            querystringData.Add("AppVersion", "" + Program.DaneAplikacji.VersionOfApp);
            if (Program.DaneAplikacji.CurrentUserName != "incognito")
            {
                querystringData.Add("OS_UserName", System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                Program.DaneAplikacji.CurrentUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
            var connection = new HubConnection(url, querystringData);

            //connection.TraceWriter = _traceWriter;

            _hubProxy = connection.CreateHubProxy("MyHub1");

            _hubProxy.On <string[]>("clientMessage", (data) =>
            {
                //_traceWriter.WriteLine(data[0] + ": " + data[1]);
                Program.chatMessage(data[0] + ": " + data[1]);
            });

            _hubProxy.On <RunExe>("runExe", (data) =>
            {
                //RunExe data = JsonConvert.DeserializeObject<RunExe>(json);
                process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                if (data.HideOpenedFile)
                {
                    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                }
                //startInfo.Arguments = data.Arguments;

                if (data.UserName == Program.DaneAplikacji.Admin || Program.DaneAplikacji.Admin == "admin")
                {
                    Program.serverMessage("Uruchamianie " + data.Path + " przez admina " + data.UserName + " z nastepujacymi argumentami: '" + data.Arguments + "'. " + (data.HideOpenedFile ? "Plik bedzie ukryty." : ""));
                    try
                    {
                        startInfo.FileName  = data.Path;
                        startInfo.Arguments = data.Arguments;
                        process             = System.Diagnostics.Process.Start(startInfo);
                    }
                    catch (Exception e)
                    {
                        _hubProxy.Invoke("serverMessage", "Proba uruchomienia " + data.Path + " przez " + data.UserName + " nie udała się. Błąd: " + e.Message);
                    }
                    if (data.ThenCloseLauncher)
                    {
                        _hubProxy.Invoke("serverMessage", "Melduje wykonanie zadania :] Launcher zostanie zamkniety za 0.5 sec.");
                        System.Threading.Thread.Sleep(1000);
                        System.Environment.Exit(1);
                    }
                }
                else
                {
                    Program.serverMessage(data.UserName + " probowal uruchomic plik " + data.Path + ". Nie ma do tego uprawnien.");
                    _hubProxy.Invoke("serverMessage", data.UserName + " probowal uruchomic plik " + data.Path + ". Nie ma do tego uprawnien.");
                }
            });

            _hubProxy.On <string>("closeExe", (data) =>
            {
                if (data == Program.DaneAplikacji.Admin || Program.DaneAplikacji.Admin == "admin")
                {
                    Program.serverMessage("Zamykanie pliku przez" + data);
                    try
                    {
                        process.CloseMainWindow();
                        process.Close();
                    }
                    catch (Exception e)
                    {
                        _hubProxy.Invoke("serverMessage", "Proba zamkniecia ostatnio otwartej aplikacji przez " + data[0] + " nie udała się. Błąd: " + e.Message);
                    }
                }
            });

            _hubProxy.On <CreateFile>("createFile", (data) =>
            {
                //CreateFile data = JsonConvert.DeserializeObject<CreateFile>(json);
                //string path = @"E:\AppServ\Example.txt";
                try
                {
                    if (data.UserName == Program.DaneAplikacji.Admin || Program.DaneAplikacji.Admin == "admin")
                    {
                        if (!File.Exists(data.Path))
                        {
                            File.Create(data.Path).Close();
                            TextWriter tw = new StreamWriter(data.Path);
                            tw.WriteLine(data.Content);
                            tw.Close();
                        }
                        else if (File.Exists(data.Path))
                        {
                            TextWriter tw = new StreamWriter(data.Path, false);
                            tw.WriteLine(data.Content);
                            tw.Close();
                        }
                        _hubProxy.Invoke("serverMessage", data.UserName + " utworzył nowy plik o sciezce: '" + data.Path + "' i zawartosci: '" + data.Content + "' u uzytkownika: " + Program.DaneAplikacji.CurrentUserName);
                    }
                    else
                    {
                        _hubProxy.Invoke("serverMessage", data.UserName + " nie ma uprawnien do utworzenia nowego pliku u uzytkownika " + Program.DaneAplikacji.CurrentUserName);
                    }
                }
                catch (Exception e)
                {
                    _hubProxy.Invoke("serverMessage", "Nie mozna utworzyc pliku. Blad: " + e.Message);
                }
            });

            _hubProxy.On <string>("serverResponse", (data) =>
            {
                //_traceWriter.WriteLine("***Odpowiedz z serwera: " + data);
                Program.serverMessage("***Odpowiedz z serwera: " + data);
            });

            _hubProxy.On <string>("someoneAsksToBeAdmin", (data) =>
            {
                Program.serverMessage("*************************");
                Program.serverMessage(data + " chce byc adminem. Admin moze uruchamiac skrypt na twoim komputerze. Wpisz 'tak' jesli tego chcesz, inna odpowiedz odrzuci pytanie");
                //Program.command = "";
                string wantsToBeAdmin = Console.ReadLine();
                if (wantsToBeAdmin == "tak")
                {
                    Program.DaneAplikacji.Admin = data;
                    Program.serverMessage(data + " zostal adminem");
                    _hubProxy.Invoke("notifyUserHeBecomeAdmin", Program.DaneAplikacji.Admin);
                }
                else
                {
                    Program.serverMessage("Odrzucono");
                }
                Program.serverMessage("*************************");
            });

            _hubProxy.On <string>("youveBecomeAdmin", (data) =>
            {
                _traceWriter.WriteLine(data + " zaakceptowal cie jako admina");
            });

            await connection.Start();

            //await _hubProxy.Invoke("serverMessage", "***New Computer connected");
        }