static void doCallback(Action <IUiApiCallback> mi) { ThreadRoutines.StartTry(() => { lock (uiApiCallbacks) { List <IUiApiCallback> dead_uacs = new List <IUiApiCallback>(); foreach (IUiApiCallback uiApiCallback in uiApiCallbacks) { try { mi(uiApiCallback); } catch (System.ServiceModel.CommunicationObjectAbortedException e) { //Log.Main.Warning2(e); dead_uacs.Add(uiApiCallback); } catch (Exception e) { Log.Main.Warning(e); dead_uacs.Add(uiApiCallback); } } foreach (IUiApiCallback dead_uac in dead_uacs) { uiApiCallbacks.Remove(dead_uac); } } }); }
static void Log_usage_example() { try { Log.Initialize(Log.Mode.EACH_SESSION_IS_IN_OWN_FORLDER); Log.Inform("test"); ThreadRoutines.StartTry(() => { Log.Inform0("to default log"); Log.Thread.Inform0("to thread log"); throw new Exception2("test exception2"); }, (Exception e) => { Log.Thread.Error(e); } ); Log.Session s1 = Log.Session.Get("Name1"); //open if not open session "Name1" Log.Writer nl = s1["Name"]; //open if not open log "Name" nl.Error("to log 'Name'"); s1.Trace("to the main log of session 'Name1'"); s1.Thread.Inform("to the thread log of session 'Name1'"); s1.Rename("Name2"); } catch (Exception e) { Log.Error(e); } }
public TcpServerConnection(Socket socket) { this.socket = socket; stream = new NetworkStream(socket); Log.Main.Inform("Starting connection from " + RemoteIp + ":" + RemotePort); thread = ThreadRoutines.StartTry( run, (Exception e) => { if (socket != null && !socket.Connected) { Log.Main.Inform("Socket from " + RemoteIp + ":" + RemotePort + " has been disconnected."); } else { Log.Main.Error(e); } }, () => { ThreadRoutines.StartTry(Dispose); } ); }
//static Dictionary<ushort, TcpServer> servers = new Dictionary<ushort, TcpServer>(); static public void Start(int local_port, IPAddress destination_ip) { if (!NetworkRoutines.IsNetworkAvailable()) throw new Exception("No network available."); IPAddress ipAddress = NetworkRoutines.GetLocalIpForDestination(destination_ip); if (local_port == LocalPort && ipAddress.Equals(LocalIp)) return; Stop(); Log.Main.Inform("Starting TCP listener on " + local_port + " for " + destination_ip); //listeningSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); //listeningSocket.Bind(localEndPoint); ////listeningSocket.Listen(100); server = new TcpListener(ipAddress, local_port); server.Start(); thread = ThreadRoutines.StartTry(run, (Exception e) => { if (e is SocketException) { Log.Main.Warning(e); } else { Log.Main.Error(e); CisteraScreenCaptureService.ExposedEvents.UiMessage.Error(Log.GetExceptionMessage(e)); } Stop(); }); }
public MainForm() { InitializeComponent(); mpegCommandLine.Text = "-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"; state.Text = ""; CreateHandle(); startEnabled = false; stopEnabled = false; ThreadRoutines.StartTry(() => { run_http_service(); }); stateText = "Wating for HTTP request..."; //Bonjour.Start("test", "_cisterascreencapturecontroller._tcp", null, null, 123); FormClosed += delegate { try { listener.Stop(); } catch { } }; }
static void beginKeepAliveServiceConnection() {//it seems to be redundant because of infinite timeout, but sometimes the channel gets closed due to errors lock (instanceContext) { if (keepAliveServiceConnection_t != null && keepAliveServiceConnection_t.IsAlive) { return; } keepAliveServiceConnection_t = ThreadRoutines.StartTry( () => { do { try { lock (instanceContext) { _this.Subscribe(); } Thread.Sleep(Settings.View.ServiceConnectionKeepAlivePulseTimeInMss); } catch (Exception e) { return; } }while (_this != null && _this.State == CommunicationState.Opened && Thread.CurrentThread == keepAliveServiceConnection_t); }, (Exception e) => { LogMessage.Error(e); }, null ); } }
public static void Start(string name) { Task task = new Task(); task.logSession = Log.Session.Get(name); ThreadRoutines.Start(task.download); ThreadRoutines.Start(task.download); }
public static void WaitUntilCheckTime() { long duration = (long)(Process.GetCurrentProcess().StartTime.AddMilliseconds(Properties.Settings.Default.ServiceCheckDurationInMss + 500) - DateTime.Now).TotalMilliseconds; if (duration > 0) { ThreadRoutines.Wait(duration); } }
public TcpServerConnection(Socket socket) { this.socket = socket ?? throw new Exception("socket is null"); stream = new NetworkStream(socket); Log.Main.Inform("Starting connection from " + RemoteIp + ":" + RemotePort); receiving_thread = ThreadRoutines.StartTry( run, (Exception e) => { lock (this) { if (this.socket == null) //disposed { return; } if (!IsAlive) { Log.Main.Inform("Connection from " + RemoteIp + ":" + RemotePort + " has been terminated."); } else { Log.Main.Error(e); } } }, () => { MpegStream.Stop(); ThreadRoutines.StartTry(Dispose); } ); //sending_thread = ThreadRoutines.StartTry( // run, // (Exception e) => // { // lock (this) // { // if (this.socket == null)//disposed // return; // if (!IsAlive) // Log.Main.Inform("Connection from " + RemoteIp + ":" + RemotePort + " has been terminated."); // else // Log.Main.Error(e); // } // }, // () => // { // ThreadRoutines.StartTry(Dispose); // } // ); }
public static InfoWindow Create(string title, string text, string image_url, string action_name, Action action) { lock (lock_object) { InfoWindow w = null; Action a = () => { w = new InfoWindow(title, text, image_url, action_name, action); WindowInteropHelper h = new WindowInteropHelper(w); h.EnsureHandle(); w.Show(); ThreadRoutines.StartTry(() => { Thread.Sleep(Settings.Default.InfoToastLifeTimeInSecs * 1000); w.BeginInvoke(() => { w.Close(); }); }); if (!string.IsNullOrWhiteSpace(Settings.Default.InfoSoundFile)) { SoundPlayer sp = new SoundPlayer(Settings.Default.InfoSoundFile); sp.Play(); } }; lock (ws) { if (dispatcher == null) {//!!!the following code does not work in static constructor because creates a deadlock!!! ThreadRoutines.StartTry(() => { //this window is used to hide notification windows from Alt+Tab panel invisible_owner_w = new Window(); invisible_owner_w.Width = 0; invisible_owner_w.Height = 0; invisible_owner_w.WindowStyle = WindowStyle.ToolWindow; invisible_owner_w.ShowInTaskbar = false; invisible_owner_w.Show(); invisible_owner_w.Hide(); dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; System.Windows.Threading.Dispatcher.Run(); }, null, null, true, ApartmentState.STA); if (!SleepRoutines.WaitForCondition(() => { return(dispatcher != null); }, 3000)) { throw new Exception("Could not get dispatcher."); } } } dispatcher.Invoke(a); return(w); } }
void activate() { //var h = new WindowInteropHelper(this).Handle; //Win32.SendMessage(h, Win32.WM_SYSCOMMAND, (int)Win32.SC_RESTORE, 0); Activate(); Focus(); //if (IntPtr.Zero == Win32.SetForegroundWindow(h)) //Win32.SendMessage(h, Win32.WM_SYSCOMMAND, (int)Win32.SC_RESTORE, 0); ThreadRoutines.StartTry(() => { Win32.SetForegroundWindow(handle); SystemSounds.Beep.Play(); }); }
void connect_socket() { if (socket != null) { if (socket.IsConnectionAlive()) { return; } try { socket.Close(); } finally { socket = null; } if (stream != null) { stream.Close(); } } IPAddress ipAddress = NetworkRoutines.GetLocalIpForDestination(IPAddress.Parse("127.0.0.1")); //IPEndPoint localEndPoint = new IPEndPoint(ipAddress, int.Parse(localTcpPort.Text)); socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); //_Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500) //_Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, Timeout) //socket.Bind(localEndPoint); socket.Connect(remoteHost, int.Parse(remotePort)); stream = new NetworkStream(socket); ThreadRoutines.StartTry(() => { while (socket != null) { Thread.Sleep(5000); poll(); } }); }
static void service() { try { Log.Main.Inform("STATRED"); actual_work = true; while (true) { if (actual_work) { CrawlerService.Run(); manage_services(); } if (actual_work != work) { if (StateChanged != null) { StateChanged.BeginInvoke(work, null, null); } actual_work = work; if (actual_work) { Log.Main.Write(Log.MessageType.INFORM, "STARTED"); } else { Log.Main.Write(Log.MessageType.INFORM, "STOPPED"); } } ThreadRoutines.Wait(Properties.Settings.Default.PollIntervalInMss); //ThreadRoutines.WaitForCondition(() => { if (!work) return work; return null; }, Properties.Settings.Default.PollIntervalInSecs * 1000, 100); } } catch (Exception e) { Log.Main.Error(e); Mailer.Send(db, Log.GetExceptionMessage(e), ReportSourceType.MANAGER, Log.GetExceptionMessage(e)); } if (StateChanged != null) { StateChanged.BeginInvoke(false, null, null); } }
void start_session() { try { set_start_button(true); Environment.CurrentDirectory = Log.AppDir; ip1 = this.listBoxStatus.Handle;//it is gotten here in order that this.InvokeRequired to work correctly listBoxStatus.BackColor = Color.FromKnownColor(KnownColor.Window); clear_status_rows(); DisplayStatus2("Session", "starting..."); DisplayStatus2("Thread Count", "0"); start_session_t = ThreadRoutines.Start(start_session_); /* * Why does InvokeRequired return false when you'd like it to return true? * I’ve seen a number of developers surprised by InvokeRequired returning false in situations when they know it’s a cross thread call. * The reason is that the underlying window handle associated with the control has not been created yet at the time of the call. * Since InvokeRequired is meant to be used with either BeginInvoke or just Invoke, and neither of these methods can succeed until a windows message pump gets associated with the control, it elects to return false. */ IntPtr ip = BotThreadManagerForm.Handle;//that's why handle is gotten here } //catch (ThreadAbortException) //{ // Session.Close(); //} catch (Exception e) { Session.Close(); if (Program.Mode == Program.ProgramMode.AUTOMATIC) { LogMessage.Exit(e); } else { LogMessage.Error(e); } } }
public static void Run() { //default configuration: everything is written to the same file in the same folder: Log.Inform("write out of box"); Log.Thread.Inform("write out of box2"); Log.Head["test"].Inform("write out of box3"); Log.Session.Get("GAME")["client"].Inform("write out of box4"); Log.Session.Get("GAME").Rename("Game"); //a session-less log which will be continued with the next launch of the application Log.Get("history").Inform("session-less log"); //optional initialization. You will like to perform it at the very beginning of the app. Log.Initialize(Log.Mode.FOLDER_PER_SESSION); //trivial usage: everything is written to the same file Log.Inform("write to the default log of the default session"); Log.Inform("Root log folder: " + Log.RootDir); //more sophisticated usage Log.Head["Action1"].Inform0("write to log 'Action1' of the default session"); //writing thread logs to the default session ThreadRoutines.Start(task); ThreadRoutines.Start(task); //writing to an explicitly created session Log.Session logSession_Task = Log.Session.Get("TASK"); //create if not exists logSession_Task.Inform("write to the default log of the session '" + logSession_Task.Name + "'"); Log.Writer log_Task_Subtask = logSession_Task["Subtask"]; //create if not exists log_Task_Subtask.Error("write to log '" + log_Task_Subtask.Name + "' of session '" + logSession_Task.Name + "''"); logSession_Task.Trace("write to the default log of the session '" + logSession_Task.Name + "'"); logSession_Task.Thread.Inform("write to the thread log " + Log.Thread.Id + " of the session '" + logSession_Task.Name + "'"); //sometimes you may need to rename a log session: logSession_Task.Rename("renamed_TASK"); //optional; close the handlers and free memory logSession_Task.Close(false); //writing thread logs to explicitly created sessions Task.Start("TASK1"); Task.Start("TASK2"); }
static public void Start(string service_name, ushort port) { Stop(); #if DEBUG //Name = "*";//works in LAN //Name = "192.168.2.13";//the actual ip works in LAN //Name = "localhost";//not work in LAN //Name = "127.0.0.1";//not work in LAN //Name = "localhos";//some string not work in LAN //Name = "192.168.2.*";//does not start //Name = "127.0.0.1";//not work in LAN Name = "localhost";//not work in LAN #else Name = service_name; Name = "*"; #endif Port = port; t = ThreadRoutines.StartTry(() => { run(); }); }
// --------------------------------------------------------------------------------------------------------------------- public MainWindow() { this.InitializeComponent(); this.Title += $@" ({Util.GetAppVersion()})"; this.foThreadRoutines = new ThreadRoutines(this); this.ReadSettings(); this.foThreadRoutines.UpdateMenusAndControls(true); this.DataContext = this; this.LblCurrentFolder.Content = ThreadRoutines.FILES_CURRENT_LABEL_START; this.tmrRunning.Tick += this.UpdateTimeRunningEvent; this.tmrRunning.Interval = TimeSpan.FromMilliseconds(250); this.SetupPieChart(); }
public static void Start(Route route) { t = ThreadRoutines.Start(() => { try { if (Log.IsMainSessionOpen) { Log.MainSession.Close(); } Log.Initialize(Log.Mode.SESSIONS, null, true, 10, route.Name); c = new Controller(route); c.Start(); } finally { Log.MainSession.Close(); Log.Initialize(Log.Mode.SESSIONS, null, false); } }); }
public static void Run() { //default configuration: everything is written to the same file in the same folder: Log.Inform("write out of box"); Log.Thread.Inform("write out of box2"); Log.Head["test"].Inform("write out of box3"); Log.Session.Get("GAME")["client"].Inform("write out of box4"); Log.Session.Get("GAME").Rename("Game"); //optional; initialize log Log.Initialize(Log.Mode.FOLDER_PER_SESSION);//if permissions allow it, log will be created in the executable directory //trivial usage: everything is written to the same file Log.Inform("write to the default log of the default session"); //more sophisticated usage is below Log.Head["Action1"].Inform0("write to log 'Action1' of the default session"); //writing thread logs to the default session ThreadRoutines.Start(task); ThreadRoutines.Start(task); //writing to an explicitly created session Log.Session logSession_Task = Log.Session.Get("TASK"); //create if not exists logSession_Task.Inform("write to the default log of the session '" + logSession_Task.Name + "'"); Log.Writer log_Task_Subtask = logSession_Task["Subtask"]; //create if not exists log_Task_Subtask.Error("write to log '" + log_Task_Subtask.Name + "' of session '" + logSession_Task.Name + "''"); logSession_Task.Trace("write to the default log of the session '" + logSession_Task.Name + "'"); logSession_Task.Thread.Inform("write to the thread log " + Log.Thread.Id + " of the session '" + logSession_Task.Name + "'"); //sometimes you may need to rename a log session: logSession_Task.Rename("renamed_TASK"); //optional; close the handlers and free memory logSession_Task.Close(false); //writing thread logs to explicitly created sessions Task.Start("TASK1"); Task.Start("TASK2"); }
//static Dictionary<ushort, TcpServer> servers = new Dictionary<ushort, TcpServer>(); static public void Start(int local_port, IPAddress destination_ip) { if (!NetworkRoutines.IsNetworkAvailable()) { throw new Exception("No network available."); } IPAddress ipAddress = NetworkRoutines.GetLocalIpForDestination(destination_ip); if (local_port == LocalPort && ipAddress.Equals(LocalIp)) { return; } Stop(); Log.Main.Inform("Starting TCP listener on " + local_port + " for " + destination_ip); //listeningSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); //listeningSocket.Bind(localEndPoint); ////listeningSocket.Listen(100); server = new TcpListener(ipAddress, local_port); server.Start(); thread = ThreadRoutines.StartTry(run, (Exception e) => { if (e is SocketException) { Log.Main.Warning(e); } else { Log.Main.Error(e); InfoWindow.Create(Log.GetExceptionMessage(e), null, "OK", null, Settings.View.ErrorSoundFile, System.Windows.Media.Brushes.WhiteSmoke, System.Windows.Media.Brushes.Red); } Stop(); }); }
static void userLoggedOn() { string user_name = GetUserName(); if (currentUserName == user_name) { return; } stop_userLoggedOn_t(); currentUserName = user_name; userLoggedOn_t = ThreadRoutines.StartTry( () => { try { //if (SysTray.This.IsOnlyTCP) //{ // Log.Main.Warning("TEST MODE: IsOnlyTCP"); // IPAddress ip1; // if (!IPAddress.TryParse(Settings.General.TcpClientDefaultIp, out ip1)) // throw new Exception("Server IP is not valid: " + Settings.General.TcpClientDefaultIp); // TcpServer.Start(Settings.General.TcpServerPort, ip1); // return; //} if (string.IsNullOrWhiteSpace(user_name)) { Log.Main.Error("Session's user name is empty."); return; } Log.Main.Inform("User logged in: " + user_name); string service = Settings.General.GetServiceName(); IReadOnlyList <IZeroconfHost> zhs = ZeroconfResolver.ResolveAsync(service, TimeSpan.FromSeconds(3), 1, 10).Result; if (zhs.Count < 1) { currentServerIp = Settings.General.TcpClientDefaultIp; string m = "Service '" + service + "' could not be resolved.\r\nUsing default ip: " + currentServerIp; Log.Main.Warning(m); InfoWindow.Create(m, null, "OK", null, Settings.View.ErrorSoundFile, System.Windows.Media.Brushes.WhiteSmoke, System.Windows.Media.Brushes.Yellow); } else if (zhs.Where(x => x.IPAddress != null).FirstOrDefault() == null) { currentServerIp = Settings.General.TcpClientDefaultIp; string m = "Resolution of service '" + service + "' has no IP defined.\r\nUsing default ip: " + currentServerIp; Log.Main.Error(m); InfoWindow.Create(m, null, "OK", null, Settings.View.ErrorSoundFile, System.Windows.Media.Brushes.WhiteSmoke, System.Windows.Media.Brushes.Red); } else { currentServerIp = zhs.Where(x => x.IPAddress != null).FirstOrDefault().IPAddress; Log.Main.Inform("Service: " + service + " has been resolved to: " + currentServerIp); } IPAddress ip; if (!IPAddress.TryParse(currentServerIp, out ip)) { throw new Exception("Server IP is not valid: " + currentServerIp); } TcpServer.Start(Settings.General.TcpServerPort, ip); string url = "http://" + currentServerIp + "/screenCapture/register?username="******"&ipaddress=" + TcpServer.LocalIp + "&port=" + TcpServer.LocalPort; Log.Main.Inform("GETing: " + url); HttpClient hc = new HttpClient(); HttpResponseMessage rm = hc.GetAsync(url).Result; if (!rm.IsSuccessStatusCode) { throw new Exception(rm.ReasonPhrase); } if (rm.Content == null) { throw new Exception("Response is empty"); } string responseContent = rm.Content.ReadAsStringAsync().Result; if (responseContent.Trim() != "OK") { throw new Exception("Response: " + responseContent); } } catch (Exception e) { Log.Main.Error(e); InfoWindow.Create(Log.GetExceptionMessage(e), null, "OK", null, Settings.View.ErrorSoundFile, System.Windows.Media.Brushes.WhiteSmoke, System.Windows.Media.Brushes.Red); } }, null, () => { userLoggedOn_t = null; } ); }
public static InfoWindow Create(string title, string text, string image_url, string action_name, Action action, string sound_file = null, Brush box_brush = null, Brush button_brush = null) { InfoWindow w = null; if (text.Length > Settings.View.InfoToastMaxTextLength) { text = text.Remove(Settings.View.InfoToastMaxTextLength, text.Length - Settings.View.InfoToastMaxTextLength) + "<...>"; } Action a = () => { w = new InfoWindow(title, text, image_url, action_name, action); w.SetAppearance(box_brush, button_brush); WindowInteropHelper h = new WindowInteropHelper(w); h.EnsureHandle(); w.Show(); ThreadRoutines.StartTry(() => { Thread.Sleep(Settings.View.InfoToastLifeTimeInSecs * 1000); w.Dispatcher.BeginInvoke((Action)(() => { w.Close(); })); }); if (string.IsNullOrWhiteSpace(sound_file)) { sound_file = Settings.View.InfoSoundFile; } sound_file = PathRoutines.GetAbsolutePath(sound_file); SoundPlayer sp = new SoundPlayer(sound_file); sp.Play(); }; lock (ws) { if (dispatcher == null) {//!!!the following code does not work in static constructor because creates a deadlock!!! dispatcher_t = ThreadRoutines.StartTry(() => { if (invisible_owner_w == null) {//this window is used to hide notification windows from Alt+Tab panel invisible_owner_w = new Window(); invisible_owner_w.Width = 0; invisible_owner_w.Height = 0; invisible_owner_w.WindowStyle = WindowStyle.ToolWindow; invisible_owner_w.ShowInTaskbar = false; invisible_owner_w.Show(); invisible_owner_w.Hide(); } if (dispatcher == null) { //dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; dispatcher = System.Windows.Threading.Dispatcher.FromThread(Thread.CurrentThread); System.Windows.Threading.Dispatcher.Run(); } }, null, null, true, ApartmentState.STA); if (!SleepRoutines.WaitForCondition(() => { return(dispatcher != null); }, 3000)) { throw new Exception("Could not get dispatcher."); } } } dispatcher.Invoke(a); return(w); }
internal static void sessionChanged(uint sessionId, bool active) { try { if (sessionId == 0 || !active) { Log.Main.Inform("User logged off: " + currentUserName); stopServingUser(); currentUserSessionId = 0; currentUserName = null; return; } string userName = WindowsUserRoutines.GetUserNameBySessionId(sessionId); if (userName == currentUserName) { return; } Log.Main.Inform("User logged in: " + userName); stopServingUser(); currentUserSessionId = sessionId; currentUserName = userName; if (string.IsNullOrWhiteSpace(currentUserName)) { Log.Main.Error("Session's user name is empty."); return; } onNewUser_t = ThreadRoutines.StartTry( () => { string service = Settings.General.GetServiceName(); IReadOnlyList <IZeroconfHost> zhs = ZeroconfResolver.ResolveAsync(service, TimeSpan.FromSeconds(3), 1, 10).Result; if (zhs.Count < 1) { currentServerIp = Settings.General.TcpClientDefaultIp; string m = "Service '" + service + "' could not be resolved.\r\nUsing default ip: " + currentServerIp; Log.Main.Warning(m); UiApi.Message(MessageType.WARNING, m); } else if (zhs.Where(x => x.IPAddress != null).FirstOrDefault() == null) { currentServerIp = Settings.General.TcpClientDefaultIp; string m = "Resolution of service '" + service + "' has no IP defined.\r\nUsing default ip: " + currentServerIp; Log.Main.Error(m); UiApi.Message(MessageType.ERROR, m); } else { currentServerIp = zhs.Where(x => x.IPAddress != null).FirstOrDefault().IPAddress; Log.Main.Inform("Service: " + service + " has been resolved to: " + currentServerIp); } IPAddress ip; if (!IPAddress.TryParse(currentServerIp, out ip)) { throw new Exception("Server IP is not valid: " + currentServerIp); } TcpServer.Start(Settings.General.TcpServerPort, ip); string url = "http://" + currentServerIp + "/screenCapture/register?username="******"&ipaddress=" + TcpServer.LocalIp + "&port=" + TcpServer.LocalPort; Log.Main.Inform("GETting: " + url); HttpClient hc = new HttpClient(); HttpResponseMessage rm = hc.GetAsync(url).Result; if (!rm.IsSuccessStatusCode) { throw new Exception(rm.ReasonPhrase); } if (rm.Content == null) { throw new Exception("Response is empty"); } string responseContent = rm.Content.ReadAsStringAsync().Result; if (responseContent.Trim().ToUpper() != "OK") { throw new Exception("Response body: " + responseContent); } Log.Main.Inform("Response body: " + responseContent); }, (Exception e) => { Log.Main.Error(e); TcpServer.Stop(); UiApi.Message(MessageType.ERROR, Log.GetExceptionMessage(e)); }, () => { onNewUser_t = null; } ); } catch (Exception e) { Log.Main.Error(e); } }
static bool launch_service(Record r, List <string> running_service_ids) { string service_id = (string)r["Id"]; List <string> parameters = new List <string>(); switch ((Service.State)r["State"]) { case Service.State.DISABLED: LogMessage.Error("Service '" + service_id + "' is disabled."); return(false); case Service.State.ENABLED: parameters.Add(Service.CommandLineParameters.PRODUCTION.ToString()); parameters.Add(Service.CommandLineParameters.AUTOMATIC.ToString()); break; case Service.State.DEBUG: parameters.Add(Service.CommandLineParameters.AUTOMATIC.ToString()); break; default: throw new Exception("Case " + r["State"] + " is absent."); } string service_directory; if (!string.IsNullOrWhiteSpace((string)r["ExeFolder"])) { service_directory = (string)r["ExeFolder"]; } else { service_directory = Properties.Settings.Default.ServiceDirectory; } service_directory = Log.GetAbsolutePath(service_directory); if (!Directory.Exists(service_directory)) { Mailer.Send(db, "Service directory '" + service_directory + "' does not exist", ReportSourceType.SERVICE, service_id); return(false); } string service_file_name = service_id + ".exe"; string service_file = FindFile(service_directory, service_file_name); if (service_file == null) { Mailer.Send(db, "Service file '" + service_file_name + "' was not found in " + service_directory, ReportSourceType.SERVICE, service_id); return(false); } Process p = new Process(); p.StartInfo.FileName = service_file; p.StartInfo.Arguments = string.Join(" ", parameters); Log.Main.Write("Starting service " + service_id); p.Start(); ThreadRoutines.Wait(CrawlerHost.Properties.Settings.Default.ServiceCheckDurationInMss); if (!IsProcessAlive(p.Id, service_id)) { db["UPDATE Services SET _NextStartTime=DATEADD(ss, RestartDelayIfBroken, GETDATE()) WHERE Id=@Id"].Execute("@Id", service_id); Mailer.Send(db, service_id + " could not start.", ReportSourceType.SERVICE, service_id); return(false); } running_service_ids.Add(service_id); Log.Main.Write("Process id: " + p.Id); return(true); }
static bool launch_crawler(string crawler_id, List <string> running_crawler_ids) { Dictionary <string, object> r = db["SELECT * FROM Crawlers WHERE Id=@Id"].GetFirstRecord("@Id", crawler_id); if (r == null) { LogMessage.Error("Crawler '" + crawler_id + "' does not exist."); return(false); } List <string> parameters = new List <string>(); Crawler.State state = (Crawler.State)(int) r["State"]; switch (state) { case Crawler.State.DISABLED: LogMessage.Error("Crawler '" + crawler_id + "' is disabled."); return(false); case Crawler.State.ENABLED: parameters.Add(Cliver.Bot.CommandLineParameters.PRODUCTION.ToString()); parameters.Add(Cliver.Bot.CommandLineParameters.AUTOMATIC.ToString()); break; case Crawler.State.DEBUG: parameters.Add(Cliver.Bot.CommandLineParameters.AUTOMATIC.ToString()); break; default: throw new Exception("Some case is absent."); } if ((int)r["Command"] == (int)Crawler.Command.RESTART_WITH_CLEAR_SESSION) { parameters.Add(Bot.CommandLineParameters.NOT_RESTORE_SESSION.ToString()); } string crawler_directory; crawler_directory = Log.GetAbsolutePath(Properties.Settings.Default.CrawlersDirectory); if (!Directory.Exists(crawler_directory)) { Mailer.Send(db, "Crawler directory '" + crawler_directory + "' does not exist", ReportSourceType.CRAWLER, crawler_id); return(false); } string crawler_file_name = crawler_id + ".exe"; string crawler_file = ServiceManager.FindFile(crawler_directory, crawler_file_name); if (crawler_file == null) { Mailer.Send(db, "Crawler file '" + crawler_file_name + "' was not found in " + crawler_directory, ReportSourceType.CRAWLER, crawler_id); return(false); } Process p = new Process(); p.StartInfo.FileName = crawler_file; p.StartInfo.Arguments = string.Join(" ", parameters); Log.Main.Write("Starting crawler " + crawler_id); p.Start(); ThreadRoutines.Wait(Cliver.CrawlerHost.Properties.Settings.Default.ServiceCheckDurationInMss); if (!ServiceManager.IsProcessAlive(p.Id, crawler_id)) { db["UPDATE Crawlers SET _NextStartTime=DATEADD(ss, RestartDelayIfBroken, GETDATE()) WHERE Id=@Id"].Execute("@Id", crawler_id); Mailer.Send(db, crawler_id + " could not start.", ReportSourceType.CRAWLER, crawler_id); return(false); } running_crawler_ids.Add(crawler_id); Log.Main.Write("Process id: " + p.Id); return(true); }
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); } }
static void beginMonitorServiceStartStop() { try { IntPtr hSCM = WinApi.Advapi32.OpenSCManager(null, null, WinApi.Advapi32.SCM_ACCESS.SC_MANAGER_CONNECT);//(WinApi.Advapi32.SCM_ACCESS)0xF003F);// if (hSCM == IntPtr.Zero) { throw new Exception("OpenSCManager: " + ErrorRoutines.GetLastError()); } IntPtr hService = WinApi.Advapi32.OpenService(hSCM, Cliver.CisteraScreenCaptureService.Program.SERVICE_NAME, WinApi.Advapi32.OpenServiceDesiredAccess.SERVICE_QUERY_STATUS); if (hService == IntPtr.Zero) { throw new Exception("OpenService: " + ErrorRoutines.GetLastError()); } ThreadRoutines.StartTry(() => { for (; ;) { serviceSatusChangedNotify = new WinApi.Advapi32.SERVICE_NOTIFY(); serviceSatusChangedNotify.dwVersion = 2; serviceSatusChangedNotify.pfnNotifyCallback = Marshal.GetFunctionPointerForDelegate(serviceStatusChangedDelegate); serviceSatusChangedNotify.pContext = IntPtr.Zero; serviceSatusChangedNotify.dwNotificationStatus = 0; WinApi.Advapi32.SERVICE_STATUS_PROCESS process; process.dwServiceType = 0; process.dwCurrentState = 0; process.dwControlsAccepted = 0; process.dwWin32ExitCode = 0; process.dwServiceSpecificExitCode = 0; process.dwCheckPoint = 0; process.dwWaitHint = 0; process.dwProcessId = 0; process.dwServiceFlags = 0; serviceSatusChangedNotify.ServiceStatus = process; serviceSatusChangedNotify.dwNotificationTriggered = 0; serviceSatusChangedNotify.pszServiceNames = Marshal.StringToHGlobalUni(Cliver.CisteraScreenCaptureService.Program.SERVICE_NAME); notifyHandle = GCHandle.Alloc(serviceSatusChangedNotify, GCHandleType.Pinned); unmanagedNotifyStructure = notifyHandle.AddrOfPinnedObject(); if (0 != WinApi.Advapi32.NotifyServiceStatusChange(hService, WinApi.Advapi32.NotifyMask.SERVICE_NOTIFY_RUNNING | WinApi.Advapi32.NotifyMask.SERVICE_NOTIFY_STOPPED, unmanagedNotifyStructure)) { LogMessage.Error("NotifyServiceStatusChange: " + ErrorRoutines.GetLastError()); } serviceStatusChangedManualResetEvent.Reset(); serviceStatusChangedManualResetEvent.WaitOne(); notifyHandle.Free(); } }, null, () => { try { notifyHandle.Free(); } catch { } } ); } catch (Exception e) { LogMessage.Error(e); } }
public static AlertWindow Create(string title, string text, string image_url, string action_name, Action action) { lock (lock_object) { Action a = () => { if (This != null) { try {//might be closed already This.Close(); } catch { } } if (invisible_owner_w == null) { //this window is used to hide notification windows from Alt+Tab panel invisible_owner_w = new Window(); invisible_owner_w.WindowStyle = WindowStyle.ToolWindow; invisible_owner_w.Width = 0; invisible_owner_w.Height = 0; //invisible_owner_w.Width = SystemParameters.FullPrimaryScreenWidth; //invisible_owner_w.Height = SystemParameters.FullPrimaryScreenHeight; //invisible_owner_w.AllowsTransparency = true; //invisible_owner_w.Background = Brushes.Transparent; //invisible_owner_w.Topmost = true; invisible_owner_w.ShowInTaskbar = false; invisible_owner_w.Top = 0; invisible_owner_w.Left = 0; //invisible_owner_w.MouseDown += delegate //{ // invisible_owner_w.Hide(); //}; //invisible_owner_w.KeyDown += delegate //{ // invisible_owner_w.Hide(); //}; invisible_owner_w.Show(); invisible_owner_w.Hide(); } This = new AlertWindow(title, text, image_url, action_name, action); //ElementHost.EnableModelessKeyboardInterop(This); WindowInteropHelper wih = new WindowInteropHelper(This); This.handle = wih.EnsureHandle(); This.Owner = invisible_owner_w; This.Show(); //ThreadRoutines.StartTry(() => //{ // Thread.Sleep(Settings.Default.InfoWindowLifeTimeInSecs * 1000); // This.BeginInvoke(() => { This.Close(); }); //}); if (!string.IsNullOrWhiteSpace(Settings.Default.InfoSoundFile)) { SoundPlayer sp = new SoundPlayer(Settings.Default.AlertSoundFile); sp.Play(); } }; if (dispatcher == null) {//!!!the following code does not work in static constructor because creates a deadlock!!! ThreadRoutines.StartTry(() => { dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; System.Windows.Threading.Dispatcher.Run(); }, null, null, true, ApartmentState.STA); if (!SleepRoutines.WaitForCondition(() => { return(dispatcher != null); }, 3000)) { throw new Exception("Could not get dispatcher."); } } dispatcher.Invoke(a); //ControlRoutines.InvokeFromUiThread(a); return(This); } }