public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas)
            {
                using (var ms = new MemoryStream())
                {
                    this.SaveHeader(ms);
                    bool retval;
                    var  ts = TimeSpan.FromMinutes(this.Timeout);

                    retval = useCas
                                                                ? client.Cas(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.HeadCas).Result
                                                                : client.Store(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);

                    if (!metaOnly)
                    {
                        ms.Position = 0;

                        using (var bw = new BinaryWriter(ms))
                        {
                            this.Data.Serialize(bw);
                            retval = useCas
                                                                                ? client.Cas(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.DataCas).Result
                                                                                : client.Store(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                        }
                    }

                    return(retval);
                }
            }
        /// <summary>
        /// Function to add a new item to the output cache. If there is already a value in the cache for the
        /// specified key, the provider must return that value and must not store the data passed by using the Add method
        /// parameters. The Add method stores the data if it is not already in the cache and returns the value
        /// read from the cache if it already exists.
        /// </summary>
        /// <param name="key">A unique identifier for entry</param>
        /// <param name="entry">The content to add to the output cache</param>
        /// <param name="utcExpiry">The time and date on which the cached entry expires</param>
        /// <returns>
        /// The value that identifies what was in the cache, or the value that was just added if it was not
        /// </returns>
        public override object Add(
            string key,
            object entry,
            DateTime utcExpiry)
        {
            // Fix the key
            key = SanitizeKey(key);

            // Make sure that the expiration date is flagged as UTC. The client converts the expiration to
            // UTC to calculate the UNIX time and this way we can skip the UTC -> ToLocal -> ToUTC chain
            utcExpiry = DateTime.SpecifyKind(utcExpiry, DateTimeKind.Utc);

            // We should only store the item if it's not in the cache. So try to add it and if it
            // succeeds, return the value we just stored
            if (client.Store(StoreMode.Add, key, entry, utcExpiry))
            {
                return(entry);
            }

            // If it's in the cache we should return it
            var retval = client.Get(key);

            // If the item got evicted between the Add and the Get (very rare) we store it anyway,
            // but this time with Set to make sure it always gets into the cache
            if (retval == null)
            {
                client.Store(StoreMode.Set, key, entry, utcExpiry);
                retval = entry;
            }

            // Return the value read from the cache if it was present
            return(retval);
        }
            public ISessionStateItemCollection Get(string id, out int timeout)
            {
                var key   = GetKey(id);
                var entry = _client.Get <SessionEntry>(key);

                ISessionStateItemCollection sessionStateItemCollection = new SessionStateItemCollection();

                if (entry == null)
                {
                    entry = new SessionEntry();
                }
                else
                {
                    foreach (var item in entry.Dictionary)
                    {
                        sessionStateItemCollection[item.Key] = item.Value.Deserialize();
                    }
                }

                timeout = entry.Timeout;

                //更新过期时间。
                _client.Store(StoreMode.Set, key, entry, TimeSpan.FromMinutes(timeout));

                return(sessionStateItemCollection);
            }
        /// <summary>
        /// Set the specified cacheKey, cacheValue and expiration.
        /// </summary>
        /// <returns>The set.</returns>
        /// <param name="cacheKey">Cache key.</param>
        /// <param name="cacheValue">Cache value.</param>
        /// <param name="expiration">Expiration.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public void Set <T>(string cacheKey, T cacheValue, TimeSpan expiration) where T : class
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
            ArgumentCheck.NotNull(cacheValue, nameof(cacheValue));
            ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration));

            _memcachedClient.Store(Enyim.Caching.Memcached.StoreMode.Set, this.HandleCacheKey(cacheKey), cacheValue, expiration);
        }
