public void StoreWithProtoTranscoder()
        {
            var config = GetConfig();
            var transcoder = new ProtoBuf.Caching.Enyim.NetTranscoder();
            config.Transcoder =  transcoder;
            SomeType obj = new SomeType { Id = 1, Name = "abc" }, clone;
            string cloneString;
            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(0, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                client.Store(StoreMode.Set, "raw1", obj);
                client.Store(StoreMode.Set, "raw2", "def");
            }
            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                clone = (SomeType)client.Get("raw1");
                cloneString = (string)client.Get("raw2");
            }
            Assert.AreEqual(1, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);

            Assert.AreEqual(1, clone.Id);
            Assert.AreEqual("abc", clone.Name);
            Assert.AreEqual("def", cloneString);
        }
Exemple #2
0
        public void RunProgram()
        {
            const string key = "testkey";
            var cacheClient = new MemcachedClient(ConfigurationManager.GetSection("enyim.com/memcached") as IMemcachedClientConfiguration);
            cacheClient.Store(StoreMode.Add, key, "testvalue");
            var item = cacheClient.Get(key);
            Console.WriteLine(item);

            cacheClient.Store(StoreMode.Set, key, "something else");
            item = cacheClient.Get(key);
            Console.WriteLine(item);
        }
        public void Get_Study()
        {
            using (var client = new MemcachedClient())
            {
                // 没有键,返回null。
                var result1 = client.Get("userid");
                Assert.Null(result1);

                client.Store(StoreMode.Set, "userid", "123456");
                var result2 = client.Get("userid");
                Assert.AreEqual("123456", result2);

                client.FlushAll();
            }
        }
        static void testMemcachedProviders()  
        {
            MemcachedClient client = new MemcachedClient("enyim.com/memcached");
            //存值  --不带过期时间的存储,Memcached将根据LRU来决定过期策略  
            bool result = client.Store(Enyim.Caching.Memcached.StoreMode.Add, "name", "dinglang");
            
            //带过期时间的缓存    
            //bool success = client.Store(StoreMode.Add, person.UserName, person, DateTime.Now.AddMinutes(10));   
            if (result)
            {
                Console.Write("成功存入缓存");

                //取值    
                object name = client.Get("name");
                if (name != null)
                {
                    Console.Write("取出的值为:" + name);
                }
                else
                {
                    Console.Write("取值失败");
                }
            }
            else
            {
                Console.Write("存入缓存失败");
            }
        }    
Exemple #5
0
        public MemcachedLocker(MemcachedClient client, string key, TimeSpan timeOut)
        {
            this.client = client;
            this.key = key;
            this.timeOut = timeOut;

            int sleep = 10;
            DateTime now = DateTime.Now;
            while (DateTime.Now - now < timeOut)
            {
                if (client.Add<DateTime?>(key, DateTime.Now.Add(timeOut)))
                    return;

                //需要排除锁未释放的可能,如果检测到超过超时时间2倍的话,尝试获得锁
                ulong version;
                var time = client.Get<DateTime?>(key, out version);
                if (time == null || (time.HasValue && time.Value.ToLocalTime().Add(timeOut + timeOut) < DateTime.Now))
                {
                    LocalLoggingService.Warning("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "MemcachedLocker", "MemcachedLocker",
                                        string.Format("发现一个超时的分布式锁,超时时间:{0} Key : {1}",
                                        time, key));
                    if (client.Add<DateTime?>(key, DateTime.Now.Add(timeOut), version))
                        return;
                }

                if (sleep < 1000)
                    sleep = sleep * 110 / 100;
                else
                    sleep = 1000;

                Thread.Sleep(sleep);
            }

            throw new TimeoutException(string.Format("获得锁的时间超过了设定的最大时间 {0}", timeOut.ToString()));
        }
 /// <summary>
 /// 获取缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <returns>返回缓存,没有找到则返回null</returns>
 public static object GetCache(string key)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Get(key);
     }
 }
 /// <summary>
 /// 是否存在该缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <returns></returns>
 public static bool IsExists(string key)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Get(key) != null;
     }
 }
        public void TestThem(List<string> servers)
        {
            var mbc = new MemcachedClientConfiguration();
            foreach (var server in servers)
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(server), 11211);
                mbc.Servers.Add(endPoint);
            }

            _couchbaseClient = new MemcachedClient(mbc);

            _couchbaseClient.Store(StoreMode.Set, Key, Value);
            Debug.Assert((string)_couchbaseClient.Get(Key) == Value);

            List<Thread> workers = new List<Thread>();

            for (int s = 0; s < NumThreads; s++)
            {
                Thread workerThread = new Thread(Run);
                workerThread.Start();
                workers.Add(workerThread);
            }

            foreach (var thread in workers)
            {
                while (thread.IsAlive)
                {
                    Thread.Sleep(1);
                }

                thread.Join();
            }
        }
Exemple #9
0
        public void CanCacheString()
        {
            var client = new MemcachedClient();

            client.Store(StoreMode.Add, "a", "b");
            var result = client.Get<string>("a");

            Assert.AreEqual("b", result);
        }
