コード例 #1
0
ファイル: HashedCache.cs プロジェクト: javithalion/NCache
        public static OperationResult Set(string key, object value, uint flags)
        {
            StoreObject obj = new StoreObject();
            obj.Flags = flags;
            obj.Value = value;
            lock (_ht)
            {
                _ht[key] = obj;
            }
            OperationResult result = new OperationResult();
            result.ReturnResult = Result.SUCCESS;
            ulong cas=1;
            result.Value = cas;

            return result;
        }
コード例 #2
0
        public OperationResult Add(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
        {
            if (string.IsNullOrEmpty(key) || dataBlock == null)
                ThrowInvalidArgumentsException();

            OperationResult returnObject = new OperationResult();

            try
            {
                returnObject = AddItemSuccessfully(key, flags, expirationTimeInSeconds, dataBlock);
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }
            return returnObject;
        }
コード例 #3
0
        public OperationResult InitCache(string cacheID)
        {
            if (string.IsNullOrEmpty(cacheID))
                ThrowInvalidArgumentsException();

            OperationResult returnObject = new OperationResult();

            try
            {
                _cache = Alachisoft.NCache.Web.Caching.NCache.InitializeCache(cacheID);
                
                if (!_cache.Contains(ItemVersionKey))
                {
                    _cache.Add(ItemVersionKey, ItemVersionValue); 
                }
                returnObject = CreateReturnObject(Result.SUCCESS, null);
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }

            return returnObject;
        }
コード例 #4
0
ファイル: MemcachedClient.cs プロジェクト: javithalion/NCache
		//Private common store method.
		private string store(string command, string key, bool keyIsChecked, object value, uint hash, int expiry, ulong unique) {
			if (!keyIsChecked) {
				checkKey(key);
			}
            SerializedType type;
				byte[] bytes;
                try
                {
                    bytes = Serializer.Serialize(value, out type, CompressionThreshold);
                }
                catch (Exception e)
                {
                    //If serialization fails, return false;

                    logger.Error("Error serializing object for key '" + key + "'.", e);
                    return "";
                }
				string commandResult = "";
                if (memcachedProvider == null)
                {
                    ConnectionError();
                    return "";
                }
                    OperationResult opResult = new OperationResult();

                    try
                    {
                        switch (command)
                        {
                            case "set":
                                opResult = memcachedProvider.Set(key, (ushort)type, expiry, bytes);
                                break;
                            case "add":
                                opResult = memcachedProvider.Add(key, (ushort)type, expiry, bytes);
                                break;
                            case "replace":
                                opResult = memcachedProvider.Replace(key, (ushort)type, expiry, bytes);
                                break;
                            case "append":
                                opResult = memcachedProvider.Append(key, bytes, unique);
                                break;
                            case "prepend":
                                opResult = memcachedProvider.Prepend(key, bytes, unique);
                                break;
                            case "cas":
                                opResult = memcachedProvider.CheckAndSet(key, (ushort)type, expiry, unique, bytes);
                                break;
                        }
                        if (command.Equals("replace") && opResult.ReturnResult == Result.ITEM_NOT_FOUND)
                            commandResult = "NOT_STORED";
                        else
                            switch (opResult.ReturnResult)
                            {
                                case Result.SUCCESS:
                                    commandResult = "STORED";
                                    break;
                                case Result.ITEM_EXISTS:
                                    commandResult = "NOT_STORED";
                                    break;
                                case Result.ITEM_NOT_FOUND:
                                    commandResult = "NOT_FOUND";
                                    break;
                                case Result.ITEM_MODIFIED:
                                    commandResult = "EXISTS";
                                    break;
                            }
                    }
                    catch (InvalidArgumentsException e)
                    {
                        commandResult = "CLIENT_ERROR bad command line format";
                    }
                    catch (CacheRuntimeException e)
                    {
                        commandResult = "SERVER_ERROR";
                    }
                    return commandResult;
		}
コード例 #5
0
ファイル: MemCachedClient.cs プロジェクト: javithalion/NCache
		/// <summary>
		/// Stores data to cache.
		/// 
		/// If data does not already exist for this key on the server, or if the key is being
		/// deleted, the specified value will not be stored.
		/// The server will automatically delete the value when the expiration time has been reached.
		/// 
		/// If compression is enabled, and the data is longer than the compression threshold
		/// the data will be stored in compressed form.
		/// 
		/// As of the current release, all objects stored will use .NET serialization.
		/// </summary>
		/// <param name="cmdname">action to take (set, add, replace)</param>
		/// <param name="key">key to store cache under</param>
		/// <param name="value">object to cache</param>
		/// <param name="expiry">expiration</param>
		/// <param name="hashCode">if not null, then the int hashcode to use</param>
		/// <param name="asString">store this object as a string?</param>
		/// <returns>true/false indicating success</returns>
		private bool Set(string cmdname, string key, object obj, DateTime expiry, object hashCode, bool asString) 
		{
			if(expiry < DateTime.Now)
				return true;

			if(cmdname == null || cmdname.Trim().Length == 0 || key == null || key.Length == 0) 
			{
				if(log.IsErrorEnabled)
				{
					log.Error(GetLocalizedString("set key null"));
				}
				return false;
			}
            if (memcachedProvider == null)
            {
                    if (log.IsErrorEnabled)
                    {
                        log.Error(GetLocalizedString("failed to get socket").Replace("$$Host$$","localhost"));
                    }
                return false;
            }
            if (expiry == DateTime.MaxValue)
                expiry = new DateTime(0);

            // store flags
            int flags = 0;
            // byte array to hold data
			byte[] val;
			int length = 0;

			// useful for sharing data between .NET and non-.NET
            // and also for storing ints for the increment method
			if(NativeHandler.IsHandled(obj)) 
			{
				if(asString) 
				{
                    if(obj != null)
                    {
						if(log.IsInfoEnabled)
						{
							log.Info(GetLocalizedString("set store data as string").Replace("$$Key$$", key).Replace("$$Class$$", obj.GetType().Name));
						}
                        try
                        {
                            val = UTF8Encoding.UTF8.GetBytes(obj.ToString());
                        }
                        catch(ArgumentException ex)
                        {
							if(log.IsErrorEnabled)
							{
								log.Error(GetLocalizedString("set invalid encoding").Replace("$$Encoding$$", _defaultEncoding), ex);
							}
                            return false;
                        }
                    }
                    else
                    {
                        val = new byte[0];
						length = 0;
                    }
				}
				else 
				{
					if(log.IsInfoEnabled)
					{
						log.Info(GetLocalizedString("set store with native handler"));
					}

					try 
					{
						val = NativeHandler.Encode(obj);
						length = val.Length;
					}
					catch(ArgumentException e) 
					{
						if(log.IsErrorEnabled)
						{
							log.Error(GetLocalizedString("set failed to native handle object"), e);
						}

						return false;
					}
				}
			}
			else 
			{
                if(obj != null)
                {
					if(log.IsInfoEnabled)
					{
						log.Info(GetLocalizedString("set serializing".Replace("$$Key$$", key).Replace("$$Class$$", obj.GetType().Name)));
					}

                    // always serialize for non-primitive types
					try
                    {
                        MemoryStream memStream = new MemoryStream();
                        new BinaryFormatter().Serialize(memStream, obj);
                        val = memStream.GetBuffer();
						length = (int) memStream.Length;
                        flags |= F_SERIALIZED;
                    }
                    catch(IOException e)
                    {
                        // if we fail to serialize, then
                        // we bail
						if(log.IsErrorEnabled)
						{
							log.Error(GetLocalizedString("set failed to serialize").Replace("$$Object$$", obj.ToString()), e);
						}

                        return false;
                    }
                }
                else
                {
                    val = new byte[0];
					length = 0;
                }
			}
		
			// now try to compress if we want to
			// and if the length is over the threshold 
			if(_compressEnable && length > _compressThreshold) 
			{
				if(log.IsInfoEnabled)
				{
					log.Info(GetLocalizedString("set trying to compress data"));
					log.Info(GetLocalizedString("set size prior").Replace("$$Size$$", length.ToString(new NumberFormatInfo())));
				}

				try 
				{
					MemoryStream memoryStream = new MemoryStream();
					GZipOutputStream gos = new GZipOutputStream(memoryStream);
					gos.Write(val, 0, length);
					gos.Finish();
				
					// store it and set compression flag
					val = memoryStream.GetBuffer();
					length = (int)memoryStream.Length;
					flags |= F_COMPRESSED;

					if(log.IsInfoEnabled)
					{
						log.Info(GetLocalizedString("set compression success").Replace("$$Size$$", length.ToString(new NumberFormatInfo())));
					}
				}
				catch(IOException e) 
				{
					if(log.IsErrorEnabled)
					{
						log.Error(GetLocalizedString("set compression failure"), e);
					}
				}
			}

			// now write the data to the cache server
			try 
			{
                OperationResult opResult = new OperationResult();
                switch (cmdname)
                {
                    case "set":
                        opResult = memcachedProvider.Set(key, (uint)flags, GetExpirationTime(expiry), val);
                        break;
                    case "add":
                        opResult = memcachedProvider.Add(key, (uint)flags, GetExpirationTime(expiry), val);
                        break;
                    case "replace":
                        opResult = memcachedProvider.Replace(key, (uint)flags, GetExpirationTime(expiry), val);
                        break;
                }
                string line = "";
                if (cmdname.Equals("replace") && opResult.ReturnResult == Result.ITEM_NOT_FOUND)
                    line = "NOT_STORED";
                else
                    switch (opResult.ReturnResult)
                    {
                        case Result.SUCCESS:
                            line = "STORED";
                            break;
                        case Result.ITEM_EXISTS:
                            line = "NOT_STORED";
                            break;
                        case Result.ITEM_NOT_FOUND:
                            line = "NOT_FOUND";
                            break;
                        case Result.ITEM_MODIFIED:
                            line = "EXISTS";
                            break;
                    }
				string cmd = cmdname + " " + key + " " + flags + " "
					+ GetExpirationTime(expiry) + " " + length + "\r\n";
				if(log.IsInfoEnabled)
				{
					log.Info(GetLocalizedString("set memcached command result").Replace("$$Cmd$$", cmd).Replace("$$Line$$", line));
				}

				if(STORED == line) 
				{
					if(log.IsInfoEnabled)
					{
						log.Info(GetLocalizedString("set success").Replace("$$Key$$", key));
					}
					return true;
				}
				else if(NOTSTORED == line) 
				{
					if(log.IsInfoEnabled)
					{
						log.Info(GetLocalizedString("set not stored").Replace("$$Key$$", key));
					}
				}
				else 
				{
					if(log.IsErrorEnabled)
					{
						log.Error(GetLocalizedString("set error").Replace("$$Key$$", key).Replace("$$Size$$", length.ToString(new NumberFormatInfo())).Replace("$$Line$$", line));
					}
				}
			}
			catch(Exception e) 
			{
				// exception thrown
				if(log.IsErrorEnabled)
				{
					log.Error(GetLocalizedString("set IOException"), e);
				}

			}

			return false;
		}
コード例 #6
0
        public OperationResult Replace(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
        {
            if (string.IsNullOrEmpty(key) || dataBlock == null)
                ThrowInvalidArgumentsException();

            OperationResult returnObject = new OperationResult();
            try
            {
                if (_cache.Contains(key))
                    returnObject = InsertItemSuccessfully(key, flags, expirationTimeInSeconds, dataBlock);
                else
                    returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }

            return returnObject;

        }
コード例 #7
0
        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;
        }
コード例 #8
0
 private OperationResult CreateReturnObject(Result result, object value)
 {
     OperationResult returnObject = new OperationResult();
     returnObject.ReturnResult = result;
     returnObject.Value = value;
     return returnObject;
 }
コード例 #9
0
 private OperationResult Concat(string key, object dataToPrepend, ulong casUnique, UpdateType updateType)
 {
     if (string.IsNullOrEmpty(key) || dataToPrepend == null)
         ThrowInvalidArgumentsException();
  
     OperationResult returnObject = new OperationResult();
     try
     {
         CacheItem getObject = _cache.GetCacheItem(key);
         if (getObject == null)
             returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
         else if (getObject.Value == null)
             returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
         else
         {
             MemcachedItem memCacheItem = (MemcachedItem)getObject.Value;
             if ((casUnique > 0 && memCacheItem.InternalVersion == casUnique) || casUnique == 0)
                 returnObject = JoinObjects(key, getObject, dataToPrepend, updateType);
             else
                 returnObject = CreateReturnObject(Result.ITEM_MODIFIED, null);
         }
     }
     catch (Exception e)
     {
         ThrowCacheRuntimeException(e);
     }
     return returnObject;
 }
コード例 #10
0
        private OperationResult AddItemSuccessfully(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
        {
            if (expirationTimeInSeconds < 0)
                return CreateReturnObject(Result.SUCCESS, 0);

            OperationResult returnObject = new OperationResult();
            try
            {
                ulong getVersion = GetLatestVersion();
                
                CacheItem cacheItem = CreateCacheItem(flags, dataBlock, expirationTimeInSeconds, getVersion);
               
                _cache.Add(key, cacheItem);
                returnObject.Value = getVersion;
                returnObject.ReturnResult = Result.SUCCESS;
            }
            catch (Alachisoft.NCache.Runtime.Exceptions.OperationFailedException e)
            {
                returnObject = CreateReturnObject(Result.ITEM_EXISTS, null);
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }
            return returnObject;
        }
コード例 #11
0
        private OperationResult InsertItemSuccessfully(string key, uint flags, long expirationTimeInSeconds, object dataBlock)
        {
            if (expirationTimeInSeconds < 0)
                return CreateReturnObject(Result.SUCCESS, 0);

            OperationResult returnObject = new OperationResult();
            
            try
            {
                ulong getVersion = GetLatestVersion();
                
                CacheItem cacheItem = CreateCacheItem(flags, dataBlock, expirationTimeInSeconds, getVersion);
                _cache.Insert(key, cacheItem);
                returnObject.Value = getVersion;
                returnObject.ReturnResult = Result.SUCCESS;
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }
            return returnObject;
        }
コード例 #12
0
        public OperationResult Touch(string key, long expirationTimeInSeconds)
        {
            if (string.IsNullOrEmpty(key))
                ThrowInvalidArgumentsException();

            OperationResult returnObject = new OperationResult();

            try
            {
               CacheItemAttributes attributes = new CacheItemAttributes();
                attributes.AbsoluteExpiration = CreateExpirationDate(expirationTimeInSeconds);
                bool result = _cache.SetAttributes(key, attributes);
                if (result)
                    returnObject = CreateReturnObject(Result.SUCCESS, null);
                else
                    returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }
            return returnObject;
        }
コード例 #13
0
        public OperationResult Flush_All(long expirationTimeInSeconds)
        {

            OperationResult returnObject = new OperationResult();
            try
            {
                if (expirationTimeInSeconds == 0)
                {

                    ulong getVersion =(ulong) _cache.Get(ItemVersionKey);
                    _cache.Clear();
                    if (getVersion != null)
                    {
                        _cache.Insert(ItemVersionKey, getVersion);
                    }
                    else
                    {
                        _cache.Insert(ItemVersionKey, ItemVersionValue);
                    }


                }
                else
                {
                    long dueTimeInMilliseconds = expirationTimeInSeconds*1000;
                    _timer = new Timer(FlushExpirationCallBack, null, dueTimeInMilliseconds, 0);
                }
                returnObject = CreateReturnObject(Result.SUCCESS, null);
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }
            return returnObject;
        }
コード例 #14
0
        public OperationResult Delete(string key, ulong casUnique)
        {
            if (string.IsNullOrEmpty(key))
                ThrowInvalidArgumentsException();

            OperationResult returnObject = new OperationResult();
            try
            {
                if (casUnique == 0)
                {
                   Object obj = _cache.Remove(key);
                    if (obj == null)
                        returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
                    else
                        returnObject = CreateReturnObject(Result.SUCCESS, null);
                }
                else
                {
                    CacheItem item = _cache.GetCacheItem(key);
                    if (item == null)
                        returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
                    else
                    {
                        MemcachedItem memCacheItem = (MemcachedItem)item.Value;
                        if (memCacheItem.InternalVersion != casUnique)
                        {
                            returnObject = CreateReturnObject(Result.ITEM_MODIFIED, null);
                        }
                        else
                        {
                            _cache.Delete(key);
                            returnObject = CreateReturnObject(Result.SUCCESS, null);
                        }
                    }
                }

            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }

            return returnObject;
        }
コード例 #15
0
        public OperationResult CheckAndSet(string key, uint flags, long expirationTimeInSeconds, ulong casUnique, object dataBlock)
        {
            if (string.IsNullOrEmpty(key) || dataBlock == null )
                ThrowInvalidArgumentsException();

            OperationResult returnObject = new OperationResult();
            try
            {
                CacheItem getCacheItem = _cache.GetCacheItem(key);
                if (getCacheItem == null)
                
                    returnObject = CreateReturnObject(Result.ITEM_NOT_FOUND, null);
                else
                {
                    MemcachedItem memCacheItem = (MemcachedItem)getCacheItem.Value;
                    if (memCacheItem.InternalVersion == casUnique)
                        returnObject = InsertItemSuccessfully(key, flags, expirationTimeInSeconds, dataBlock);
                    else
                        returnObject = CreateReturnObject(Result.ITEM_MODIFIED, null);
                }
            }
            catch (Exception e)
            {
                ThrowCacheRuntimeException(e);
            }
            return returnObject;
        }