Beispiel #5
0
        public IActionResult Store(string key, [FromBody] StoreCacheItem item)
        {
            if (item == null)
            {
                return(this.NullValueErrorResult(key, _logger));
            }

            if (!item.Cas.HasValue || item.Cas.Value == 0)
            {
                bool result = true;
                if (item.ValidFor.HasValue)
                {
                    result = _memcachedClient.Store(GetMode(item), key, item.Value, item.ValidFor.Value);
                }
                else if (item.ExpireAt.HasValue)
                {
                    result = _memcachedClient.Store(GetMode(item), key, item.Value, item.ExpireAt.Value);
                }
                else
                {
                    result = _memcachedClient.Store(GetMode(item), key, item.Value);
                }

                if (!result)
                {
                    return(StatusCode(StatusCodes.Status400BadRequest, result));
                }

                return(StatusCode(StatusCodes.Status201Created));
            }
            else
            {
                CasResult <bool> result = new CasResult <bool>();

                if (item.ValidFor.HasValue)
                {
                    result = _memcachedClient.Cas(GetMode(item), key, item.Value, item.ValidFor.Value, item.Cas.Value);
                }
                else if (item.ExpireAt.HasValue)
                {
                    result = _memcachedClient.Cas(GetMode(item), key, item.Value, item.ExpireAt.Value, item.Cas.Value);
                }
                else
                {
                    result = _memcachedClient.Cas(GetMode(item), key, item.Value, item.Cas.Value);
                }

                if (!result.Result)
                {
                    return(StatusCode(StatusCodes.Status400BadRequest, result));
                }

                return(StatusCode(StatusCodes.Status201Created, result));
            }
        }
        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            var item = _client.Get(key);

            if (item != null)
            {
                return(item);
            }

            _client.Store(StoreMode.Add, key, entry, utcExpiry);
            return(entry);
        }
 public override object Add(string key, object entry, DateTime utcExpiry)
 {
     if (client.Get(key) != null)
     {
         return(client.Get(key));
     }
     else
     {
         //var objString = entry.ToString();
         bool result = client.Store(StoreMode.Set, key, entry);
         return(result.ToString());
     }
 }
Beispiel #8
0
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="cacheValue">缓存值</param>
        /// <param name="expiry">过期时间</param>
        public void Set <T>(string cacheKey, T cacheValue, TimeSpan expiry)
        {
            Check.NotNullOrEmpty(cacheKey, nameof(cacheKey));
            Check.NotNull(cacheValue, nameof(cacheValue));
            Check.NotNegativeOrZero(expiry, nameof(expiry));

            if (MaxRdSecond > 0)
            {
                var addSec = new Random().Next(1, MaxRdSecond);
                expiry.Add(new TimeSpan(0, 0, addSec));
            }

            _memcachedClient.Store(StoreMode.Set, this.HandleCacheKey(cacheKey), cacheValue, expiry);
        }
Beispiel #9
0
        /// <summary>
        /// Set the specified cacheKey, cacheValue and expiration.
        /// </summary>
        /// <returns>The set.</returns>
        /// <param name="cacheKey">Cache key.</param>
        /// <param name="cacheValue">Cache value.</param>
        /// <param name="expiration">Expiration.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public void Set <T>(string cacheKey, T cacheValue, TimeSpan expiration) where T : class
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
            ArgumentCheck.NotNull(cacheValue, nameof(cacheValue));
            ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration));

            if (MaxRdSecond > 0)
            {
                var addSec = new Random().Next(1, MaxRdSecond);
                expiration.Add(new TimeSpan(0, 0, addSec));
            }

            _memcachedClient.Store(Enyim.Caching.Memcached.StoreMode.Set, this.HandleCacheKey(cacheKey), cacheValue, expiration);
        }
        bool StoreValue(string key, byte[] value, int timeout)
#endif
        {
            TimeSpan ChatTimeout = new TimeSpan(0, timeout, 0);
            var      expires     = DateTime.Now + ChatTimeout;

            if (AwsUtilityMethods.IsRunningOnAWS)
            {
                BeginSubsegment("POST");
            }

            try
            {
                return(Client.Store(StoreMode.Set, key, value, expires));
            }
            catch (Exception ex)
            {
                if (AwsUtilityMethods.IsRunningOnAWS)
                {
                    AWSXRayRecorder.Instance.AddException(ex);
                }
                logger.ErrorFormat("Network: Memcache Store Error. '{0}'", ex.Message);
                throw;
            }
            finally
            {
                if (AwsUtilityMethods.IsRunningOnAWS)
                {
                    AWSXRayRecorder.Instance.EndSubsegment();
                }
            }
        }