Exemple #10
0
        public void CanCacheList()
        {
            var client = new MemcachedClient();
            var list = new List<string> { "a", "b" };

            client.Store(StoreMode.Set, "d", list);

            var result = client.Get<List<string>>("d");
            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("a", result[0]);
            Assert.AreEqual("b", result[1]);
        }
		public void TestThrottlingFailurePolicy()
		{
			var config = new MemcachedClientConfiguration();
			config.AddServer("nonexisting.enyim.com:2244");

			config.SocketPool.FailurePolicyFactory = new ThrottlingFailurePolicyFactory(4, TimeSpan.FromMilliseconds(2000));
			config.SocketPool.ConnectionTimeout = TimeSpan.FromMilliseconds(10);
			config.SocketPool.ReceiveTimeout = TimeSpan.FromMilliseconds(10);
			config.SocketPool.MinPoolSize = 1;
			config.SocketPool.MaxPoolSize = 1;

			var client = new MemcachedClient(config);
			var canFail = false;
			var didFail = false;

			client.NodeFailed += node =>
			{
				Assert.IsTrue(canFail, "canfail");

				didFail = true;
			};

			Assert.IsNull(client.Get("a"), "Get should have failed. 1");
			Assert.IsNull(client.Get("a"), "Get should have failed. 2");

			canFail = true;
			Thread.Sleep(2000);

			Assert.IsNull(client.Get("a"), "Get should have failed. 3");
			Assert.IsNull(client.Get("a"), "Get should have failed. 4");
			Assert.IsNull(client.Get("a"), "Get should have failed. 5");
			Assert.IsNull(client.Get("a"), "Get should have failed. 6");

			Assert.IsTrue(didFail, "didfail");
		}
        static MemcachedContainerStrategy()
        {
            // //初始化memcache服务器池
            //SockIOPool pool = SockIOPool.GetInstance();
            ////设置Memcache池连接点服务器端。
            //pool.SetServers(serverlist);
            ////其他参数根据需要进行配置

            //pool.InitConnections = 3;
            //pool.MinConnections = 3;
            //pool.MaxConnections = 5;

            //pool.SocketConnectTimeout = 1000;
            //pool.SocketTimeout = 3000;

            //pool.MaintenanceSleep = 30;
            //pool.Failover = true;

            //pool.Nagle = false;
            //pool.Initialize();

            //cache = new MemcachedClient();
            //cache.EnableCompression = false;
            try
            {
                //config.Authentication.Type = typeof(PlainTextAuthenticator);
                //config.Authentication.Parameters["userName"] = "******";
                //config.Authentication.Parameters["password"] = "******";
                //config.Authentication.Parameters["zone"] = "zone";//domain?   ——Jeffrey 2015.10.20
                DateTime dt1 = DateTime.Now;
                var config = GetMemcachedClientConfiguration();
                var cache = new MemcachedClient(config);

                var testKey = Guid.NewGuid().ToString();
                var testValue = Guid.NewGuid().ToString();
                cache.Store(StoreMode.Set, testKey, testValue);
                var storeValue = cache.Get(testKey);
                if (storeValue as string != testValue)
                {
                    throw new Exception("MemcachedStrategy失效,没有计入缓存!");
                }
                cache.Remove(testKey);
                DateTime dt2 = DateTime.Now;

                WeixinTrace.Log(string.Format("MemcachedStrategy正常启用,启动及测试耗时:{0}ms", (dt2 - dt1).TotalMilliseconds));
            }
            catch (Exception ex)
            {
                //TODO:记录是同日志
                WeixinTrace.Log(string.Format("MemcachedStrategy静态构造函数异常:{0}", ex.Message));
            }
        }
		public void TestIfCalled()
		{
			var config = new MemcachedClientConfiguration();
			config.AddServer("nonexisting.enyim.com:2244");

			config.SocketPool.FailurePolicyFactory = new FakePolicy();
			config.SocketPool.ConnectionTimeout = TimeSpan.FromSeconds(4);
			config.SocketPool.ReceiveTimeout = TimeSpan.FromSeconds(6);

			var client = new MemcachedClient(config);

			Assert.IsNull(client.Get("a"), "Get should have failed.");
		}
        public void AddSetReplaceTest()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.Store(StoreMode.Set, "VALUE", "1");

            Assert.AreEqual("1", mc.Get("VALUE"), "Store failed");

            mc.Store(StoreMode.Add, "VALUE", "2");
            Assert.AreEqual("1", mc.Get("VALUE"), "Item should not have been Added");

            mc.Store(StoreMode.Replace, "VALUE", "4");
            Assert.AreEqual("4", mc.Get("VALUE"), "Replace failed");

            mc.Remove("VALUE");

            mc.Store(StoreMode.Replace, "VALUE", "8");
            Assert.IsNull(mc.Get("VALUE"), "Item should not have been Replaced");

            mc.Remove("VALUE");

            mc.Store(StoreMode.Add, "VALUE", "16");
            Assert.AreEqual("16", mc.Get("VALUE"), "Add failed");
        }
Exemple #15
0
 public void StoreWithDefaultTranscoder()
 {
     var config = GetConfig();
     SomeType obj = new SomeType { Id = 1, Name = "abc" }, clone;
     using (var client = new MemcachedClient(config))
     {
         client.Store(StoreMode.Set, "raw1", obj);
     }
     using (var client = new MemcachedClient(config))
     {
         clone = (SomeType) client.Get("raw1");
     }
     Assert.AreEqual(1, clone.Id);
     Assert.AreEqual("abc", clone.Name);
 }
Exemple #16
0
        public void CanCacheDTO()
        {
            var client = new MemcachedClient();
            var obj = new Dto
            {
                Name = "b",
                Title = "c"
            };

            client.Store(StoreMode.Set, "c", obj);
            var result = client.Get<Dto>("c");

            Assert.AreEqual("b", result.Name);
            Assert.AreEqual("c", result.Title);
        }
Exemple #17
0
        private static void StressTest(MemcachedClient client, string keyPrefix)
        {
            var i = 0;
            var last = true;

            var progress = @"-\|/".ToCharArray();
            Console.CursorVisible = false;
            Dictionary<bool, int> counters = new Dictionary<bool, int>() { { true, 0 }, { false, 0 } };

            while (true)
            {
                var key = keyPrefix + i;
                var state = client.Store(StoreMode.Set, key, i) & client.Get<int>(key) == i;

                Action updateTitle = () => Console.Title = "Success: " + counters[true] + " Fail: " + counters[false];

                if (state != last)
                {
                    Console.ForegroundColor = state ? ConsoleColor.White : ConsoleColor.Red;
                    Console.Write(".");

                    counters[state] = 0;
                    last = state;

                    updateTitle();
                }
                else if (i % 200 == 0)
                {
                    //Console.ForegroundColor = state ? ConsoleColor.White : ConsoleColor.Red;

                    //Console.Write(progress[(i / 200) % 4]);
                    //if (Console.CursorLeft == 0)
                    //{
                    //    Console.CursorLeft = Console.WindowWidth - 1;
                    //    Console.CursorTop -= 1;
                    //}
                    //else
                    //{
                    //    Console.CursorLeft -= 1;
                    //}

                    updateTitle();
                }

                i++;
                counters[state] = counters[state] + 1;
            }
        }
