public static void Run() { try { LogMessage.DisableStumblingDialogs = ProgramRoutines.IsParameterSet(CommandLineParameters.AUTOMATIC); Log.MODE = Log.Mode.ONLY_LOG; LogMessage.Output2Console = true; ProcessRoutines.RunSingleProcessOnly(); LogMessage.Inform(MessageMark.STARTED + " \r\nCommand line: " + string.Join("|", Environment.GetCommandLineArgs()) + " \r\nRunning as:" + System.Security.Principal.WindowsIdentity.GetCurrent().Name); Assembly service_assembly = Assembly.GetEntryAssembly(); List <Type> service_types = (from t in service_assembly.GetExportedTypes() where t.IsSubclassOf(typeof(Service)) select t).ToList(); if (service_types.Count < 1) { LogMessage.Exit("Could not find Service implementation in the entry assembly: " + service_assembly.FullName); } if (service_types.Count > 1) { LogMessage.Exit("Found more than one Service implementations in the entry assembly: " + service_assembly.FullName); } Service service = (Service)Activator.CreateInstance(service_types[0]); service.Do(); service.complete(); } catch (Exception e) { LogMessage.Exit(e); } }
public static void Main(string[] args) { try { //Wpf.Message.ResourceDictionaryPath = "assembly=" + System.Reflection.Assembly.GetEntryAssembly().EscapedCodeBase + ";resources/style.xaml"; //Uri u = new System.Uri("/" + PathRoutines.GetFileNameFromPath(System.Reflection.Assembly.GetEntryAssembly().EscapedCodeBase) + ";component/resources/style.xaml", System.UriKind.Relative); //System.Windows.ResourceDictionary rd = new System.Windows.ResourceDictionary(); //System.Windows.Application.LoadComponent(rd, u); //Wpf.Message.ResourceDictionary = rd; //System.Windows.Resources.StreamResourceInfo info = System.Windows.Application.GetContentStream(u); //System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader(); //Wpf.Message.ResourceDictionary = (System.Windows.ResourceDictionary)reader.LoadAsync(info.Stream); Log.Main.Inform("Version: " + AssemblyRoutines.GetAppVersion()); string user = ProcessRoutines.GetProcessUserName(); string m = "User: "******" (as administrator)"; } Log.Main.Inform(m); ProcessRoutines.RunSingleProcessOnly(); if (ProgramRoutines.IsParameterSet <CommandLineParameters>(CommandLineParameters.INITIAL_CONFIGURATION)) { Message.Inform("Please configure service in the next window."); SettingsWindow.OpenDialog(); return; } #if !test Application.Run(SysTray.This); #else UiApiClient.testCreateInstanceContext(); SettingsWindow.Open(); Application.Run(SysTray.This); //UiApiClient.testSubscribe(); //UiApiClient.testSubscribe(); //Thread.Sleep(1000); //UiApiClient.testCloseInstanceContext(); //UiApiClient.testCreateInstanceContext(); //UiApiClient.testSubscribe(); //UiApiClient.testSubscribe(); //for (; ; ) //{ // System.Threading.Thread.Sleep(10000); //} #endif } catch (Exception e) { LogMessage.Error(e); } finally { Exit(); } }
public static void Run() { try { if (ProgramRoutines.IsParameterSet(CommandLineParameters.WINDOWLESS)) { Cliver.Bot.Program.Run(); return; } LogMessage.Output2Console = false; Cliver.Bot.Program.Initialize(); if (Bot.Properties.App.Default.SingleProcessOnly) { ProcessRoutines.RunSingleProcessOnly(); } Application.Run(MainForm.This); } catch (Exception e) { LogMessage.Exit(e); } }
public static void Stop() { if (mpeg_stream_process != null) { Log.Main.Inform("Terminating:\r\n" + commandLine); ProcessRoutines.KillProcessTree(mpeg_stream_process.Id); mpeg_stream_process = null; } ProcessRoutines.AntiZombieTracker.This.KillTrackedProcesses();//to close the job object commandLine = null; }
virtual public void HelpRequest() { try { ProcessRoutines.Open(Settings.Constants.HelpFile); } catch (Exception ex) { Log.Error(ex); Message.Error(ex, TemplateForm); } }
public static void Main() { try { ProcessRoutines.RunSingleProcessOnly(); SysTrayForm.This.Hide(); Cliver.Bot.ThreadLog.MaxFileSize = Properties.Settings.Default.LogFileChunkSizeInBytes; Application.Run(); } catch (Exception e) { LogMessage.Error(e); } }
static public void StartStopService(bool start) { lock (instanceContext) { try { //if(!WindowsUserRoutines.CurrentUserHasElevatedPrivileges()) if (!ProcessRoutines.ProcessHasElevatedPrivileges() && !ProcessRoutines.ProcessIsSystem() /*used for configuration during installing*/) { if (Message.YesNo("This action requires elevated privileges. Would you like to restart this application 'As Administrator'?")) { ProcessRoutines.Restart(true); } return; } double timeoutSecs = 20; using (ServiceController serviceController = new ServiceController(Cliver.CisteraScreenCaptureService.Program.SERVICE_NAME)) { if (start) { serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(timeoutSecs)); if (serviceController.Status != ServiceControllerStatus.Running) { Message.Error("Could not start service '" + Cliver.CisteraScreenCaptureService.Program.SERVICE_NAME + "' within " + timeoutSecs + " secs."); } } else { serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(timeoutSecs)); if (serviceController.Status != ServiceControllerStatus.Stopped) { Message.Error("Could not stop service '" + Cliver.CisteraScreenCaptureService.Program.SERVICE_NAME + "' within " + timeoutSecs + " secs."); } } } } catch (Exception ex) { LogMessage.Error(ex); } finally { } } }
static void stop() { lock (lockObject) { if (mpeg_stream_process != null) { if (!mpeg_stream_process.HasExited) { Log.Main.Inform("Terminating:\r\n" + commandLine); ProcessRoutines.KillProcessTree(mpeg_stream_process.Id); } mpeg_stream_process = null; } antiZombieGuard.KillTrackedProcesses(); } }
static void start() { lock (lockObject) { if (mpeg_stream_process != null && !mpeg_stream_process.HasExited) { Log.Main.Warning("The previous MpegStream was not stopped!"); } stop(); uint processId = ProcessRoutines.CreateProcessAsUserOfCurrentProcess(sessionId, commandLine, dwCreationFlags); mpeg_stream_process = Process.GetProcessById((int)processId); if (mpeg_stream_process == null) { throw new Exception("Could not find process #" + processId); } if (mpeg_stream_process.HasExited) { throw new Exception("Process #" + processId + " exited with code: " + mpeg_stream_process.ExitCode); } antiZombieGuard.KillTrackedProcesses(); antiZombieGuard.Track(mpeg_stream_process); mpeg_stream_process.EnableRaisingEvents = true; mpeg_stream_process.Exited += delegate(object sender, EventArgs e) { lock (lockObject) { if (commandLine != null && (Process)sender == mpeg_stream_process) { restart_count++; if (restart_count <= 3) { Log.Main.Warning("!!!Terminated by unknown reason:\r\n" + commandLine + "\r\n. Restarting..."); start(); } else { Log.Main.Error("!!!Terminated by unknown reason and could not be restarted:\r\n" + commandLine); TcpServer.NotifyServerOnError("ffmpeg terminated by unknown reason and could not be restarted."); } } } }; } }
public static void Main(string[] args) { try { ProcessRoutines.RunSingleProcessOnly(); Application.Run(new MainForm()); } catch (Exception e) { Message.Error(e); } finally { Environment.Exit(0); } }
SettingsWindow() { InitializeComponent(); System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(this); Icon = AssemblyRoutines.GetAppIconImageSource(); ContentRendered += delegate { //this.MinHeight = this.ActualHeight; //this.MaxHeight = this.ActualHeight; //this.MinWidth = this.ActualWidth; }; WpfRoutines.AddFadeEffect(this, 300); WindowStartupLocation = WindowStartupLocation.CenterScreen; //WindowStartupLocation = WindowStartupLocation.CenterScreen; //DefaultServerIp.ValueDataType = typeof(IPAddress); general = UiApiClient.GetServiceSettings(); if (general == null) { ok.IsEnabled = false; reset.IsEnabled = false; Message.Error("The service is unavailable."); return; } set(); if (!ProcessRoutines.ProcessHasElevatedPrivileges() && !ProcessRoutines.ProcessIsSystem() /*used for configuration during installing*/) { ok.IsEnabled = false; reset.IsEnabled = false; if (Message.YesNo("Settings modification requires elevated privileges. Would you like to restart this application 'As Administrator'?")) { ProcessRoutines.Restart(true); } } }
public static void Stop() { if (mpeg_stream_process != null) { Log.Main.Inform("Terminating:\r\n" + commandLine); ProcessRoutines.KillProcessTree(mpeg_stream_process.Id); mpeg_stream_process = null; } if (fileStream != null) { fileStream.Flush(); fileStream.Dispose(); fileStream = null; } if (antiZombieTracker != null) { antiZombieTracker.KillTrackedProcesses(); antiZombieTracker = null; } commandLine = null; }
public ProjectInstaller() { InitializeComponent(); this.Committed += delegate { //try //{ //starts for initial configuration under SYSTEM account Process p = Process.Start(Assembly.GetExecutingAssembly().Location, "-initial_configuration"); p.WaitForExit(); ProcessRoutines.CreateProcessAsUserOfCurrentSession(Assembly.GetExecutingAssembly().Location); //starts the process as the current user while the installer runs as SYSTEM //} //catch (Exception ex) //{ // //Message.Error(ex);//brings to an error: object is null // MessageBox.Show(); //} }; this.BeforeUninstall += delegate { //try //{ foreach (Process p in Process.GetProcessesByName(PathRoutines.GetFileNameWithoutExtentionFromPath(Assembly.GetExecutingAssembly().Location))) { ProcessRoutines.KillProcessTree(p.Id); } //} //catch (Exception e) //{ // //Message.Error(ex);//brings to an error: object is null // MessageBox.Show(); // //throw e;//to stop uninstalling(?) //} }; }
static void Main() { try { Log.Main.Inform("Version: " + AssemblyRoutines.GetAppVersion()); string user = ProcessRoutines.GetProcessUserName(); string m = "User: "******" (as administrator)"; } Log.Main.Inform(m); #if !test ServiceBase.Run(new Service()); #else MpegStream.Start(1, "-f gdigrab -framerate 10 -f rtp_mpegts -srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params aMg7BqN047lFN72szkezmPyN1qSMilYCXbqP/sCt srtp://127.0.0.1:5920"); //Service.sessionChanged(1, true); //System.Threading.Thread.Sleep(1000000); //s.Stop //MpegStream.Start(1, ""); UserSessionApi.OpenApi(); UiApi.OpenApi(); ServiceControllerStatus scs = ServiceControllerStatus.Running; for (; ;) { System.Threading.Thread.Sleep(10000); UiApi.Message(MessageType.INFORM, "test"); scs = scs == ServiceControllerStatus.Running ? ServiceControllerStatus.Stopped : ServiceControllerStatus.Running; } #endif } catch (Exception e) { Log.Main.Error(e); } }
public static void Main(string[] args) { try { uint dwSessionId = WinApi.Wts.WTSGetActiveConsoleSessionId(); MpegStream.Start(dwSessionId, "-f gdigrab -framerate 10 -f rtp_mpegts -srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params aMg7BqN047lFN72szkezmPyN1qSMilYCXbqP/sCt srtp://127.0.0.1:5920"); //Process mpeg_stream_process; //var processId = Win32Process.CreateProcessInConsoleSession("cmd"); //mpeg_stream_process = Process.GetProcessById((int)processId); //ProcessRoutines.AntiZombieTracker.Track(mpeg_stream_process); // try // { // var p = new Process(); // p.StartInfo.UseShellExecute = false; // //const string file = "cmd.exe"; // const string file = @"psexec.exe"; // p.StartInfo.WorkingDirectory = Path.GetDirectoryName(file); // p.StartInfo.FileName = Path.GetFileName(file); // //proc.StartInfo.Domain = "WIN08"; // p.StartInfo.Arguments = "-i -d -s cmd"; // //p.StartInfo.UserName = "******"; // //var password = new System.Security.SecureString(); // //foreach (var c in "123") // // password.AppendChar(c); // //p.StartInfo.Password = password; // p.StartInfo.LoadUserProfile = false; // p.Start(); // } // catch (Exception e) // { // Console.WriteLine(e); // } //MpegStream.Start("-f gdigrab -framerate 10 -f rtp_mpegts -srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params aMg7BqN047lFN72szkezmPyN1qSMilYCXbqP/sCt srtp://127.0.0.1:5920"); //Thread.Sleep(2000); //MpegStream.Stop(); Log.Main.Inform("Version: " + AssemblyRoutines.GetAppVersion()); string m = "User: "******"("; if (WindowsUserRoutines.CurrentUserIsAdministrator()) { m += "administrator"; if (WindowsUserRoutines.CurrentUserHasElevatedPrivileges()) { m += ", elevated privileges"; } else { m += ", not elevated privileges"; } } else { m += "not administrator"; } Log.Main.Inform(m + ")"); ProcessRoutines.RunSingleProcessOnly(); Service.Running = true; Application.Run(SysTray.This); } catch (Exception e) { Message.Error(e); } finally { Environment.Exit(0); } }
public static void Start(uint sessionId, string arguments) { lock (lockObject) { restart_count = 0; MpegStream.sessionId = sessionId; if (sessionId < 1) { throw new Exception("sessionId == " + sessionId); } //if (string.IsNullOrWhiteSpace(Settings.General.CapturedMonitorDeviceName)) //{ // Settings.General.CapturedMonitorDeviceName = MonitorRoutines.GetDefaultMonitorName(); // if (string.IsNullOrWhiteSpace(Settings.General.CapturedMonitorDeviceName)) // throw new Exception("No monitor was found."); //} //WinApi.User32.RECT? an = MonitorRoutines.GetMonitorAreaByMonitorName(Settings.General.CapturedMonitorDeviceName); //if (an == null) //{ // string defaultMonitorName = MonitorRoutines.GetDefaultMonitorName(); // Log.Main.Warning("Monitor '" + Settings.General.CapturedMonitorDeviceName + "' was not found. Using default one '" + defaultMonitorName + "'"); // Settings.General.CapturedMonitorDeviceName = defaultMonitorName; // an = MonitorRoutines.GetMonitorAreaByMonitorName(Settings.General.CapturedMonitorDeviceName); // if (an == null) // throw new Exception("Monitor '" + Settings.General.CapturedMonitorDeviceName + "' was not found."); //} string source; if (Settings.General.CapturedMonitorDeviceName == null || Settings.General.CapturedMonitorDeviceName == Settings.GeneralSettings.CapturedMonitorDeviceName_ALL_DISPLAYS) { source = " -i desktop "; } else { if (Settings.General.CapturedMonitorRectangle == null) { Log.Main.Inform("CapturedMonitorRectangle is empty. Running " + userSessionAgent); UserSessionApi.OpenApi(); WinApi.Advapi32.CreationFlags cfs = 0; cfs |= WinApi.Advapi32.CreationFlags.CREATE_NO_WINDOW; string cl = "\"" + Log.AppDir + "\\" + userSessionAgent + "\""; uint pid = ProcessRoutines.CreateProcessAsUserOfCurrentProcess(sessionId, cl, cfs); Process p = Process.GetProcessById((int)pid); if (p != null && !p.HasExited) { p.WaitForExit(); } UserSessionApi.CloseApi(); Settings.General.Reload(); if (Settings.General.CapturedMonitorRectangle == null) { throw new Exception("Could not get rectangle for monitor '" + Settings.General.CapturedMonitorDeviceName + "'"); } //if (Settings.General.CapturedMonitorRectangle == null) // throw new Exception("Could not get rectangle for monitor '" + Settings.General.CapturedMonitorDeviceName + "'. Properly edit and save monitor setting in the systray menu."); } WinApi.User32.RECT a = (WinApi.User32.RECT)Settings.General.CapturedMonitorRectangle; source = " -offset_x " + a.Left + " -offset_y " + a.Top + " -video_size " + (a.Right - a.Left) + "x" + (a.Bottom - a.Top) + " -show_region 1 -i desktop "; } arguments = Regex.Replace(arguments, @"-framerate\s+\d+", "$0" + source); commandLine = "\"" + Log.AppDir + "\\ffmpeg.exe\" " + arguments; dwCreationFlags = 0; if (!Settings.General.ShowMpegWindow) { dwCreationFlags |= WinApi.Advapi32.CreationFlags.CREATE_NO_WINDOW; //startupInfo.dwFlags |= Win32Process.STARTF_USESTDHANDLES; //startupInfo.wShowWindow = Win32Process.SW_HIDE; } if (Settings.General.WriteMpegOutput2Log) { string file0 = Log.WorkDir + "\\ffmpeg_" + DateTime.Now.ToString("yyMMddHHmmss"); string file = file0; for (int count = 1; File.Exists(file); count++) { file = file0 + "_" + count.ToString(); } file += ".log"; File.WriteAllText(file, @"STARTED AT " + DateTime.Now.ToString() + @": >" + commandLine + @" ", Encoding.UTF8); FileSecurity fileSecurity = File.GetAccessControl(file); FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.AppendData, AccessControlType.Allow); fileSecurity.AddAccessRule(fileSystemAccessRule); File.SetAccessControl(file, fileSecurity); commandLine = Environment.SystemDirectory + "\\cmd.exe /c \"" + commandLine + " 1>>\"" + file + "\",2>&1\""; } start(); } }
void save(object sender, EventArgs e) { try { ushort v; //if (!ushort.TryParse(ServerDefaultPort.Text, out v)) // throw new Exception("Server port must be an integer between 0 and " + ushort.MaxValue); //general.TcpClientDefaultPort = v; if (string.IsNullOrWhiteSpace(ServerDefaultIp.Text)) { throw new Exception("Default server ip is not specified."); } IPAddress ia; if (!IPAddress.TryParse(ServerDefaultIp.Text, out ia)) { throw new Exception("Default server ip is not a valid value."); } general.TcpClientDefaultIp = ia.ToString(); if (!ushort.TryParse(ClientPort.Text, out v)) { throw new Exception("Client port must be an between 0 and " + ushort.MaxValue); } general.TcpServerPort = v; if (string.IsNullOrWhiteSpace(ServiceDomain.Text)) { throw new Exception("Service domian is not specified."); } general.ServiceDomain = ServiceDomain.Text.Trim(); if (string.IsNullOrWhiteSpace(ServiceType.Text)) { throw new Exception("Service type is not specified."); } general.ServiceType = ServiceType.Text.Trim(); if (Monitors.SelectedIndex < 0) { throw new Exception("Captured Video Source is not specified."); } general.CapturedMonitorDeviceName = (string)Monitors.SelectedValue; general.ShowMpegWindow = ShowMpegWindow.IsChecked ?? false; general.WriteMpegOutput2Log = WriteMpegOutput2Log.IsChecked ?? false; //general.CapturedMonitorRectangle = MonitorRoutines.GetMonitorAreaByMonitorName(general.CapturedMonitorDeviceName); //if (general.CapturedMonitorRectangle == null) // throw new Exception("Could not get rectangle for monitor '" + general.CapturedMonitorDeviceName + "'"); general.CapturedMonitorRectangle = null; general.DeleteLogsOlderDays = int.Parse(DeleteLogsOlderDays.Text); UiApiClient.SaveServiceSettings(general); if (Settings.View.DeleteLogsOlderDays != general.DeleteLogsOlderDays) { Settings.View.DeleteLogsOlderDays = general.DeleteLogsOlderDays; Settings.View.Save(); } System.ServiceProcess.ServiceControllerStatus?status = UiApiClient.GetServiceStatus(); if (status != null && status != System.ServiceProcess.ServiceControllerStatus.Stopped && (ProcessRoutines.ProcessIsSystem() ||/*used for configuration during installing*/ Message.YesNo("The changes have been saved and will be engaged after service restart. Would you like to restart the service (all the present connections if any, will be terminated)?") ) ) { MessageForm mf = null; ThreadRoutines.StartTry(() => { mf = new MessageForm(System.Windows.Forms.Application.ProductName, System.Drawing.SystemIcons.Information, "Resetting the service. Please wait...", null, 0, null); mf.ShowDialog(); }); UiApiClient.StartStopService(false); UiApiClient.StartStopService(true); if (null == SleepRoutines.WaitForObject(() => { return(mf); }, 1000)) { throw new Exception("Could not get MessageForm"); } mf.Invoke(() => { mf.Close(); }); } Close(); } catch (Exception ex) { Message.Exclaim(ex.Message); } }