Beispiel #11
0
        public void Set(string key, object value, ICacheEntryOptions options)
        {
            DateTime ExpireAt = DateTime.Now.AddTicks(CacheEntryOptions.Expiration.Never.AbsoluteExpirationRelativeToNow.Value.Ticks);

            if (options != null)
            {
                if (options.AbsoluteExpiration != null)
                {
                    ExpireAt = options.AbsoluteExpiration.Value.DateTime;
                }
                else if (options.AbsoluteExpirationRelativeToNow != null)
                {
                    ExpireAt = DateTime.Now.AddTicks(options.AbsoluteExpirationRelativeToNow.Value.Ticks);
                }
                else if (options.SlidingExpiration != null)
                {
                    ExpireAt = DateTime.Now.AddTicks(options.SlidingExpiration.Value.Ticks);
                }
            }
            _client.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value, ExpireAt);

            if (key != _keyCollection && !Keys.Contains(key))
            {
                SyncKeys(Keys.Append(key).ToHashSet <string>());
            }
        }
Beispiel #12
0
 public void Add(string cacheKey, DateTime absoluteExpiry, object dataToAdd)
 {
     try
     {
         var sanitisedKey = SanitiseCacheKey(cacheKey);
         var success      = _client.Store(StoreMode.Set, sanitisedKey, dataToAdd, absoluteExpiry);
         if (!success)
         {
             _logger.WriteErrorMessage(string.Format("Unable to store item in cache. CacheKey:{0}", sanitisedKey));
         }
     }
     catch (Exception ex)
     {
         _logger.WriteException(ex);
     }
 }
        public void StoreItem <TResult>(ProxyRequest <T, TResult> proxyRequest, CachePolicy cachePolicy, TResult item)
        {
            var key          = proxyRequest.CreateHash();
            var cachedObject = new MemcachedObject <TResult>()
            {
                Created = DateTime.Now,
                Object  = item
            };

            if (cachePolicy.MaxAge > 0)
            {
                _client.Store(StoreMode.Set, key, cachedObject, TimeSpan.FromSeconds(cachePolicy.MaxAge));
            }
            else
            {
                _client.Store(StoreMode.Set, key, cachedObject);
            }
        }
        protected bool Store(StoreMode mode = StoreMode.Set, string key = null, object value = null)
        {
            if (key == null)
            {
                key = GetUniqueKey("store");
            }
            if (value == null)
            {
                value = GetRandomString();
            }

            return(client.Store(mode, key, value));
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="key"></param>
 /// <param name="data"></param>
 /// <param name="expiry"></param>
 public override void Set(string key, object data, DateTime expiry)
 {
     if (key == null)
     {
         throw new ArgumentNullException("key");
     }
     if (data == null)
     {
         throw new ArgumentNullException("value");
     }
     var cacheKey = GetCacheKey(key);
     var r        = client.Store(StoreMode.Set, cacheKey, data, GetExpiry(expiry));
 }
            public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas)
            {
                using (var ms = new MemoryStream()) {
                    // Save the header first
                    SaveHeader(ms);
                    var ts = TimeSpan.FromMinutes(Timeout);

                    // Attempt to save the header and fail if the CAS fails
                    bool retval = useCas
                        ? client.Cas(StoreMode.Set, HeaderPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, HeadCas).Result
                        : client.Store(StoreMode.Set, HeaderPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                    if (retval == false)
                    {
                        return(false);
                    }

                    // Save the data
                    if (!metaOnly)
                    {
                        ms.Position = 0;

                        // Serialize the data
                        using (var bw = new BinaryWriter(ms)) {
                            Data.Serialize(bw);

                            // Attempt to save the data and fail if the CAS fails
                            retval = useCas
                                ? client.Cas(StoreMode.Set, DataPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, DataCas).Result
                                : client.Store(StoreMode.Set, DataPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                        }
                    }

                    // Return the success of the operation
                    return(retval);
                }
            }
        public void CreateUninitializedItem(System.Web.HttpContext context, string id, int timeout)
        {
            var session = new MemcachedSessionDo()
            {
                ApplicationName = "",
                Locked          = false,
                LockId          = 0,
                LockDate        = DateTime.Now,
                Created         = DateTime.Now,
                Flags           = 1
            };

            client.Store(StoreMode.Set, id, session, DateTime.Now.AddMinutes(sessionStateSection.Timeout.TotalMinutes));
        }
Beispiel #18
0
        public async Task PersistGermPlasmOutputAsync(
            ILambdaContext context,
            string cacheReportName,
            int reportId,
            Germplasm germPlasm,
            string headOrOther,
            List <ReducedEntryMeans> reducedEntryMeansList)
        {
            bool stored = memcachedClient.Store(StoreMode.Set, $"{cacheReportName}_{germPlasm.GermplasmId}", JsonConvert.SerializeObject(germPlasm), this.expiration);

            context.Logger.Log($"PersistGermPlasmOutputAsync {cacheReportName}_{germPlasm.GermplasmId} and {JsonConvert.SerializeObject(germPlasm)} in ElastiCache");
            if (!stored)
            {
                context.Logger.Log($"failed to set value for {cacheReportName}_{germPlasm.GermplasmId} in ElastiCache");
                throw new Exception($"failed to set value for {cacheReportName}_{germPlasm.GermplasmId} in ElastiCache");
            }
            this.TrackCacheKey(cacheReportName, $"{cacheReportName}_{germPlasm.GermplasmId}");

            if (reducedEntryMeansList.Count == 0)
            {
                context.Logger.Log($"no data to save for: {germPlasm.GermplasmId}");
            }
            ReducedBandKey key;

            foreach (ReducedEntryMeans reducedEntryMeans in reducedEntryMeansList)
            {
                if (reducedEntryMeans.Summary.Count == 0)
                {
                    context.Logger.Log($"{reducedEntryMeans.ReportGrouping}: no data to save for: {germPlasm.GermplasmId}");
                }
                foreach (KeyValuePair <GroupBySet, AnalyisTypeSummary> pair in reducedEntryMeans.Summary)
                {
                    key = new ReducedBandKey(cacheReportName, reportId, reducedEntryMeans.ReportGrouping.ToString(), germPlasm.GetProduct(), headOrOther, pair.Key, germPlasm.CEvent);
                    await SendAsync(context, cacheReportName, key);

                    string cacheKey = key.CacheKey;
                    if (string.IsNullOrEmpty(germPlasm.Alias))
                    {
                        context.Logger.Log($"trying to store: {cacheKey} for key: {key.ToKeyString()}");
                        stored = memcachedClient.Store(StoreMode.Add, cacheKey, pair.Value, this.expiration);
                        if (!stored)
                        {
                            throw new Exception($"failed to set value in ElastiCache");
                        }
                        this.TrackCacheKey(cacheReportName, cacheKey);
                    }
                    else
                    {
                        StoreBandKeyAsArrayItem(context, cacheReportName, reportId, cacheKey, pair.Value);
                    }
                    //context.Logger.Log($"stored");
                }
            }
            return;
        }
Beispiel #19
0
        public static double SetAndGetEnyim(int numberOfOperations, IMemcachedClient cli)
        {
            var start = DateTime.Now;

            //enyim is synchronous so no need to handle callbacks
            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "ey" + i;
                var value = key + " value";
                cli.Store(StoreMode.Set, key, value);
            }

            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "ey" + i;
                var value = cli.Get(key);
            }

            return (DateTime.Now - start).TotalSeconds;
        }
        public void SetUserAccessToken(UserAccessToken accessToken)
        {
            var hash       = GenerateSaltedHash(accessToken.Email + ":" + accessToken.Ticket, GenerateSalt());
            var hashString = Convert.ToBase64String(hash);

            if (!_memcachedClient.Store(StoreMode.Set, hashString, accessToken))
            {
                _logger.Error("Failed to set access token for: " + accessToken.Email);
                throw new UserTokenPersistenceFailedExpcetion();
            }

            CurrentAccessToken = accessToken;

            var cookie = new HttpCookie(_cookieName, hashString)
            {
                Secure   = _useSecureCookie,                    /* Ensures that this cookie is only used on SSL connections - this prevents Man-in-the-middle attacks */
                HttpOnly = true,                                /* Ensures that the cookie cannot be read from JavaScript - this prevents XSS attacks */
            };

            HttpContext.Current.Response.Cookies.Add(cookie);

            _logger.Info("Set access token for: " + accessToken.Email);
        }