Exemple #18
0
 public void ShouldBeAbleToCacheContractTypes()
 {
     ContractType original = new ContractType { Id = 123, Name = "abc" }, clone;
     using (var client = new MemcachedClient())
     {
         client.Store(StoreMode.Set, "ShouldBeAbleToCacheBasicTypes", original);
     }
     using (var client = new MemcachedClient())
     {
         clone = client.Get<ContractType>("ShouldBeAbleToCacheBasicTypes");
     }
     Assert.IsNotNull(clone);
     Assert.AreNotSame(original, clone);
     Assert.AreEqual(original.Id, clone.Id);
     Assert.AreEqual(original.Name, clone.Name);
 }
Exemple #19
0
        public void CanConnectToMemcached()
        {
            var config = GetConfig();
            string s1 = Guid.NewGuid().ToString();
            string s2 = Guid.NewGuid().ToString();
            Assert.AreNotEqual(s1, s2);
            using (var client1 = new MemcachedClient(config))
            using (var client2 = new MemcachedClient(config))
            {
                client1.Store(StoreMode.Set, "key1", s1);
                client2.Store(StoreMode.Set, "key2", s2);

                Assert.AreEqual(s2, client1.Get("key2"), "client1.key2");
                Assert.AreEqual(s1, client2.Get("key1"), "client2.key1");
            }
        }
        public void Online() {
            using (MemcachedClient client = new MemcachedClient("enyim.com/memcached")) {
                String key = Guid.NewGuid().ToString("n");
                Object value = client.Get(key);
                Assert.IsNull(value);

                var exist = client.TryGet(key, out value);
                Assert.IsFalse(exist);
                Assert.IsNull(value);

                value = new Person {
                    Id = 2,
                    Name = "Rattz",
                    Address = new Address {
                        Line1 = "Haidin Shuzhoujie",
                        Line2 = "Beijing China"
                    }
                };
                client.Store(StoreMode.Set, key, value);
                exist = client.TryGet(key, out value);
                Assert.IsTrue(exist);
                Assert.IsNotNull(value);
            }
        }
Exemple #21
0
 public static T Get <T>(string key)
 {
     return(_client.Get <T>(key));
 }
Exemple #22
0
        public static void Main(String[] args)
        {
            int runs  = 100;
            int start = 200;

            if (args.Length > 1)
            {
                runs  = int.Parse(args[0]);
                start = int.Parse(args[1]);
            }

            string[] serverlist = { "140.192.34.72:11211", "140.192.34.73:11211" };

            // initialize the pool for memcache servers
            SockIOPool pool = SockIOPool.GetInstance();

            pool.SetServers(serverlist);

            pool.InitConnections = 3;
            pool.MinConnections  = 3;
            pool.MaxConnections  = 5;

            pool.SocketConnectTimeout = 1000;
            pool.SocketTimeout        = 3000;

            pool.MaintenanceSleep = 30;
            pool.Failover         = true;

            pool.Nagle = false;
            pool.Initialize();

            // initialize the pool for memcache servers
//			SockIOPool pool = SockIOPool.Instance;
//			pool.Servers = serverlist;
//
//			pool.InitConn = 5;
//			pool.MinConn = 5;
//			pool.MaxConn = 50;
//			pool.MaintSleep = 30;
//			pool.SocketTO = 1000;
//
//			pool.Nagle = false;
//			pool.Initialize();

//
//			// get client instance
            MemcachedClient mc = new MemcachedClient();

            mc.EnableCompression = false;

//			MemcachedClient mc = new MemcachedClient();
//			mc.CompressEnable = false;
//			mc.CompressThreshold = 0;
//			mc.Serialize = true;

            string keyBase = "testKey";
            string obj     = "This is a test of an object blah blah es, serialization does not seem to slow things down so much.  The gzip compression is horrible horrible performance, so we only use it for very large objects.  I have not done any heavy benchmarking recently";

            long begin = DateTime.Now.Ticks;

            for (int i = start; i < start + runs; i++)
            {
                mc.Set(keyBase + i, obj);
            }
            long end  = DateTime.Now.Ticks;
            long time = end - begin;

            Console.WriteLine(runs + " sets: " + new TimeSpan(time).ToString() + "ms");

            begin = DateTime.Now.Ticks;
            int hits   = 0;
            int misses = 0;

            for (int i = start; i < start + runs; i++)
            {
                string str = (string)mc.Get(keyBase + i);
                if (str != null)
                {
                    ++hits;
                }
                else
                {
                    ++misses;
                }
            }
            end  = DateTime.Now.Ticks;
            time = end - begin;

            Console.WriteLine(runs + " gets: " + new TimeSpan(time).ToString() + "ms");
            Console.WriteLine("Cache hits: " + hits.ToString());
            Console.WriteLine("Cache misses: " + misses.ToString());

            IDictionary stats = mc.Stats();

            foreach (string key1 in stats.Keys)
            {
                Console.WriteLine(key1);
                Hashtable values = (Hashtable)stats[key1];
                foreach (string key2 in values.Keys)
                {
                    Console.WriteLine(key2 + ":" + values[key2]);
                }
                Console.WriteLine();
            }

            SockIOPool.GetInstance().Shutdown();
        }
Exemple #23
0
 //读取缓存
 public T GetCache <T>(string cacheKey) where T : class
 {
     return((T)memClient.Get(cacheKey));
 }
Exemple #24
0
 public static object Get(string key)
 {
     return(client.Get(key));
 }
Exemple #25
0
 /// <summary>
 /// 读取数据缓存
 /// </summary>
 /// <param name="key">键</param>
 public static T Get <T>(string key)
 {
     return((T)mc.Get(key));
 }
