public void Setup() { if (counters == null) counters = new PerfCounters("test"); else counters.Clear(); }
private void Save() { PerfCounters pc = new PerfCounters(); pc.Counters = Counters.ToList(); if (_cfg.AppSettings.Settings.AllKeys.Contains(ConfigConstants.Counters) == true) _cfg.AppSettings.Settings[ConfigConstants.Counters].Value = pc.GetSerialized(); else _cfg.AppSettings.Settings.Add(ConfigConstants.Counters, pc.GetSerialized()); _cfg.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); }
internal CacheMemoryTotalMemoryPressure() { /* * The chart below shows physical memory in megabytes, and the 1, 3, and 10% values. * When we reach "middle" pressure, we begin trimming the cache. * * RAM 1% 3% 10% * ----------------------------- * 128 1.28 3.84 12.8 * 256 2.56 7.68 25.6 * 512 5.12 15.36 51.2 * 1024 10.24 30.72 102.4 * 2048 20.48 61.44 204.8 * 4096 40.96 122.88 409.6 * 8192 81.92 245.76 819.2 * * Low memory notifications from CreateMemoryResourceNotification are calculated as follows * (.\base\ntos\mm\initsup.c): * * MiInitializeMemoryEvents() { * ... * // * // Scale the threshold so on servers the low threshold is * // approximately 32MB per 4GB, capping it at 64MB. * // * * MmLowMemoryThreshold = MmPlentyFreePages; * * if (MmNumberOfPhysicalPages > 0x40000) { * MmLowMemoryThreshold = MI_MB_TO_PAGES (32); * MmLowMemoryThreshold += ((MmNumberOfPhysicalPages - 0x40000) >> 7); * } * else if (MmNumberOfPhysicalPages > 0x8000) { * MmLowMemoryThreshold += ((MmNumberOfPhysicalPages - 0x8000) >> 5); * } * * if (MmLowMemoryThreshold > MI_MB_TO_PAGES (64)) { * MmLowMemoryThreshold = MI_MB_TO_PAGES (64); * } * ... * * E.g. * * RAM(mb) low % * ------------------- * 256 20 92% * 512 24 95% * 768 28 96% * 1024 32 97% * 2048 40 98% * 3072 48 98% * 4096 56 99% * 5120 64 99% */ long memory = TotalPhysical; Debug.Assert(memory != 0, "memory != 0"); if (memory >= 0x100000000) { _pressureHigh = 99; } else if (memory >= 0x80000000) { _pressureHigh = 98; } else if (memory >= 0x40000000) { _pressureHigh = 97; } else if (memory >= 0x30000000) { _pressureHigh = 96; } else { _pressureHigh = 95; } _pressureMiddle = _pressureHigh - 2; _pressureLow = _pressureHigh - 9; InitHistory(); // PerfCounter: Cache Percentage Machine Memory Limit Used // = total physical memory used / total physical memory used limit PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_MACH_MEM_LIMIT_USED_BASE, _pressureHigh); }
// insert cached vary or output cache entry internal static void InsertResponse(String cachedVaryKey, CachedVary cachedVary, String rawResponseKey, CachedRawResponse rawResponse, CacheDependency dependencies, DateTime absExp, TimeSpan slidingExp) { // if the provider is undefined or the fragment can't be inserted in the // provider, insert it in the internal cache. OutputCacheProvider provider = GetProvider(HttpContext.Current); // // CachedVary can be serialized. // CachedRawResponse is not always serializable. // bool useProvider = (provider != null); if (useProvider) { bool canUseProvider = (IsSubstBlockSerializable(rawResponse._rawResponse) && rawResponse._settings.IsValidationCallbackSerializable() && slidingExp == Cache.NoSlidingExpiration && (dependencies == null || dependencies.IsFileDependency())); if (useProvider && !canUseProvider) { throw new ProviderException(SR.GetString(SR.Provider_does_not_support_policy_for_responses, provider.Name)); } } #if DBG bool cachedVaryPutInCache = (cachedVary != null); #endif if (cachedVary != null) { /* * Add the CachedVary item so that a request will know * which headers are needed to issue another request. * * Use the Add method so that we guarantee we only use * a single CachedVary and don't overwrite existing ones. */ CachedVary cachedVaryInCache; if (!useProvider) { cachedVaryInCache = OutputCache.UtcAdd(cachedVaryKey, cachedVary); } else { cachedVaryInCache = (CachedVary)provider.Add(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } if (cachedVaryInCache != null) { if (!cachedVary.Equals(cachedVaryInCache)) { if (!useProvider) { HttpRuntime.CacheInternal.UtcInsert(cachedVaryKey, cachedVary); } else { provider.Set(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } } else { cachedVary = cachedVaryInCache; #if DBG cachedVaryPutInCache = false; #endif } } if (!useProvider) { AddCacheKeyToDependencies(ref dependencies, cachedVaryKey); } // not all caches support cache key dependencies, but we can use a "change number" to associate // the ControlCachedVary and the PartialCachingCacheEntry rawResponse._cachedVaryId = cachedVary.CachedVaryId; } // Now insert into the cache (use cache provider if possible, otherwise use internal cache) if (!useProvider) { HttpRuntime.CacheInternal.UtcInsert(rawResponseKey, rawResponse, dependencies, absExp, slidingExp, CacheItemPriority.Normal, s_entryRemovedCallback); IncrementCount(); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_ENTRIES); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_TURNOVER_RATE); } else { string depKey = null; string[] fileDeps = null; if (dependencies != null) { depKey = OUTPUTCACHE_KEYPREFIX_DEPENDENCIES + dependencies.GetUniqueID(); fileDeps = dependencies.GetFileDependencies(); } OutputCacheEntry oce = Convert(rawResponse, depKey, fileDeps); provider.Set(rawResponseKey, oce, absExp); if (dependencies != null) { // use Add and dispose dependencies if there's already one in the cache Object d = HttpRuntime.CacheInternal.UtcAdd(depKey, new DependencyCacheEntry(rawResponseKey, oce.KernelCacheUrl, provider.Name), dependencies, absExp, Cache.NoSlidingExpiration, CacheItemPriority.Normal, s_dependencyRemovedCallback); if (d != null) { dependencies.Dispose(); } } } #if DBG string cachedVaryType = (cachedVaryPutInCache) ? "CachedVary" : ""; string providerUsed = (useProvider) ? provider.Name : "CacheInternal"; Debug.Trace("OutputCache", "InsertResposne(" + cachedVaryKey + ", " + cachedVaryType + ", " + rawResponseKey + ", CachedRawResponse, ...) -->" + providerUsed); #endif }
internal ISAPIWorkerRequest(IntPtr ecb) { this._ecb = ecb; PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_TOTAL); }
public bool TryGet(Guid database, IRequestContext requestContext, out BackEndServer backEndServer) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } backEndServer = null; PerfCounters.HttpProxyCacheCountersInstance.BackEndServerLocalCacheHitsRateBase.Increment(); PerfCounters.HttpProxyCacheCountersInstance.BackEndServerOverallCacheHitsRateBase.Increment(); PerfCounters.IncrementMovingPercentagePerformanceCounterBase(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerLocalCacheHitsRate); PerfCounters.IncrementMovingPercentagePerformanceCounterBase(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerOverallCacheHitsRate); MailboxServerCacheEntry mailboxServerCacheEntry = null; bool flag = false; bool flag2 = this.serversCache.TryGetValue(database, out mailboxServerCacheEntry); if (flag2) { if (MailboxServerCache.IsE14ServerStale(mailboxServerCacheEntry)) { this.Remove(database, requestContext); return(false); } backEndServer = mailboxServerCacheEntry.BackEndServer; PerfCounters.HttpProxyCacheCountersInstance.BackEndServerLocalCacheHitsRate.Increment(); PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerLocalCacheHitsRate); if (mailboxServerCacheEntry.IsDueForRefresh(MailboxServerCache.GetRefreshInterval(backEndServer))) { flag = true; } } if (HttpProxySettings.MailboxServerLocatorSharedCacheEnabled.Value && (!flag2 || flag)) { MailboxServerCacheEntry sharedCacheEntry = null; long latency = 0L; string diagInfo = null; bool latency2 = LatencyTracker.GetLatency <bool>(() => this.sharedCacheClient.TryGet <MailboxServerCacheEntry>(database.ToString(), requestContext.ActivityId, out sharedCacheEntry, out diagInfo), out latency); requestContext.LogSharedCacheCall(latency, diagInfo); if (latency2 && (!flag2 || sharedCacheEntry.LastRefreshTime > mailboxServerCacheEntry.LastRefreshTime)) { this.Add(database, sharedCacheEntry, requestContext, false); mailboxServerCacheEntry = sharedCacheEntry; flag2 = true; } } if (flag2) { backEndServer = mailboxServerCacheEntry.BackEndServer; PerfCounters.HttpProxyCacheCountersInstance.BackEndServerOverallCacheHitsRate.Increment(); PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerOverallCacheHitsRate); if (!this.LazyRefreshDisabled && mailboxServerCacheEntry.IsDueForRefresh(MailboxServerCache.GetRefreshInterval(mailboxServerCacheEntry.BackEndServer))) { if (MailboxServerCache.BackgroundServerRefreshEnabled.Value) { this.RegisterRefresh(new DatabaseWithForest(database, mailboxServerCacheEntry.ResourceForest, requestContext.ActivityId)); } RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "ServerLocatorRefresh", database); RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "RefreshingCacheEntry", mailboxServerCacheEntry.ToString()); } } return(flag2); }
internal static void InsertResponse(string cachedVaryKey, CachedVary cachedVary, string rawResponseKey, CachedRawResponse rawResponse, CacheDependency dependencies, DateTime absExp, TimeSpan slidingExp) { OutputCacheProvider provider = GetProvider(HttpContext.Current); bool flag = provider != null; if (flag) { bool flag2 = ((IsSubstBlockSerializable(rawResponse._rawResponse) && rawResponse._settings.IsValidationCallbackSerializable()) && (slidingExp == Cache.NoSlidingExpiration)) && ((dependencies == null) || dependencies.IsFileDependency()); if (flag && !flag2) { throw new ProviderException(System.Web.SR.GetString("Provider_does_not_support_policy_for_responses", new object[] { provider.Name })); } } if (cachedVary != null) { CachedVary vary; if (!flag) { vary = UtcAdd(cachedVaryKey, cachedVary); } else { vary = (CachedVary)provider.Add(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } if (vary != null) { if (!cachedVary.Equals(vary)) { if (!flag) { HttpRuntime.CacheInternal.UtcInsert(cachedVaryKey, cachedVary); } else { provider.Set(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } } else { cachedVary = vary; } } if (!flag) { AddCacheKeyToDependencies(ref dependencies, cachedVaryKey); } rawResponse._cachedVaryId = cachedVary.CachedVaryId; } if (!flag) { HttpRuntime.CacheInternal.UtcInsert(rawResponseKey, rawResponse, dependencies, absExp, slidingExp, CacheItemPriority.Normal, s_entryRemovedCallback); IncrementCount(); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_ENTRIES); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_TURNOVER_RATE); } else { string depKey = null; string[] fileDependencies = null; if (dependencies != null) { depKey = "aD" + dependencies.GetUniqueID(); fileDependencies = dependencies.GetFileDependencies(); } OutputCacheEntry entry = Convert(rawResponse, depKey, fileDependencies); provider.Set(rawResponseKey, entry, absExp); if ((dependencies != null) && (HttpRuntime.CacheInternal.UtcAdd(depKey, new DependencyCacheEntry(rawResponseKey, entry.KernelCacheUrl, provider.Name), dependencies, absExp, Cache.NoSlidingExpiration, CacheItemPriority.Normal, s_dependencyRemovedCallback) != null)) { dependencies.Dispose(); } } }
protected override void OnAfterUninstall(System.Collections.IDictionary savedState) { PerfCounters.Remove(); base.OnAfterUninstall(savedState); }
static void Main(string[] args) { string runId = string.Empty; string startTime = string.Empty; string endTime = string.Empty; List <DateTime> times = new List <DateTime>(); if (args.Length == 1) { foreach (string arg in args) { string tArg = arg.Trim(); try { if (tArg.Substring(0, 7).ToLower() == "-runid:") { runId = tArg.Substring(7).Trim(); if (DbHelper.ValidateConnection() && PerfCounters.ValidateStorage()) { if (PerfCounters.ValidateTestDetails(runId)) { PerfCounters.InitiateDownload(runId, DbHelper.GetTestTimes(runId)); } } } else if (tArg.Substring(0, 6).ToLower() == "-usage") { Console.WriteLine("RunId of load test is mandatory if start and end time is not provided"); Console.WriteLine("Usage PerfMon -rundid:<valid run id> \n " + "or \n" + "PerfMon -st:<Start time to begin collecting perfmon data> -ed:<end time>"); } } catch (Exception e) { Console.WriteLine("Usage PerfMon -rundid:<valid run id> \n " + "or \n" + "PerfMon -st:<Start time to begin collecting perfmon data> -ed:<end time>"); } } } else if (args.Length == 2) { try { foreach (string arg in args) { string tArg = arg.Trim(); if (tArg.Substring(0, 4).ToLower() == "-st:") { startTime = tArg.Substring(4).Trim(); times.Add(DateTime.ParseExact(startTime, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal)); } else if (tArg.Substring(0, 4).ToLower() == "-ed:") { endTime = tArg.Substring(4).ToLower().Trim(); times.Add(DateTime.ParseExact(endTime, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal)); } } } catch (Exception e) { Console.WriteLine("Usage PerfMon -rundid:<valid run id> \n " + "or \n" + "PerfMon -st:<Start time to begin collecting perfmon data> -ed:<end time>"); } if (DbHelper.ValidateConnection() && PerfCounters.ValidateStorage()) { PerfCounters.InitiateDownload("CustomImport", times); } } else { Console.WriteLine("Usage PerfMon -rundid:<valid run id> \n " + "or \n" + "PerfMon -st:<Start time to begin collecting perfmon data> -ed:<end time>"); } }
protected internal override void IncrementPerfCounters() { base.IncrementPerfCounters(); PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_APP); }
internal override void UpdateInitialCounters() { PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.REQUESTS_CURRENT); PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_TOTAL); }
protected internal override void IncrementPerfCounters() { base.IncrementPerfCounters(); PerfCounters.IncrementCounter(AppPerfCounter.EVENTS_HTTP_INFRA_ERROR); PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.GLOBAL_EVENTS_HTTP_INFRA_ERROR); }
internal OutOfProcConnection(IntPtr socket) { this._socketHandle = new HandleRef(this, socket); PerfCounters.IncrementCounter(AppPerfCounter.SESSION_STATE_SERVER_CONNECTIONS); }
// Token: 0x060005F2 RID: 1522 RVA: 0x00021190 File Offset: 0x0001F390 private static void FinalizeRequestLatencies(HttpContext httpContext, RequestDetailsLogger requestDetailsLogger, IActivityScope activityScope, LatencyTracker tracker, int traceContext) { if (tracker == null) { return; } if (requestDetailsLogger == null) { throw new ArgumentNullException("requestDetailsLogger"); } if (activityScope == null) { throw new ArgumentNullException("activityScope"); } if (httpContext == null) { throw new ArgumentNullException("httpContext"); } HttpContextBase wrapper = SharedHttpContextWrapper.GetWrapper(httpContext); long num = tracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency); if (num >= 0L) { long num2 = 0L; long.TryParse(activityScope.GetProperty(6), out num2); long num3 = 0L; bool flag = requestDetailsLogger.TryGetLatency(37, ref num3); long num4 = requestDetailsLogger.GetLatency(34, 0L) + requestDetailsLogger.GetLatency(36, 0L) + num3 + requestDetailsLogger.GetLatency(39, 0L) + requestDetailsLogger.GetLatency(40, 0L); long num5 = num - num4; if (!NativeProxyHelper.WasProxiedByNativeProxyHandler(wrapper)) { PerfCounters.UpdateMovingAveragePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingAverageCasLatency, num5); } RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 43, num5); long num6 = num5 - num2; if (flag) { RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 42, Math.Max(num6, 0L)); string property = activityScope.GetProperty(13); if (PerfCounters.RoutingLatenciesEnabled && !string.IsNullOrEmpty(property)) { string empty = string.Empty; Utilities.TryExtractForestFqdnFromServerFqdn(property, ref empty); PercentilePerfCounters.UpdateRoutingLatencyPerfCounter(empty, (double)num6); PerfCounters.GetHttpProxyPerForestCountersInstance(empty).TotalProxyWithLatencyRequests.Increment(); } } long val = num6 - requestDetailsLogger.GetLatency(35, 0L) - requestDetailsLogger.GetLatency(38, 0L); RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 41, Math.Max(val, 0L)); long currentLatency = tracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency); long num7 = currentLatency - num; num = currentLatency; if (num7 > 5L) { RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestDetailsLogger, "TotalRequestTimeDelta", num7); } } RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 16, num); }
public object Clone() { CacheServerConfigSetting config = new CacheServerConfigSetting(); config.Name = Name != null ? (string)Name.Clone() : null; config.cacheType = this.cacheType; config.InProc = InProc; config.Alias = Alias; config.LastModified = LastModified != null ? (string)LastModified.Clone() : null; config.Log = Log != null ? (Alachisoft.NCache.Config.Dom.Log)Log.Clone() : null; config.PerfCounters = PerfCounters != null ? (Alachisoft.NCache.Config.Dom.PerfCounters)PerfCounters.Clone() : null; config.autoBalancing = this.autoBalancing != null ? (Alachisoft.NCache.Config.Dom.AutoLoadBalancing) this.autoBalancing.Clone() : null; config.Cleanup = Cleanup != null ? (Alachisoft.NCache.Config.Dom.Cleanup)Cleanup.Clone() : null; config.Storage = Storage != null ? (Alachisoft.NCache.Config.Dom.Storage)Storage.Clone() : null; config.EvictionPolicy = EvictionPolicy != null ? (Alachisoft.NCache.Config.Dom.EvictionPolicy)EvictionPolicy.Clone() : null; config.QueryIndices = QueryIndices != null ? (Alachisoft.NCache.Config.Dom.QueryIndex)QueryIndices.Clone() : null; config.cacheTopology = this.cacheTopology; return(config); }
public object Clone() { CacheServerConfigSetting config = new CacheServerConfigSetting(); config.cacheType = this.cacheType; config.InProc = InProc; config.LastModified = LastModified != null ? (string)LastModified.Clone() : null; config.Log = Log != null ? (Alachisoft.NCache.Config.Dom.Log)Log.Clone() : null; config.PerfCounters = PerfCounters != null ? (Alachisoft.NCache.Config.Dom.PerfCounters)PerfCounters.Clone() : null; #if SERVER config.autoBalancing = this.autoBalancing != null ? (Alachisoft.NCache.Config.Dom.AutoLoadBalancing) this.autoBalancing.Clone() : null; #endif config.Cleanup = Cleanup != null ? (Alachisoft.NCache.Config.Dom.Cleanup)Cleanup.Clone() : null; config.Storage = Storage != null ? (Alachisoft.NCache.Config.Dom.Storage)Storage.Clone() : null; config.EvictionPolicy = EvictionPolicy != null ? (Alachisoft.NCache.Config.Dom.EvictionPolicy)EvictionPolicy.Clone() : null; config.backingSource = backingSource != null ? (Alachisoft.NCache.Config.Dom.BackingSource) this.backingSource.Clone() : null; config.Security = Security != null ? (Alachisoft.NCache.Config.Dom.Security)Security.Clone() : null; config.Notifications = Notifications != null ? (Alachisoft.NCache.Config.Dom.Notifications)Notifications.Clone() : null; config.SynchronizationStrategy = SynchronizationStrategy != null ? (Alachisoft.NCache.Config.Dom.SynchronizationStrategy)SynchronizationStrategy.Clone() : null; config.cacheTopology = this.cacheTopology; config.DataFormat = this.DataFormat; config.ClientDeathDetection = ClientDeathDetection != null ? (ClientDeathDetection)ClientDeathDetection.Clone() : null; config.ClientActivityNotification = ClientActivityNotification != null ? (ClientActivityNotification)ClientActivityNotification.Clone() : null; return(config); }
/*public*/ void IStateClientManager.Set(String id, SessionStateItem item, bool inStorage) { string key = CreateSessionStateCacheKey(id); bool doInsert = true; CacheInternal cacheInternal = HttpRuntime.CacheInternal; Debug.Assert(!item.locked, "!item.locked"); Debug.Assert(item.lockAge == TimeSpan.Zero, "item.lockAge == TimeSpan.Zero"); if (inStorage) { Debug.Assert(item.lockCookie != 0, "item.lockCookie != 0"); InProcSessionState stateCurrent = (InProcSessionState)cacheInternal.Get(key); /* If the state isn't there, we probably took too long to run. */ if (stateCurrent == null) { return; } Debug.Trace("SessionStateClientSet", "state is inStorage; key = " + key); stateCurrent.spinLock.AcquireWriterLock(); try { /* Only set the state if we are the owner */ if (!stateCurrent.locked || stateCurrent.lockCookie != item.lockCookie) { Debug.Trace("SessionStateClientSet", "Leave because we're not the owner; key = " + key); return; } /* We can change the state in place if the timeout hasn't changed */ if (stateCurrent.timeout == item.timeout) { stateCurrent.Copy( item.dict, item.staticObjects, item.timeout, item.isCookieless, item.streamLength, false, DateTime.MinValue, item.lockCookie); doInsert = false; Debug.Trace("SessionStateClientSet", "Changing state inplace; key = " + key); } else { /* prevent overwriting when we drop the lock */ stateCurrent.lockCookie = 0; } } finally { stateCurrent.spinLock.ReleaseWriterLock(); } } else { PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL); PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE); TraceSessionStats(); } if (doInsert) { Debug.Trace("SessionStateClientSet", "Inserting state into Cache; key = " + key); InProcSessionState state = new InProcSessionState( item.dict, item.staticObjects, item.timeout, item.isCookieless, item.streamLength, false, DateTime.MinValue, 1); cacheInternal.UtcInsert( key, state, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, state.timeout, 0), CacheItemPriority.NotRemovable, s_callback); } }
internal override void FlushCore(byte[] status, byte[] header, int keepConnected, int totalBodySize, int numBodyFragments, IntPtr[] bodyFragments, int[] bodyFragmentLengths, int doneWithSession, int finalStatus, out bool async) { async = false; if (base._ecb != IntPtr.Zero) { if (this._headersSentFromExecuteUrl) { status = null; header = null; } if (((doneWithSession != 0) && !HttpRuntime.ShutdownInProgress) && (base._ignoreMinAsyncSize || (totalBodySize >= 0x800))) { if (base._requiresAsyncFlushCallback) { this._asyncFlushCompletionCallback = new ISAPIAsyncCompletionCallback(this.OnAsyncFlushCompletion); this._asyncFinalStatus = finalStatus; this._rootedThis = GCHandle.Alloc(this); doneWithSession = 0; async = true; Interlocked.Increment(ref _asyncIoCount); } else { this._asyncFlushCompletionCallback = null; doneWithSession = 0; async = true; } } int num = this._trySkipIisCustomErrors ? (finalStatus | 0x40) : finalStatus; int hr = UnsafeNativeMethods.EcbFlushCore(base._ecb, status, header, keepConnected, totalBodySize, numBodyFragments, bodyFragments, bodyFragmentLengths, doneWithSession, num, this._cacheInKernelMode ? 1 : 0, async ? 1 : 0, this._asyncFlushCompletionCallback); if ((!base._requiresAsyncFlushCallback && (hr == 0)) && async) { base.UnlockCachedResponseBytesOnceAfterIoComplete(); base.CallEndOfRequestCallbackOnceAfterAllIoComplete(); } else if ((hr != 0) && async) { async = false; UnsafeNativeMethods.EcbFlushCore(base._ecb, null, null, 0, 0, 0, null, null, 1, this._asyncFinalStatus, 0, 0, null); if (this._asyncFlushCompletionCallback != null) { this._rootedThis.Free(); Interlocked.Decrement(ref _asyncIoCount); } } else if (((hr != 0) && !async) && ((doneWithSession == 0) && !this._serverSupportFunctionError)) { this._serverSupportFunctionError = true; string name = "Server_Support_Function_Error"; switch (hr) { case -2147014843: case -2147014842: name = "Server_Support_Function_Error_Disconnect"; PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.REQUESTS_DISCONNECTED); break; } throw new HttpException(System.Web.SR.GetString(name, new object[] { hr.ToString("X8", CultureInfo.InvariantCulture) }), hr); } } }
void ProcessValuables(IEnumerable <LocationValuablesCollectionItemContainer> locationValuables) { m_perf = new PerfCounters(); m_perf.Start("v"); // Group items by the sets of locations they reference. // The goal here is to reduce the number of locations we visit, ideally as close to 1 // visit per location as possible. SetDictionary <IEnumerable <Location>, LocationValuablesCollectionItemContainer> fixedSets = new SetDictionary <IEnumerable <Location>, LocationValuablesCollectionItemContainer>(); // Location sets per story tag Dictionary <string, IEnumerable <Location> > tagSets = new Dictionary <string, IEnumerable <Location> >(); // Location sets per location type Dictionary <string, IEnumerable <Location> > typeSets = new Dictionary <string, IEnumerable <Location> >(); SetDictionary <string, LocationValuablesCollectionItemContainer> tagLvcs = new SetDictionary <string, LocationValuablesCollectionItemContainer>(); SetDictionary <string, LocationValuablesCollectionItemContainer> typeLvcs = new SetDictionary <string, LocationValuablesCollectionItemContainer>(); foreach (var lvc in locationValuables) { if (lvc.SpawnItem.Locations != null) { fixedSets.Add(lvc.SpawnItem.Locations, lvc); } if (lvc.SpawnItem.LocationTypes != null) { foreach (var type in lvc.SpawnItem.LocationTypes) { if (!typeSets.ContainsKey(type)) { typeSets[type] = LocationCache.Instance.GetLocationsWithType(type); } typeLvcs.Add(type, lvc); } } if (lvc.SpawnItem.StoryTags != null) { foreach (var tag in lvc.SpawnItem.StoryTags) { if (!tagSets.ContainsKey(tag)) { tagSets[tag] = LocationCache.Instance.GetLocationsWithStoryTag(tag); } tagLvcs.Add(tag, lvc); } } } Dictionary <string, Location> processedLocations = new Dictionary <string, Location>(); // Processes the set of locations, optionally creating a union with an existing set Action <IEnumerable <Location>, IEnumerable <LocationValuablesCollectionItemContainer> > processLocations = (locs, lvcsIn) => { m_perf.Start("l"); m_perf.Start("u"); HashSet <LocationValuablesCollectionItemContainer> lvcs = new HashSet <LocationValuablesCollectionItemContainer>(); if (lvcsIn != null) { lvcs.UnionWith(lvcsIn); } m_perf.Stop("u"); m_perf.Start("locs"); if (locs != null) { foreach (var location in locs) { if (!processedLocations.ContainsKey(location.Id)) { processedLocations.Add(location.Id, location); if (location.LocationTypes != null) { foreach (var type in location.LocationTypes) { var tl = typeLvcs[type]; if (tl != null) { lvcs.UnionWith(tl); } } } if (location.StoryTags != null) { foreach (var tag in location.StoryTags) { var tl = tagLvcs[tag]; if (tl != null) { lvcs.UnionWith(tl); } } } m_perf.Start("c"); // Can be smarter here: if LVCs haven't changed, only locations, then // any location that's been checked can be skipped foreach (var lvc in lvcs) { // Have we processed this lvc/location combo recently?? // Note: this currently persists until the resource is deactivated. LocationSpawnItemResults <LocationValuablesCollection> results = null; lock (m_locationComputedItems) { results = GetResults(lvc.ActivationContext.InstanceId, location); if (results != null) { continue; } results = new LocationSpawnItemResults <LocationValuablesCollection>(lvc.ActivationContext.InstanceId, location, lvc.SpawnItem); var prob = lvc.SpawnItem.Probability.GetValueOrDefault(1); var rnd = Tools.RandomDouble(0, 1); if (rnd < prob) { // Tada! results.DidSpawn = true; } AddComputedResult(location, lvc.InstanceId, results); } if (results.DidSpawn) { OnItemsSpawned(lvc.InstanceId, results); } } m_perf.Stop("c"); } else { // TODO: locations re-used } } } m_perf.Stop("locs"); m_perf.Stop("l"); }; foreach (var set in fixedSets.Keys) { processLocations(set, fixedSets[set]); } foreach (var set in tagSets.Values) { processLocations(set, null); } foreach (var set in typeSets.Values) { processLocations(set, null); } /* * m_activationContexts.Add(e.ActivationContext.InstanceId, e.ActivationContext); */ //if (IsRunning) { //AddSpawnItems(e.LocationValuables, null/*e.ActivationContext.GetStorageAgent()*/); } m_perf.Stop("v"); m_logger.Debug("ProcessValuables perf={0}", m_perf.ToShortString()); }
// Token: 0x06000246 RID: 582 RVA: 0x0000B4CC File Offset: 0x000096CC private void RefreshDatabase(DatabaseWithForest database) { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <string>((long)this.GetHashCode(), "[MailboxServerCache::RefreshDatabase]: Refreshing cache for database {0}.", database.Database.ToString()); } Diagnostics.Logger.LogEvent(FrontEndHttpProxyEventLogConstants.Tuple_RefreshingDatabaseBackEndServer, null, new object[] { HttpProxyGlobals.ProtocolType, database.Database, database.ResourceForest }); Dictionary <Guid, DatabaseToServerMappingInfo> dictionary = null; try { using (MailboxServerLocator mailboxServerLocator = MailboxServerLocator.Create(database.Database, null, database.ResourceForest, true, GuardedSlsExecution.MailboxServerLocatorCallbacks, null)) { PerfCounters.HttpProxyCountersInstance.MailboxServerLocatorCalls.Increment(); mailboxServerLocator.GetServer(); dictionary = mailboxServerLocator.AvailabilityGroupDatabaseToServerMappings; bool isSourceCachedData = mailboxServerLocator.IsSourceCachedData; PerfCounters.HttpProxyCountersInstance.MailboxServerLocatorLatency.RawValue = mailboxServerLocator.Latency; PerfCounters.HttpProxyCountersInstance.MailboxServerLocatorAverageLatency.IncrementBy(mailboxServerLocator.Latency); PerfCounters.HttpProxyCountersInstance.MailboxServerLocatorAverageLatencyBase.Increment(); PerfCounters.UpdateMovingAveragePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingAverageMailboxServerLocatorLatency, mailboxServerLocator.Latency); PerfCounters.IncrementMovingPercentagePerformanceCounterBase(PerfCounters.HttpProxyCountersInstance.MovingPercentageMailboxServerLocatorRetriedCalls); if (mailboxServerLocator.LocatorServiceHosts.Length > 1) { PerfCounters.HttpProxyCountersInstance.MailboxServerLocatorRetriedCalls.Increment(); PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingPercentageMailboxServerLocatorRetriedCalls); } } } catch (Exception ex) { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(3)) { ExTraceGlobals.VerboseTracer.TraceError <Guid, string, Exception>((long)this.GetHashCode(), "[MailboxServerCache::RefreshDatabase]: MailboxServerLocator threw exception when locating database {0} in forest {1}. Error: {2}", database.Database, database.ResourceForest, ex); } Diagnostics.Logger.LogEvent(FrontEndHttpProxyEventLogConstants.Tuple_ErrorRefreshingDatabaseBackEndServer, database.Database.ToString(), new object[] { HttpProxyGlobals.ProtocolType, database.Database, database.ResourceForest, ex.ToString() }); if (ex is ServerLocatorClientException || ex is ServerLocatorClientTransientException || ex is MailboxServerLocatorException || ex is AmServerTransientException || ex is AmServerException) { PerfCounters.HttpProxyCountersInstance.MailboxServerLocatorFailedCalls.Increment(); PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingPercentageMailboxServerLocatorFailedCalls); } else if (!(ex is DatabaseNotFoundException) && !(ex is ADTransientException) && !(ex is DataValidationException) && !(ex is DataSourceOperationException) && !(ex is DagDecomException)) { throw; } } if (dictionary != null) { this.PopulateCache(dictionary, database.ResourceForest); } }
internal override CacheEntry UpdateCache(CacheKey cacheKey, CacheEntry newEntry, bool replace, CacheItemRemovedReason removedReason, out object valueOld) { CacheEntry cacheEntry = null; CacheEntry key = null; CacheDependency dependency = null; bool flag4 = false; bool flag5 = false; DateTime minValue = DateTime.MinValue; CacheEntry.EntryState notInCache = CacheEntry.EntryState.NotInCache; bool flag6 = false; CacheItemRemovedReason removed = CacheItemRemovedReason.Removed; valueOld = null; bool flag2 = !replace && (newEntry == null); bool flag3 = !replace && (newEntry != null); Label_003E: if (flag4) { this.UpdateCache(cacheKey, null, true, CacheItemRemovedReason.Expired, out valueOld); flag4 = false; } cacheEntry = null; DateTime utcNow = DateTime.UtcNow; if ((this._useInsertBlock && (newEntry != null)) && newEntry.HasUsage()) { this.WaitInsertBlock(); } bool lockTaken = false; if (!flag2) { Monitor.Enter(this._lock, ref lockTaken); } try { cacheEntry = (CacheEntry)this._entries[cacheKey]; if (cacheEntry != null) { notInCache = cacheEntry.State; if (base._cacheCommon._enableExpiration && (cacheEntry.UtcExpires < utcNow)) { if (flag2) { if (notInCache == CacheEntry.EntryState.AddedToCache) { flag4 = true; goto Label_003E; } cacheEntry = null; } else { replace = true; removedReason = CacheItemRemovedReason.Expired; } } else { flag5 = base._cacheCommon._enableExpiration && (cacheEntry.SlidingExpiration > TimeSpan.Zero); } } if (!flag2) { if (replace && (cacheEntry != null)) { if (notInCache != CacheEntry.EntryState.AddingToCache) { key = cacheEntry; key.State = CacheEntry.EntryState.RemovingFromCache; this._entries.Remove(key); } else if (newEntry == null) { cacheEntry = null; } } if (newEntry != null) { bool flag9 = true; if ((cacheEntry != null) && (key == null)) { flag9 = false; removed = CacheItemRemovedReason.Removed; } if (flag9) { dependency = newEntry.Dependency; if ((dependency != null) && dependency.HasChanged) { flag9 = false; removed = CacheItemRemovedReason.DependencyChanged; } } if (flag9) { newEntry.State = CacheEntry.EntryState.AddingToCache; this._entries.Add(newEntry, newEntry); if (flag3) { cacheEntry = null; } else { cacheEntry = newEntry; } } else { if (!flag3) { cacheEntry = null; flag6 = true; } else { flag6 = cacheEntry == null; } if (!flag6) { newEntry = null; } } } } } finally { if (lockTaken) { Monitor.Exit(this._lock); } } if (flag2) { if (cacheEntry != null) { if (flag5) { minValue = utcNow + cacheEntry.SlidingExpiration; if (((minValue - cacheEntry.UtcExpires) >= CacheExpires.MIN_UPDATE_DELTA) || (minValue < cacheEntry.UtcExpires)) { this._expires.UtcUpdate(cacheEntry, minValue); } } this.UtcUpdateUsageRecursive(cacheEntry, utcNow); } if (cacheKey.IsPublic) { PerfCounters.IncrementCounter(AppPerfCounter.API_CACHE_RATIO_BASE); if (cacheEntry != null) { PerfCounters.IncrementCounter(AppPerfCounter.API_CACHE_HITS); } else { PerfCounters.IncrementCounter(AppPerfCounter.API_CACHE_MISSES); } } PerfCounters.IncrementCounter(AppPerfCounter.TOTAL_CACHE_RATIO_BASE); if (cacheEntry != null) { PerfCounters.IncrementCounter(AppPerfCounter.TOTAL_CACHE_HITS); return(cacheEntry); } PerfCounters.IncrementCounter(AppPerfCounter.TOTAL_CACHE_MISSES); return(cacheEntry); } int num = 0; int num2 = 0; int delta = 0; int num4 = 0; if (key != null) { if (key.InExpires()) { this._expires.Remove(key); } if (key.InUsage()) { this._usage.Remove(key); } key.State = CacheEntry.EntryState.RemovedFromCache; valueOld = key.Value; num--; delta++; if (key.IsPublic) { num2--; num4++; } } if (newEntry != null) { if (flag6) { newEntry.State = CacheEntry.EntryState.RemovedFromCache; newEntry.Close(removed); newEntry = null; } else { if (base._cacheCommon._enableExpiration && newEntry.HasExpiration()) { this._expires.Add(newEntry); } if ((base._cacheCommon._enableMemoryCollection && newEntry.HasUsage()) && ((!newEntry.HasExpiration() || (newEntry.SlidingExpiration > TimeSpan.Zero)) || ((newEntry.UtcExpires - utcNow) >= CacheUsage.MIN_LIFETIME_FOR_USAGE))) { this._usage.Add(newEntry); } newEntry.State = CacheEntry.EntryState.AddedToCache; num++; delta++; if (newEntry.IsPublic) { num2++; num4++; } } } if (key != null) { key.Close(removedReason); } if (newEntry != null) { newEntry.MonitorDependencyChanges(); if ((dependency != null) && dependency.HasChanged) { base.Remove(newEntry, CacheItemRemovedReason.DependencyChanged); } } switch (num) { case 1: Interlocked.Increment(ref this._totalCount); PerfCounters.IncrementCounter(AppPerfCounter.TOTAL_CACHE_ENTRIES); break; case -1: Interlocked.Decrement(ref this._totalCount); PerfCounters.DecrementCounter(AppPerfCounter.TOTAL_CACHE_ENTRIES); break; } switch (num2) { case 1: Interlocked.Increment(ref this._publicCount); PerfCounters.IncrementCounter(AppPerfCounter.API_CACHE_ENTRIES); break; case -1: Interlocked.Decrement(ref this._publicCount); PerfCounters.DecrementCounter(AppPerfCounter.API_CACHE_ENTRIES); break; } if (delta > 0) { PerfCounters.IncrementCounterEx(AppPerfCounter.TOTAL_CACHE_TURNOVER_RATE, delta); } if (num4 > 0) { PerfCounters.IncrementCounterEx(AppPerfCounter.API_CACHE_TURNOVER_RATE, num4); } return(cacheEntry); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static void InvokeTransacted(TransactedCallback callback, TransactionOption mode, ref bool transactionAborted) { // check for hosting permission even if no user code on the stack HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Medium, SR.Transaction_not_supported_in_low_trust); bool executeWithoutTransaction = false; #if !FEATURE_PAL // FEATURE_PAL does not enable Transactions if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major <= 4) { throw new PlatformNotSupportedException(SR.GetString(SR.RequiresNT)); } #else // !FEATURE_PAL throw new NotImplementedException("ROTORTODO"); #endif // !FEATURE_PAL if (mode == TransactionOption.Disabled) { executeWithoutTransaction = true; } if (executeWithoutTransaction) { // bypass the transaction logic callback(); transactionAborted = false; return; } TransactedInvocation call = new TransactedInvocation(callback); TransactedExecCallback execCallback = new TransactedExecCallback(call.ExecuteTransactedCode); PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_PENDING); int rc; try { rc = UnsafeNativeMethods.TransactManagedCallback(execCallback, (int)mode); } finally { PerfCounters.DecrementCounter(AppPerfCounter.TRANSACTIONS_PENDING); } // rethrow the expection originally caught in managed code if (call.Error != null) { throw new HttpException(null, call.Error); } PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_TOTAL); if (rc == 1) { PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_COMMITTED); transactionAborted = false; } else if (rc == 0) { PerfCounters.IncrementCounter(AppPerfCounter.TRANSACTIONS_ABORTED); transactionAborted = true; } else { throw new HttpException(SR.GetString(SR.Cannot_execute_transacted_code)); } }
private void FlushCachedResponse(bool isFinal) { if (this._ecb != IntPtr.Zero) { bool async = false; int minimumLength = 0; IntPtr[] bodyFragments = null; int[] bodyFragmentLengths = null; long num2 = 0L; try { if (this._cachedResponseBodyLength > 0) { minimumLength = this._cachedResponseBodyBytes.Count; bodyFragments = RecyclableArrayHelper.GetIntPtrArray(minimumLength); bodyFragmentLengths = RecyclableArrayHelper.GetIntegerArray(minimumLength); for (int i = 0; i < minimumLength; i++) { MemoryBytes bytes = (MemoryBytes)this._cachedResponseBodyBytes[i]; bodyFragments[i] = bytes.LockMemory(); if (!isFinal || !bytes.IsBufferFromUnmanagedPool) { this._requiresAsyncFlushCallback = true; } if (bytes.UseTransmitFile) { bodyFragmentLengths[i] = -bytes.Size; this._ignoreMinAsyncSize = true; num2 += bytes.FileSize; } else { bodyFragmentLengths[i] = bytes.Size; num2 += bytes.Size; } } } int doneWithSession = isFinal ? 1 : 0; int finalStatus = isFinal ? ((this._cachedResponseKeepConnected != 0) ? 2 : 1) : 0; this._cachedResponseBodyBytesIoLockCount = 2; this._endOfRequestCallbackLockCount++; if (isFinal) { PerfCounters.DecrementCounter(AppPerfCounter.REQUESTS_EXECUTING); } int delta = (int)num2; if (delta > 0) { PerfCounters.IncrementCounterEx(AppPerfCounter.REQUEST_BYTES_OUT, delta); } try { this.FlushCore(this._cachedResponseStatus, this._cachedResponseHeaders, this._cachedResponseKeepConnected, this._cachedResponseBodyLength, minimumLength, bodyFragments, bodyFragmentLengths, doneWithSession, finalStatus, out async); } finally { if (isFinal) { this.Close(); this._ecb = IntPtr.Zero; } } } finally { if (!async) { this._cachedResponseBodyBytesIoLockCount--; this._endOfRequestCallbackLockCount--; } this.UnlockCachedResponseBytesOnceAfterIoComplete(); RecyclableArrayHelper.ReuseIntPtrArray(bodyFragments); RecyclableArrayHelper.ReuseIntegerArray(bodyFragmentLengths); } } }
internal LowPhysicalMemoryMonitor() { /* * The chart below shows physical memory in megabytes, and the 1, 3, and 10% values. * * RAM 1% 3% 10% * ----------------------------- * 128 1.28 3.84 12.8 * 256 2.56 7.68 25.6 * 512 5.12 15.36 51.2 * 1024 10.24 30.72 102.4 * 2048 20.48 61.44 204.8 * 4096 40.96 122.88 409.6 * 8192 81.92 245.76 819.2 * * Low memory notifications from CreateMemoryResourceNotification are calculated as follows * (.\base\ntos\mm\initsup.c): * * MiInitializeMemoryEvents() { * ... * // * // Scale the threshold so on servers the low threshold is * // approximately 32MB per 4GB, capping it at 64MB. * // * * MmLowMemoryThreshold = MmPlentyFreePages; * * if (MmNumberOfPhysicalPages > 0x40000) { * MmLowMemoryThreshold = MI_MB_TO_PAGES (32); * MmLowMemoryThreshold += ((MmNumberOfPhysicalPages - 0x40000) >> 7); * } * else if (MmNumberOfPhysicalPages > 0x8000) { * MmLowMemoryThreshold += ((MmNumberOfPhysicalPages - 0x8000) >> 5); * } * * if (MmLowMemoryThreshold > MI_MB_TO_PAGES (64)) { * MmLowMemoryThreshold = MI_MB_TO_PAGES (64); * } * ... * * E.g. * * RAM(mb) low % * ------------------- * 256 20 92% * 512 24 95% * 768 28 96% * 1024 32 97% * 2048 40 98% * 3072 48 98% * 4096 56 99% * 5120 64 99% */ long memory = AspNetMemoryMonitor.s_totalPhysical; Debug.Assert(memory != 0, "memory != 0"); if (memory >= 0x100000000) { _pressureHigh = 99; } else if (memory >= 0x80000000) { _pressureHigh = 98; } else if (memory >= 0x40000000) { _pressureHigh = 97; } else if (memory >= 0x30000000) { _pressureHigh = 96; } else { _pressureHigh = 95; } _pressureLow = _pressureHigh - 9; InitHistory(); _appManager = ApplicationManager.GetApplicationManager(); _observers = new List <IObserver <LowPhysicalMemoryInfo> >(); CacheSection cacheConfig = null; RuntimeConfig lkgAppConfig = RuntimeConfig.GetAppLKGConfig(); RuntimeConfig appConfig = null; try { appConfig = RuntimeConfig.GetAppConfig(); cacheConfig = appConfig.Cache; } catch (Exception) { cacheConfig = lkgAppConfig.Cache; } ReadConfig(cacheConfig); // PerfCounter: Cache Percentage Machine Memory Limit Used // = total physical memory used / total physical memory used limit PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_MACH_MEM_LIMIT_USED_BASE, _pressureHigh); // start timer with initial poll interval _timer = new Timer(new TimerCallback(this.MonitorThread), null, Timeout.Infinite, _currentPollInterval); }
public object Clone() { CacheServerConfigSetting config = new CacheServerConfigSetting(); config.cacheType = this.cacheType; config.InProc = InProc; config.Log = Log != null ? (Alachisoft.NCache.Config.Dom.Log)Log.Clone() : null; config.PerfCounters = PerfCounters != null ? (Alachisoft.NCache.Config.Dom.PerfCounters)PerfCounters.Clone() : null; config.Cleanup = Cleanup != null ? (Alachisoft.NCache.Config.Dom.Cleanup)Cleanup.Clone() : null; config.Storage = Storage != null ? (Alachisoft.NCache.Config.Dom.Storage)Storage.Clone() : null; config.EvictionPolicy = EvictionPolicy != null ? (Alachisoft.NCache.Config.Dom.EvictionPolicy)EvictionPolicy.Clone() : null; config.ExpirationPolicy = ExpirationPolicy != null ? (Alachisoft.NCache.Config.Dom.ExpirationPolicy)ExpirationPolicy.Clone() : null; config.backingSource = this.backingSource != null ? (Alachisoft.NCache.Config.Dom.BackingSource) this.backingSource.Clone() : null; config.QueryIndices = QueryIndices != null ? (Alachisoft.NCache.Config.Dom.QueryIndex)QueryIndices.Clone() : null; config.Notifications = Notifications != null ? (Alachisoft.NCache.Config.Dom.Notifications)Notifications.Clone() : null; config.SQLDependencyConfig = SQLDependencyConfig != null ? (Alachisoft.NCache.Config.Dom.SQLDependencyConfig)SQLDependencyConfig.Clone() : null; config.SynchronizationStrategy = SynchronizationStrategy != null ? (Alachisoft.NCache.Config.Dom.SynchronizationStrategy)SynchronizationStrategy.Clone() : null; config.cacheTopology = this.cacheTopology; config.DataFormat = this.DataFormat; config.ClientDeathDetection = ClientDeathDetection != null ? (ClientDeathDetection)ClientDeathDetection.Clone() : null; config.TaskConfiguration = TaskConfiguration != null ?(TaskConfiguration)TaskConfiguration.Clone() : null; config.ClientActivityNotification = ClientActivityNotification != null ? (ClientActivityNotification)ClientActivityNotification.Clone() : null; return(config); }
internal SqlStateConnection(string sqlconnectionstring) { Debug.Trace("SessionStateConnectionIdentity", "Connecting under " + WindowsIdentity.GetCurrent().Name); try { _sqlConnection = new SqlConnection(sqlconnectionstring + ";Initial Catalog=ASPState"); _sqlConnection.Open(); } catch (Exception e) { _sqlConnection = null; throw new HttpException( HttpRuntime.FormatResourceString(SR.Cant_connect_sql_session_database), e); } try { /* * Prepare commands. */ SqlParameter p; GetServerSupportOptions(); Debug.Assert(SqlStateClientManager.s_support != SupportFlags.Uninitialized); if ((SqlStateClientManager.s_support & SupportFlags.GetLockAge) != 0) { // Use the set of functions that support LockAge _cmdTempGet = new SqlCommand("TempGetStateItem2", _sqlConnection); _cmdTempGet.CommandType = CommandType.StoredProcedure; _cmdTempGet.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); p = _cmdTempGet.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH)); p.Direction = ParameterDirection.Output; p = _cmdTempGet.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit)); p.Direction = ParameterDirection.Output; p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockAge", SqlDbType.Int)); p.Direction = ParameterDirection.Output; p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); p.Direction = ParameterDirection.Output; _cmdTempGetExclusive = new SqlCommand("TempGetStateItemExclusive2", _sqlConnection); _cmdTempGetExclusive.CommandType = CommandType.StoredProcedure; _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH)); p.Direction = ParameterDirection.Output; p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit)); p.Direction = ParameterDirection.Output; p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockAge", SqlDbType.Int)); p.Direction = ParameterDirection.Output; p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); p.Direction = ParameterDirection.Output; } else { _cmdTempGet = new SqlCommand("TempGetStateItem", _sqlConnection); _cmdTempGet.CommandType = CommandType.StoredProcedure; _cmdTempGet.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); p = _cmdTempGet.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH)); p.Direction = ParameterDirection.Output; p = _cmdTempGet.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit)); p.Direction = ParameterDirection.Output; p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockDate", SqlDbType.DateTime)); p.Direction = ParameterDirection.Output; p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); p.Direction = ParameterDirection.Output; _cmdTempGetExclusive = new SqlCommand("TempGetStateItemExclusive", _sqlConnection); _cmdTempGetExclusive.CommandType = CommandType.StoredProcedure; _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH)); p.Direction = ParameterDirection.Output; p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit)); p.Direction = ParameterDirection.Output; p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockDate", SqlDbType.DateTime)); p.Direction = ParameterDirection.Output; p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); p.Direction = ParameterDirection.Output; } /* ReleaseExlusive */ _cmdTempReleaseExclusive = new SqlCommand("TempReleaseStateItemExclusive", _sqlConnection); _cmdTempReleaseExclusive.CommandType = CommandType.StoredProcedure; _cmdTempReleaseExclusive.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempReleaseExclusive.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); /* Insert */ _cmdTempInsertShort = new SqlCommand("TempInsertStateItemShort", _sqlConnection); _cmdTempInsertShort.CommandType = CommandType.StoredProcedure; _cmdTempInsertShort.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempInsertShort.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH)); _cmdTempInsertShort.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int)); _cmdTempInsertLong = new SqlCommand("TempInsertStateItemLong", _sqlConnection); _cmdTempInsertLong.CommandType = CommandType.StoredProcedure; _cmdTempInsertLong.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempInsertLong.Parameters.Add(new SqlParameter("@itemLong", SqlDbType.Image, 8000)); _cmdTempInsertLong.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int)); /* Update */ _cmdTempUpdateShort = new SqlCommand("TempUpdateStateItemShort", _sqlConnection); _cmdTempUpdateShort.CommandType = CommandType.StoredProcedure; _cmdTempUpdateShort.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempUpdateShort.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH)); _cmdTempUpdateShort.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int)); _cmdTempUpdateShort.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); _cmdTempUpdateShortNullLong = new SqlCommand("TempUpdateStateItemShortNullLong", _sqlConnection); _cmdTempUpdateShortNullLong.CommandType = CommandType.StoredProcedure; _cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH)); _cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int)); _cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); _cmdTempUpdateLong = new SqlCommand("TempUpdateStateItemLong", _sqlConnection); _cmdTempUpdateLong.CommandType = CommandType.StoredProcedure; _cmdTempUpdateLong.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempUpdateLong.Parameters.Add(new SqlParameter("@itemLong", SqlDbType.Image, 8000)); _cmdTempUpdateLong.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int)); _cmdTempUpdateLong.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); _cmdTempUpdateLongNullShort = new SqlCommand("TempUpdateStateItemLongNullShort", _sqlConnection); _cmdTempUpdateLongNullShort.CommandType = CommandType.StoredProcedure; _cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@itemLong", SqlDbType.Image, 8000)); _cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int)); _cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); /* Remove */ _cmdTempRemove = new SqlCommand("TempRemoveStateItem", _sqlConnection); _cmdTempRemove.CommandType = CommandType.StoredProcedure; _cmdTempRemove.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); _cmdTempRemove.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int)); /* ResetTimeout */ _cmdTempResetTimeout = new SqlCommand("TempResetTimeout", _sqlConnection); _cmdTempResetTimeout.CommandType = CommandType.StoredProcedure; _cmdTempResetTimeout.Parameters.Add(new SqlParameter("@id", SqlDbType.Char, ID_LENGTH)); if (SqlStateClientManager.s_appSuffix == null) { SqlCommand cmdTempGetAppId = new SqlCommand("TempGetAppID", _sqlConnection); cmdTempGetAppId.CommandType = CommandType.StoredProcedure; p = cmdTempGetAppId.Parameters.Add(new SqlParameter("@appName", SqlDbType.VarChar, APPID_MAX)); p.Value = HttpRuntime.AppDomainAppIdInternal; p = cmdTempGetAppId.Parameters.Add(new SqlParameter("@appId", SqlDbType.Int)); p.Direction = ParameterDirection.Output; p.Value = Convert.DBNull; cmdTempGetAppId.ExecuteNonQuery(); Debug.Assert(!Convert.IsDBNull(p), "!Convert.IsDBNull(p)"); int appId = (int)p.Value; SqlStateClientManager.s_appSuffix = (appId).ToString(APP_SUFFIX_FORMAT); } PerfCounters.IncrementCounter(AppPerfCounter.SESSION_SQL_SERVER_CONNECTIONS); } catch { Dispose(); throw; } }
/// <summary> /// This is the initial console harness - it may become the full thing /// </summary> /// <param name="args"></param> /// <returns></returns> static int Main(string[] args) { var returnCode = 0; var returnCodeOffset = 0; var logger = LogManager.GetLogger(typeof(Bootstrapper)); try { CommandLineParser parser; if (!ParseCommandLine(args, out parser)) { return(parser.ReturnCodeOffset + 1); } LogManager.GetRepository().Threshold = parser.LogLevel; returnCodeOffset = parser.ReturnCodeOffset; var filter = BuildFilter(parser); string outputFile; if (!GetFullOutputFile(parser, out outputFile)) { return(returnCodeOffset + 1); } IPerfCounters perfCounter = new NullPerfCounter(); if (parser.EnablePerformanceCounters) { if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { perfCounter = new PerfCounters(); } else { throw new InvalidCredentialException("You must be running as an Administrator to enable performance counters."); } } using (var container = new Bootstrapper(logger)) { var persistance = new FilePersistance(parser, logger); container.Initialise(filter, parser, persistance, perfCounter); persistance.Initialise(outputFile); var registered = false; try { if (parser.Register) { ProfilerRegistration.Register(parser.UserRegistration); registered = true; } var harness = container.Resolve <IProfilerManager>(); harness.RunProcess((environment) => { returnCode = 0; if (parser.Service) { RunService(parser, environment, logger); } else { returnCode = RunProcess(parser, environment); } }, parser.Service); DisplayResults(persistance, parser, logger); } catch (Exception ex) { Trace.WriteLine(string.Format("Exception: {0}\n{1}", ex.Message, ex.InnerException)); throw; } finally { if (parser.Register && registered) { ProfilerRegistration.Unregister(parser.UserRegistration); } } } perfCounter.ResetCounters(); } catch (Exception ex) { if (logger.IsFatalEnabled) { logger.FatalFormat("An exception occured: {0}", ex.Message); logger.FatalFormat("stack: {0}", ex.StackTrace); } returnCode = returnCodeOffset + 1; } return(returnCode); }
internal void OnEnter(object source, EventArgs eventArgs) { this._key = null; this._recordedCacheMiss = false; if (OutputCache.InUse) { string[] strArray2 = null; string[] strArray3 = null; HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; context.GetFilePathData(); HttpRequest request = context.Request; HttpResponse response = context.Response; switch (request.HttpVerb) { case HttpVerb.GET: case HttpVerb.HEAD: case HttpVerb.POST: { string str; this._key = str = this.CreateOutputCachedItemKey(context, null); object obj2 = OutputCache.Get(str); if (obj2 != null) { int num; int length; CachedVary cachedVary = obj2 as CachedVary; if (cachedVary != null) { str = this.CreateOutputCachedItemKey(context, cachedVary); if (str == null) { return; } if (cachedVary._contentEncodings == null) { obj2 = OutputCache.Get(str); } else { obj2 = null; bool flag3 = true; string knownRequestHeader = context.WorkerRequest.GetKnownRequestHeader(0x16); if (knownRequestHeader != null) { string[] contentEncodings = cachedVary._contentEncodings; int startIndex = 0; bool flag4 = false; while (!flag4) { flag4 = true; int index = GetAcceptableEncoding(contentEncodings, startIndex, knownRequestHeader); if (index > -1) { flag3 = false; obj2 = OutputCache.Get(str + contentEncodings[index]); if (obj2 == null) { startIndex = index + 1; if (startIndex < contentEncodings.Length) { flag4 = false; } } } else if (index == -2) { flag3 = false; } } } if ((obj2 == null) && flag3) { obj2 = OutputCache.Get(str); } } if ((obj2 == null) || (((CachedRawResponse)obj2)._cachedVaryId != cachedVary.CachedVaryId)) { if (obj2 != null) { OutputCache.Remove(str, context); } return; } } CachedRawResponse response2 = (CachedRawResponse)obj2; HttpCachePolicySettings settings = response2._settings; if ((cachedVary == null) && !settings.IgnoreParams) { if (request.HttpVerb == HttpVerb.POST) { this.RecordCacheMiss(); return; } if (request.HasQueryString) { this.RecordCacheMiss(); return; } } if (settings.IgnoreRangeRequests) { string str8 = request.Headers["Range"]; if (StringUtil.StringStartsWithIgnoreCase(str8, "bytes")) { return; } } if (!settings.HasValidationPolicy()) { string str4 = request.Headers["Cache-Control"]; if (str4 != null) { strArray2 = str4.Split(s_fieldSeparators); for (num = 0; num < strArray2.Length; num++) { string str6 = strArray2[num]; switch (str6) { case "no-cache": case "no-store": this.RecordCacheMiss(); return; } if (StringUtil.StringStartsWith(str6, "max-age=")) { int num4; try { num4 = Convert.ToInt32(str6.Substring(8), CultureInfo.InvariantCulture); } catch { num4 = -1; } if (num4 >= 0) { int num6 = (int)((context.UtcTimestamp.Ticks - settings.UtcTimestampCreated.Ticks) / 0x989680L); if (num6 >= num4) { this.RecordCacheMiss(); return; } } } else if (StringUtil.StringStartsWith(str6, "min-fresh=")) { int num5; try { num5 = Convert.ToInt32(str6.Substring(10), CultureInfo.InvariantCulture); } catch { num5 = -1; } if (((num5 >= 0) && settings.IsExpiresSet) && !settings.SlidingExpiration) { int num7 = (int)((settings.UtcExpires.Ticks - context.UtcTimestamp.Ticks) / 0x989680L); if (num7 < num5) { this.RecordCacheMiss(); return; } } } } } string str5 = request.Headers["Pragma"]; if (str5 != null) { strArray3 = str5.Split(s_fieldSeparators); for (num = 0; num < strArray3.Length; num++) { if (strArray3[num] == "no-cache") { this.RecordCacheMiss(); return; } } } } else if (settings.ValidationCallbackInfo != null) { HttpValidationStatus valid = HttpValidationStatus.Valid; HttpValidationStatus ignoreThisRequest = valid; num = 0; length = settings.ValidationCallbackInfo.Length; while (num < length) { ValidationCallbackInfo info = settings.ValidationCallbackInfo[num]; try { info.handler(context, info.data, ref valid); } catch (Exception exception) { valid = HttpValidationStatus.Invalid; HttpApplicationFactory.RaiseError(exception); } switch (valid) { case HttpValidationStatus.Invalid: OutputCache.Remove(str, context); this.RecordCacheMiss(); return; case HttpValidationStatus.IgnoreThisRequest: ignoreThisRequest = HttpValidationStatus.IgnoreThisRequest; break; case HttpValidationStatus.Valid: break; default: valid = ignoreThisRequest; break; } num++; } if (ignoreThisRequest == HttpValidationStatus.IgnoreThisRequest) { this.RecordCacheMiss(); return; } } HttpRawResponse rawResponse = response2._rawResponse; if ((cachedVary == null) || (cachedVary._contentEncodings == null)) { string acceptEncoding = request.Headers["Accept-Encoding"]; string contentEncoding = null; ArrayList headers = rawResponse.Headers; if (headers != null) { foreach (HttpResponseHeader header in headers) { if (header.Name == "Content-Encoding") { contentEncoding = header.Value; break; } } } if (!IsAcceptableEncoding(contentEncoding, acceptEncoding)) { this.RecordCacheMiss(); return; } } int num3 = -1; if (!rawResponse.HasSubstBlocks) { string ifModifiedSince = request.IfModifiedSince; if (ifModifiedSince != null) { num3 = 0; try { DateTime time = HttpDate.UtcParse(ifModifiedSince); if ((settings.IsLastModifiedSet && (settings.UtcLastModified <= time)) && (time <= context.UtcTimestamp)) { num3 = 1; } } catch { } } if (num3 != 0) { string ifNoneMatch = request.IfNoneMatch; if (ifNoneMatch != null) { num3 = 0; string[] strArray = ifNoneMatch.Split(s_fieldSeparators); num = 0; length = strArray.Length; while (num < length) { if ((num == 0) && strArray[num].Equals("*")) { num3 = 1; break; } if (strArray[num].Equals(settings.ETag)) { num3 = 1; break; } num++; } } } } if (num3 == 1) { response.ClearAll(); response.StatusCode = 0x130; } else { bool sendBody = request.HttpVerb != HttpVerb.HEAD; response.UseSnapshot(rawResponse, sendBody); } response.Cache.ResetFromHttpCachePolicySettings(settings, context.UtcTimestamp); string originalCacheUrl = response2._kernelCacheUrl; if (originalCacheUrl != null) { response.SetupKernelCaching(originalCacheUrl); } PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_RATIO_BASE); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_HITS); this._key = null; this._recordedCacheMiss = false; application.CompleteRequest(); return; } return; } } } }
override protected int GetCurrentPressure() { // Call GetUpdatedTotalCacheSize to update the total // cache size, if there has been a recent Gen 2 Collection. // This update must happen, otherwise the CacheManager won't // know the total cache size. int gen2Count = GC.CollectionCount(2); SRefMultiple sref = _sizedRef; if (gen2Count != _gen2Count && sref != null) { // update _gen2Count _gen2Count = gen2Count; // the SizedRef is only updated after a Gen2 Collection // increment the index (it's either 1 or 0) Debug.Assert(SAMPLE_COUNT == 2); _idx = _idx ^ 1; // remember the sample time _cacheSizeSampleTimes[_idx] = DateTime.UtcNow; // remember the sample value _cacheSizeSamples[_idx] = sref.ApproximateSize; #if DBG Debug.Trace("CacheMemory", "SizedRef.ApproximateSize=" + _cacheSizeSamples[_idx]); #endif // we may not be "hosted" ApplicationManager appManager = HostingEnvironment.GetApplicationManager(); if (appManager != null) { // update total cache size long sizeUpdate = _cacheSizeSamples[_idx] - _cacheSizeSamples[_idx ^ 1]; _totalCacheSize = appManager.GetUpdatedTotalCacheSize(sizeUpdate); } else { // if we're not hosted, this cache's size is the total cache size _totalCacheSize = _cacheSizeSamples[_idx]; } } // if there's no memory limit, then there's nothing more to do if (_memoryLimit <= 0) { return(0); } long cacheSize = _cacheSizeSamples[_idx]; // use _memoryLimit as an upper bound so that pressure is a percentage (between 0 and 100, inclusive). if (cacheSize > _memoryLimit) { cacheSize = _memoryLimit; } // PerfCounter: Cache Percentage Process Memory Limit Used // = memory used by this process / process memory limit at pressureHigh // Set private bytes used in kilobytes because the counter is a DWORD // PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_PROC_MEM_LIMIT_USED, (int)(cacheSize >> KILOBYTE_SHIFT)); int result = (int)(cacheSize * 100 / _memoryLimit); return(result); }
internal static void IncreaseBytesSentCount(long bytes) { PerfCounters.AddBytesSent(bytes); }
public void AddCounter(Counterlist aCounter, int whichCounter) { if (!String.IsNullOrEmpty(aCounter.query)) { if (aCounter.counters != null) { int whichOfTheseCounters = -1; foreach (var testCounter in aCounter.counters) { whichOfTheseCounters++; if (String.IsNullOrEmpty(testCounter.counter)) { Log.WriteLog(String.Format("{0} contains malformed counter: 'counters' in counterlist[{1}] missing 'counter' in element {2}. Please review and compare to template.", fileName, whichCounter, whichOfTheseCounters), Log.LogLevel.ERROR); continue; } } } WMIQueries.Add(new WMIQuery(aCounter.query, aCounter.eventname, aCounter.querytype, aCounter.querynamespace, aCounter.counters)); } else { if (String.IsNullOrEmpty(aCounter.provider) || String.IsNullOrEmpty(aCounter.category)) { Log.WriteLog(String.Format("{0} contains malformed counter: counterlist[{1}] missing 'provider' or 'category'. Please review and compare to template.", fileName, whichCounter), Log.LogLevel.ERROR); } if (aCounter.counters == null) { Log.WriteLog(String.Format("{0} contains malformed counter: counterlist[{1}] missing 'counters'. Please review and compare to template.", fileName, whichCounter), Log.LogLevel.ERROR); } string instanceName = string.Empty; if (!String.IsNullOrEmpty(aCounter.instance) && !String.Equals(aCounter.instance, "*")) { instanceName = aCounter.instance.ToString(); } int whichOfTheseCounters = -1; foreach (var testCounter in aCounter.counters) { whichOfTheseCounters++; if (String.IsNullOrEmpty(testCounter.counter)) { Log.WriteLog(String.Format("{0} contains malformed counter: 'counters' in counterlist[{1}] missing 'counter' in element {2}. Please review and compare to template.", fileName, whichCounter, whichOfTheseCounters), Log.LogLevel.ERROR); continue; } } if (String.Equals(aCounter.provider, PerfCounterType)) { List <string> pcounters = new List <string>(); foreach (var pCounter in aCounter.counters) { pcounters.Add(pCounter.counter); } PerfCounter AddPC = RUser.RunAsRemoteUser <PerfCounter>(() => new PerfCounter(aCounter.category, pcounters, instanceName, MachineName)); PerfCounters.Add(AddPC); } else { string countersStr = ""; foreach (var wCounter in aCounter.counters) { if (String.IsNullOrEmpty(countersStr)) { countersStr = wCounter.counter; } else { countersStr += (", " + wCounter.counter); } } if (!String.IsNullOrEmpty(countersStr)) { WMIQueries.Add(new WMIQuery(aCounter.provider, aCounter.category, countersStr, instanceName)); } } } }
public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { string key = this.CreateSessionStateCacheKey(id); bool flag = true; CacheInternal cacheInternal = HttpRuntime.CacheInternal; int newLockCookie = NewLockCookie; ISessionStateItemCollection sessionItems = null; HttpStaticObjectsCollection staticObjects = null; SessionIDManager.CheckIdLength(id, true); if (item.Items.Count > 0) { sessionItems = item.Items; } if (!item.StaticObjects.NeverAccessed) { staticObjects = item.StaticObjects; } if (!newItem) { InProcSessionState state = (InProcSessionState)cacheInternal.Get(key); int lockCookie = (int)lockId; if (state == null) { return; } state._spinLock.AcquireWriterLock(); try { if (!state._locked || (state._lockCookie != lockCookie)) { return; } if (state._timeout == item.Timeout) { state.Copy(sessionItems, staticObjects, item.Timeout, false, DateTime.MinValue, lockCookie, state._flags); flag = false; } else { state._flags |= 2; newLockCookie = lockCookie; state._lockCookie = 0; } } finally { state._spinLock.ReleaseWriterLock(); } } if (flag) { InProcSessionState state2 = new InProcSessionState(sessionItems, staticObjects, item.Timeout, false, DateTime.MinValue, newLockCookie, 0); try { } finally { cacheInternal.UtcInsert(key, state2, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, state2._timeout, 0), CacheItemPriority.NotRemovable, this._callback); PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL); PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE); } } }