Beispiel #21
0
 public bool Store(StoreMode mode, string key, object value)
 {
     return(_memcachedClient.Store(mode, key, value));
 }
 public override bool Set <T>(string key, T t, DateTime expire)
 {
     return(_memcachedClient.Store(StoreMode.Set, key, t, expire));
 }
            public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas)
            {
                using (var ms = new MemoryStream())
                {
                    this.SaveHeader(ms);
                    bool retval;
                    var ts = TimeSpan.FromMinutes(this.Timeout);

                    retval = useCas
                                ? client.Cas(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.HeadCas).Result
                                : client.Store(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);

                    if (!metaOnly)
                    {
                        ms.Position = 0;

                        using (var bw = new BinaryWriter(ms))
                        {
                            this.Data.Serialize(bw);
                            retval = useCas
                                        ? client.Cas(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.DataCas).Result
                                        : client.Store(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                        }
                    }

                    return retval;
                }
            }
        public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas, ICompressor compressor, Logger logger)
        {
            var ts = TimeSpan.FromMinutes(Timeout);

            bool retval;

            using (var ms = new MemoryStream())
            {
                // Save the header first
                SaveHeader(ms);

                // Attempt to save the header and fail if the CAS fails
                retval = useCas
                             ? client.Cas(StoreMode.Set, HeaderPrefix + id,
                                          new ArraySegment<byte>(ms.GetBuffer(), 0, (int) ms.Length), ts, HeadCas).Result
                             : client.Store(StoreMode.Set, HeaderPrefix + id,
                                            new ArraySegment<byte>(ms.GetBuffer(), 0, (int) ms.Length), ts);
                if (retval == false)
                {
                    return false;
                }
            }

            // Save the data
            if (!metaOnly)
            {

                byte[] data;

                ArraySegment<byte> arraySegment;

                using (var ms = new MemoryStream())
                {
                    using (var bw = new BinaryWriter(ms))
                    {
                        // Serialize the data
                        Data.Serialize(bw);
                        data = ms.ToArray();
                    }
                }

                if (compressor == null)
                {
                    if (logger != null)
                        logger.Info(string.Format("Save Item with id '{0}' with size {1}", id, data.LongLength));

                    arraySegment = new ArraySegment<byte>(data);
                }
                else
                {
                    var tempdata = compressor.Compress(data);

                    if (logger != null)
                        logger.Info(string.Format("Save Item with id '{0}' that was compressed from {1} bytes to {2} bytes", id, data.LongLength, tempdata.LongLength));

                    arraySegment = new ArraySegment<byte>(tempdata);
                }

                // Attempt to save the data and fail if the CAS fails
                retval = useCas
                             ? client.Cas(StoreMode.Set, DataPrefix + id, arraySegment, ts, DataCas).Result
                             : client.Store(StoreMode.Set, DataPrefix + id, arraySegment, ts);
            }

            // Return the success of the operation
            return retval;
        }