Exemple #26
0
        public static void test()
        {
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();

            config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11211));
            config.Protocol = MemcachedProtocol.Binary;
            //config.Authentication.Type = typeof(PlainTextAuthenticator);
            //config.Authentication.Parameters["userName"] = "******";
            //config.Authentication.Parameters["password"] = "******";

            var mc = new MemcachedClient(config);

            for (var i = 0; i < 100; i++)
            {
                mc.Store(StoreMode.Set, "Hello", "World");
            }


            // simple multiget; please note that only 1.2.4 supports it (windows version is at 1.2.1)
            List <string> keys = new List <string>();

            for (int i = 1; i < 100; i++)
            {
                string k = "aaaa" + i + "--" + (i * 2);
                keys.Add(k);

                mc.Store(StoreMode.Set, k, i);
            }

            IDictionary <string, ulong>  cas;
            IDictionary <string, object> retvals = mc.Get(keys);

            List <string> keys2 = new List <string>(keys);

            keys2.RemoveRange(0, 50);

            IDictionary <string, object> retvals2 = mc.Get(keys2);

            retvals2 = mc.Get(keys2);

            ServerStats ms = mc.Stats();

            // store a string in the cache
            mc.Store(StoreMode.Set, "MyKey", "Hello World");

            // retrieve the item from the cache
            Console.WriteLine(mc.Get("MyKey"));

            Console.WriteLine(mc.Increment("num1", 1, 10));
            Console.WriteLine(mc.Increment("num1", 1, 10));
            Console.WriteLine(mc.Decrement("num1", 1, 14));

            // store some other items
            mc.Store(StoreMode.Set, "D1", 1234L);
            mc.Store(StoreMode.Set, "D2", DateTime.Now);
            mc.Store(StoreMode.Set, "D3", true);
            mc.Store(StoreMode.Set, "D4", new Person());

            mc.Store(StoreMode.Set, "D5", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });


            //mc2.Store(StoreMode.Set, "D1", 1234L);
            //mc2.Store(StoreMode.Set, "D2", DateTime.Now);
            //mc2.Store(StoreMode.Set, "D3", true);
            //mc2.Store(StoreMode.Set, "D4", new Product());

            Console.WriteLine("D1: {0}", mc.Get("D1"));
            Console.WriteLine("D2: {0}", mc.Get("D2"));
            Console.WriteLine("D3: {0}", mc.Get("D3"));
            Console.WriteLine("D4: {0}", mc.Get("D4"));

            byte[] tmp = mc.Get <byte[]>("D5");

            // delete them from the cache
            mc.Remove("D1");
            mc.Remove("D2");
            mc.Remove("D3");
            mc.Remove("D4");

            ServerStats stats = mc.Stats();

            Console.WriteLine(stats.GetValue(ServerStats.All, StatItem.ConnectionCount));
            Console.WriteLine(stats.GetValue(ServerStats.All, StatItem.GetCount));

            // add an item which is valid for 10 mins
            mc.Store(StoreMode.Set, "D4", new Person(), new TimeSpan(0, 10, 0));
        }
Exemple #27
0
 public Employee Get()
 {
     return((Employee)_memcachedClient.Get(MemcachedKeys.EmployeeKey));
 }
Exemple #28
0
        public System.Runtime.Caching.CacheItem GetItem(string key)
        {
            object value = client.Get(key);

            return(new System.Runtime.Caching.CacheItem(key, value));
        }
Exemple #29
0
		public void StoreStringTest()
		{
			MemcachedClient mc = new MemcachedClient();
			mc.Store(StoreMode.Set, "TestString", "Hello world!");

			Assert.AreEqual("Hello world!", mc.Get<string>("TestString"));
		}
 public object Get(string key)
 {
     return(Cached.Get(key));
 }
Exemple #31
0
 public static object GetMemcachedData(string key)
 {
     return(MemcachedClient.Get(key));
 }
 public object GetCache(string key)
 {
     return(memcachedClient.Get(key));
 }
Exemple #33
0
        /// <summary>
        /// 通过key删除缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <bool> DeleteAsync(string key)
        {
            var result = _memcachedClient.Remove(key);

            if (result == false)
            {
                var empty = _memcachedClient.Get(key);
                if (empty == null)
                {
                    result = true;
                }
            }

            return(await Task.FromResult(result));
        }
Exemple #34
0
 public object Get(string key)
 {
     return(m_memcachedClientIns.Get(key));
 }
Exemple #35
0
 public object Get(string key)
 {
     return(MC.Get(key));
 }
Exemple #36
0
		public void StoreLongTest()
		{
			MemcachedClient mc = new MemcachedClient();
			mc.Store(StoreMode.Set, "TestLong", 65432123456L);

			Assert.AreEqual(65432123456L, mc.Get<long>("TestLong"));
		}
Exemple #37
0
 public object GetValue(string key)
 {
     return(client.Get(key));
 }
Exemple #38
0
 public object LocalMemcachedQuery()
 {
     return(localMemcached.Get("testdoc2." + QueryId));
 }
Exemple #39
0
 /// <summary>
 /// 读取Memcached缓存
 /// </summary>
 /// <param name="cacheKey">缓存键值</param>
 /// <returns>键值对应的缓存值</returns>
 public static object MemcachedRead(this string cacheKey)
 {
     return(mClient.Get(cacheKey));
 }
Exemple #40
0
		public void ExpirationTest()
		{
			MemcachedClient mc = new MemcachedClient();

			mc.Store(StoreMode.Set, "ExpirationTest:TimeSpan", "ExpirationTest:TimeSpan", new TimeSpan(0, 0, 5));

			Assert.AreEqual("ExpirationTest:TimeSpan", mc.Get("ExpirationTest:TimeSpan"), "Expires:Timespan store failed");

			Thread.Sleep(8000);
			Assert.IsNull(mc.Get("ExpirationTest:TimeSpan"), "ExpirationTest:TimeSpan item did not expire");

			DateTime expiresAt = DateTime.Now.AddSeconds(5);

			mc.Store(StoreMode.Set, "Expires:DateTime", "Expires:DateTime", expiresAt);

			Assert.AreEqual("Expires:DateTime", mc.Get("Expires:DateTime"), "Expires:DateTime store failed");

			expiresAt = expiresAt.AddSeconds(4); // wait more than the expiration

			while (DateTime.Now < expiresAt)
			{
				Thread.Sleep(100);
			}

			object o = mc.Get("Expires:DateTime");

			Assert.IsNull(o, "Expires:DateTime item did not expire");
		}
Exemple #41
0
 public Product Get(int id)
 {
     return(client.Get <Product>(id.ToString()));
 }
