/// <summary> Insert list of <see cref="CacheItem"/> to the cache </summary> /// <param name="keys">The cache keys used to reference the items.</param> /// <param name="items">The items that are to be stored</param> /// <returns>returns keys that are added or updated successfully and their status.</returns> /// <remarks> If CacheItem contains invalid values the related exception is thrown. /// See <see cref="CacheItem"/> for invalid property values and related exceptions</remarks> /// <example>The following example demonstrates how to assign an item high priority when you insert /// it into your application's <see cref="Cache"/> object. /// <para><b>Note: </b>For more information about how to use this method with the <see cref="CacheItemRemovedCallback"/> /// delegate, see <see cref="CacheItemRemovedCallback"/>. /// </para> /// First create CacheItems. /// <code> /// string[] keys = {"SQLDSN", "ORADSN"}; /// CacheItem items[] = new CacheItem[2]; /// items[0] = new CacheItem(sqlConnectionString); /// item.AbsoluteExpiration = DateTime.Now.AddMinutes(2); /// item.SlidingExpiration = TimeSpan.Zero; /// item.Priority = CacheItemPriority.High; /// item.ItemRemoveCallback = onRemove; /// /// items[1] = new CacheItem(oraConnectionString); /// item.AbsoluteExpiration = DateTime.Now.AddMinutes(1); /// item.SlidingExpiration = TimeSpan.Zero; /// item.Priority = CacheItemPriority.Low; /// item.ItemRemoveCallback = onRemove; /// </code> /// /// Then insert CacheItems to the cache /// <code> /// /// NCache.Cache.Insert(keys, items); /// /// </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.Insert(keys, items); /// /// </code> /// </example> public override IDictionary Insert(string[] keys, CacheItem[] items, long[] sizes) { if (_nCache == null) return null; object[] entries = new object[items.Length]; ExpirationHint hint = null; short itemRemovedCallback = -1; short itemUpdatedCallback = -1; for (int i = 0; i < items.Length; i++) { string key = keys[i]; CacheItem item = items[i]; itemRemovedCallback = -1; itemUpdatedCallback = -1; if (item.CacheItemRemovedCallback != null) { short[] callabackIds = _parent.EventManager.RegisterSelectiveEvent(item.CacheItemRemovedCallback, EventType.ItemRemoved, item.ItemRemovedCallabackDataFilter); itemRemovedCallback = callabackIds[1]; } if (item.CacheItemUpdatedCallback != null) { short[] callabackIds = _parent.EventManager.RegisterSelectiveEvent(item.CacheItemUpdatedCallback, EventType.ItemUpdated, item.ItemUpdatedCallabackDataFilter); itemUpdatedCallback = callabackIds[0]; } Hashtable queryInfoDic = item.QueryInfo["query-info"] as Hashtable; if (queryInfoDic != null) { IDictionaryEnumerator queryInfoEnum = queryInfoDic.GetEnumerator(); while (queryInfoEnum.MoveNext()) { ArrayList valuesEnum = (ArrayList)queryInfoEnum.Value; for (int j = 0; j < valuesEnum.Count; j++) { if (valuesEnum[j] is DateTime) { valuesEnum[j] = ((DateTime)valuesEnum[j]).Ticks.ToString(); } } } } entries[i] = MakeCompactEntry(key, item.Value, item.AbsoluteExpiration, item.SlidingExpiration, item.Priority, itemRemovedCallback, itemRemovedCallback, item.QueryInfo, item.FlagMap, null, LockAccessType.IGNORE_LOCK, item.ItemUpdatedCallabackDataFilter, item.ItemRemovedCallabackDataFilter); } OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); operationContext.Add(OperationContextFieldName.ValueDataSize, sizes); return _nCache.InsertEntries(entries, operationContext); }
public void Insert(string key, CacheItem item, bool enableRetry) { _cache.Insert(key, item); }
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); }
/// <summary> /// Add a <see cref="CacheItem"/> to the cache /// </summary> /// <param name="key">The cache key used to reference the item.</param> /// <param name="item">The item that is to be stored</param> /// <remarks> If CacheItem contains invalid values the related exception is thrown. /// See <see cref="CacheItem"/> for invalid property values and related exceptions</remarks> /// <example>The following example demonstrates how to add an item to the cache with an absolute /// expiration of 2 minutes from now, a priority of high, and that notifies the application when the item is removed from the cache. /// /// First create a CacheItem. /// <code> /// object someData = new object(); /// CacheItem item = new CacheItem(someData); /// item.AbsoluteExpiration = DateTime.Now.AddMinutes(2); /// item.Priority = CacheItemPriority.High; /// item.ItemRemoveCallback = onRemove; /// </code> /// /// Then add CacheItem to the cache /// <code> /// /// Cache cache = NCache.InitializeCache("myCache"); /// cache.Add("someData", item); /// /// </code> /// </example> public virtual void Add(string key, CacheItem item) { try { long size = 0; if (item == null) throw new ArgumentNullException("CacheItem"); AddOperation(key, item.Value, item.AbsoluteExpiration, item.SlidingExpiration, item.Priority, item.CacheItemUpdatedCallback, item.CacheItemRemovedCallback, item.ItemUpdatedCallabackDataFilter, item.ItemRemovedCallabackDataFilter , ref size, true); } catch (Exception) { if (ExceptionsEnabled) throw; } }
internal bool GetKeysDistributionMap(string[] keys, CacheItem[] items, ref Dictionary<Address, KeyValuePair<string[], CacheItem[]>> keysDistributionMap) { bool itemNull = false; bool AddNull = false; bool pairKey = false; bool pairvalue = false; bool result = _importHashmap; bool itemsAvailable = items != null; try { if (result) { Dictionary<Address, Hashtable> keysDistributionList = new Dictionary<Address, Hashtable>(); Hashtable keysAndItems = null; string key = String.Empty; CacheItem item = null; for (int i = 0; i < keys.Length; i++) { key = keys[i]; if (itemsAvailable) item = items[i]; if (item == null) itemNull = true; Address address; lock (_hashmapUpdateMutex) { address = _pool.GetIp(key); if (address == null) AddNull = true; } if (keysDistributionList.ContainsKey(address)) { keysAndItems = keysDistributionList[address]; keysAndItems[key] = item; } else { keysAndItems = new Hashtable(); keysAndItems[key] = item; keysDistributionList[address] = keysAndItems; } } KeyValuePair<string[], CacheItem[]> tmp; Address serverAddress; foreach (KeyValuePair<Address, Hashtable> pair in keysDistributionList) { int index = 0; if (pair.Key == null) pairKey = true; else if (pair.Value == null) pairvalue = true; serverAddress = pair.Key; keysAndItems = pair.Value; string[] distributedKeys = new string[keysAndItems.Count]; CacheItem[] distributedItems = null; if (itemsAvailable) distributedItems = new CacheItem[keysAndItems.Count]; IDictionaryEnumerator ide = keysAndItems.GetEnumerator(); while (ide.MoveNext()) { distributedKeys[index] = ide.Key as string; if (itemsAvailable) distributedItems[index] = ide.Value as CacheItem; index++; } tmp = new KeyValuePair<string[], CacheItem[]>(distributedKeys, distributedItems); keysDistributionMap.Add(serverAddress, tmp); } } } catch (Exception e) { throw new Exception(" Custome exception : value null " + pairvalue + " key null : " + pairKey + " item null : " + itemNull + "Address null : " + AddNull + " Exception : " + e.ToString()); } return result; }
/// <summary> /// Add a <see cref="CacheItem"/> to the cache /// </summary> /// <param name="key">The cache key used to reference the item.</param> /// <param name="item">The item that is to be stored</param> /// <remarks> If CacheItem contains invalid values the related exception is thrown. /// See <see cref="CacheItem"/> for invalid property values and related exceptions</remarks> /// <example>The following example demonstrates how to add an item to the cache with a sliding expiration of 5 minutes and a priority of /// high, and that notifies the application when the item is removed from the cache. /// /// First create a CacheItem. /// <code> /// CacheItem item = new CacheItem(timeStamp); /// item.SlidingExpiration = new TimeSpan(0,5,0); /// item.Priority = CacheItemPriority.High; /// item.ItemRemoveCallback = onRemove; /// </code> /// /// Then add CacheItem to the cache /// <code> /// Cache cache = NCache.InitializeCache("myCache"); /// cache.Insert("timestamp", item); /// /// </code> /// </example> public virtual void Insert(string key, CacheItem item) { if (item == null) throw new ArgumentNullException("CacheItem"); long size = 0; InsertOperation(key, item.Value,item.AbsoluteExpiration, item.SlidingExpiration, item.Priority, null, LockAccessType.IGNORE_LOCK, item.CacheItemUpdatedCallback, item.CacheItemRemovedCallback, item.ItemUpdatedCallabackDataFilter, item.ItemRemovedCallabackDataFilter, ref size, true); }
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; }
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 IDictionary InsertBulk(string[] keys, CacheItem[] items) { System.Collections.IDictionary iDict = null; string exceptionMessage = null; try { iDict = _webCache.InsertBulk(keys, items); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "InsertBulk(string[] keys, CacheItem[] items)"; logItem.NoOfKeys = keys.Length; logItem.ExceptionMessage = exceptionMessage; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return iDict; }
private MutateOpResult UpdateIfNumeric(string key, CacheItem cacheItem, ulong value, UpdateType updateType) { MutateOpResult returnObject = new MutateOpResult(); MemcachedItem memCachedItem = (MemcachedItem)cacheItem.Value; if (memCachedItem != null) { ObjectArrayData objectDataArray = GetObjectArrayData(memCachedItem.Data); string tempObjectString = ""; try { tempObjectString = Encoding.ASCII.GetString(objectDataArray.dataBytes); } catch (Exception e) { ThrowCacheRuntimeException(e); } if (IsUnsignedNumeric(tempObjectString)) { ulong originalValue = Convert.ToUInt64(tempObjectString); ulong finalValue; if (updateType == UpdateType.Increment) { finalValue = originalValue + value; } else { if (value > originalValue) finalValue = 0; else finalValue = originalValue - value; } try { MemcachedItem memCacheItem = new MemcachedItem(); memCacheItem.Data = CreateObjectArray(objectDataArray.flags, Encoding.ASCII.GetBytes(finalValue + "")); ulong getVersion = GetLatestVersion(); memCacheItem.InternalVersion = getVersion; cacheItem.Value = memCacheItem; _cache.Insert(key, cacheItem); returnObject.ReturnResult = Result.SUCCESS; returnObject.Value = getVersion; returnObject.MutateResult = finalValue; } catch (Exception e) { ThrowCacheRuntimeException(e); } } else { returnObject.ReturnResult = Result.ITEM_TYPE_MISMATCHED; returnObject.Value = null; returnObject.MutateResult = 0; } } return returnObject; }
internal override IDictionary InsertBulkOperation(string[] keys, CacheItem[] items, ref long[] sizes, bool allowQueryTags) { return _webCache.InsertBulkOperation(keys, items, ref sizes, true); }
private OperationResult JoinObjects(string key, CacheItem cacheItem, object objectToJoin, UpdateType updateType) { OperationResult returnObject = new OperationResult(); ObjectArrayData objectDataArray = GetObjectArrayData(((MemcachedItem)cacheItem.Value).Data); byte[] originalByteObject = objectDataArray.dataBytes; byte[] byteObjectToJoin = (byte[])objectToJoin; byte[] joinedObject = new byte[originalByteObject.Length + byteObjectToJoin.Length]; if (updateType == UpdateType.Append) { System.Buffer.BlockCopy(originalByteObject, 0, joinedObject, 0, originalByteObject.Length); System.Buffer.BlockCopy(byteObjectToJoin, 0, joinedObject, originalByteObject.Length, byteObjectToJoin.Length); } else { System.Buffer.BlockCopy(byteObjectToJoin, 0, joinedObject, 0, byteObjectToJoin.Length); System.Buffer.BlockCopy(originalByteObject, 0, joinedObject, byteObjectToJoin.Length, originalByteObject.Length); } try { MemcachedItem memCacheItem = new MemcachedItem(); memCacheItem.Data = CreateObjectArray(objectDataArray.flags, joinedObject); ulong getVersion = GetLatestVersion(); memCacheItem.InternalVersion = getVersion; cacheItem.Value = memCacheItem; _cache.Insert(key, cacheItem); returnObject = CreateReturnObject(Result.SUCCESS, getVersion); } catch (Exception e) { ThrowCacheRuntimeException(e); } return returnObject; }
private GetOpResult CreateGetObject(string key, CacheItem cacheItem) { GetOpResult getObject = new GetOpResult(); MemcachedItem memCacheItem = (MemcachedItem)cacheItem.Value; ObjectArrayData objectArrayData = GetObjectArrayData(memCacheItem.Data); getObject.Key = key; getObject.Flag = objectArrayData.flags; getObject.Value = objectArrayData.dataBytes; getObject.Version = memCacheItem.InternalVersion; getObject.ReturnResult = Result.SUCCESS; return getObject; }
//whenever the item is updated, the version is incremented by 1 private CacheItem CreateCacheItem(uint flags, object dataBlock, long expirationTimeInSeconds, ulong version) { MemcachedItem memCacheItem = new MemcachedItem(); memCacheItem.Data = CreateObjectArray(flags, dataBlock); memCacheItem.InternalVersion = version; CacheItem cacheItem = new CacheItem(memCacheItem); ; if (expirationTimeInSeconds != 0) cacheItem.AbsoluteExpiration = CreateExpirationDate(expirationTimeInSeconds); return cacheItem; }
/// <summary> Insert list of <see cref="CacheItem"/> to the cache </summary> /// <param name="keys">The cache keys used to reference the items.</param> /// <param name="items">The items that are to be stored</param> /// <returns>returns keys that are added or updated successfully and their status.</returns> /// <remarks> If CacheItem contains invalid values the related exception is thrown. /// See <see cref="CacheItem"/> for invalid property values and related exceptions</remarks> /// <example>The following example demonstrates how to assign an item high priority when you insert /// it into your application's <see cref="Cache"/> object. /// <para><b>Note: </b>For more information about how to use this method with the <see cref="CacheItemRemovedCallback"/> /// delegate, see <see cref="CacheItemRemovedCallback"/>. /// </para> /// First create CacheItems. /// <code> /// string[] keys = {"SQLDSN", "ORADSN"}; /// CacheItem items[] = new CacheItem[2]; /// items[0] = new CacheItem(sqlConnectionString); /// item.AbsoluteExpiration = DateTime.Now.AddMinutes(2); /// item.SlidingExpiration = TimeSpan.Zero; /// item.Priority = CacheItemPriority.High; /// item.ItemRemoveCallback = onRemove; /// /// items[1] = new CacheItem(oraConnectionString); /// item.AbsoluteExpiration = DateTime.Now.AddMinutes(1); /// item.SlidingExpiration = TimeSpan.Zero; /// item.Priority = CacheItemPriority.Low; /// item.ItemRemoveCallback = onRemove; /// </code> /// /// Then insert CacheItems to the cache /// <code> /// /// NCache.Cache.Insert(keys, items); /// /// </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.Insert(keys, items); /// /// </code> /// </example> public override IDictionary Insert(string[] keys, CacheItem[] items, long[] sizes) { Dictionary<Address, KeyValuePair<string[], CacheItem[]>> keysDistributionMap = new Dictionary<Address, KeyValuePair<string[], CacheItem[]>>(); Request request; if (_broker.ImportHashmap) { if (!_broker.PoolFullyConnected) { BulkInsertCommand command = new BulkInsertCommand(keys, items, _parent, CacheId); request = _broker.CreateDedicatedRequest(command); } else { request = new Request(true, _broker.OperationTimeOut); _broker.GetKeysDistributionMap(keys, items, ref keysDistributionMap); foreach (Address serverAddress in keysDistributionMap.Keys) { KeyValuePair<string[], CacheItem[]> keysAndItems = keysDistributionMap[serverAddress]; BulkInsertCommand command = new BulkInsertCommand(keysAndItems.Key, keysAndItems.Value, _parent, CacheId); command.ClientLastViewId = _broker.ClientLastViewId; request.AddCommand(serverAddress, command); } } } else { BulkInsertCommand command = new BulkInsertCommand(keys, items, _parent, CacheId); request = _broker.CreateRequest(command); } _broker.ExecuteRequest(request); CommandResponse res = request.Response; res.ParseResponse(); return res.KeyValueDic; }
CacheItem CreateCacheItem(object value, Expiration expiration) { DateTime absolute = Cache.NoAbsoluteExpiration; TimeSpan sliding = Cache.NoSlidingExpiration; if (expiration != null) { switch (expiration.ExpirationType) { case ExpirationType.Absolute: absolute = DateTime.Now.AddMinutes(expiration.Duration); break; case ExpirationType.Sliding: sliding = TimeSpan.FromMinutes(expiration.Duration); break; } } CacheItem item = new CacheItem(value); item.AbsoluteExpiration = absolute; item.SlidingExpiration = sliding; return item; }
/// <summary> /// Creates a shallow copy of CacheItem /// </summary> /// <returns></returns> public object Clone() { CacheItem newItem = new CacheItem(); newItem._abs = this._abs; newItem._sld = this._sld; newItem.FlagMap = this.FlagMap; newItem._p = this._p; newItem._queryInfo = this._queryInfo; newItem._v = this._v; newItem._cacheItemUpdateCallback = _cacheItemUpdateCallback; newItem._cacheItemRemovedCallback = this._cacheItemRemovedCallback; newItem._itemUpdatedDataFilter = this._itemUpdatedDataFilter; newItem._itemRemovedDataFilter = this._itemRemovedDataFilter; return newItem; }
private static bool LoadCache() { try { if (InitializeCache()) { Console.WriteLine("Loading products into " + _cache.ToString() + "..."); Hashtable keyVals = _db.LoadProducts(); String[] keys = new String[keyVals.Keys.Count]; CacheItem[] items = new CacheItem[keyVals.Keys.Count]; IDictionaryEnumerator ide = keyVals.GetEnumerator(); int i = 0; while (ide.MoveNext()) { keys[i] = ide.Key.ToString(); items[i++] = new CacheItem(ide.Value); } _cache.AddBulk(keys, items); } else return false; } catch(Exception ex) { Console.WriteLine("Exception : " + ex.Message); return false; } return true; }
/// <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); }
public BulkInsertCommand(string[] keys, CacheItem[] items, Cache parent, string cacheId) { base.name = "BulkInsertCommand"; _parent = parent; base.BulkKeys = keys; _bulkInsertCommand = new Alachisoft.NCache.Common.Protobuf.BulkInsertCommand(); _bulkInsertCommand.requestId = base.RequestId; for (int i = 0; i < keys.Length; i++) { CacheItem item = items[i]; _insertCommand = new Alachisoft.NCache.Common.Protobuf.InsertCommand(); _insertCommand.key = keys[i]; Alachisoft.NCache.Caching.UserBinaryObject ubObject = Alachisoft.NCache.Caching.UserBinaryObject.CreateUserBinaryObject((byte[])item.Value); _insertCommand.data.AddRange(ubObject.DataList); if (item.AbsoluteExpiration != Cache.NoAbsoluteExpiration) _insertCommand.absExpiration = item.AbsoluteExpiration.Ticks; if (item.SlidingExpiration != Cache.NoSlidingExpiration) _insertCommand.sldExpiration = item.SlidingExpiration.Ticks; _insertCommand.flag = item.FlagMap.Data; _insertCommand.priority = (int)item.Priority; // Updated in Version 4.2 [Dated 20-Nov-2013; Author: Sami] ObjectQueryInfo objectQueryInfo = new ObjectQueryInfo(); if (item.QueryInfo["query-info"] != null) objectQueryInfo.queryInfo = ProtobufHelper.GetQueryInfoObj(item.QueryInfo["query-info"] as Hashtable); _insertCommand.objectQueryInfo = objectQueryInfo; short removeCallbackId = -1; short updateCallbackId = -1; EventDataFilter itemUpdateDataFilter = EventDataFilter.None; EventDataFilter itemRemovedDataFilter = EventDataFilter.None; if (item.CacheItemRemovedCallback != null) { itemRemovedDataFilter = item.ItemRemovedCallabackDataFilter; short[] callabackIds = _parent.EventManager.RegisterSelectiveEvent(item.CacheItemRemovedCallback, EventType.ItemRemoved, itemRemovedDataFilter); removeCallbackId = callabackIds[1]; } if (item.CacheItemUpdatedCallback != null) { itemUpdateDataFilter = item.ItemUpdatedCallabackDataFilter; short[] callabackIds = _parent.EventManager.RegisterSelectiveEvent(item.CacheItemUpdatedCallback, EventType.ItemUpdated, itemUpdateDataFilter); updateCallbackId = callabackIds[0]; } _insertCommand.removeCallbackId = removeCallbackId; _insertCommand.updateCallbackId = updateCallbackId; _insertCommand.updateDataFilter = (short)itemUpdateDataFilter; _insertCommand.removeDataFilter = (short)itemRemovedDataFilter; _bulkInsertCommand.insertCommand.Add(_insertCommand); } }
/// <summary> Insert list of <see cref="CacheItem"/> to the cache </summary> /// <param name="keys">The cache keys used to reference the items.</param> /// <param name="items">The items that are to be stored</param> /// <param name="sizes"></param> /// <param name="allowQueryTags"></param> /// <returns>returns keys that are added or updated successfully and their status.</returns> /// <remarks> If CacheItem contains invalid values the related exception is thrown. /// See <see cref="CacheItem"/> for invalid property values and related exceptions</remarks> /// <example>The following example demonstrates how to assign an item high priority when you insert /// it into your application's <see cref="Cache"/> object. /// <para><b>Note: </b>For more information about how to use this method with the <see cref="CacheItemRemovedCallback"/> /// delegate, see <see cref="CacheItemRemovedCallback"/>. /// </para> /// First create CacheItems. /// <code> /// string[] keys = {"SQLDSN", "ORADSN"}; /// CacheItem items[] = new CacheItem[2]; /// items[0] = new CacheItem(sqlConnectionString); /// item.AbsoluteExpiration = DateTime.Now.AddMinutes(2); /// item.Priority = CacheItemPriority.High; /// item.ItemRemoveCallback = onRemove; /// /// items[1] = new CacheItem(oraConnectionString); /// item.AbsoluteExpiration = DateTime.Now.AddMinutes(1); /// item.Priority = CacheItemPriority.Low; /// item.ItemRemoveCallback = onRemove; /// </code> /// /// Then insert CacheItems to the cache /// <code> /// Cache cache = NCache.InitializeCache("myCache"); /// string[] keys = new string[] { "myItem1", "myItem2" }; /// CacheItem[] items = new CacheItem[]{myItem1, myItem2}; /// cache.Insert(keys, items, "Connection", null); /// /// </code> /// </example> internal virtual IDictionary InsertBulkOperation(string[] keys, CacheItem[] items, ref long[] sizes, bool allowQueryTags) { if (_cacheImpl == null) throw new OperationFailedException("Cache is not initialized"); if (keys == null) throw new ArgumentNullException("keys"); if (items == null) throw new ArgumentNullException("items"); if (keys.Length != items.Length) throw new ArgumentException("keys count is not equals to items count"); if (keys.Length == 0) throw new ArgumentException("There is no key present in keys array"); if (IsNullOrDupliate(keys)) throw new ArgumentException("Duplicate keys found in provided 'key' array."); CacheItem[] clonedItems = new CacheItem[items.Length]; int noOfObjects = 0; long sumObjectSize = 0; if (DebugAPIConfiguraions.LoggingEnabled) noOfObjects = items.Length; for (int i = 0; i < items.Length; i++) { string key = keys[i]; BitSet flagMap = new BitSet(); if (items[i] == null) throw new Exception("CacheItem cannot be null"); CacheItem cloned = items[i].Clone() as CacheItem; long size = 0; if (sizes[i] > 0) size = sizes[i]; ValidateKeyValue(key, cloned.Value); Hashtable queryInfo = new Hashtable(); if (allowQueryTags) { queryInfo["query-info"] = GetQueryInfo(cloned.Value); } cloned.QueryInfo = queryInfo; cloned.Value = SafeSerialize(cloned.Value, _serializationContext, ref flagMap, ref size); sizes[i] = size; if (DebugAPIConfiguraions.LoggingEnabled) sumObjectSize += cloned.Value is byte[] ? ((byte[])cloned.Value).Length : 0; if (_perfStatsCollector != null) { if (cloned.Value != null) _perfStatsCollector.IncrementAvgItemSize(((byte[])cloned.Value).Length); } cloned.FlagMap = flagMap; cloned.AbsoluteExpiration = ToUTC(cloned.AbsoluteExpiration); clonedItems[i] = cloned; } if (DebugAPIConfiguraions.LoggingEnabled) LogSizeInfo(true, sumObjectSize, noOfObjects); short dsItemAddedCallbackID = -1; try { return _cacheImpl.Insert(keys, clonedItems, sizes); } catch (Exception) { if (ExceptionsEnabled) throw; return null; } }
/// <summary> /// Insert information in cache, along with the expirations and callback. /// </summary> /// <param name="id">Session ID</param> /// <param name="table">Value needed to be stored</param> /// private void PutInNCache(string id, Hashtable table, object lockID, bool enableRetry) { byte[] buffer = null; using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, table); buffer = stream.ToArray(); stream.Close(); } CacheItem sessionItem = new CacheItem(buffer); sessionItem.Priority = CacheItemPriority.NotRemovable; sessionItem.SlidingExpiration = new TimeSpan(0, (int)table[TIMEOUT_KEY], 0); lock (s_dataLock) { if (s_cacheNeedInit) InitializeCache(); } if (_lockSessions) { _cache.Insert(GetUniqueSessionId(id), sessionItem, lockID as LockHandle, true, enableRetry); } else _cache.Insert(GetUniqueSessionId(id), sessionItem, enableRetry); _cache.CurrentSessionCache = null; }
/// <summary> /// Add array of <see cref="CacheItem"/> to the cache. /// </summary> /// <param name="keys">The cache keys used to reference the items.</param> /// <param name="items">The items that are to be stored</param> /// <returns>keys that are added or that alredy exists in the cache and their status.</returns> /// <remarks> If CacheItem contains invalid values the related exception is thrown. /// See <see cref="CacheItem"/> for invalid property values and related exceptions</remarks> /// <example>The following example demonstrates how to add items to the cache with an absolute /// expiration 2 minutes from now, a priority of /// high, and that notifies the application when the item is removed from the cache. /// /// First create a CacheItems. /// <code> /// string keys = {"First", "Second"}; /// CacheItem items = new CacheItem[2] /// items[0] = new CacheItem(firstTimeStamp); /// items[0].AbsoluteExpiration = DateTime.Now.AddMinutes(2); /// items[0].Priority = CacheItemPriority.High; /// items[0].ItemRemoveCallback = onRemove; /// /// items[1] = new CacheItem(secondTimeStamp); /// items[1].AbsoluteExpiration = DateTime.Now.AddMinutes(2); /// items[1].Priority = CacheItemPriority.Low; /// items[1].ItemRemoveCallback = onRemove; /// </code> /// /// Then add CacheItem to the cache /// <code> /// /// Cache cache = NCache.InitializeCache("myCache"); /// cache.Add(keys, items); /// /// </code> /// </example> public virtual IDictionary AddBulk(string[] keys, CacheItem[] items) { long[] sizes = new long[items.Length]; return AddBulkOperation(keys, items, ref sizes, true); }
public virtual IDictionary Insert(string[] keys, CacheItem[] items, long[] sizes) { return null; }