Beispiel #25
0
        public void Replace(string key, object value)
        {
            IMemcachedClient client = this.GetMemcachedClient();

            client.Store(StoreMode.Replace, key, value);
        }
Beispiel #26
0
 public bool Add(string key, object obj)
 {
     return(mc.Store(StoreMode.Add, key, obj));
 }
 public bool Set <T>(string key, T value) where T : class
 {
     return(_memcachedClient.Store(StoreMode.Set, key, value));
 }
Beispiel #28
0
 private void SetItem(string key, V item)
 {
     client.Store(StoreMode.Set, GetMemcacheKey(key), item);
 }
Beispiel #29
0
 public static IOperationResult Set(this IMemcachedClient self, string key, object value, ulong cas = Protocol.NO_CAS)
 {
     return(self.Store(StoreMode.Set, key, value, Expiration.Never, cas));
 }
 //using object rather than type safe T
 public static void Add(object objectToCache, string key, int cacheDuration)
 {
     Cache.Store(StoreMode.Set, key, objectToCache, DateTime.Now.AddMinutes(cacheDuration));
 }
Beispiel #31
0
 public static IOperationResult Add(this IMemcachedClient self, string key, object value, Expiration expiration, ulong cas = Protocol.NO_CAS)
 {
     return(self.Store(StoreMode.Add, key, value, expiration, cas));
 }