Exemple #42
0
        /// <summary>
        /// 从指定服务器获取
        /// </summary>
        /// <param name="server">服务器,Svr1,Svr2</param>
        /// <param name="key">键</param>
        /// <param name="value"></param>
        /// <param name="asString">是否把值作为字符串返回</param>
        public static object GetFrom(string server, string key, object value, bool asString)
        {
            MemcachedClient client = GetClient(server);

            return(client.Get(key, value, asString));
        }
Exemple #43
0
 /// <summary>
 /// 获取数据
 /// </summary>
 public static object Get(string key)
 {
     return(mc.Get(key));
 }
        public static void TestNMemcachedClient()
        {
            /*
             * Connect to memcached server
             */
            ServerConnectionCollection MemCachedServers = new ServerConnectionCollection();

            /*
             * Add Server from Config Settings
             */
            MemCachedServers.Add("192.168.1.48", 11211);

            /*
             * Create the client
             */
            IConnectionProvider provider = new ConnectionProvider(MemCachedServers);
            MemcachedClient client = new MemcachedClient(provider);

            System.Console.WriteLine("Dumping contents of cache...");
            System.Console.WriteLine("Printing California Customers table [calcustomers]");
            System.Console.WriteLine();

            ResponseCode response = ResponseCode.UnknownCommand;

            IDictionary<string, object> Responses = client.Get(new string[] { "calcustomers.key=1", "calcustomers.key=2", "calcustomers.key=3" });

            foreach (KeyValuePair<string, object> item in Responses)
            {
                System.Console.WriteLine("key: {0}, CustomerName: {1}", item.Key, item.Value.ToString());
            }

            System.Console.WriteLine("Press any key to exit....");
            System.Console.ReadLine();
        }
