/// <summary> /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running. /// </summary> protected override void OnStop() { try { this.OnStopInternal(); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new WindowsCacheService() }; #if TEST using (WindowsCacheService s = new WindowsCacheService()) { s.OnStartInternal(); } #else ServiceBase.Run(ServicesToRun); #endif }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new WindowsCacheService() }; #if TEST using (WindowsCacheService s = new WindowsCacheService()) { s.OnStartInternal(); } #else ServiceBase.Run(ServicesToRun); #endif }
internal void OnStartInternal() { try { //Start serviceHost if (this.serviceHost != null) { this.serviceHost.Close(); } // Create a ServiceHost for the CacheService type and // provide the base address. this.serviceHost = new ServiceHost(typeof(CacheService)); // Open the ServiceHostBase to create listeners and start // listening for messages. this.serviceHost.Open(); //Check storage connection string using (SqlAzManStorage s = new SqlAzManStorage(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString)) { s.OpenConnection(); s.CloseConnection(); } //Start cache building in a new thread this.setNextExecution(); CacheService.startStorageBuildCache(); #if TEST while (true) { System.Threading.Thread.Sleep(500); System.Windows.Forms.Application.DoEvents(); } #endif this.faultState = false; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o => this.Setup())); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); this.faultState = true; this.timer1.Interval = 60000; //Retry after 1 minute this.timer1.Start(); } }
/// <summary> /// Handles the Elapsed event of the timer1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param> private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { this.timer1.Stop(); if (DateTime.Now < this.nextExecution && !this.faultState) { TimeSpan delta = this.nextExecution.Subtract(DateTime.Now); double d = delta.TotalMilliseconds; if (d > int.MaxValue) { this.timer1.Interval = int.MaxValue; } else { if (d > 0) { this.timer1.Interval = d; } } } else if (DateTime.Now >= this.nextExecution || this.faultState) { //Check storage connection string using (SqlAzManStorage s = new SqlAzManStorage(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString)) { s.OpenConnection(); s.CloseConnection(); } CacheService.startStorageBuildCache(); this.faultState = false; this.setNextExecution(); } } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); this.faultState = true; this.timer1.Interval = 60000; //Retry after 1 minute } finally { this.timer1.Start(); } }
public void InvalidateCache(bool invalidateCacheOnServicePartners) { Debug.WriteLine("InvalidateCache invoked."); if (invalidateCacheOnServicePartners) { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( delegate(object o) { string[] partnerEndpoints = (string[])o; foreach (string partnerEndpoint in partnerEndpoints) { try { using (NetSqlAzMan.NetSqlAzManWCFCacheService.CacheServiceClient csc = new NetSqlAzMan.NetSqlAzManWCFCacheService.CacheServiceClient()) { try { csc.Endpoint.Address = new EndpointAddress(partnerEndpoint); csc.Open(); csc.BeginInvalidateCacheOnServicePartners(false, null, null); WindowsCacheService.writeEvent(String.Format("Invalidate Cache invoked on WCF Cache Service Partner: '{0}'.", partnerEndpoint), System.Diagnostics.EventLogEntryType.Information); } finally { ((IDisposable)csc).Dispose(); } } } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("WCF Cache Service Partner error.\r\n Endpoint: '{0}'\r\nError: {1}.", partnerEndpoint, ex.Message), System.Diagnostics.EventLogEntryType.Warning); } } } ), ConfigurationManager.AppSettings["WCFCacheServicePartners"].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); } CacheService.startStorageBuildCache(); }
/// <summary> /// Sets the next execution. /// </summary> private void setNextExecution() { try { this.timer1.Stop(); string expirationValue = ConfigurationManager.AppSettings["expirationValue"].Trim(); TimeSpan tsFreq = new TimeSpan(int.Parse(expirationValue.Split(' ')[0]), int.Parse(expirationValue.Split(' ')[1]), int.Parse(expirationValue.Split(' ')[2]), int.Parse(expirationValue.Split(' ')[3])); this.nextExecution = DateTime.Now.Add(tsFreq); TimeSpan delta = this.nextExecution.Subtract(DateTime.Now); double d = delta.TotalMilliseconds; if (d > int.MaxValue) { this.timer1.Interval = int.MaxValue; } else { if (d >= 500) { this.timer1.Interval = d; } else { this.timer1.Interval = 500D; } } if (this.faultState) { this.timer1.Interval = 60000; //Retry after 1 minute if faulted } } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); } finally { this.timer1.Start(); } }
internal static void startStorageBuildCache(string storeName, string applicationName) { //Design Feature 1: If Not already building cache ... ignore new InvalidateCache lock (CacheService.locker) { if (!CacheService.buildingCache) { CacheService.buildingCache = true; WindowsCacheService.writeEvent(String.Format("Invalidate Cache invoked from user '{0}'. Store: '{1}' - Application: '{2}'.", ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).Name, storeName ?? String.Empty, applicationName ?? String.Empty), System.Diagnostics.EventLogEntryType.Information); Boolean AsyncCacheBuilding; if (!Boolean.TryParse(ConfigurationManager.AppSettings["AsyncCacheBuilding"], out AsyncCacheBuilding)) { AsyncCacheBuilding = true; } //Design Feature 2: Async Cache Building if (AsyncCacheBuilding) { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o => { try { StorageCache sc = new StorageCache(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString); sc.BuildStorageCache(storeName, applicationName); if (CacheService.storageCache != null) { //Design Feature 3: When Build ... replace the old cache with new one //3.1) This means that while building ... User can invoke CheckAccess on the OLD cache //3.2) Replacement is thread safe lock (CacheService.storageCache) { CacheService.storageCache = sc; } } else { CacheService.storageCache = sc; } WindowsCacheService.writeEvent("Cache Built (Async).", System.Diagnostics.EventLogEntryType.Information); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Cache building error (Async):\r\n{0}\r\n\r\nStack Track:\r\n{1}", ex.Message, ex.StackTrace), System.Diagnostics.EventLogEntryType.Error); } finally { lock (CacheService.locker) { CacheService.buildingCache = false; } } } )); } else { //Sync Cache Build try { StorageCache sc = new StorageCache(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString); sc.BuildStorageCache(storeName, applicationName); if (CacheService.storageCache != null) { //Design Feature 3: When Build ... replace the old cache with new one //3.1) This means that while building ... User can invoke CheckAccess on the OLD cache //3.2) Replacement is thread safe lock (CacheService.storageCache) { CacheService.storageCache = sc; } } else { CacheService.storageCache = sc; } WindowsCacheService.writeEvent("Cache Built (Sync).", System.Diagnostics.EventLogEntryType.Information); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Cache building error (Sync):\r\n{0}\r\n\r\nStack Track:\r\n{1}", ex.Message, ex.StackTrace), System.Diagnostics.EventLogEntryType.Error); } finally { lock (CacheService.locker) { CacheService.buildingCache = false; } } } } else { WindowsCacheService.writeEvent("Invalidate Cache invoked while building cache. Command ignored.", System.Diagnostics.EventLogEntryType.Warning); } } }