public override void down(Event evt) { if (top_prot != null) { top_prot.receiveDownEvent(evt); } else { NCacheLog.Error("ProtocolStack", "no down protocol available !"); } }
/// <summary> /// /// </summary> /// <param name="newMap"></param> /// <param name="newBucketsOwnershipMap"></param> /// <param name="leftMbrs"></param> public void InstallHashMap(DistributionMaps distributionMaps, ArrayList leftMbrs) { ArrayList newMap = null; Hashtable newBucketsOwnershipMap = null; _sync.AcquireWriterLock(Timeout.Infinite); try { if (distributionMaps == null) { return; } newMap = distributionMaps.Hashmap; newBucketsOwnershipMap = distributionMaps.BucketsOwnershipMap; if (newMap == null || newBucketsOwnershipMap == null) { return; } if (_installedHashMap != null) { for (int i = 0; i < newMap.Count; i++) { HashMapBucket newBucket = (HashMapBucket)newMap[i]; int index = _installedHashMap.IndexOf(newBucket); HashMapBucket oldBucket = (HashMapBucket)_installedHashMap[index]; if (!oldBucket.PermanentAddress.Equals(newBucket.PermanentAddress) && oldBucket.TempAddress.Equals(newBucket.TempAddress)) { NCacheLog.Error("Install Hasmap", "BucketID: " + index.ToString() + "\toldBucket: " + oldBucket.PermanentAddress.ToString() + "\toldBucket.Temp: " + oldBucket.TempAddress.ToString() + "\tnewBucket: " + newBucket.PermanentAddress.ToString() + "\tnewBucekt.Temp: " + newBucket.TempAddress.ToString()); } else { oldBucket.PermanentAddress = newBucket.PermanentAddress; oldBucket.TempAddress = newBucket.TempAddress; oldBucket.Status = newBucket.Status; } } } else { _installedHashMap = newMap; } _bucketsOwnershipMap = newBucketsOwnershipMap; NotifyBucketUpdate(); } finally { _sync.ReleaseWriterLock(); } }
/// <summary> /// Returns the location identifier for this HttpRequest context. Response cookies are searched first /// and if no cookie is found then Requeset cookies are searched for location identifier. /// If there isno cookie in Request or Response then the Location Identifier in the SessionId id returned. /// </summary> /// <param name="context">Context of current HttpRequest</param> /// <param name="sessionId">SessionId for the Request</param> /// <returns>Location Identifer if cookie is found other wise the sessionId is returned.</returns> private string GetLocationID(HttpContext context, string sessionId) { string locationID = sessionId; if (_isLocationAffinityEnabled) { try { if (context.Response.Cookies.Get(LOC_IDENTIFIER) == null) { context.Response.Cookies.Remove(LOC_IDENTIFIER); } else if (string.IsNullOrEmpty(context.Response.Cookies.Get(LOC_IDENTIFIER).Value)) { context.Response.Cookies.Remove(LOC_IDENTIFIER); } else { if (NCacheLog != null) { NCacheLog.Info(sessionId + " :" + "New Location in Response Cookie = " + context.Response.Cookies.Get(LOC_IDENTIFIER).Value); } return(context.Response.Cookies.Get(LOC_IDENTIFIER).Value); } if (context.Request.Cookies.Get(LOC_IDENTIFIER) == null) { context.Request.Cookies.Remove(LOC_IDENTIFIER); } else if (string.IsNullOrEmpty(context.Request.Cookies.Get(LOC_IDENTIFIER).Value)) { context.Request.Cookies.Remove(LOC_IDENTIFIER); } else { if (NCacheLog != null) { NCacheLog.Info(sessionId + " :" + "New Location in Request Cookie = " + context.Request.Cookies.Get(LOC_IDENTIFIER).Value); } return(context.Request.Cookies.Get(LOC_IDENTIFIER).Value); } } catch (Exception e) { if (NCacheLog != null) { NCacheLog.Error(sessionId + " :" + e.ToString()); } } } return(locationID); }
private void SendPollRequestTask() { try { // Waiting 30 minutes to declare a client dead. // No of notifications to be sent in 30 minutes float deadClientTest = (float)_deadClientInterval / _pollRequestInterval; HPTime lastDeadClientCheckTime = HPTime.Now; bool looped = false; while (!_isDisposing) { try { for (float i = 0; i < deadClientTest; i++) { looped = true; if (_isDisposing) { break; } SendPollRequest(); lock (this) { Monitor.Wait(this, _pollRequestInterval); } } if (looped) { CleanDeadClients(lastDeadClientCheckTime); } lastDeadClientCheckTime = HPTime.Now; } catch (ThreadAbortException) { break; } catch (ThreadInterruptedException) { break; } } } catch (ThreadAbortException) { } catch (ThreadInterruptedException) { } catch (Exception e) { NCacheLog.Error("PullBasedNotificationManager.SendPollRequest", e.ToString()); } }
private void PrintStats() { while (_printThread != null) { try { if (_logger != null) { StringBuilder sb = new StringBuilder(); sb.Append("[ print_interval :" + _printInterval); if (_pcBcastQueueCount != null) { sb.Append(" ; BCastQueueCount : " + _pcBcastQueueCount.RawValue); } if (_pcBcastQueueCount != null) { sb.Append(" ; TcpDownQueueCount : " + _pcTcpDownQueueCount.RawValue); } if (_pcBcastQueueCount != null) { sb.Append(" ; TcpUpQueueCount : " + _pcTcpUpQueueCount.RawValue); } if (_pcBcastQueueCount != null) { sb.Append(" ; MCastQueueCount : " + _pcMcastQueueCount.RawValue); } sb.Append(" ]"); _logger.WriteLogEntry("ClStatsCollector.PrintStats", sb.ToString()); System.Threading.Thread.Sleep(_printInterval); } } catch (ThreadInterruptedException ti) { break; } catch (ThreadAbortException te) { break; } catch (Exception e) { NCacheLog.Error("ClusterStatsCollector.PrintStats", e.ToString()); } } }
public override void Stop() { try { base.Stop(); if (_dependencyProvider != null) { _dependencyProvider.Dispose(); } } catch (Exception exc) { NCacheLog.Error("NotificationBasedDependencyManager.NosDBDependencyListener", exc.ToString()); } }
public void InitializeCache(string cache) { _caches = new Hashtable(); if (_settings.PrimaryCache != null && _settings.PrimaryCache.Count > 0) { foreach (string cacheId in _settings.PrimaryCache.Values) { if (!_caches.ContainsKey(cacheId)) { try { _caches.Add(cacheId, Alachisoft.NCache.Web.Caching.NCache.InitializeCache(cacheId)); _primaryCache = cacheId; } catch (Exception e) { throw e; } break; } } foreach (string prefix in _settings.PrimaryCache.Keys) { this._sid = prefix; break; } } if (_settings.SecondaryCaches != null && _settings.SecondaryCaches.Count > 0) { foreach (string cacheId in _settings.SecondaryCaches.Values) { if (!_caches.ContainsKey(cacheId)) { try { _caches.Add(cacheId, Alachisoft.NCache.Web.Caching.NCache.InitializeCache(cacheId)); } catch (Exception e) { if (NCacheLog != null) { NCacheLog.Error("RegionalCache.InitializeCache", "Failed to initialize \"" + cacheId + "\". Exception: " + e.ToString()); } } } } } }
/// <summary> /// Writes the exception to event log /// </summary> /// <param name="exc">Exception to be written</param> private void RaiseException(Exception exc, string sessionID) { if (sessionID == null) { sessionID = ""; } if (NCacheLog != null) { NCacheLog.Error("[Error]", sessionID + " :" + exc.ToString()); } if (_exceptionsEnabled) { throw new ProviderException(exc.Message, exc); } }
public virtual void Wait(object key) { if (key != null) { if (_installedHashMap != null) { int bucketId = GetBucketId(key as string); HashMapBucket bucket = (HashMapBucket)_installedHashMap[bucketId]; bucket.StateTxfrLatch.WaitForAny(BucketStatus.Functional | BucketStatus.NeedTransfer); } else { NCacheLog.Error("DistributionManager.Wait", "_installedHashMap == null"); } } }
public void LogError(string message, string sessionID) { try { if (sessionID == null) { sessionID = ""; } if (NCacheLog != null) { NCacheLog.Error("[Error]", sessionID + " :" + message); } } catch (Exception ex) { LogError(ex, sessionID); } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { if (_dsReader != null) { lock (_dsReader) { try { _dsReader.Dispose(); } catch (Exception e) { NCacheLog.Error("ReadThruProviderMgr", "User code threw " + e.ToString()); } } _dsReader = null; } }
private bool IsSessionCookieless(HttpContext context) { bool cookieless = true; if (_isLocationAffinityEnabled) { try { if (context.Response.Cookies.Get(LOC_IDENTIFIER) == null) { context.Response.Cookies.Remove(LOC_IDENTIFIER); } else if (string.IsNullOrEmpty(context.Response.Cookies.Get(LOC_IDENTIFIER).Value)) { context.Response.Cookies.Remove(LOC_IDENTIFIER); } else { cookieless = false; } if (context.Request.Cookies.Get(LOC_IDENTIFIER) == null) { context.Request.Cookies.Remove(LOC_IDENTIFIER); } else if (string.IsNullOrEmpty(context.Request.Cookies.Get(LOC_IDENTIFIER).Value)) { context.Request.Cookies.Remove(LOC_IDENTIFIER); } else { cookieless = false; } } catch (Exception e) { if (NCacheLog != null) { NCacheLog.Error(e.ToString()); } } } return(cookieless); }
public override void Stop() { try { base.Stop(); #if !NETCORE if (_handler != null) { this._sqlYukonDep.OnChange -= _handler; } #endif //if QueueName is null default queue will be stopped _notifBasedDepManager.StopDependency(base._connString, _context.SQLDepSettings.QueueName); } catch (Exception exc) { NCacheLog.Error("NotificationBasedDependencyManager.YukonDependencyListener", exc.ToString()); } }
/// <summary> /// Resposible of disposing cache when application domain disposes. /// </summary> /// <param name="source"></param> /// <param name="ea"></param> private void OnDisposed(object source, EventArgs ea) { try { if (this._cache != null) { if (NCacheLog != null) { NCacheLog.Error("NSessionStateModule.Disposed", ""); } this._cache.Dispose(); this._cache = null; } } catch (Exception e) { RaiseExceptions(e, "NSessionStateModule.Disposed"); } }
/// <summary> /// Remove the data kept for synchronization /// </summary> public void FlushSyncData() { try { _oledbConPool.FlushSyncData(); } catch (Exception e) { NCacheLog.Error("CacheDbSyncManager", e.ToString()); } try { _sqlConPool.FlushSyncData(); } catch (Exception e) { NCacheLog.Error("CacheDbSyncManager", e.ToString()); } }
/// <summary> /// Register callback and associate query result set with the command /// </summary> /// <param name="command"></param> private void RegisterNotification(SqlCommand sqlCmd) { SqlDataReader reader = null; try { #if !NETCORE if (_context.SQLDepSettings.UseDefaultServiceQueue) //If configured to use existing service and queue { this._sqlYukonDep = new SqlDependency(); this._sqlYukonDep.AddCommandDependency(sqlCmd); } else { this._sqlYukonDep = new SqlDependency(sqlCmd, _context.SQLDepSettings.GetDependencyOptions(base._connString), int.MaxValue); } _notifBasedDepManager.StartDependency(base._connString, _context.SQLDepSettings.QueueName); _handler = new System.Data.SqlClient.OnChangeEventHandler(this.OnYukonDependencyChanged); this._sqlYukonDep.OnChange += _handler; reader = sqlCmd.ExecuteReader(); reader.Read(); #elif NETCORE //TODO: ALACHISOFT throw new NotImplementedException(); #endif } catch (Exception ex) { NCacheLog.Error("YukoNDep", ex.ToString()); throw ex; } finally { if (reader != null) { reader.Close(); } } }
/// <summary> /// initializes the secondary cache connections after the secondary-connection-recycle-interval. /// </summary> private void InitializeSecondaryCaches() { if (_settings.SecondaryCaches != null && _settings.SecondaryCaches.Count > 0) { foreach (string cacheId in _settings.SecondaryCaches.Values) { try { _caches[cacheId] = Alachisoft.NCache.Web.Caching.NCache.InitializeCache(cacheId); } catch (Exception e) { if (NCacheLog != null) { NCacheLog.Error("RegionalCache.RecycleSecondaryConnections", "Failed to initialize \"" + cacheId + "\". Exception: " + e.ToString()); } } } ExceptionsEnabled = true; } }
private object GetItemFromSyncCache(SyncItem item, ref ulong version, ref BitSet flag, ref DateTime absoluteExpiration, ref TimeSpan slidingExpiration, ref long size, ref string group, ref string subGroup, ref Hashtable queryInfo) { if (item != null) { ISyncCache cache = _synCaches[item.CacheId] as ISyncCache; if (cache != null) { try { absoluteExpiration = DateTime.MaxValue.ToUniversalTime(); slidingExpiration = TimeSpan.Zero; return(cache.Get((string)item.Key, ref version, ref flag, ref absoluteExpiration, ref slidingExpiration, ref size, ref group, ref subGroup, ref queryInfo)); } catch (Exception e) { NCacheLog.Error("CacheSyncManager:", e.ToString()); } } } return(null); }
private void RemoveSyncItem(SyncItem item, bool unregisterCallbacks) { if (_cache != null) { try { ClusteredArrayList dependentKeys = null; lock (_dependenciesStatus.SyncRoot) { _dependenciesStatus.Remove(item); if (_dependenciesKeyMap.Contains(item)) { dependentKeys = _dependenciesKeyMap[item] as ClusteredArrayList; } _dependenciesKeyMap.Remove(item); } ISyncCache syncCache = _synCaches[item.CacheId] as ISyncCache; ISyncCacheEventsListener listener = _listeners[item.CacheId] as ISyncCacheEventsListener; if (syncCache != null && listener != null && unregisterCallbacks) { syncCache.UnRegisterSyncKeyNotifications((string)item.Key, listener); } if (dependentKeys != null) { foreach (object key in dependentKeys) { OperationContext context = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); _cache.Remove(key, context); } } } catch (Exception e) { NCacheLog.Error("CacheSyncManager:", e.ToString()); } } }
/// <summary> /// Initializes all the inactive dependencies. /// </summary> public void ActivateDependencies() { try { IDictionaryEnumerator iDic = _inactiveDependencies.GetEnumerator(); while (iDic.MoveNext()) { SyncItem item = (SyncItem)iDic.Key; CacheSyncDependency dependency = (CacheSyncDependency)iDic.Value; AddDependency(item.ThisKey, dependency); } lock (_inactiveDependencies.SyncRoot) { _inactiveDependencies.Clear(); } } catch (Exception e) { NCacheLog.Error("CacheSyncManager.ActivateDependencies()", e.ToString()); } }
/// <summary> /// Occurs when ASP.NET acquires the current state (for example, session state) associated /// with the current request. /// </summary> /// <param name="source"></param> /// <param name="ea"></param> private void OnAcquireRequestState(object source, EventArgs ea) { _transformer = new MonolithicDistribution(); this._acquireCalled = true; this._releaseCalled = false; HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; _httpSession = context.Session; if (_httpSession != null) { FillAspNetSessionFromNCache(context); } else { if (NCacheLog != null) { NCacheLog.Error("NSessionStateModule.OnAcquireRequestState", "Session is null"); } } }
private void CleanDeadClients(HPTime lastDeadClientTimeCheck) { try { lock (this) { List <string> deadClients = new List <string>(); foreach (KeyValuePair <string, ClientNotificationMgr> kvp in _clients) { ClientNotificationMgr client = kvp.Value; if (client.LastPollTime.CompareTo(lastDeadClientTimeCheck) < 0) { deadClients.Add(kvp.Key); RemoveClient(kvp.Key); } } } } catch (Exception ex) { NCacheLog.Error("PullBaseNotificationManager.CleanDeadClients()", " Exception: " + ex); } }
/// <summary> /// Register callback and associate query result set with the command /// </summary> private void RegisterNotification() { try { string fullAssemblyName = "Alachisoft.NCache.NosDBCacheDependency, Version=" + ServiceConfiguration.NosDBDependencyProviderVersion + ", Culture=neutral, PublicKeyToken=cff5926ed6a53769, processorArchitecture=MSIL"; Assembly assembly = Assembly.Load(fullAssemblyName); Type providerType = assembly.GetType("Alachisoft.NCache.NosDBCacheDependency.NosDBDependencyProvider"); if (providerType == null) { throw new Exception("Alachisoft.NCache.NosDBCacheDependency.NosDBDependencyProvider is not found in assembly Alachisoft.NCache.NosDBCacheDependency"); } _dependencyProvider = Activator.CreateInstance(providerType) as IDependencyProvider; if (_dependencyProvider != null) { _dependencyProvider.RegisterNotification(_connString, _queryString, _cmdParams, _timeout, this); } } catch (Exception ex) { NCacheLog.Error("NosDBDependencyListener", ex.ToString()); throw ex; } }
internal void RaiseExceptions(Exception exc, string sessionID) { if (NCacheLog != null) { NCacheLog.Error(sessionID + " :" + exc.ToString()); } if (this._writeExceptionsToEventLog) { try { AppUtil.LogEvent(SOURSE, exc.ToString(), EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError); } catch (Exception) { throw exc; } } if (this._exceptionsEnabled) { throw exc; } }
/// <summary> /// disposes the secondary cache connections after secondary-connection-recycle-interval. /// </summary> private void DisposeSecondaryCaches() { if (_caches != null) { IDictionaryEnumerator ide = _caches.GetEnumerator(); while (ide.MoveNext()) { if (((string)ide.Key).ToLower() != _primaryCache.ToLower()) { try { ((Alachisoft.NCache.Web.Caching.Cache)ide.Value).Dispose(); } catch (Exception e) { if (NCacheLog != null) { NCacheLog.Error("RegionalCache.RecycleSecondaryConnections", "Failed to dispose \"" + ide.Key + "\". Exception: " + e.ToString()); } } } } } }
/// <summary> /// Called by the scheduler to remove the items that has expired /// </summary> public bool Expire() { //indicates whether some items expired during this interval or not... bool expired = false; //if user has updated the file then the new values will be reloaded. _sleepInterval = ServiceConfiguration.ExpirationBulkRemoveDelay; _removeThreshhold = ServiceConfiguration.ExpirationBulkRemoveSize; CacheBase cacheInst = _context.CacheImpl; CacheBase cache = _context.CacheInternal; Cache rootCache = _context.CacheRoot; if (cache == null) { throw new InvalidOperationException("No cache instance defined"); } bool allowExpire = AllowClusteredExpiry; //in case of replication and por, only the coordinator/sub-coordinator is responsible to expire the items. if (!allowExpire) { return(false); } ClusteredArrayList selectedKeys = new ClusteredArrayList(); int oldItemsCount = 0; HashVector oldeItems = null; try { StartLogging(); DateTime startTime = DateTime.Now; int currentTime = AppUtil.DiffSeconds(startTime); int cleanSize = (int)Math.Ceiling(cache.Count * _cleanRatio); //set the flag that we are going to expire the items. if (_cacheLastAccessLoggingIntervalPassed >= _cacheLastAccessLoggingInterval) { _cacheLastAccessLoggingInterval = CacheLastAccessLoggingInterval; _cacheLastAccessCountEnabled = IsCacheLastAccessCountEnabled; _cacheLastAccessCountLoggingEnabled = IsCacheLastAccessLoggingEnabled; _cacheLastAccessInterval = CacheLastAccessCountInterval; } else { _cacheLastAccessLoggingIntervalPassed++; } if (_cacheLastAccessCountEnabled && _cacheLastAccessCountLoggingEnabled) { if (_cacheLastAccessLoggingIntervalPassed >= _cacheLastAccessLoggingInterval) { _cacheLastAccessLoggingIntervalPassed = 0; oldeItems = new HashVector(); } } lock (_mainIndex.SyncRoot) { IDictionaryEnumerator em = _mainIndex.GetEnumerator(); if (em != null) { while (em.MoveNext()) { ExpirationHint hint = em.Value as ExpirationHint; if (hint != null && _cacheLastAccessCountEnabled && hint is IdleExpiration) { IdleExpiration slidingExpHint = hint as IdleExpiration; TimeSpan diff = AppUtil.GetDateTime(AppUtil.DiffSeconds(DateTime.Now)) - AppUtil.GetDateTime(slidingExpHint.LastAccessTime); if (diff.TotalMinutes >= _cacheLastAccessInterval) { oldItemsCount++; if (oldeItems != null) { oldeItems.Add(em.Key, null); } } } if (hint == null || hint.SortKey.CompareTo(currentTime) >= 0) { continue; } if (hint.DetermineExpiration(_context)) { selectedKeys.Add(em.Key); if (cleanSize > 0 && selectedKeys.Count == cleanSize) { break; } } } } } if (NCacheLog.IsInfoEnabled) { NCacheLog.Info("ExpirationManager.Expire()", String.Format("Expiry time for {0}/{1} Items: " + (DateTime.UtcNow - startTime), selectedKeys.Count, /*_expiryIndex.KeyCount*/ cache.Count)); } } catch (Exception e) { NCacheLog.Error("ExpirationManager.Expire(bool)", "LocalCache(Expire): " + e.ToString()); } finally { _context.PerfStatsColl.IncrementCacheLastAccessCountStats(oldItemsCount); ApplyLoggs(); ClusteredArrayList dependentItems = new ClusteredArrayList(); DateTime startTime = DateTime.Now; HashVector expiredItemTable = new HashVector(); expiredItemTable.Add(ItemRemoveReason.Expired, selectedKeys);//Time based expiration try { IDictionaryEnumerator ide = expiredItemTable.GetEnumerator(); while (ide.MoveNext()) { selectedKeys = ide.Value as ClusteredArrayList; ItemRemoveReason removedReason = (ItemRemoveReason)ide.Key; if (selectedKeys.Count > 0) { //new architectural changes begins from here. ClusteredArrayList keysTobeRemoved = new ClusteredArrayList(); for (int i = 0; i < selectedKeys.Count && !_cacheCleared; i++) { keysTobeRemoved.Add(selectedKeys[i]); if (keysTobeRemoved.Count % _removeThreshhold == 0) { try { if (this.IsDisposed) { break; } OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); object[][] keysExposed = keysTobeRemoved.ToInternalArray(); foreach (object[] collection in keysExposed) { cache.RemoveSync(collection, removedReason, false, operationContext); } //set the flag that item has expired from cache... expired = true; if (_context.PerfStatsColl != null) { _context.PerfStatsColl.IncrementExpiryPerSecStatsBy(keysTobeRemoved.Count); } } catch (Exception e) { NCacheLog.Error("ExpiryManager.Expire", "an error occurred while removing expired items. Error " + e.ToString()); } keysTobeRemoved.Clear(); //we stop the activity of the current thread so that normal user operation is not affected. Thread.Sleep(_sleepInterval); } } if (!this.IsDisposed && keysTobeRemoved.Count > 0) { try { OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); object[][] keysExposed = keysTobeRemoved.ToInternalArray(); foreach (object[] keyCollection in keysExposed) { cache.RemoveSync(keyCollection, removedReason, false, operationContext); } //set the flag that item has expired from cache... expired = true; if (_context.PerfStatsColl != null) { _context.PerfStatsColl.IncrementExpiryPerSecStatsBy(keysTobeRemoved.Count); } } catch (Exception e) { NCacheLog.Error("ExpiryManager.Expire", "an error occurred while removing expired items. Error " + e.ToString()); } } } } } finally { _transitoryIndex.Clear(); lock (this) { _cacheCleared = false; } if (oldeItems != null) { StringBuilder sb = new StringBuilder(); IDictionaryEnumerator ide = oldeItems.GetEnumerator(); int count = 1; while (ide.MoveNext()) { sb.Append(ide.Key + ", "); if (count % 10 == 0) { sb.Append("\r\n"); count = 1; } else { count++; } } NCacheLog.Info(sb.ToString().Trim()); } } } return(expired); }
/// <summary> /// Initializes the oracle dependency instance. registers the change event handler for it. /// </summary> /// <returns>true if the dependency was successfully initialized.</returns> public override bool Initialize() { OracleCommand oracleCmd = null; OracleConnection connection = null; try { connection = (OracleConnection)_connectionPool.AddToDbConnectionPool(_connString, new OracleConnection(base._connString)); oracleCmd = new OracleCommand(base._queryString, connection); oracleCmd.AddRowid = true; switch (_cmdType) { case CommandType.Text: oracleCmd.CommandType = CommandType.Text; break; case CommandType.StoredProcedure: oracleCmd.CommandType = CommandType.StoredProcedure; break; default: oracleCmd.CommandType = CommandType.Text; break; } if (_cmdParams != null && _cmdParams.Count > 0) { IDictionaryEnumerator ide = _cmdParams.GetEnumerator(); while (ide.MoveNext()) { OracleCommandParams param = (OracleCommandParams)ide.Value; OracleParameter oracleParam = new OracleParameter(ide.Key.ToString(), ConvertToOracleDbType(param.Type)); oracleParam.Direction = param.Direction; oracleParam.Value = param.Value; oracleCmd.Parameters.Add(oracleParam); } } } catch (Exception ex) { throw ex; } if (oracleCmd != null) { try { this.RegisterNotification(oracleCmd); return(true); } catch (Exception ex) { NCacheLog.Error("NotificationBasedDependencyManager.OracleDependencyListener: " + ex.ToString()); connection.Close(); base._connectionPool.RemoveFromDbConnectionPool(_connString, true); connection = (OracleConnection)base._connectionPool.AddToDbConnectionPool(_connString, new OracleConnection(base._connString)); oracleCmd = new OracleCommand(base._queryString, connection); if (oracleCmd != null) { try { this.RegisterNotification(oracleCmd); return(true); } catch (Exception e) { _connectionPool.RemoveFromDbConnectionPool(_connString); connection.Close(); throw e; } } } } return(false); }
/// <summary> /// Initializes the sql dependency instance. registers the change event handler for it. /// </summary> /// <returns>true if the dependency was successfully initialized.</returns> public override bool Initialize() { SqlCommand sqlCmd = null; SqlConnection con = null; try { con = (SqlConnection)_connectionPool.AddToDbConnectionPool(_connString, new SqlConnection(base._connString)); sqlCmd = this.GetCommand(con); } catch (Exception ex) { throw ex; } if (sqlCmd != null) { try { this.RegisterNotification(sqlCmd); return(true); } catch (Exception ex) { if (ex is System.InvalidOperationException || (ex is System.Data.SqlClient.SqlException && ((System.Data.SqlClient.SqlException)ex).Number == 233)) { NCacheLog.Error("NotificationBasedDependencyManager.YukonDependencyListener: " + ex.ToString()); con.Close(); _connectionPool.RemoveFromDbConnectionPool(_connString, true); con = (SqlConnection)_connectionPool.AddToDbConnectionPool(_connString, new SqlConnection(base._connString)); sqlCmd = this.GetCommand(con); if (sqlCmd != null) { #if !NETCORE try { SqlDependency.Start(_connString); this.RegisterNotification(sqlCmd); return(true); } catch (Exception exc) { if (ex is System.InvalidOperationException || (ex is System.Data.SqlClient.SqlException && ((System.Data.SqlClient.SqlException)ex).Number == 233)) { NCacheLog.Error("NotificationBasedDependencyManager.YukonDependencyListener: " + exc.ToString()); con.Close(); _connectionPool.RemoveFromDbConnectionPool(_connString, true); con = (SqlConnection)_connectionPool.AddToDbConnectionPool(_connString, new SqlConnection(base._connString)); sqlCmd = this.GetCommand(con); if (sqlCmd != null) { try { SqlDependency.Start(_connString); this.RegisterNotification(sqlCmd); return(true); } catch (Exception e) { _connectionPool.RemoveFromDbConnectionPool(_connString); con.Close(); throw e; } } return(true); } else { throw exc; } } #elif NETCORE //TODO: ALACHISOFT throw new NotImplementedException(); #endif } return(true); } else { throw ex; } } } return(false); }
public void AcquireSyncData() { string connString = string.Empty; if (_cacheID == null) { return; } try { IDictionaryEnumerator oleDbEn = ((Hashtable)_connStringTable["oledb"]).GetEnumerator(); while (oleDbEn.MoveNext()) { connString = oleDbEn.Value.ToString(); AddToOleDbConnectionPool(oleDbEn.Value.ToString()); } _oledbConPool.AcquireSyncData(SYNC_TABLE, _cacheID); } catch (OleDbException s) { if (s.Message.Contains("SQL Server does not exist or access denied")) { if (((Hashtable)_connStringTable["oledb"]).ContainsKey(connString.ToLower())) { ((Hashtable)_connStringTable["oledb"]).Remove(connString.ToLower()); } RemoveFromOleDbConnectionPool(connString); NCacheLog.Error("CacheDbSyncManager", s.ToString()); } else { throw; } } catch (Exception e) { NCacheLog.Error("CacheDbSyncManager", e.ToString()); } try { connString = string.Empty; IDictionaryEnumerator sqlEn = ((Hashtable)_connStringTable["sql"]).GetEnumerator(); while (sqlEn.MoveNext()) { connString = sqlEn.Value.ToString(); AddToSqlConnectionPool(sqlEn.Value.ToString()); } _sqlConPool.AcquireSyncData(SYNC_TABLE, _cacheID); } catch (OleDbException s) { if (s.Message.Contains("SQL Server does not exist or access denied")) { if (((Hashtable)_connStringTable["sql"]).ContainsKey(connString.ToLower())) { ((Hashtable)_connStringTable["sql"]).Remove(connString.ToLower()); } RemoveFromOleDbConnectionPool(connString); NCacheLog.Error("CacheDbSyncManager", s.ToString()); } else { throw; } } catch (Exception e) { NCacheLog.Error("CacheDbSyncManager", e.ToString()); } }
/// <summary> /// Remove the related records from ncache_db_sync table /// </summary> private void RemoveAllResources() { object[] tableInfo = { SYNC_TABLE, _cacheID }; lock (_oledbConPool) { OleDbConnection connection; IEnumerator em = _oledbConPool.Keys.GetEnumerator(); while (em.MoveNext()) { OleDbDataReader reader = null; OleDbCommand command; try { OleDbConnectionPool.SqlDbResourceInfo connInfo = (OleDbConnectionPool.SqlDbResourceInfo)_oledbConPool.GetResource((string)em.Current); connection = connInfo.Connection; command = connection.CreateCommand(); command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE CACHE_ID = '{1}'", tableInfo); command.CommandType = CommandType.Text; reader = command.ExecuteReader(); } catch (Exception ex) { NCacheLog.Error(ex.ToString()); } finally { if (reader != null) { reader.Close(); reader.Dispose(); reader = null; } } } _oledbConPool.RemoveAllResources(); //clear the table for dependency count. _tblDepCount = null; } lock (_sqlConPool) { IDbConnection connection = null; IEnumerator em = _sqlConPool.Keys.GetEnumerator(); while (em.MoveNext()) { IDataReader reader = null; IDbCommand command = null; try { DbConnectionPool.DbResourceInfo connInfo = (DbConnectionPool.DbResourceInfo)_sqlConPool.GetResource((string)em.Current); connection = connInfo.Connection; command = connection.CreateCommand(); command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE CACHE_ID = '{1}'", tableInfo); command.CommandType = CommandType.Text; reader = command.ExecuteReader(); } catch (Exception ex) { NCacheLog.Error(ex.ToString()); } finally { if (reader != null) { reader.Close(); reader.Dispose(); reader = null; } } } _sqlConPool.RemoveAllResources(); } }