Exemple #45
0
        /// <summary>
        /// 从指定服务器获取
        /// </summary>
        /// <param name="server">服务器,Svr1,Svr2</param>
        /// <param name="key">键</param>
        /// <param name="hashCode">哈希码</param>
        public static object GetFrom(string server, string key, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            return(client.Get(key, hashCode));
        }
 /// <summary>
 /// 获取Memcache数据
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public static object Get(string key) => mc.Get(key);
Exemple #47
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            FileInfo fileInfo = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath));
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = false;
            m_context = context;
            m_httpMethod = m_context.Request.HttpMethod;
            m_memcachedClient = (Client)context.Application["memcached"];
            m_queueClient = (QueueClient)context.Application["queueclient"];
            m_xslTransformationManager = (XsltTransformationManager)context.Application["xslTransformationManager"];
            m_transform = m_xslTransformationManager.Transform;
            m_xsltParams = (Hashtable)context.Application["globalXsltParams"];
            m_namedXsltHashtable = (Hashtable)context.Application["namedXsltHashtable"];
            m_transformContext = new Transform.Context(context, m_hashAlgorithm, (string)context.Application["hashkey"], fileInfo, (Hashtable)m_xsltParams.Clone(), fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_transformAsyncResult = new NuxleusAsyncResult(cb, extraData);
            m_callback = cb;
            m_transformAsyncResult.m_context = context;
            m_builder = new StringBuilder();
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = (bool)context.Application["usememcached"];

            bool hasXmlSourceChanged = m_xslTransformationManager.HasXmlSourceChanged(m_transformContext.RequestXmlETag);
            bool hasBaseXsltSourceChanged = m_xslTransformationManager.HasBaseXsltSourceChanged();

            if (m_USE_MEMCACHED)
            {

                string obj = (string)m_memcachedClient.Get(m_transformContext.GetRequestHashcode(true));

                if (obj != null && !(hasXmlSourceChanged || hasBaseXsltSourceChanged) && !(m_context.Request.CurrentExecutionFilePath.StartsWith("/service/session")  && !(m_context.Request.CurrentExecutionFilePath.StartsWith("/service/geo"))))
                {
                    m_builder.Append(obj);
                    m_CONTENT_IS_MEMCACHED = true;
                    if ((bool)context.Application["debug"])
                        context.Response.ContentType = "text";
                    else
                        context.Response.ContentType = "text/xml";
                }
                else
                {
                    m_writer = new StringWriter(m_builder);
                    m_CONTENT_IS_MEMCACHED = false;
                }
            }
            else
            {
                m_writer = new StringWriter(m_builder);
            }

            //if ((bool)context.Application["debug"])
            //{
            //    context.Response.Write("<debug>");
            //    context.Response.Write("<file-info>");
            //    context.Response.Write("Has Xml Changed: " + hasXmlSourceChanged + ":" + m_transformContext.RequestXmlETag + "<br/>");
            //    context.Response.Write("Has Xslt Changed: " + hasBaseXsltSourceChanged + "<br/>");
            //    context.Response.Write("Xml ETag: " + m_transformContext.GetRequestHashcode(true) + "<br/>");
            //    context.Response.Write("XdmNode Count: " + m_xslTransformationManager.GetXdmNodeHashtableCount() + "<br/>");
            //    context.Response.Write("</file-info>");
            //    context.Application["debugOutput"] = (string)("<DebugOutput>" + WriteDebugOutput(m_transformContext, m_xslTransformationManager, new StringBuilder(), m_CONTENT_IS_MEMCACHED).ToString() + "</DebugOutput>");
            //    context.Response.Write("</debug>");
            //}

            try
            {

                switch (m_httpMethod)
                {
                    case "GET":
                    case "HEAD":
                        {
                            if (m_CONTENT_IS_MEMCACHED)
                            {
                                m_transformAsyncResult.CompleteCall();
                                return m_transformAsyncResult;
                            }
                            else
                            {
                                try
                                {
                                    string file = m_context.Request.FilePath;
                                    string baseXslt;

                                    if (file.EndsWith("index.page"))
                                    {
                                        baseXslt = "precompile-atomictalk";
                                    }
                                    else if (file.EndsWith("service.op"))
                                        baseXslt = "base";
                                    else
                                        baseXslt = m_xslTransformationManager.BaseXsltName;

                                    //m_transform.BeginTransformProcess(m_transformContext, context, m_xslTransformationManager, m_writer, baseXslt, m_transformAsyncResult);
                                    return m_transformAsyncResult;
                                }
                                catch (Exception e)
                                {
                                    m_exception = e;
                                    WriteError();
                                    m_transformAsyncResult.CompleteCall();
                                    return m_transformAsyncResult;
                                }
                            }
                        }
                    case "PUT":
                        {
                            
                            return m_transformAsyncResult;
                        }
                    case "POST":
                        {
                            return m_transformAsyncResult;
                        }
                    case "DELETE":
                        {
                            return m_transformAsyncResult;
                        }
                    default:
                        {
                            return m_transformAsyncResult;
                        }
                }

            }
            catch (Exception ex)
            {
                m_exception = ex;
                WriteError();
                m_transformAsyncResult.CompleteCall();
                return m_transformAsyncResult;
            }
        }
        public IAsyncResult BeginProcessRequest ( HttpContext context, AsyncCallback cb, object extraData ) {

            m_stopwatch.Start();

            FileInfo fileInfo = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath));
            this.LogDebug("File Date: {0}; File Length: {1}", fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = false;
            m_httpContext = context;
            m_returnOutput = true;
            m_httpMethod = m_httpContext.Request.HttpMethod;
            m_memcachedClient = (Client)context.Application["memcached"];
            m_encoding = (UTF8Encoding)context.Application["encoding"];
            m_queueClient = (QueueClient)context.Application["queueclient"];
            m_hashkey = (string)context.Application["hashkey"];
            m_xmlServiceOperationManager = (XPathServiceOperationManager)context.Application["xmlServiceOperationManager"];
            m_xslTransformationManager = (XsltTransformationManager)context.Application["xslTransformationManager"];
            m_transform = m_xslTransformationManager.Transform;
            m_xsltParams = (Hashtable)context.Application["globalXsltParams"];
            m_transformContext = new Transform.Context(context, m_hashAlgorithm, (string)context.Application["hashkey"], fileInfo, (Hashtable)m_xsltParams.Clone(), fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_namedXsltHashtable = (Hashtable)context.Application["namedXsltHashtable"];
            m_xmlSourceETagDictionary = m_xmlServiceOperationManager.XmlSourceETagDictionary;
            m_xmlReaderDictionary = m_xmlServiceOperationManager.XmlReaderDictionary;
            m_context = new Context(context, m_hashAlgorithm, m_hashkey, fileInfo, fileInfo.LastWriteTimeUtc, fileInfo.Length);
            this.LogDebug("File Date: {0}; File Length: {1}", m_context.RequestXmlFileInfo.LastWriteTimeUtc, m_context.RequestXmlFileInfo.Length);
            m_nuxleusAsyncResult = new Nuxleus.Core.NuxleusAsyncResult(cb, extraData);
            m_callback = cb;
            m_nuxleusAsyncResult.m_context = context;
            m_builder = new StringBuilder();
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = (bool)context.Application["usememcached"];
            Uri requestUri = new Uri(m_context.RequestUri);
            m_requestHashcode = m_context.GetRequestHashcode(true).ToString();
            m_lastModifiedKey = String.Format("LastModified:{0}", m_context.RequestUri.GetHashCode());
            m_lastModifiedDate = String.Empty;
            m_request = new TransformRequest();
            m_response = new TransformResponse();
            Guid requestGuid = Guid.NewGuid();
            m_request.ID = requestGuid;

            
            context.Response.ContentType = "text/xml";

            IEnumerator headers = context.Request.Headers.GetEnumerator();
            for (int i = 0; headers.MoveNext(); i++) {
                string local = context.Request.Headers.AllKeys[i].ToString();
                this.LogDebug("KeyName: {0}, KeyValue: {1}", local, context.Request.Headers[local]);
            }
            bool hasXmlSourceChanged = m_xmlServiceOperationManager.HasXmlSourceChanged(m_context.RequestXmlETag, requestUri);

            //if (m_USE_MEMCACHED) {

            //    string obj = (string)m_memcachedClient.Get(m_context.GetRequestHashcode(true).ToString());

            //    if (obj != null && !hasXmlSourceChanged) {
            //        m_response.TransformResult = (string)obj;
            //        m_CONTENT_IS_MEMCACHED = true;
            //        if ((bool)context.Application["debug"]) {
            //            context.Response.ContentType = "text";
            //        }
            //    } else {
            //        //m_writer = new StringWriter(m_builder);
            //        m_CONTENT_IS_MEMCACHED = false;
            //    }
            //} else {
            //    m_writer = new StringWriter(m_builder);
            //}

            m_writer = new StringWriter(m_builder);

            try {

                switch (m_httpMethod) {
                    case "GET":
                    case "HEAD":
                    case "POST": {                     
                            string name = String.Format("Name: {0}", context.Request.QueryString["name"]);
                            this.LogDebug("QueryString Length: {0}", context.Request.QueryString.Count);
                            this.LogDebug(name);
                            this.LogDebug("If-None-Match: {0}, RequestHashCode: {1}", context.Request.Headers["If-None-Match"], m_requestHashcode);
                            this.LogDebug(context.Request.Path);
                            if (context.Request.Headers["If-None-Match"] == m_requestHashcode) {
                                object lastModified;
                                this.LogDebug("They matched.");
                                this.LogDebug("Use memcached: {0}, KeyExists: {1}, XmlSource Changed: {2}", m_USE_MEMCACHED, m_memcachedClient.TryGet(m_lastModifiedKey, out lastModified), hasXmlSourceChanged);
                                this.LogDebug("Last Modified Key Value: {0}", m_lastModifiedKey);
                                if (m_USE_MEMCACHED && m_memcachedClient.TryGet(m_lastModifiedKey, out lastModified) && !hasXmlSourceChanged)
                                {
                                    m_lastModifiedDate = (string)m_memcachedClient.Get(m_lastModifiedKey);
                                    this.LogDebug("Last Modified Date: {0}", m_lastModifiedDate);
                                    if (context.Request.Headers["If-Modified-Since"] == m_lastModifiedDate) {

                                        context.Response.StatusCode = 304;
                                        m_returnOutput = false;
                                        goto CompleteCall;
                                    } else {
                                        goto Process;
                                    }
                                } else if (m_CONTENT_IS_MEMCACHED) {
                                    goto CompleteCall;
                                } else {
                                    goto Process;
                                }
                            } else {
                                this.LogDebug("Headers do not match.  Beginning transformation process...");
                                m_returnOutput = true;
                                goto Process;
                            }
                        }
                    case "PUT": {
                            goto CompleteCall;
                        }
                    case "DELETE": {
                            goto CompleteCall;
                        }
                    default: {
                            goto CompleteCall;
                        }
                }

            } catch (Exception ex) {
                m_exception = ex;
                WriteError();
                goto CompleteCall;
            }
        Process:
            try {
                this.LogDebug("Processing Transformation");
                this.LogDebug("Request XML ETag Value: {0}, Request URI: {1}", m_context.RequestXmlETag, requestUri);

                XPathNavigator navigator = m_xmlServiceOperationManager.GetXPathNavigator(m_context.RequestXmlETag, requestUri);
                //if (initialReader == null) {
                //    initialReader = reader;
                //} else {
                //    this.LogDebug("XmlReaders are the same object: {0}", initialReader.Equals(reader));
                //}
                //this.LogDebug("XML Reader Value: {0}", reader.ReadOuterXml());
                //this.LogDebug("XML Reader Hash: {0}", reader.GetHashCode());
                XPathServiceOperationNavigator serviceOperationReader = new XPathServiceOperationNavigator(context, m_context, m_transformContext, navigator, m_request, m_response, m_xslTransformationManager);
                m_response = serviceOperationReader.Process();

            } catch (Exception e) {
                this.LogDebug("Error: {0} in transformation.", e.Message);
                m_exception = e;
                WriteError();
            }

            goto CompleteCall;

        CompleteCall:
            this.LogDebug("CompleteCall reached");
            if (m_lastModifiedDate == String.Empty) {
                m_lastModifiedDate = DateTime.UtcNow.ToString("r");
            }
            context.Response.AppendHeader("Cache-Control", "max-age=86400");
            context.Response.AddHeader("Last-Modified", m_lastModifiedDate);
            context.Response.AddHeader("ETag", String.Format("\"{0}\"", m_requestHashcode));
            m_nuxleusAsyncResult.CompleteCall();
            return m_nuxleusAsyncResult;
        }
 object ICacheProvider.Get(string key)
 {
     return(client.Get(key));
 }
        public ActionResult AddItem(int idProducto, int cantidad)
        {
            if (!ModelState.IsValid)
            {
                return(View("Index"));
            }

            //consulto el usuario logueado
            var currentUser = System.Web.HttpContext.Current.User as CustomPrincipal;

            if (currentUser == null)
            {
                return(RedirectToAction("Index", "Account"));
            }

            var clientConfiguration = new MemcachedClientConfiguration {
                Protocol = MemcachedProtocol.Binary
            };

            clientConfiguration.Servers.Add(new IPEndPoint(IPAddress.Parse("192.168.99.100"), 32768));

            using (var memcachedclient = new MemcachedClient(clientConfiguration))
            {
                //consulto el cache del usuario logueado
                var cart = memcachedclient.Get <Cart>("Cart-" + currentUser.UserName);

                var proxy = new ServiceProxyB2CClient();

                var producto = proxy.ConsultarProducto(TipoConsultaProducto.ID, idProducto.ToString()).First();

                if (null == cart)
                {
                    //si el carrito es vacio cree uno nuevo
                    cart = new Cart
                    {
                        UserId = (int)currentUser.CustId,
                        Items  = new List <Item>()
                    };

                    var item = new Item
                    {
                        Producto = producto,
                        Cantidad = cantidad
                    };
                    cart.Items.Add(item);
                    memcachedclient.Store(StoreMode.Set, "Cart-" + currentUser.UserName, cart);
                }
                else
                {
                    foreach (var i in cart.Items.Where(i => i.Producto.id_producto == idProducto))
                    {
                        //Si existe un carrito busco el item y adiciono la cantidad
                        i.Cantidad = i.Cantidad + cantidad;
                        memcachedclient.Store(StoreMode.Set, "Cart-" + currentUser.UserName, cart);
                        return(View("cart", cart));
                    }

                    //si no existe el item en el carrito lo agrego a la coleccion y guardo el carro
                    var item = new Item
                    {
                        Producto = producto,
                        Cantidad = cantidad
                    };
                    cart.Items.Add(item);
                    memcachedclient.Store(StoreMode.Set, "Cart-" + currentUser.UserName, cart);
                }
                return(View("Cart", cart));
            }
        }
 private string GetJson()
 {
     var internalContainer = new MemcachedClient(SECTION_NAME);
     var text = internalContainer.Get("solrcloud-state");
     if(text==null)
     {
     var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
      text = System.IO.File.ReadAllText(baseDirectory+"\\clusterstate.json");
     }
     return text.ToString();
 }
 /// <summary>
 /// 获取缓存
 /// </summary>
 public static object Get(string key)
 {
     key = key.ToLower();
     return(mclient.Get(key));
 }
Exemple #53
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //DataTable dt1 = (DataTable)DbCache.GetInstance.GetCacheData("aaa");

            //foreach (DataRow drw in dt1.Rows)
            //{
            //    Response.Write(drw["className"].ToString() + "<br />");
            //}
            //dt1.Rows[3]["className"] = "ff";

            //dt1.Clear();
            //DbCache.GetInstance.RemoveCache("aaa");

            //DbCache.GetInstance.RemoveCacheAll();

            Response.Write(DistCache.KeySuffix);
            MemcachedClient mc = new MemcachedClient();

            //MemcachedCacheProvider
            //mc.FlushAll();
            //DistCache.Decrement

            if (true)
            {
                object obj = mc.Get("s1");

                //object obj = DistCache.Get("s1");


                if (obj != null)
                {
                    DataTable dt1 = (DataTable)obj;
                    foreach (DataRow drw in dt1.Rows)
                    {
                        Response.Write(drw["proname"].ToString() + "<br />");
                    }
                }
                else
                {
                    Response.Write("null");
                }
            }
            else
            {
                object obj = DbCache.GetInstance.GetCacheData("s1");
                if (obj != null)
                {
                    DataTable dt1 = (DataTable)obj;
                    foreach (DataRow drw in dt1.Rows)
                    {
                        Response.Write(drw["className"].ToString() + "<br />");
                    }
                }
                else
                {
                    Response.Write("null");
                }
            }

            //mc.Remove("s1");
        }
