public override object Remove(string key, LockHandle lockHandle) { object obj = null; string exceptionMessage = null; try { obj = _webCache.Remove(key, lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Remove(string key, LockHandle lockHandle)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return(obj); }
public override void Delete(string key, LockHandle lockHandle) { string exceptionMessage = null; try { _webCache.Delete(key, lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Delete(string key, LockHandle lockHandle)"; _apiLogger.Log(logItem); } } catch (Exception) { } } }
public override void Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock) { string exceptionMessage = null; try { _webCache.Insert(key, item, lockHandle, releaseLock); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, item, exceptionMessage); logItem.Signature = "Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } }
public override bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle) { bool result; string exceptionMessage = null; try { result = _webCache.Lock(key, lockTimeout, out lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle)"; logItem.LockTimeout = lockTimeout; _apiLogger.Log(logItem); } } catch (Exception) { } } return(result); }
public override object Get(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock) { Object obj = null; try { obj = _webCache.Get(key, lockTimeout, ref lockHandle, acquireLock); } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Get(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock)"; logItem.Key = key; logItem.LockTimeout = lockTimeout; logItem.AcquireLock = acquireLock; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return(obj); }
public override CacheItem GetCacheItem(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock) { CacheItem cItem = null; string exceptionMessage = null; try { cItem = _webCache.GetCacheItem(key, lockTimeout, ref lockHandle, acquireLock); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "GetCacheItem(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock)"; logItem.LockTimeout = lockTimeout; logItem.AcquireLock = acquireLock; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return(cItem); }
public static void Main(string[] args) { try { //Initialize cache Cache cache; cache = NCache.InitializeCache("mypartitionedcache"); cache.Clear(); //Locking prevents multiple clients from updating the same data simultaneously //and also provides the data consistency. //Adding an item the cache Customer customer = new Customer(); customer.Name = "Kirsten Goli"; customer.Age = 40; customer.Address = "45-A West Boulevard, Cartago, Costa Rica"; customer.Gender = "Female"; customer.ContactNo = "52566-1779"; cache.Add("Customer:KirstenGoli", customer); //Get TimeSpan timeSpan = new TimeSpan(0,0,0,20); LockHandle lockHandle = new LockHandle(); Customer getCustomer = (Customer) cache.Get("Customer:KirstenGoli", timeSpan, ref lockHandle, true); PrintCustomerDetails(getCustomer); Console.WriteLine("Lock acquired on " + lockHandle.LockId); //Lock item in cache bool isLocked = cache.Lock("Customer:KirstenGoli", timeSpan, out lockHandle); if (!isLocked) { Console.WriteLine("Lock acquired on " + lockHandle.LockId); } //Unlock item in cache cache.Unlock("Customer:KirstenGoli"); //Unlock via lockhandle cache.Unlock("Customer:KirstenGoli", lockHandle); //Must dispose cache cache.Dispose(); Environment.Exit(0); } catch (Exception ex) { Console.WriteLine(ex.Message); Environment.Exit(0); } }
internal virtual void Delete(string key, LockHandle lockHandle, LockAccessType accessType) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (key == null) throw new ArgumentNullException("key"); if (key == string.Empty) throw new ArgumentException("key cannot be empty string"); try { UsageStats stats = new UsageStats(); stats.BeginSample(); object lockId = (lockHandle == null) ? null : lockHandle.LockId; BitSet flagMap = new BitSet(); _cacheImpl.Delete(key, flagMap, lockId, accessType); } catch (Exception) { if (ExceptionsEnabled) throw; } }
internal virtual object GetInternal(string key, LockAccessType accessType, TimeSpan lockTimeout, ref LockHandle lockHandle) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (key == null) throw new ArgumentNullException("key"); if (key == string.Empty) throw new ArgumentException("key cannot be empty string"); long objectSize = 0; CompressedValueEntry result = null; try { BitSet flagMap = new BitSet(); UsageStats stats = new UsageStats(); stats.BeginSample(); result = _cacheImpl.Get(key, flagMap, ref lockHandle, lockTimeout, accessType); if (_perfStatsCollector != null) { stats.EndSample(); _perfStatsCollector.IncrementMsecPerGetSample(stats.Current); _perfStatsCollector.IncrementGetPerSecStats(); } if (result != null && result.Value != null) { if (result.Value is CallbackEntry) { CallbackEntry e = result.Value as CallbackEntry; result.Value = e.Value; } if (DebugAPIConfiguraions.LoggingEnabled) objectSize = result.Value is byte[] ? ((byte[])result.Value).Length : 0; result.Value = SafeDeserialize(result.Value, _serializationContext, result.Flag); if (DebugAPIConfiguraions.LoggingEnabled) LogSizeInfo(false, objectSize); return result.Value; } } catch (Exception) { if (ExceptionsEnabled) throw; else return null; } return null; }
/// <summary> /// Inserts a <see cref="CacheItem"/> to the cache if not already existing. /// Otherwise updates an existing item if it not already locked or if the correct lock-id is specified. /// </summary> /// <param name="key">The cache key used to reference the item.</param> /// <param name="item">The item that is to be stored</param> /// <param name="lockHandle">An instance of <see cref="LockHandle"/>. If the item is locked, then it can be updated only if the correct lockHandle is specified.</param> /// <param name="releaseLock">A flag to determine whether or not release lock after operation is performed.</param> /// <remarks>If lockId does not match with the lockId associated with cached item, /// an exception will be thrown.</remarks> /// <example>The following example demonstrates how to update a locked item in the cache. /// /// First create a CacheItem. /// <code> /// Cache theCache = NCache.InitializeCache("myreplicatedcache"); /// </code> /// Add an item int the cache. /// <code> /// theCache.Add("cachedItemKey", new CacheItem("cachedItemValue")); /// </code> /// Create the objects for lockid and lockdate. /// <code> /// LockHandle lockHandle = new LockHandle(); /// </code> /// Get the added item from cache and acquire a lock. /// <code> /// object cachedItem = theCache.Get("cachedItemKey", Cache.NoLockingExpiration, ref lockHandle, true); /// if (cachedItem != null) /// { /// try /// { /// theCache.Insert("cachedItemKey", new CacheItem("someothervalue"), lockHandle, true); /// string cachedValue = (string)theCache.Get("cachedItemKey"); /// } /// catch (OperationFailedException ex) /// { /// //Do something /// } /// } /// </code> /// </example> public virtual void Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock) { if (item == null) throw new ArgumentNullException("CacheItem"); LockAccessType accessType = releaseLock ? LockAccessType.RELEASE : LockAccessType.DONT_RELEASE; long size = 0; InsertOperation(key, item.Value, item.AbsoluteExpiration, item.SlidingExpiration, item.Priority, lockHandle, accessType, item.CacheItemUpdatedCallback, item.CacheItemRemovedCallback, item.ItemUpdatedCallabackDataFilter, item.ItemRemovedCallabackDataFilter, ref size, true); }
/// <summary> /// Removes an item from cache if it is not already locked or if the correct lock-id is specified. /// </summary> /// <param name="key">key of item to be removed</param> /// <param name="lockHandle">If the item is locked then, it can be removed only if the correct lockHandle is specified.</param> /// <returns>The item removed from the Cache. If the value in the key parameter /// is not found, returns a null reference (Nothing in Visual Basic).</returns> /// <example>The following example demonstrates how to remove a locked item from the cache. /// /// First create a CacheItem. /// <code> /// Cache theCache = NCache.InitializeCache("myreplicatedcache"); /// </code> /// Add an item int the cache. /// <code> /// theCache.Add("cachedItemKey", "cachedItemValue"); /// </code> /// Create the lock-handle. /// <code> /// LockHandle lockHandle = new LockHandle(); /// </code> /// Get the added item from cache and acquire a lock. /// <code> /// object cachedItem = theCache.Get("cachedItemKey", ref lockHandle, true); /// if (cachedItem != null) /// { /// try /// { /// //Now remove the cached item using lockHandle acquired earlier. /// object removedItem = theCache.Remove("cachedItemKey", lockHandle); /// } /// catch (OperationFailedException ex) /// { /// //Do something /// } /// } /// </code> /// </example> public virtual object Remove(string key, LockHandle lockHandle) { return Remove(key, lockHandle, LockAccessType.DEFAULT); }
internal override bool IsLocked(string key, ref LockHandle lockHandle) { if (_nCache != null) { object lockId = null; DateTime lockDate = new DateTime(); if (lockHandle == null) lockHandle = new LockHandle(); bool result = _nCache.IsLocked(key, ref lockId, ref lockDate, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation)); lockHandle.LockId = lockId == null ? "" : lockId as string; lockHandle.LockDate = lockDate; return result; } return false; }
public object Get(string key, ref LockHandle lockHandle, bool acquireLock, bool enableRetry) { object value = null; int retry = _operationRetry; do { try { value = _cache.Get(key, Alachisoft.NCache.Web.Caching.Cache.NoLockExpiration, ref lockHandle, acquireLock); break; } catch (Exception ex) { string message = ex.Message; if (message != null && !(message.ToLower().Contains("connection with server") || message.ToLower().Contains("no server is available")) || !enableRetry) { throw; } if (retry <= 0) throw ex; retry--; if (_operationRetryDelayInterval > 0) Thread.Sleep(_operationRetryDelayInterval); } } while (retry >= 0); return value; }
public virtual CompressedValueEntry Get(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) { return(null); }
internal override void InsertOperation(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, LockHandle lockHandle, LockAccessType accessType, CacheDataNotificationCallback cacheItemUdpatedCallback, CacheDataNotificationCallback cacheItemRemovedCallaback, EventDataFilter itemUpdateDataFilter, EventDataFilter itemRemovedDataFilter, ref long size, bool allowQueryTags) { _webCache.InsertOperation(key, value, absoluteExpiration, slidingExpiration, priority, lockHandle, accessType, cacheItemUdpatedCallback, cacheItemRemovedCallaback, itemUpdateDataFilter, itemRemovedDataFilter, ref size, true); }
public override bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle) { bool result; string exceptionMessage = null; try { result = _webCache.Lock(key, lockTimeout, out lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle)"; logItem.LockTimeout = lockTimeout; _apiLogger.Log(logItem); } } catch (Exception) { } } return result; }
internal virtual bool IsLocked(string key, ref LockHandle lockHandle) { return(false); }
public virtual bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle) { lockHandle = null; return(false); }
public virtual object GetCacheItem(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) { return(null); }
public override object Get(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock) { Object obj = null; try { obj = _webCache.Get(key, lockTimeout, ref lockHandle, acquireLock); } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Get(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock)"; logItem.Key = key; logItem.LockTimeout = lockTimeout; logItem.AcquireLock = acquireLock; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return obj; }
public void Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock, bool enableRetry) { int retry = _operationRetry; do { try { _cache.Insert(key, item, lockHandle, releaseLock); break; } catch(Exception ex) { string message = ex.Message; if (message != null && !(message.ToLower().Contains("connection with server") || message.ToLower().Contains("no server is available")) || !enableRetry) { throw; } if (retry <= 0) throw ex; retry--; if (_operationRetryDelayInterval > 0) Thread.Sleep(_operationRetryDelayInterval); } } while (retry >= 0); }
internal override object GetInternal(string key, LockAccessType accessType, TimeSpan lockTimeout, ref LockHandle lockHandle) { return(_webCache.GetInternal(key, accessType, lockTimeout, ref lockHandle)); }
public override object Remove(string key, LockHandle lockHandle) { object obj = null; string exceptionMessage = null; try { obj = _webCache.Remove(key, lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Remove(string key, LockHandle lockHandle)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return obj; }
public object Remove(string key, LockHandle lockHandle, bool enableRetry) { object value = null; int retry = _operationRetry; do{ try { value = _cache.Remove(key, lockHandle); break; } catch(Exception ex) { string message = ex.Message; if (message != null && !(message.ToLower().Contains("connection with server") || message.ToLower().Contains("no server is available")) || !enableRetry) { throw; } if (retry <= 0) throw ex; retry--; if (_operationRetryDelayInterval > 0) Thread.Sleep(_operationRetryDelayInterval); } } while(retry>=0); return value; }
public override object GetCacheItem(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) { if (lockHandle == null) lockHandle = new LockHandle(); object lockId = lockHandle.LockId; DateTime lockDate = new DateTime(); OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true); CacheEntry entry = _nCache.GetCacheEntry(key, ref lockId, ref lockDate, lockTimeout, accessType, operationContext) as CacheEntry; if (entry != null) { if (entry.Value is CallbackEntry) { CallbackEntry cbEntry = entry.Value as CallbackEntry; if (cbEntry.Value is UserBinaryObject) { cbEntry.Value = ((UserBinaryObject)cbEntry.Value).GetFullObject(); } } else { if (entry.Value is UserBinaryObject) { entry.Value = ((UserBinaryObject)entry.Value).GetFullObject(); } } } lockHandle.LockId = lockId == null ? null : lockId as string; lockHandle.LockDate = lockDate; return entry; }
/// <summary> /// Acquire a lock on an item in cache. /// </summary> /// <param name="key">key of cached item to be locked.</param> /// <param name="lockTimeout">TimeSpan after which the lock is automatically released.</param> /// <param name="lockHandle">An instance of <see cref="Lockhandle"/> that will be filled in with the lock information if lock is acquired successfully.</param> /// <returns>Whether or not lock was acquired successfully.</returns> /// <example> /// Following example demonstrates how to lock a cached item. /// <code> /// ... /// LockHandle lockHandle = new LockHandle(); /// bool locked = theCache.lock("cachedItemKey", new TimeSpan(0,0,10), out lockHandle); /// ... /// </code> /// </example> public override bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle) { object lockId = null; DateTime lockDate = DateTime.Now; lockHandle = null; if (_nCache != null) { bool result = _nCache.Lock(key, lockTimeout, out lockId, out lockDate, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation)); lockHandle = new LockHandle(lockId == null ? null : lockId as string, lockDate); return result; } return false; }
public override object GetCacheItem(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) { if (lockHandle == null) lockHandle = new LockHandle(); object lockId = lockHandle.LockId; GetCacheItemCommand command = new GetCacheItemCommand(key, flagMap, accessType, lockId, lockTimeout); Request request = _broker.CreateRequest(command); _broker.ExecuteRequest(request); CommandResponse res = request.Response; res.ParseResponse(); lockHandle.LockId = res.LockId as string; lockHandle.LockDate = res.LockDate; return res.Item; }
/// <summary> /// Retrieves the specified item from the Cache object. If the object is read thru the data source, ///</summary> /// <param name="key">The identifier for the cache item to retrieve.</param> /// <returns>The retrieved cache item, or a null reference (Nothing /// in Visual Basic) if the key is not found.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> contains a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="key"/> is not serializable.</exception> /// <remarks> /// <para><b>Note:</b> If exceptions are enabled through the <see cref="NCache.ExceptionsEnabled"/> /// setting, this property throws exception incase of failure.</para> /// </remarks> /// <example>The following example demonstrates how to retrieve the value cached for an ASP.NET text /// box server control. /// <code> /// /// NCache.Cache.Get("MyTextBox.Value"); /// /// </code> /// Or simply in a class deriving from <see cref="Alachisoft.NCache.Web.UI.NPage"/> or <see cref="Alachisoft.NCache.Web.UI.NUserControl"/>. /// <code> /// /// Cache.Get("MyTextBox.Value"); /// /// </code> /// </example> public override CompressedValueEntry Get(string key, BitSet flagMap, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType) { object lockId = lockHandle == null ? null : lockHandle.LockId; DateTime lockDate = new DateTime(); if (_nCache != null) { CompressedValueEntry cmpEntry = _nCache.Get(key, flagMap, ref lockId, ref lockDate, lockTimeout, accessType, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation)); if (cmpEntry != null && cmpEntry.Value != null) { //muds: //incase of inproc local cache we will get the user object directly... //therefore, we need to confirm if the value is user binary object or not... if (cmpEntry.Value is UserBinaryObject) { if (cmpEntry.Value is UserBinaryObject) { UserBinaryObject ubObject = cmpEntry.Value as UserBinaryObject; cmpEntry.Value = ubObject.GetFullObject(); } } } if (lockHandle == null) lockHandle = new LockHandle(); lockHandle.LockId = lockId == null ? null : lockId as string; lockHandle.LockDate = lockDate; return cmpEntry; } return null; }
public override CacheItem GetCacheItem(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock) { CacheItem cItem = null; string exceptionMessage = null; try { cItem = _webCache.GetCacheItem(key, lockTimeout, ref lockHandle, acquireLock); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "GetCacheItem(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock)"; logItem.LockTimeout = lockTimeout; logItem.AcquireLock = acquireLock; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return cItem; }
internal override bool IsLocked(string key, ref LockHandle lockHandle) { if (lockHandle == null) lockHandle = new LockHandle(); IsLockedCommand command = new IsLockedCommand(key, lockHandle.LockId); Request request = _broker.CreateRequest(command); _broker.ExecuteRequest(request); CommandResponse res = request.Response; res.ParseResponse(); lockHandle.LockId = res.LockId as string; lockHandle.LockDate = res.LockDate; return res.IsLocked; }
internal override bool IsLocked(string key, ref LockHandle lockHandle) { return(_webCache.IsLocked(key, ref lockHandle)); }
public override bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHanlde) { LockCommand command = new LockCommand(key, lockTimeout); Request request = _broker.CreateRequest(command); _broker.ExecuteRequest(request); CommandResponse res = request.Response; res.ParseResponse(); lockHanlde = new LockHandle(res.LockId as string, res.LockDate); return res.LockAcquired; }
internal override object Remove(string key, LockHandle lockHandle, LockAccessType accessType) { return(_webCache.Remove(key, lockHandle, accessType)); }
/// <summary> /// Acquire a lock on an item in cache. /// </summary> /// <param name="key">key of cached item to be locked.</param> /// <param name="lockTimeout">TimeSpan after which the lock is automatically released.</param> /// <param name="lockHandle">An instance of <see cref="Lockhandle"/> that will be filled in with the lock information if lock is acquired successfully.</param> /// <returns>Whether or not lock was acquired successfully.</returns> /// <example> /// Following example demonstrates how to lock a cached item. /// <code> /// ... /// LockHandle lockHandle = new LockHandle(); /// bool locked = theCache.lock("cachedItemKey", new TimeSpan(0,0,10), out lockHandle); /// ... /// </code> /// </example> public virtual bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (key == null) throw new ArgumentNullException("key is null."); lockHandle = null; bool lockAcquired = false; try { lockAcquired = _cacheImpl.Lock(key, lockTimeout, out lockHandle); } catch (Exception) { if (ExceptionsEnabled) throw; } return lockAcquired; }
internal override void Delete(string key, LockHandle lockHandle, LockAccessType accessType) { _webCache.Delete(key, lockHandle, accessType); }
/// <summary> /// Unlocks a locked cached item if the correct lock-id is specified. /// </summary> /// <param name="key">key of a cached item to be unlocked</param> /// <param name="lockHandle">An instance of <see cref="LockHandle"/> that was generated when lock was acquired.</param> /// <example> /// Following example demonstrates how to unlock a cached item. /// <code> /// ... /// theCache.Unlock("cachedItemKey", lockHandle); /// ... /// </code> /// </example> public virtual void Unlock(string key, LockHandle lockHandle) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (key == null) throw new ArgumentNullException("key is null."); object lockId = (lockHandle == null) ? null : lockHandle.LockId; try { _cacheImpl.Unlock(key, lockId); } catch (Exception) { if (ExceptionsEnabled) throw; } }
/// <summary> /// Determines if item in cache is locked. /// </summary> /// <param name="key">key of item to check for lock</param> /// <param name="lockHandle">lockHandle will be set if item is locked</param> /// <returns>true if the item is locked, false otherwise</returns> internal virtual bool IsLocked(string key, ref LockHandle lockHandle) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (key == null) throw new ArgumentNullException("key is null."); try { return _cacheImpl.IsLocked(key, ref lockHandle); } catch (Exception) { if (ExceptionsEnabled) throw; } return false; }
internal virtual CacheItem GetCacheItemInternal(string key, LockAccessType accessType, TimeSpan lockTimeout, ref LockHandle lockHandle) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (key == null) throw new ArgumentNullException("keys"); if (key == string.Empty) throw new ArgumentException("key cannot be empty string"); try { CacheItem item = new CacheItem(); Alachisoft.NCache.Caching.CacheEntry entry = null; BitSet flagMap = new BitSet(); object value = _cacheImpl.GetCacheItem(key, flagMap, ref lockHandle, lockTimeout, accessType); long objectSize = 0; if (value == null) return null; if (value is CacheItem) { item = (CacheItem)value; if (_perfStatsCollector != null && ((CacheItem)value).Value != null && ((CacheItem)value).Value is byte[]) _perfStatsCollector.IncrementAvgItemSize(((byte[])((CacheItem)value).Value).Length); if (DebugAPIConfiguraions.LoggingEnabled) objectSize = ((byte[])item.Value).Length; item.Value = SafeDeserialize(item.Value, _serializationContext, item.FlagMap); if (item.AbsoluteExpiration != Cache.NoAbsoluteExpiration) { item.AbsoluteExpiration = item.AbsoluteExpiration.ToLocalTime(); } if (DebugAPIConfiguraions.LoggingEnabled) LogSizeInfo(false, objectSize); return item; } entry = (Alachisoft.NCache.Caching.CacheEntry)value; item.FlagMap = entry.Flag; if (entry.Value is CallbackEntry) { CallbackEntry cb = (CallbackEntry)entry.Value; if (cb.ItemRemoveCallbackListener != null && cb.ItemRemoveCallbackListener.Count > 0) { foreach (CallbackInfo cbInfo in cb.ItemRemoveCallbackListener) { if (cbInfo.Client == _cacheImpl.ClientID) { item.SetCacheDataNotification((CacheDataNotificationCallback)_callbackIDsMap.GetResource(cbInfo.Callback), EventType.ItemRemoved); break; } } } if (cb.ItemUpdateCallbackListener != null && cb.ItemUpdateCallbackListener.Count > 0) { foreach (CallbackInfo cbInfo in cb.ItemUpdateCallbackListener) { if (cbInfo.Client == _cacheImpl.ClientID) { item.SetCacheDataNotification((CacheDataNotificationCallback)_callbackIDsMap.GetResource(cbInfo.Callback), EventType.ItemUpdated); break; } } } item.Value = cb.Value; if (_perfStatsCollector != null && item.Value != null && item.Value is byte[]) _perfStatsCollector.IncrementAvgItemSize(((byte[])item.Value).Length); item.Value = SafeDeserialize(cb.Value, _serializationContext, item.FlagMap); } else { item.Value = entry.Value; if (_perfStatsCollector != null && item.Value != null && item.Value is byte[]) _perfStatsCollector.IncrementAvgItemSize(((byte[])item.Value).Length); if (DebugAPIConfiguraions.LoggingEnabled) objectSize = ((byte[])entry.Value).Length; item.Value = SafeDeserialize(entry.Value, _serializationContext, item.FlagMap); } if (DebugAPIConfiguraions.LoggingEnabled) LogSizeInfo(false, objectSize); if (entry != null) { item.Priority = (CacheItemPriority)entry.Priority; } ExpirationHint hint = entry.ExpirationHint; DateTime absoluteExpiration = DateTime.MaxValue.ToUniversalTime(); TimeSpan slidingExpiration = TimeSpan.Zero; Alachisoft.NCache.Caching.AutoExpiration.DependencyHelper.GetActualCacheDependency(hint, ref absoluteExpiration, ref slidingExpiration); if (absoluteExpiration != Cache.NoAbsoluteExpiration) { item.AbsoluteExpiration = absoluteExpiration.ToLocalTime(); } item.SlidingExpiration = slidingExpiration; item._creationTime = entry.CreationTime; item._lastModifiedTime = entry.LastModifiedTime; return item; } catch (Exception) { if (ExceptionsEnabled) throw; } return null; }
/// <summary> /// Removes an item from cache if it is not already locked or if the correct lock-id is specified. /// </summary> /// <param name="key">key of item to be removed</param> /// <param name="lockHandle">If the item is locked then, it can be removed only if the correct lockHandle is specified.</param> /// <example>The following example demonstrates how to remove a locked item from the cache. /// /// First create a CacheItem. /// <code> /// Cache theCache = NCache.InitializeCache("myreplicatedcache"); /// </code> /// Add an item int the cache. /// <code> /// theCache.Add("cachedItemKey", "cachedItemValue"); /// </code> /// Create the lock-handle. /// <code> /// LockHandle lockHandle = new LockHandle(); /// </code> /// Get the added item from cache and acquire a lock. /// <code> /// object cachedItem = theCache.Get("cachedItemKey", ref lockHandle, true); /// if (cachedItem != null) /// { /// try /// { /// //Now remove the cached item using lockHandle acquired earlier. /// theCache.Delete("cachedItemKey", lockHandle); /// } /// catch (OperationFailedException ex) /// { /// //Do something /// } /// } /// </code> /// </example> public virtual void Delete(string key, LockHandle lockHandle) { Delete(key, lockHandle, LockAccessType.DEFAULT); }
/// <summary> /// Function that choose the appropriate function of NCache's Cache, that need to be called /// according to the data provided to it.</summary> internal virtual void InsertOperation(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, LockHandle lockHandle, LockAccessType accessType, CacheDataNotificationCallback cacheItemUdpatedCallback, CacheDataNotificationCallback cacheItemRemovedCallaback, EventDataFilter itemUpdateDataFilter, EventDataFilter itemRemovedDataFilter, ref long size, bool allowQueryTags) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); ValidateKeyValue(key, value); UsageStats stats = new UsageStats(); stats.BeginSample(); Hashtable queryInfo = new Hashtable(); object lockId = (lockHandle == null) ? null : lockHandle.LockId; if (allowQueryTags) { queryInfo["query-info"] = GetQueryInfo(value); } short removeCallbackId = -1; short updateCallbackId = -1; short dsItemUpdateCallbackId = -1; BitSet flagMap = new BitSet(); try { value = SafeSerialize(value, _serializationContext, ref flagMap, ref size); long objectSize = 0; if (DebugAPIConfiguraions.LoggingEnabled) objectSize = value is byte[] ? ((byte[])value).Length : 0; if (_perfStatsCollector != null && value != null && value is byte[]) _perfStatsCollector.IncrementAvgItemSize(((byte[])value).Length); if (cacheItemRemovedCallaback != null) { short[] callabackIds = _eventManager.RegisterSelectiveEvent(cacheItemRemovedCallaback, EventType.ItemRemoved, itemRemovedDataFilter); removeCallbackId = callabackIds[1]; } if (cacheItemUdpatedCallback != null) { short[] callabackIds = _eventManager.RegisterSelectiveEvent(cacheItemUdpatedCallback, EventType.ItemUpdated, itemUpdateDataFilter); updateCallbackId = callabackIds[0]; } if (lockId != null && ((string)lockId) != string.Empty) flagMap.SetBit(BitSetConstants.LockedItem); else flagMap.UnsetBit(BitSetConstants.LockedItem); absoluteExpiration = ToUTC(absoluteExpiration); _cacheImpl.Insert(key, value, absoluteExpiration, slidingExpiration, priority, removeCallbackId, updateCallbackId, queryInfo, flagMap, lockId, accessType, itemUpdateDataFilter, itemRemovedDataFilter, size); if (_perfStatsCollector != null) { stats.EndSample(); _perfStatsCollector.IncrementMsecPerUpdSample(stats.Current); _perfStatsCollector.IncrementUpdPerSecStats(); } } catch (Exception) { if (ExceptionsEnabled) throw; } }
internal virtual object Remove(string key, LockHandle lockHandle, LockAccessType accessType) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (key == null) throw new ArgumentNullException("key"); if (key == string.Empty) throw new ArgumentException("key cannot be empty string"); long objectSize = 0; try { UsageStats stats = new UsageStats(); stats.BeginSample(); object lockId = (lockHandle == null) ? null : lockHandle.LockId; BitSet flagMap = new BitSet(); short dsItemRemovedCallbackId = -1; CompressedValueEntry result = _cacheImpl.Remove(key, flagMap, lockId, accessType); if (result != null && result.Value != null) { if (result.Value != null && result.Value is CallbackEntry) { result.Value = ((CallbackEntry)result.Value).Value; } if (DebugAPIConfiguraions.LoggingEnabled) objectSize = result.Value is byte[] ? ((byte[])result.Value).Length : 0; result.Value = SafeDeserialize(result.Value, _serializationContext, result.Flag); if (_perfStatsCollector != null) { stats.EndSample(); _perfStatsCollector.IncrementMsecPerDelSample(stats.Current); _perfStatsCollector.IncrementDelPerSecStats(); } if (DebugAPIConfiguraions.LoggingEnabled) LogSizeInfo(false, objectSize); return result.Value; } else { if (_perfStatsCollector != null) { stats.EndSample(); _perfStatsCollector.IncrementMsecPerDelSample(stats.Current); _perfStatsCollector.IncrementDelPerSecStats(); } } } catch (Exception) { if (ExceptionsEnabled) throw; } return null; }
private SessionStateStoreData getSessionStoreItem(bool acquireLock, HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockID, out SessionStateActions action) { //lock age is set to zero, so SessionStateModule will, //after 0.5 sec, calls this GetItemExclusive function until a value or //null reference is returned. If no data was found, 'locked' is set to false and //null reference is returned which tells SessionStateModule to call CreateDataStore //function to create new data store locked = false; lockAge = TimeSpan.Zero; lockID = null; action = SessionStateActions.InitializeItem; DateTime lockDate = DateTime.UtcNow; LockHandle lockHandle = new LockHandle(null, lockDate); SessionStateStoreData items = null; Hashtable table = null; bool lockTimedOut = false; try { byte[] buffer = null; lock (s_dataLock) { if (s_cacheNeedInit) InitializeCache(); } if (_lockSessions) { try { buffer = (byte[])_cache.Get(GetUniqueSessionId(id), ref lockHandle, acquireLock, true); } catch (Exception) { buffer = (byte[])_cache.Get(GetUniqueSessionId(id), ref lockHandle, acquireLock, false); } lockID = lockHandle.LockId == null ? null : lockHandle; lockDate = lockHandle == null ? DateTime.UtcNow : lockHandle.LockDate; } else { try { buffer = (byte[])_cache.Get(GetUniqueSessionId(id), true); } catch (Exception) { buffer = (byte[])_cache.Get(GetUniqueSessionId(id), false); } } if (buffer != null) { using (MemoryStream stream = new MemoryStream(buffer)) { BinaryFormatter formatter = new BinaryFormatter(); table = formatter.Deserialize(stream) as Hashtable; stream.Close(); } } if (_lockSessions && !String.IsNullOrEmpty(lockHandle.LockId)) { DateTime now = DateTime.UtcNow; if ((0L < lockDate.Ticks) && (lockDate.Ticks < now.Ticks)) { lockAge = (TimeSpan)(now - lockDate); } else { lockAge = TimeSpan.Zero; } /// Following 'if' block is executed if item is locked. /// i.e NCache API returns null and out variables are populated with lockId and lockDate /// Note: Item exists in cache but is locked. if (table == null) { locked = true; return null; } } /// If item exists in cahce and lock acqusition was successfull or locking was disabled. if (table != null) { items = GetContents(context, table, ref action); if (action == SessionStateActions.InitializeItem) { items = CreateNewStoreData(context, items.Timeout); } } else { if(NCacheLog!= null) NCacheLog.Error(id + " :session not found in cache"); } } catch (Exception exc) { /// If item is not found in Remote cache. /// Update cookies to do any further operations for this session request on current primary cache; /// and do not raise exception. RaiseException(exc, id); } finally { if ((lockTimedOut || table != null) && context.Items.Contains(SESSION_LOCK_COUNT)) context.Items.Remove(SESSION_LOCK_COUNT); } return items; }
/// <summary> /// Get the cache item stored in cache. /// </summary> /// <param name="key">Key used to reference the desired object</param> /// <param name="lockTimeout">The TimeSpan after which the lock is automatically released.</param> /// <param name="lockHandle">An instance of <see cref="LockHandle"/> to hold the lock information.</param> /// <param name="acquireLock">A flag to determine whether to acquire a lock or not.</param> /// <returns>The retrieved cache item, or a null reference (Nothing /// in Visual Basic) if the key is not found. /// </returns> /// <remarks> /// /// <para><b>Note:</b> If exceptions are enabled through the <see cref="ExceptionsEnabled"/> /// setting, this property throws exception incase of failure.</para> /// </remarks> /// <example>The following example demonstrates how to retrieve the value cached for an ASP.NET text /// box server control. /// <code> /// Cache cache = NCache.InitializeCache("myCache"); /// LockHandle lockHandle = new LockHandle(); /// CacheItem item = cache.GetCacheItem("cachedItemKey",TimeSpan.FromSeconds(30) , ref lockHandle, true); /// /// </code> /// </example> public virtual CacheItem GetCacheItem(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock) { try { LockAccessType accessType = acquireLock ? LockAccessType.ACQUIRE : LockAccessType.DONT_ACQUIRE; return GetCacheItemInternal(key, accessType, lockTimeout, ref lockHandle); } catch (Exception) { if (ExceptionsEnabled) throw; return null; } }
public virtual object GetCacheItem(string key, BitSet flagMap, string group, string subGroup, ref CacheItemVersion version, ref LockHandle lockHandle, TimeSpan lockTimeout, LockAccessType accessType, string providerName) { return(null); }