/// <summary>
        /// Reads the value from the cache for a specific key
        /// </summary>
        /// <typeparam name="TExpected">Expected type of the value</typeparam>
        /// <param name="keyName">Name of the key</param>
        /// <returns>Value for the key</returns>
        public Maybe <TExpected> Read <TExpected>(ICacheKey key)
        {
            try
            {
                // Retrieve the default db
                IDatabase defaultDb = GetDefaultRedisDb(readOnly: true);

                // Read the value
                RedisValue redisValue = defaultDb.StringGet(key.Name);
                if (redisValue.IsNull)
                {
                    return(new Maybe <TExpected>());
                }

                // Parse to the expected type
                TExpected value = RedisConverter.ConvertTo <TExpected>(redisValue);

                return(new Maybe <TExpected>(value));
            }
            catch (Exception ex)
            {
                string exceptionMessage = string.Format("Something went wrong while reading the key '{0}' from the cache.", key.Name);
                var    cacheException   = new CacheException(exceptionMessage, ex);

                return(new Maybe <TExpected>());
            }
        }
Пример #2
0
        public void MessageIsSet()
        {
            var cacheException = new CacheException("special message");

            Assert.AreEqual(cacheException.Message, "special message");
            Assert.AreEqual(cacheException.InnerException, null);
        }
Пример #3
0
        /// <summary>
        /// Makes a key and data package form the keys and values of hashtable, for bulk operations
        /// </summary>
        /// <param name="dic">Hashtable containing the keys and values to be packaged</param>
        /// <param name="keys">Contains packaged keys after execution</param>
        /// <param name="data">Contains packaged data after execution</param>
        internal static void PackageKeysExceptions(Hashtable dic, Alachisoft.NCache.Common.Protobuf.KeyExceptionPackageResponse keyExceptionPackage)
        {
            int errorCode = -1;

            if (dic != null && dic.Count > 0)
            {
                IDictionaryEnumerator enu = dic.GetEnumerator();
                while (enu.MoveNext())
                {
                    CacheException cacheException = enu.Value as CacheException;
                    if (cacheException != null)
                    {
                        errorCode = cacheException.ErrorCode;
                    }
                    Exception ex = enu.Value as Exception;

                    if (ex != null)
                    {
                        keyExceptionPackage.keys.Add((string)enu.Key);

                        Alachisoft.NCache.Common.Protobuf.Exception exc = new Alachisoft.NCache.Common.Protobuf.Exception();
                        exc.message   = ex.Message;
                        exc.exception = ex.ToString();
                        exc.type      = Alachisoft.NCache.Common.Protobuf.Exception.Type.GENERALFAILURE;
                        exc.errorCode = errorCode;
                        keyExceptionPackage.exceptions.Add(exc);
                    }
                }
            }
        }
Пример #4
0
        public void MessageExceptionConstructor()
        {
            var exception = new CacheException(Message, _innerException);

            exception.Message.Should().Be(Message);
            exception.InnerException.Should().Be(_innerException);
        }
Пример #5
0
        public void ExceptionFormatConstructor()
        {
            var exception = new CacheException(_innerException, Format, Arg);

            exception.InnerException.Should().Be(_innerException);
            exception.Message.Should().Be(Formatted);
        }
Пример #6
0
        internal static Exception CacheEntityNotHaveKeyAttribute(string type)
        {
            CacheException exception = new CacheException(CacheErrorCodes.EntityNotHaveKeyAttribute);

            exception.Data["Type"] = type;

            return(exception);
        }
Пример #7
0
        internal static Exception CacheSlidingTimeBiggerThanMaxAlive(string type)
        {
            CacheException exception = new CacheException(CacheErrorCodes.SlidingTimeBiggerThanMaxAlive);

            exception.Data["Type"] = type;

            return(exception);
        }
Пример #8
0
        public void InnerExceptionAndMessageIsSet()
        {
            var inner          = new Exception("inner");
            var cacheException = new CacheException("special message", inner);

            Assert.AreEqual(cacheException.Message, "special message");
            Assert.AreEqual(cacheException.InnerException, inner);
        }
Пример #9
0
        internal static Exception SmsCacheError(string cause, CacheException ex)
        {
            SmsException exception = new SmsException(AliyunErrorCodes.SmsCacheError, ex);

            exception.Data["Cause"] = cause;

            return(exception);
        }
Пример #10
0
        public void ConstructorInner()
        {
            Exception      e         = new Exception();
            CacheException exception = new CacheException("Message", e);

            Assert.AreEqual("Message", exception.Message);
            Assert.AreEqual(e, exception.InnerException);
        }
Пример #11
0
        internal static Exception ConvertError(string key, Exception innerException)
        {
            CacheException exception = new CacheException(CacheErrorCodes.ConvertError, innerException);

            exception.Data["Key"] = key;

            return(exception);
        }
Пример #12
0
        internal static Exception Unkown(object key, object?value, Exception innerException)
        {
            CacheException exception = new CacheException(CacheErrorCodes.Unkown, innerException);

            exception.Data["Key"]   = key;
            exception.Data["Value"] = value;

            return(exception);
        }
        /// <summary>
        /// Removes the specified keys.
        /// </summary>
        /// <param name="keys">list of keys</param>
        /// <returns>The number of keys that were removed</returns>
        public long Remove(System.Collections.Generic.List <ICacheKey> keys)
        {
            try
            {
                return(RemoveKeys(keys));
            }
            catch (Exception ex)
            {
                string exceptionMessage = "Something went wrong while deleting the list of keys from the cache.";
                var    cacheException   = new CacheException(exceptionMessage, ex);

                return(0);
            }
        }