Exemple #54
0
 /// <summary>
 /// 通过键获取缓存
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public T GetCache <T>(string key)
 {
     return(mc.Get <T>(key));
 }
Exemple #55
0
		public void MultiGetTest()
		{
			// note, this test will fail, if memcached version is < 1.2.4
			MemcachedClient mc = new MemcachedClient();

			List<string> keys = new List<string>();

			for (int i = 0; i < 100; i++)
			{
				string k = "multi_get_test_" + i;
				keys.Add(k);

				mc.Store(StoreMode.Set, k, i);
			}

			IDictionary<string, ulong> cas;
			IDictionary<string, object> retvals = mc.Get(keys, out cas);

			Assert.AreEqual<int>(100, retvals.Count, "MultiGet should have returned 100 items.");

			object value;

			for (int i = 0; i < retvals.Count; i++)
			{
				string key = "multi_get_test_" + i;

				Assert.IsTrue(retvals.TryGetValue(key, out value), "missing key: " + key);
				Assert.AreEqual(value, i, "Invalid value returned: " + value);
			}
		}
Exemple #56
0
 /// <seealso cref="Z.Caching.ICacheManager.Get"/>
 public object Get(string key)
 {
     return(defaultClient.Get(key));
 }
Exemple #57
0
		public void FlushTest()
		{
			MemcachedClient mc = new MemcachedClient();
			mc.Store(StoreMode.Set, "qwer", "1");
			mc.Store(StoreMode.Set, "tyui", "1");
			mc.Store(StoreMode.Set, "polk", "1");
			mc.Store(StoreMode.Set, "mnbv", "1");
			mc.Store(StoreMode.Set, "zxcv", "1");
			mc.Store(StoreMode.Set, "gfsd", "1");

			Assert.AreEqual("1", mc.Get("mnbv"), "Setup for FlushAll() failed");

			mc.FlushAll();

			Assert.IsNull(mc.Get("qwer"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("tyui"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("polk"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("mnbv"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("zxcv"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("gfsd"), "FlushAll() failed.");
		}
 public static object GetMemCache(string key)
 {
     MemClient = getInstance();
     return(MemClient.Get(key));
 }
Exemple #59
0
		public void StoreArrayTest()
		{
			byte[] bigBuffer = new byte[200 * 1024];

			for (int i = 0; i < bigBuffer.Length / 256; i++)
			{
				for (int j = 0; j < 256; j++)
				{
					bigBuffer[i * 256 + j] = (byte)j;
				}
			}

			MemcachedClient mc = new MemcachedClient();

			mc.Store(StoreMode.Set, "BigBuffer", bigBuffer);

			byte[] bigBuffer2 = mc.Get<byte[]>("BigBuffer");

			for (int i = 0; i < bigBuffer.Length / 256; i++)
			{
				for (int j = 0; j < 256; j++)
				{
					if (bigBuffer2[i * 256 + j] != (byte)j)
					{
						Assert.AreEqual(j, bigBuffer[i * 256 + j], "Data should be {0} but its {1}");
						break;
					}
				}
			}
		}
        public static void test1()
        {
            mc.Set("foo", true);
            bool b = (bool)mc.Get("foo");

            Assert.AreEqual(b, true);

            mc.Set("foo", int.MaxValue);
            int i = (int)mc.Get("foo");

            Assert.AreEqual(i, int.MaxValue);

            string input = "test of string encoding";

            mc.Set("foo", input);
            string s = (string)mc.Get("foo");

            Assert.IsTrue(s == input);
            int unique = 2;

            s = mc.Get("foo", unique).ToString();
            Assert.IsTrue(s == input);


            mc.Set("foo", 'z');
            char c = (char)mc.Get("foo");

            Assert.IsTrue(c == 'z');

            mc.Set("foo", (byte)127);
            byte b1 = (byte)mc.Get("foo");

            Assert.IsTrue(b1 == 127);

            mc.Set("foo", new StringBuilder("hello"));
            StringBuilder o = (StringBuilder)mc.Get("foo");

            Assert.IsTrue(o.ToString() == "hello");

            mc.Set("foo", (short)100);
            short o1 = (short)mc.Get("foo");

            Assert.IsTrue(o1 == 100);

            mc.Set("foo", long.MaxValue);
            long o2 = (long)mc.Get("foo");

            Assert.IsTrue(o2 == long.MaxValue);

            mc.Set("foo", 1.1d);
            double o3 = (double)mc.Get("foo");

            Assert.IsTrue(o3 == 1.1d);

            mc.Set("foo", 1.1f);
            float o4 = (float)mc.Get("foo");

            Assert.IsTrue(o4 == 1.1f);

            mc.Delete("foo");
            mc.Set("foo", 100, DateTime.Now);
            System.Threading.Thread.Sleep(1000);
            var o5 = mc.Get("foo");

            Assert.IsTrue(o5 != null);

            long i1 = 0;

            mc.StoreCounter("foo", i1);
            mc.Increment("foo");                   // foo now == 1
            mc.Increment("foo", (long)5);          // foo now == 6
            long j = mc.Decrement("foo", (long)2); // foo now == 4

            Assert.IsTrue(j == 4);
            Assert.IsTrue(j == mc.GetCounter("foo"));

            DateTime d1 = new DateTime();

            mc.Set("foo", d1);
            DateTime d2 = (DateTime)mc.Get("foo");

            Assert.IsTrue(d1 == d2);

            if (mc.KeyExists("foobar123"))
            {
                mc.Delete("foobar123");
            }
            Assert.IsTrue(!mc.KeyExists("foobar123"));
            mc.Set("foobar123", 100000);
            Assert.IsTrue(mc.KeyExists("foobar123"));

            if (mc.KeyExists("counterTest123"))
            {
                mc.Delete("counterTest123");
            }
            Assert.IsTrue(!mc.KeyExists("counterTest123"));
            mc.StoreCounter("counterTest123", 0);
            Assert.IsTrue(mc.KeyExists("counterTest123"));
        }