private void startButton_Click(object sender, System.EventArgs args) { try { SysLog.LogInformation("Starting..."); try { service.Start(this, this.args); } catch (Exception e) { SysLog.LogException(e); } SetStatus(service.State.ToString()); SysLog.LogInformation("Status: {0}", service.State); } catch (Exception e) { SysLog.LogException(e); } startButton.Enabled = false; shutDownButton.Enabled = true; stopButton.Enabled = true; }
public void Send(SipMessage message) { using (TimedLock.Lock(transport)) { if (sendPending) { sendQueue.Enqueue(message); return; } try { var packet = message.ToArray(); sock.BeginSendAll(packet, 0, packet.Length, SocketFlags.None, onSend, null); sendPending = true; } catch (SocketException) { CloseAndRemove(); } catch (Exception e) { SysLog.LogException(e); } } }
/// <summary> /// Handles the reception of inbound HTTP requests by queuing them to /// worker threads until <see cref="Stop" /> is called. /// </summary> private void ReceiveThread() { HttpListenerContext ctx; HttpListenerWorkerRequest request; while (!stop) { try { ctx = listener.GetContext(); request = new HttpListenerWorkerRequest(ctx, virtualPath, physicalPath); Helper.UnsafeQueueUserWorkItem(onHttpRequest, request); } catch (Exception e) { if (!stop) { SysLog.LogException(e); } } finally { receiveThread = null; } } }
/// <summary> /// Implements background task processing. /// </summary> /// <param name="o">Not used.</param> private void OnBkTask(object o) { if (!isRunning) { return; } try { if (SysTime.Now >= nextDnsRefresh) { LoadDeviceMap(devices); nextDnsRefresh = SysTime.Now + dnsRefreshInterval; } // $todo(jeff.lill): // // If I really wanted to get fancy, I'd poll for // IP address changes if networkBinding.Address == IPAddress.Any // to transparently handle DHCP lease changes. } catch (Exception e) { SysLog.LogException(e); } }
private void OnSend(IAsyncResult ar) { using (TimedLock.Lock(transport)) { if (sock == null) { return; } if (sendQueue.Count == 0) { sendPending = false; return; } // There's another message queued for sending // so dequeue it and start transmitting it. var message = sendQueue.Dequeue(); var packet = message.ToArray(); try { sock.BeginSendAll(packet, 0, packet.Length, SocketFlags.None, onSend, null); } catch (SocketException) { CloseAndRemove(); } catch (Exception e) { SysLog.LogException(e); } } }
/// <summary> /// Called when a transfer completes. /// </summary> /// <param name="ar">The operation's <see cref="IAsyncResult" /> instance.</param> private void OnTransfer(IAsyncResult ar) { var info = (TransferInfo)ar.AsyncState; try { if (info.Direction == TransferDirection.Upload) { try { info.Session.EndTransfer(ar); packageFolder.EndTransit(info.Path, true); } catch { packageFolder.EndTransit(info.Path, false); throw; } } else { info.Session.EndTransfer(ar); cDownloads++; } } catch (Exception e) { SysLog.LogException(e); } }
bool RemoveCustomerLevel(int customerLevelId) { try { DB.ExecuteSQL( "delete from dbo.ExtendedPrice where CustomerLevelID = @CustomerLevelID", new[] { new SqlParameter("CustomerLevelID", customerLevelId) }); DB.ExecuteSQL( "update dbo.Customer set CustomerLevelID=0 where CustomerLevelID = @CustomerLevelID", new[] { new SqlParameter("CustomerLevelID", customerLevelId) }); DB.ExecuteSQL( "delete from dbo.CustomerLevel where CustomerLevelID = @CustomerLevelID", new[] { new SqlParameter("CustomerLevelID", customerLevelId) }); return(true); } catch (Exception ex) { SysLog.LogException(ex, MessageTypeEnum.DatabaseException, MessageSeverityEnum.Error); return(false); } }
public void FlightRecorder_PassThru_SysLogProvider() { // Verify that the ISysLogProvider implementation works. Queue <FlightEvent> queue = new Queue <FlightEvent>(); ISysLogProvider orgProvider = SysLog.LogProvider; try { FlightEvent flightEvent; using (var recorder = new FlightRecorder(evt => queue.Enqueue(evt))) { SysLog.LogProvider = recorder; SysLog.LogError("Test Error"); SysLog.LogWarning("Test Warning"); SysLog.LogInformation("Test Information"); SysLog.Flush(); Assert.AreEqual(3, queue.Count); flightEvent = queue.Dequeue(); Assert.AreEqual("SysLog:Error", flightEvent.Operation); Assert.IsTrue(flightEvent.Details.Contains("Test Error")); Assert.IsTrue(flightEvent.IsError); flightEvent = queue.Dequeue(); Assert.AreEqual("SysLog:Warning", flightEvent.Operation); Assert.IsTrue(flightEvent.Details.Contains("Test Warning")); Assert.IsFalse(flightEvent.IsError); flightEvent = queue.Dequeue(); Assert.AreEqual("SysLog:Information", flightEvent.Operation); Assert.IsTrue(flightEvent.Details.Contains("Test Information")); Assert.IsFalse(flightEvent.IsError); // Verify that system events actually serialize exception // and stack trace related information. try { throw new AssertException(); } catch (Exception e) { SysLog.LogException(e); SysLog.Flush(); flightEvent = queue.Dequeue(); Assert.AreEqual("SysLog:Exception", flightEvent.Operation); Assert.IsTrue(flightEvent.Details.Contains("AssertException")); } } } finally { SysLog.LogProvider = orgProvider; } }
public void OnMsg(AppStoreMsg msg) { if (netFail) { return; } try { switch (msg.Command) { case AppStoreQuery.RemoveCmd: packageFolder.Remove(msg.AppRef); break; case AppStoreQuery.SyncCmd: using (TimedLock.Lock(syncLock)) { this.forceSync = true; this.primaryPollTime = SysTime.Now; } break; default: throw SessionException.Create("Unexpected AppStore command [{0}].", msg.Command); } } catch (Exception e) { SysLog.LogException(e); } }
/// <summary> /// Deletes all one-time files that are not currently being accessed by NeonSwitch. /// </summary> private void PurgeOneTime() { var utcNow = DateTime.UtcNow; try { foreach (var path in Directory.EnumerateFiles(settings.OneTimePhraseFolder, "*.wav", SearchOption.TopDirectoryOnly)) { try { if (File.GetCreationTimeUtc(path) - utcNow < settings.MaxOneTimePhraseTTL) { continue; // Leave files that were created recently because their } // use may still be pending. } catch { // I'm going to ignore these with the assumption that NeonSwitch must have // the file open for reading. } } } catch (Exception e) { SysLog.LogException(e); } }
Image GetImage(string imagePath, string copyrightImageUrl, string copyrightText) { var image = CommonLogic.LoadImage(imagePath); // If copyright image and text are not specified, return the original image untouched. if (string.IsNullOrEmpty(copyrightImageUrl) && string.IsNullOrEmpty(copyrightText)) { return(image); } // Favor the copyright image over text. if (!string.IsNullOrEmpty(copyrightImageUrl) && CommonLogic.FileExists(copyrightImageUrl)) { copyrightText = string.Empty; } try { return(CommonLogic.AddWatermark(image, copyrightText, copyrightImageUrl)); } catch (Exception ex) { SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error); return(null); } }
public void OnExternalMsg(IPToGeoFixMsg msg) { try { perf.IPGeocode.Increment(); if (!settings.IPGeocodeEnabled) { throw new NotAvailableException("GeoTracker: IP Geocoding is disabled."); } if (msg.Address.AddressFamily != AddressFamily.InterNetwork) { throw new NotSupportedException(string.Format("GeoTracker: [{0}] network addresses cannot be geocoded. Only IPv4 addresses are supported.", msg.Address.AddressFamily)); } var fix = ipGeocoder.MapIPAddress(msg.Address); router.ReplyTo(msg, new IPToGeoFixAck(fix)); } catch (Exception e) { SysLog.LogException(e); throw; } }
/// <summary> /// Performs any necessary shut down activites (flushing cached fixes, etc). /// </summary> /// <remarks> /// <note> /// <see cref="IGeoFixArchiver" /> implementations must silently handle any internal /// error conditions. <see cref="GeoTrackerNode" /> does not expect to see any /// exceptions raised from calls to any of these methods. Implementations should /// catch any exceptions thrown internally and log errors or warnings as necessary. /// </note> /// </remarks> public void Stop() { lock (syncLock) { if (!isRunning || stopPending) { return; } // Signal the background thread to stop and give it 30 seconds to stop cleanly // before aborting it. stopPending = true; } try { flushThread.Join(TimeSpan.FromSeconds(30)); } catch (Exception e) { SysLog.LogException(e); flushThread.Abort(); } finally { isRunning = false; isStopped = true; } }
/// <summary> /// Removes the performance counters from the system if present. /// </summary> /// <remarks> /// <note> /// The calling process must have sufficient rights to perform this operation. If /// this is not the case, then this method will fail silently. /// </note> /// </remarks> public void Uninstall() { foreach (var counter in counters.Values) { counter.Close(); } if (!PerfCounter.ProcessLocalOnly && PerformanceCounterCategory.Exists(categoryName)) { try { PerformanceCounterCategory.Delete(categoryName); } catch (SecurityException) { SysLog.LogWarning("Process does not have sufficient rights to uninstall performance counters."); return; } catch (UnauthorizedAccessException) { SysLog.LogWarning("Process does not have sufficient rights to uninstall performance counters."); return; } catch (Exception e) { SysLog.LogException(e, "Process was not able to uninstall performance counters."); return; } } installed = false; }
private void FormServiceHost_Closing(object sender, System.ComponentModel.CancelEventArgs args) { switch (service.State) { case ServiceState.Starting: case ServiceState.Running: case ServiceState.Shutdown: try { service.Stop(); } catch (Exception e) { SysLog.LogException(e); } break; } SysLog.LogProvider = null; if (timer != null) { timer.Dispose(); timer = null; } Environment.Exit(0); }
/// <summary> /// Initalizes the fix archiver instance. /// </summary> /// <param name="node">The parent <see cref="GeoTrackerNode" /> instance.</param> /// <param name="args"> /// This implementation's settings come directly from the application /// configuration as described below. /// </param> /// <remarks> /// <note> /// <para> /// Note that some of the application log settings are loaded directly from the application's <b>LillTek.AppLog</b> /// configuration settings section as described in <see cref="AppLog" />. The valid arguments passed to the /// <see cref="Start" /> are: /// </para> /// <list type="table"> /// <item> /// <term><b>LogName</b></term> /// <description> /// The name of the application log. This defaults to <b>GeoTrackerFixes</b>. /// </description> /// </item> /// <item> /// <term><b>MaxSize</b></term> /// <description> /// The approximate maximum size of the log on disk or zero for no limit. /// This defaults to <b>5GB</b>. /// </description> /// </item> /// <item> /// <term><b>PurgeInterval</b></term> /// <description> /// The interval at which the log will purge old log files so that the /// total log size remains within the <b>MaxSize</b> limit. /// This defaults to <b>5 minutes</b>. /// </description> /// </item> /// </list> /// <see cref="IGeoFixArchiver" /> implementations must silently handle any internal /// error conditions. <see cref="GeoTrackerNode" /> does not expect to see any /// exceptions raised from calls to any of these methods. Implementations should /// catch any exceptions thrown internally and log errors or warnings as necessary. /// </note> /// </remarks> public void Start(GeoTrackerNode node, ArgCollection args) { lock (syncLock) { try { if (this.logWriter != null) { throw new InvalidOperationException("AppLogGeoFixArchiver: Archiver has already been started."); } if (this.isStopped) { throw new InvalidOperationException("AppLogGeoFixArchiver: Cannot restart a stopped archiver."); } this.node = node; this.logName = args.Get("LogName", "GeoTrackerFixes"); this.maxSize = args.Get("MaxSize", 5L * 1024L * 1024L * 1024L); this.purgeInterval = args.Get("PurgeInterval", TimeSpan.FromMinutes(5)); this.logWriter = new AppLogWriter(logName, SchemaName, SchemaVersion, maxSize); this.logWriter.PurgeInterval = purgeInterval; } catch (Exception e) { SysLog.LogException(e); } } }
/// <summary> /// Handles message packets received on the socket. /// </summary> /// <param name="ar">The async result.</param> private void OnSocketReceive(IAsyncResult ar) { int cb; Msg msg = null; byte[] msgBuf; int cbMsg; IPEndPoint fromEP = NetworkBinding.Any; using (TimedLock.Lock(router.SyncRoot)) { if (!isOpen) { return; } try { cb = sock.EndReceiveFrom(ar, ref recvEP); if (cb > 0) { msgBuf = router.DecryptFrame(recvBuf, cb, out cbMsg); msg = Msg.Load(new EnhancedMemoryStream(msgBuf)); fromEP = (IPEndPoint)recvEP; msg._SetFromChannel(new ChannelEP(transport, fromEP)); } } catch (MsgException) { // Ignore messages that can't be parsed } catch (Exception e) { SysLog.LogException(e); } // Initiate the receive of the next message if (sock.IsOpen) { try { sock.BeginReceiveFrom(recvBuf, 0, recvBuf.Length, SocketFlags.None, ref recvEP, onSocketReceive, null); } catch (Exception e) { SysLog.LogException(e, "LillTek UDP message channel is no longer able to receive messages."); } } } if (msg != null) { msg._Trace(router, 2, "UDP: Recv", string.Format("From: {0}", fromEP)); msg._Trace(router, 0, "Receive", string.Empty); router.OnReceive(this, msg); } }
public void OnMsg(AuthControlMsg msg) { try { using (TimedLock.Lock(this)) { if (!isOpen) { return; } switch (msg.Command) { case "auth-key-update": publicKey = null; // This will force the retrieval of a new key break; // on the next auth request case "cache-clear": if (cache != null) { cache.Clear(); } break; case "cache-remove-realm": if (cache != null) { CacheRemove(msg.Get("realm", string.Empty) + "\t"); } break; case "lock-account": case "cache-remove-account": if (cache != null) { CacheRemove(msg.Get("realm", string.Empty) + "\t" + msg.Get("account", string.Empty) + "\t"); } break; default: SysLog.LogWarning("Unexpected authentication control command [{0}].", msg.Command); break; } } } catch (Exception e) { SysLog.LogException(e); } }
/// <summary> /// The application worker thread. /// </summary> private void AppThread() { // All NeonSwitch applications (except for the core service) need to wait for // the core to be initialized before the application can be started. We're // going to spin here until the core indicates that it's ready. var warningTimer = new PolledTimer(TimeSpan.FromSeconds(60)); if (!SwitchApp.IsCore) { while (true) { if (String.Compare(Switch.GetGlobal(SwitchGlobal.NeonSwitchReady), "true", true) == 0) { break; } if (warningTimer.HasFired) { warningTimer.Disable(); SysLog.LogWarning("NeonSwitch application [{0}] has waited [{1}] for the core NeonSwitch service to start.", SwitchApp.Name, warningTimer.Interval); } Thread.Sleep(TimeSpan.FromSeconds(1)); } } // Continue performing wwitch initialization. We needed to wait until after // the NeonSwitch core service started before calling this. Switch.Initialize(); // Call the application entry point so it can initalize itself. try { InMain = true; Main(); InMain = false; mainCalled = true; } catch (Exception e) { SysLog.LogException(e, "The NeonSwitch application's Main() method threw an exception."); throw; } finally { InMain = false; } // NeonSwitch handles the event dispatching. Switch.EventLoop(); }
/// <summary> /// Called when the server receives an unserialized request. /// </summary> /// <param name="requestBytes">The serialized request.</param> private void OnRequest(byte[] requestBytes) { try { using (var input = new EnhancedMemoryStream(requestBytes)) { int typeCode = input.ReadInt32(); SharedMemMessage request; SharedMemMessage response; if (typeCode < 0) { request = new SharedMemErrorMessage(); } else { request = messageFactory.Create(typeCode); } request.InternalReadFrom(input); request.ReadFrom(input); try { response = requestHandler(request); if (response == null) { throw new NullReferenceException("Server request handler returned a NULL response message."); } } catch (Exception e) { response = new SharedMemErrorMessage(); response.InternalError = string.Format("{0}: {1}", e.GetType().FullName, e.Message); } response.InternalRequestId = request.InternalRequestId; response.InternalClientInbox = request.InternalClientInbox; using (var output = new EnhancedMemoryStream(response.SerializedCapacityHint)) { output.WriteInt32(response.TypeCode); response.InternalWriteTo(output); response.WriteTo(output); // This call is synchronous but should execute very quickly (microseconds). outbox.Send(response.InternalClientInbox, output.ToArray()); } } } catch (Exception e) { SysLog.LogException(e); } }
/// <summary> /// Installs the set of performance counters to the system if necessary. /// </summary> /// <remarks> /// <note> /// The calling process must have sufficient rights to perform this operation. If /// this is not the case, then this method will fail silently. /// </note> /// </remarks> public void Install() { if (!enabled || installed) { return; } // Install the counters as necessary. if (!PerfCounter.ProcessLocalOnly && !PerformanceCounterCategory.Exists(categoryName)) { var creationData = new CounterCreationDataCollection(); foreach (var counter in counters.Values.OrderBy(c => c.Name.ToLowerInvariant())) { creationData.Add(new CounterCreationData(counter.Name, counter.Help, counter.Type)); } try { PerformanceCounterCategory.Create(categoryName, categoryHelp, multiInstance ? PerformanceCounterCategoryType.MultiInstance : PerformanceCounterCategoryType.SingleInstance, creationData); } catch (InvalidOperationException e) { // We can see this error sometimes when multiple processes attempt // to create the performance counters at the same time and one // attempt failes because the counters already exist. We're going // log and ignore this. SysLog.LogException(e, "This can happen if more than one process or thread is trying to register performance counters at the same time. This is probably not a problem."); } catch (SecurityException) { SysLog.LogWarning("Process does not have sufficient rights to install performance counters. Falling back to simulated local performance counters."); installFailed = true; } catch (UnauthorizedAccessException) { SysLog.LogWarning("Process does not have sufficient rights to install performance counters. Falling back to simulated local performance counters."); installFailed = true; } catch (Exception e) { SysLog.LogException(e, "Process was unable to install performance counters. Falling back to simulated local performance counters."); installFailed = true; } } // Mark the set as installed. installed = true; }