Пример #14
0
        public void ConstructorDeserialize()
        {
            CacheException  exception = new CacheException("Message");
            BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All));

            byte[] buffer = null;
            using (MemoryStream ms = new MemoryStream()) {
                formatter.Serialize(ms, exception);
                buffer = ms.ToArray();
            }

            CacheException deserializeException = null;

            using (MemoryStream ms = new MemoryStream(buffer)) {
                deserializeException = (CacheException)formatter.Deserialize(ms);
            }

            Assert.AreEqual("Message", deserializeException.Message);
        }
        /// <summary>
        /// Removes a key from the cache
        /// </summary>
        /// <param name="keyName">Name of the key</param>
        /// <returns>Indication whether or not the operation succeeded</returns>
        public bool Remove(ICacheKey key)
        {
            try
            {
                // Remove using the existing functionality
                long operationResult = RemoveKeys(new List <ICacheKey>()
                {
                    key
                });
                return(operationResult == 1);
            }
            catch (Exception ex)
            {
                string exceptionMessage = string.Format("Something went wrong while deleting the key '{0}' from the cache.", key.Name);
                var    cacheException   = new CacheException(exceptionMessage, ex);

                return(false);
            }
        }
Пример #16
0
        /// <summary>
        /// Gets the cache client response.
        /// </summary>
        /// <typeparam name="T">Return value type.</typeparam>
        /// <param name="key">The key.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// Returns the cache client response.</returns>
        private async Task <CacheClientResponse> GetCacheClientResponse <T>(string key)
        {
            CacheException exception = null;
            object         result    = null;

            GetOperationResult <string> valueResult = await this.client.GetAsync <string>(key) as GetOperationResult <string>;

            if (valueResult.Success)
            {
                result = typeof(T) == typeof(string)
                    ? valueResult.Value
                    : (object)this.cacheSerializer.Deserialize <T>(valueResult.Value);
            }
            else
            {
                exception = new CacheException(valueResult.Message, valueResult.Exception);
            }

            return(new CacheClientResponse(result, exception));
        }
        private ConnectionMultiplexer ConnectToRedisCache(string configurationString)
        {
            try
            {
                // Assign options for the connection
                var configOptions = ConfigurationOptions.Parse(configurationString);
                configOptions.ClientName = "Codit Cache Client";

                // Connect to the cache
                ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(configOptions);

                return(connection);
            }
            catch (Exception ex)
            {
                string exceptionMessage  = string.Format("Failed to connect to the Redis cache with configuration string '{0}'.", configurationString);
                var    cacheConnectionEx = new CacheException(exceptionMessage, ex);

                throw cacheConnectionEx;
            }
        }
        /// <summary>
        /// Writes a value to a specific key
        /// </summary>
        /// <typeparam name="TValue">Type of the value</typeparam>
        /// <param name="keyName">Name of the key</param>
        /// <param name="value">New value of the key</param>
        /// <param name="expiration">Duration that the key will live in the cache</param>
        /// <returns>Indication whether or not the operation succeeded</returns>
        public bool Write <TValue>(ICacheKey key, TValue value, TimeSpan expiration)
        {
            try
            {
                // Retrieve the default db
                IDatabase defaultDb = GetDefaultRedisDb(readOnly: false);

                // Convert the value to native redis value
                RedisValue nativeValue = RedisConverter.ConvertFrom <TValue>(value);

                // Write the value to the key
                bool operationResult = defaultDb.StringSet(key.Name, nativeValue, expiration, When.Always);

                return(operationResult);
            }
            catch (Exception ex)
            {
                string exceptionMessage = string.Format("Something went wrong while writing the key '{0}' to the cache.", key.Name);
                var    cacheException   = new CacheException(exceptionMessage, ex);

                return(false);
            }
        }
Пример #19
0
        /// <summary>
        /// Desirializes the given type.
        /// </summary>
        /// <param name="serializedObject">The serialized object. A <see cref="T:System.Byte[]"/> Object.</param>
        /// <returns>A <see cref="T:T"/> Object.</returns>
        //[System.Diagnostics.DebuggerStepThrough]
        public static T BinaryDeSerialize <T>(byte[] serializedObject)
        {
            #region Access Log
#if TRACE
            {
                Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
            }
#endif
            #endregion Access Log

            try
            {
                MemoryStream ms = new MemoryStream();
                ms.Write(serializedObject, 0, serializedObject.Length);
                ms.Seek(0, 0);
                BinaryFormatter b   = new BinaryFormatter();
                Object          obj = b.Deserialize(ms);
                ms.Close();
                return((T)obj);
            }
            catch (Exception ex)
            {
                MemoryStream ms = new MemoryStream();
                ms.Write(serializedObject, 0, serializedObject.Length);
                ms.Seek(0, 0);
                BinaryFormatter b   = new BinaryFormatter();
                Object          obj = b.Deserialize(ms);
                ms.Close();
                CacheException cex = (CacheException)obj;
                if (cex != null)
                {
                    // TODO: Shared Cache Exception
                    Handler.LogHandler.Error(cex.StackTrace, ex);
                }
                return((T)obj);
            }
        }
Пример #20
0
        public void ConstructorMessage()
        {
            CacheException exception = new CacheException("Message");

            Assert.AreEqual("Message", exception.Message);
        }
Пример #21
0
        public void FormatConstructor()
        {
            var exception = new CacheException(Format, Arg);

            exception.Message.Should().Be(Formatted);
        }
Пример #22
0
        public void MessageConstructor()
        {
            var exception = new CacheException(Message);

            exception.Message.Should().Be(Message);
        }
Пример #23
0
 public CacheClientResponse(object value, CacheException exception)
 {
     this.Value     = value;
     this.Exception = exception;
 }
Пример #24
0
 public void ConstructorDefault()
 {
     CacheException exception = new CacheException();
 }