Beispiel #32
0
        public void Set(string key, object value)
        {
            IMemcachedClient client = this.GetMemcachedClient();

            client.Store(StoreMode.Set, key, value);
        }
        public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas, ICompressor compressor, Logger logger)
        {
            var ts = TimeSpan.FromMinutes(Timeout);

            bool retval;

            using (var ms = new MemoryStream())
            {
                // Save the header first
                SaveHeader(ms);

                // Attempt to save the header and fail if the CAS fails
                retval = useCas
                                                 ? client.Cas(StoreMode.Set, HeaderPrefix + id,
                                                              new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, HeadCas).Result
                                                 : client.Store(StoreMode.Set, HeaderPrefix + id,
                                                                new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                if (retval == false)
                {
                    return(false);
                }
            }

            // Save the data
            if (!metaOnly)
            {
                byte[] data;

                ArraySegment <byte> arraySegment;

                using (var ms = new MemoryStream())
                {
                    using (var bw = new BinaryWriter(ms))
                    {
                        // Serialize the data
                        Data.Serialize(bw);
                        data = ms.ToArray();
                    }
                }

                if (compressor == null)
                {
                    if (logger != null)
                    {
                        logger.Info(string.Format("Save Item with id '{0}' with size {1}", id, data.LongLength));
                    }

                    arraySegment = new ArraySegment <byte>(data);
                }
                else
                {
                    var tempdata = compressor.Compress(data);

                    if (logger != null)
                    {
                        logger.Info(string.Format("Save Item with id '{0}' that was compressed from {1} bytes to {2} bytes", id, data.LongLength, tempdata.LongLength));
                    }

                    arraySegment = new ArraySegment <byte>(tempdata);
                }

                // Attempt to save the data and fail if the CAS fails
                retval = useCas
                                                 ? client.Cas(StoreMode.Set, DataPrefix + id, arraySegment, ts, DataCas).Result
                                                 : client.Store(StoreMode.Set, DataPrefix + id, arraySegment, ts);
            }

            // Return the success of the operation
            return(retval);
        }
            public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas)
            {
                using (var ms = new MemoryStream()) {
                    // Save the header first
                    SaveHeader(ms);
                    var ts = TimeSpan.FromMinutes(Timeout);

                    // Attempt to save the header and fail if the CAS fails
                    bool retval = useCas
                        ? client.Cas(StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, HeadCas).Result
                        : client.Store(StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                    if (retval == false) {
                        return false;
                    }

                    // Save the data
                    if (!metaOnly) {
                        ms.Position = 0;

                        // Serialize the data
                        using (var bw = new BinaryWriter(ms)) {
                            Data.Serialize(bw);

                            // Attempt to save the data and fail if the CAS fails
                            retval = useCas
                                ? client.Cas(StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, DataCas).Result
                                : client.Store(StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                        }
                    }

                    // Return the success of the operation
                    return retval;
                }
            }