Exemple #1
0
        public void Set(string key, object data, TimeSpan cacheTime)
        {
            DataCacheLockHandle handle = null;

            handle = RetryHelper.Execute(
                () =>
            {
                DataCacheLockHandle innerHandle = null;
                var output = _cache.GetAndLock(key, TimeSpan.FromSeconds(240), out innerHandle);
                return(innerHandle);
            }, (ex) => true, 50, false, 50);
            DataCacheItemVersion version = null;

            if (handle == null)
            {
                version = _cache.Put(key, data, cacheTime);
            }
            else
            {
                version = _cache.PutAndUnlock(key, data, handle, cacheTime);
            }
            OnObjectPut(new ObjectPutEventArgs()
            {
                Key = key, Version = version
            });
        }
 private void ItemChangedCallbackDelegate(
     string cacheName, 
     string region, 
     string key, 
     DataCacheItemVersion version, 
     DataCacheOperations operation, 
     DataCacheNotificationDescriptor descriptior)
 {
     if(cacheKeys.Contains(key) && region == regionName)
         this.OnChanged(null);
 }
 public void DataCacheItemCallBackHandler(string cacheName, string regionName, string key,
                                          DataCacheItemVersion version, DataCacheOperations cacheOperation, DataCacheNotificationDescriptor nd)
 {
     try
     {
         string result = string.Format("Time: {0} CacheName: {1}  Region {2} Key: {3} DataCacheOperation: {4}", DateTime.Now.ToLongTimeString(),
                                       cacheName, regionName, key, cacheOperation.ToString());
         rtbMontiorCache.Invoke((MethodInvoker) delegate { rtbMontiorCache.AppendText("\r\n" + result); });
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
        public void Add(string key, object value)
        {
            if (null == value)
            {
                return;
            }

            DataCacheItemVersion version = _Cache.Add(key, value, REGION_NAME);

            if (version == null)
            {
                throw new ApplicationException("DataCache.Add failed");
            }
        }
Exemple #5
0
        //method invoked by notification "ndCacheLvlAllOps"
        private static void myCacheLvlDelegate(string myCacheName,
                                               string myRegion,
                                               string myKey,
                                               DataCacheItemVersion itemVersion,
                                               DataCacheOperations OperationId,
                                               DataCacheNotificationDescriptor nd)
        {
            //try
            //{
            // update the key list
            if (keys != null)
            {
                if (OperationId == DataCacheOperations.RemoveItem)
                {
                    keys.Remove(myKey);
                }
                if ((OperationId == DataCacheOperations.AddItem) && (!keys.Contains(myKey)))
                {
                    // This is where we can try to guess the TYPE, based on how our system works
                    Type thisType = null;

                    if (((myKey.IndexOf("ITEM_") == 0) || (myKey.IndexOf("USERITEM") == 0)))
                    {
                        thisType = typeof(SobekCM_Item);
                    }
                    if ((thisType == null) && ((myKey.IndexOf("ITEMSEARCH_") == 0) || (myKey.IndexOf("BROWSEBY_") == 0)))
                    {
                        thisType = typeof(List <string>);
                    }
                    if ((thisType == null) && (myKey.IndexOf("SKIN_") == 0))
                    {
                        thisType = typeof(SobekCM_Skin_Object);
                    }
                    if ((thisType == null) && (myKey.IndexOf("AGGR_") == 0))
                    {
                        thisType = typeof(Item_Aggregation);
                    }


                    keys.Add(myKey, thisType);
                }
            }
            //}
            //catch
            //{

            //}
        }
 /// <summary>
 /// Adds or replaces the value with key. Return false if a version exists but is not the lastversion.
 /// </summary>
 /// <param name="key">The key.</param>
 /// <param name="value">The value.</param>
 /// <param name="expiresAt">The expires at.</param>
 /// <param name="checkLastVersion"> The check last version</param>
 /// <returns>True; if it succeeded</returns>
 private bool CacheSet(string key, object value, DateTime expiresAt, DataCacheItemVersion checkLastVersion = null)
 {
     if (checkLastVersion != null)
     {
         object entry = DataCache.GetIfNewer(key, ref checkLastVersion);
         if (entry != null)
         {
             //update value and version
             DataCache.Put(key, value, checkLastVersion, expiresAt.Subtract(DateTime.Now));
             return(true);
         }
         if (TryGetValue(key, out entry))
         {//version exists but is older.
             return(false);
         }
     }
     //if we don't care about version, then just update
     DataCache.Put(key, value, expiresAt.Subtract(DateTime.Now));
     return(true);
 }
        internal void CacheNotificationCallback(
            string cacheName,
            string regionName,
            string key,
            DataCacheItemVersion version,
            DataCacheOperations cacheOperation,
            DataCacheNotificationDescriptor nd)
        {
            var notification = new ItemNotification
                                   {
                                       CacheName = cacheName,
                                       RegionName = regionName,
                                       Key = key,
                                       Version = version,
                                       CacheOperation = cacheOperation,
                                       NotificationDescriptor = nd
                                   };

            _instance.BeginResumeBookmark(
                new Bookmark(WaitForItemNotification.GetNotificationBookmarkName(nd)),
                notification,
                (asr) => _instance.EndResumeBookmark(asr),
                null);
        }
Exemple #8
0
        private void AddGetAndLock()
        {
            //
            // TESTING SIMPLE Add/GetAndLock
            // without version
            //
            // Try this variation
            // - Put a BreakPoint on the second GetAndLock, and hold the execution for 5 seconds.
            //   It will return the object and lock the object for 10 seconds, since the first lock has expired.

            Console.ForegroundColor = ConsoleColor.Gray;
            string item;

            Console.WriteLine("-----------------------------");
            Console.WriteLine("Testing Simple Add/Get/GetAndLock/GetIfNewer/Put/PutAndUnlock");
            Console.WriteLine("Cache       = default");
            Console.WriteLine("Tags        = Not Supported");
            Console.WriteLine("Version     = <none>");

            DataCacheItemVersion myVersionBeforeChange = null, myVersionAfterChange = null, myVersionChangedOnceMore = null;
            DataCacheLockHandle  lockHandle;
            string myKey = "KeyToMyStringTryingLock";

            try
            {
                //First, clear any old value in cache due to some previous run of the sample
                TryClearOldKey(myDefaultCache, myKey);

                // Initialize the object with a Add
                myDefaultCache.Add(myKey, myObjectForCaching);
                WriteSuccess("Add-Object Added to Cache [key={0}]", myKey);

                // Do a Simple Get, lock the object for 5 seconds
                item = (string)myDefaultCache.GetAndLock(myKey, new TimeSpan(0, 0, 5), out lockHandle);
                if (item != null)
                {
                    WriteSuccess("GetAndLock-Object Get from cache [key={0}]", myKey);
                }
                else
                {
                    WriteFailure("GetAndLock-Object did not Get from cache [key={0}]", myKey);
                }


                // Do a optimistic Get
                if ((item = (string)myDefaultCache.Get(myKey, out myVersionBeforeChange)) != null)
                {
                    WriteSuccess("Get-Object returned. Get will always pass. Will not wait");
                    WriteSuccess("          on a updating object. Current Version will be returned. [key={0}]", myKey);
                }
                else
                {
                    WriteFailure("Get-Object did not return. [key={0}]", myKey);
                }

                try
                {
                    // Do a one more Simple Get, and attempt lock the object for 10 seconds
                    item = (string)myDefaultCache.GetAndLock(myKey, new TimeSpan(0, 0, 10), out lockHandle);
                    WriteFailure("GetAndLock-Object Get from cache [key={0}]", myKey);
                }
                catch (DataCacheException ex)
                {
                    WriteSuccess("GetAndLock hit a exception, because Object is already locked. [key={0}]", myKey);
                    WriteSuccess("Expected GetAndLock-Distributed Cache Generated Exception: {0}", ex.Message);
                }

                // Get the Object only if the version has changed
                if ((item = (string)myDefaultCache.GetIfNewer(myKey, ref myVersionBeforeChange)) != null)
                {
                    WriteFailure("GetIfNewer-Object changed. Should not return as Object has");
                    WriteFailure("            not been changed. [key={0}]", myKey);
                }
                else
                {
                    WriteSuccess("GetIfNewer-Object has not changed. Hence did not return. [key={0}]", myKey);
                }

                // Now update the object with a Put
                myVersionAfterChange = myDefaultCache.Put(myKey, myObjectForCaching + "Put1");

                WriteSuccess("Put1-null-version-Object changed. Put will pass even if Object");
                WriteSuccess("          is locked. Object will also be unlocked. [key={0}]", myKey);
                myObjectForCaching += "Put1";

                // Object with older version changed
                if ((item = (string)myDefaultCache.GetIfNewer(myKey, ref myVersionBeforeChange)) != null)
                {
                    WriteSuccess("GetIfNewer-Object has been changed. [key={0}]", myKey);
                }
                else
                {
                    WriteFailure("GetIfNewer-Object did not return. Put ");
                    WriteFailure("            did modify the Object. Should return. [key={0}]", myKey);
                }

                // Object with newer version after Put
                if ((item = (string)myDefaultCache.GetIfNewer(myKey, ref myVersionAfterChange)) != null)
                {
                    WriteFailure("GetIfNewer-Object with newer version not changed.");
                    WriteFailure("            Should not return. [key={0}]", myKey);
                }
                else
                {
                    WriteSuccess("GetIfNewer-Object with newer version not changed. [key={0}]", myKey);
                }

                // Object with newer version after Put
                myVersionChangedOnceMore = myDefaultCache.Put(myKey, myObjectForCaching + "Put2", myVersionBeforeChange);
                WriteSuccess("Put2-version from Put1-Object changed. [key={0}]", myKey);
                myObjectForCaching += "Put2";

                try
                {
                    // Try the above PutAndUnlock
                    myVersionChangedOnceMore = myDefaultCache.PutAndUnlock(myKey, myObjectForCaching + "Put3", lockHandle);
                    WriteFailure("[This code should not be hit]PutAndUnlock-Object updated and unlocked. [key={0}]", myKey);
                    myObjectForCaching += "Put3";
                }
                catch (DataCacheException ex)
                {
                    WriteSuccess("PutAndUnlock-Expected exception since Object is already unlocked. [key={0}]", myKey);
                    WriteSuccess("PutAndUnlock-Distributed Cache Generated Exception: {0}", ex.Message);
                }

                // Unlock Object
                try
                {
                    myDefaultCache.Unlock(myKey, lockHandle);
                    WriteFailure("[This code should not be hit]Unlock-Object unlocked. [key={0}]", myKey);
                }
                catch (DataCacheException ex)
                {
                    WriteSuccess("Unlock-Expected exception since Object is already unlocked. [key={0}]", myKey);
                    WriteSuccess("Expected Unlock-Distributed Cache Generated Exception: {0}", ex.Message);
                }

                // Finally, Test the state of object should be "This is my Object.Put1Put2"
                if ((item = (string)myDefaultCache.Get(myKey, out myVersionChangedOnceMore)) == myObjectForCaching)
                {
                    WriteSuccess("Get-Object retrived from cache. [key={0}]", myKey);
                }
                else
                {
                    WriteFailure("Get-Object was not retrived from cache. [key={0}]", myKey);
                }
            }
            catch (DataCacheException ex)
            {
                WriteFailure("Add-Get-GetAndLock-GetIfVersionMismatch-Put-PutAndUnlock-Distributed Cache Generated Exception:");
                WriteFailure(ex.ToString());
            }
        }
        /// <summary>
        /// Get the cached version of the feed
        /// If data is cached it is retrieved from the cache
        /// If data is not in the cahce then it is stored in the cache and feed result is fetched
        /// </summary>
        /// <param name="FeedName"></param>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List <FeedData> GetFeedCacheJson(string FeedName, string UserID)
        {
            try
            {
                string _caheName     = string.Empty;
                string _cacheService = string.Empty;
                lock (local_Lock)
                {
                    QueryCacheForFeed(FeedName, out _caheName, out _cacheService);
                }

                if (string.IsNullOrEmpty(_caheName) && string.IsNullOrEmpty(_cacheService))
                {
                    DataCacheFactory cachefactory = new DataCacheFactory(new DataCacheFactoryConfiguration(CACHENAME));
                    DataCache        cache        = cachefactory.GetCache("CS218NonExpiration"); //GetDefaultCache();  // TO.Do GetCache

                    //object result = cache.Get(FeedName);

                    // if (result == null)
                    // {
                    Stopwatch stpwatch = new Stopwatch();
                    stpwatch.Start();
                    string strUrl = getFeedsURL(FeedName);
                    getFeed(strUrl);
                    DataCacheItemVersion ver = cache.Put(FeedName, this.Feeds);  // store result in cache
                    //cache.AddItemLevelCallback(FeedName, DataCacheOperations.RemoveItem, );
                    stpwatch.Stop();
                    Trace.TraceInformation(@"Feed " + FeedName + " called for userID " + UserID +
                                           " ,Total time ellapse for calling API and result stored in cache "
                                           + stpwatch.ElapsedMilliseconds + " milli-sec");
                    StoreCacheDetailInTable(CACHENAME, FeedName, "CS218NonExpiration");

                    return(this.Feeds);
                }
                else
                {
                    List <FeedData> data = null;
                    lock (local_Lock)
                    {
                        DataCacheFactory cachefactory = new DataCacheFactory(new DataCacheFactoryConfiguration(_caheName));
                        DataCache        cache        = cachefactory.GetCache(_cacheService); //GetDefaultCache();  // TO.Do GetCache

                        //Trace.TraceInformation("Service Cache start time" + DateTime.Now.ToLongDateString());
                        Stopwatch stpwatch = new Stopwatch();
                        stpwatch.Start();
                        data = (List <FeedData>)cache.Get(FeedName);

                        stpwatch.Stop();
                        Trace.TraceInformation(@"Feed " + FeedName + " called for userID " + UserID +
                                               " ,Result Called from Cache "
                                               + stpwatch.ElapsedMilliseconds + " milli-sec");

                        UpdateFeedCacheItem(_caheName, FeedName);
                    }
                    return(data);
                }
            }
            catch (Exception exp)
            {
                Trace.TraceError(exp.Message + Environment.NewLine + exp.StackTrace);
                return(null);
            }
        }
Exemple #10
0
 static void CacheEvent(string cacheName, string regionName, string itemName, 
                        DataCacheItemVersion v, DataCacheOperations ops, DataCacheNotificationDescriptor d)
 {
     Console.WriteLine(String.Format("CacheEvent Occurred: {0} {1} {2} {3} {4} {5}",cacheName,regionName,itemName,v,ops,d));
 }
 public object Get(string key, out DataCacheItemVersion version)
 {
     return(DataCache.Get(key, out version));
 }
        //method invoked by notification "ndCacheLvlAllOps"
        private static void myCacheLvlDelegate(string myCacheName,
            string myRegion,
            string myKey,
            DataCacheItemVersion itemVersion,
            DataCacheOperations OperationId,
            DataCacheNotificationDescriptor nd)
        {
            //try
            //{
                // update the key list
                if (keys != null)
                {
                    if (OperationId == DataCacheOperations.RemoveItem)
                        keys.Remove(myKey);
                    if ((OperationId == DataCacheOperations.AddItem) && (!keys.Contains(myKey)))
                    {
                        // This is where we can try to guess the TYPE, based on how our system works
                        Type thisType = null;

                        if (((myKey.IndexOf("ITEM_") == 0) || (myKey.IndexOf("USERITEM") == 0)))
                        {
                            thisType = typeof(SobekCM_Item);
                        }
                        if ((thisType == null) && ((myKey.IndexOf("ITEMSEARCH_") == 0) || ( myKey.IndexOf("BROWSEBY_") == 0 )))
                        {
                            thisType = typeof(List<string>);
                        }
                        if ((thisType == null) && (myKey.IndexOf("SKIN_") == 0))
                        {
                            thisType = typeof(SobekCM_Skin_Object);
                        }
                        if ((thisType == null) && (myKey.IndexOf("AGGR_") == 0))
                        {
                            thisType = typeof(Item_Aggregation);
                        }

                        keys.Add(myKey, thisType);
                    }
                }
            //}
            //catch
            //{

            //}
        }
Exemple #13
0
        public void RunSampleTest()
        {
            DataCacheItemVersion itemVersion;
            string item;

            //
            // CREATING A REGION
            //
            // Point to remember - This region will be re-created everytime this sampletest is run.
            Console.WriteLine();
            Console.WriteLine("Creating Region for general use in default cache");
            string myRegion = "MyRegion";

            if (!CreateRegion(myRegion))
            {
                return;
            }

            Console.WriteLine();
            //
            // CREATING A REGION For the LoadTest Sample
            //
            // Point to remember - This region will be re-created everytime this sampletest is run
            Console.WriteLine("Creating Region for the load test in the default cache");
            string myLoadTestRegion = "LetsLoadTheRegion";

            if (!CreateRegion(myLoadTestRegion))
            {
                return;
            }

            Console.WriteLine();
            //
            // TESTING SIMPLE Add/Get on default cache
            //
            // no regions
            //
            // Need to catch exception here to allow the program to run continuously
            // Try this variation
            // - Comment the try catch on this block of code
            // - Run this program twice within 10 mins (default timeout for data eviction from cache)
            // - Result, Add will throw a exception
            // - Run this program after 10 mins
            // - Result, Program will run ok
            // Try this variation
            // - Put a BreakPoint at the Get("KeyToMyString") call
            // - Run the sample test after 10 mins
            // - Get will fail
            Console.WriteLine("----------------------");
            Console.WriteLine("Testing Simple Add/Get");
            Console.WriteLine("Cache       = default");
            Console.WriteLine("Region      = <none>");
            Console.WriteLine("Tags        = <none>");
            Console.WriteLine("Version     = <none>");

            try
            {
                // Store the object in the default Cache with a Add
                if ((itemVersion = myDefaultCache.Add("KeyToMyString", myObjectForCaching)) != null)
                {
                    Console.WriteLine("PASS--->Add-Object Added to Cache [key=KeyToMyString]");
                }
                else
                {
                    Console.WriteLine("**FAIL--->Add-Object did not add to cache - FAIL");
                }

                // Do a Simple Get using valid Key from the default Cache
                if ((item = (string)myDefaultCache.Get("KeyToMyString")) != null)
                {
                    Console.WriteLine("PASS--->Get-Object Get from cache [key=KeyToMyString]");
                }
                else
                {
                    Console.WriteLine("**FAIL--->Get-Object did not Get from cache [key=KeyToMyString]");
                }

                // Do a Simple Get using an invalid Key from the default Cache
                if ((item = (string)myDefaultCache.Get("InCorrectKeySpecified")) == null)
                {
                    Console.WriteLine("PASS--->Get-Object did not Get, since invalid key specified [key=InCorrectKeySpecified]");
                }
                else
                {
                    Console.WriteLine("**FAIL--->Get-Object Get from cache, unexpected result");
                }
            }
            catch (DataCacheException ex)
            {
                Console.WriteLine("**FAIL--->Add-Get-This is failing probably because you are running this");
                Console.WriteLine("          sample test within 10mins (default TTL for the named cache) in clusterconfig.xml");
                Console.WriteLine("          To get this working, in the admin tool");
                Console.WriteLine("          - restart-cachecluster");
                Console.Write("**FAIL--->Distributed Cache Generated Exception:");
                Console.WriteLine(ex.ToString());
            }

            //
            // TESTING SIMPLE Add/Get on default cache USING Region
            //
            // without Tags
            // without version
            //
            Console.WriteLine("----------------------");
            Console.WriteLine("Testing Simple Add/Get");
            Console.WriteLine("Cache       = default");
            Console.WriteLine("Region      = " + myRegion);
            Console.WriteLine("Tags        = <none>");
            Console.WriteLine("Version     = <none>");

            try
            {
                // Store the object in a region with a Add
                if ((itemVersion = myDefaultCache.Add("KeyToMyString", myObjectForCaching, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Add-Object Added to Cache [key=KeyToMyString]");
                }
                else
                {
                    Console.WriteLine("**FAIL----->Add-Object did not add to cache");
                }

                // Do a Simple Get using valid Key from a named region
                if ((item = (string)myDefaultCache.Get("KeyToMyString", myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Get-Object Get from cache [key=KeyToMyString]");
                }
                else
                {
                    Console.WriteLine("**FAIL----->Get-Object did not Get from cache [key=KeyToMyString]");
                }

                // Do a Simple Get with invalid key
                if ((item = (string)myDefaultCache.Get("InvalidKey", myRegion)) != null)
                {
                    Console.WriteLine("**FAIL----->Get-Object returned from Cache, should not since key is invalid [key=InvalidKey]");
                }
                else
                {
                    Console.WriteLine("PASS----->Get-Object did not Get from cache. Expected since key is invalid [key=InvalidKey]");
                }
            }
            catch (DataCacheException ex)
            {
                Console.Write("**FAIL----->Add-Get-Distributed Cache Generated Exception:");
                Console.WriteLine(ex.ToString());
                // Will never get this error since we are Removing existing regions and creating new ones
            }

            //
            // TESTING SIMPLE Add/GetAndLock using Region
            //
            // without Tags
            // without version
            //
            // Try this variation
            // - Put a BreakPoint on the second GetAndLock, and hold the execution for 5 seconds.
            //   It will return the object and lock the object for 10 seconds. Since the first lock has expired.
            //   Additionally : Study behaviour of Put and PutAndUnlock
            Console.WriteLine("-----------------------------");
            Console.WriteLine("Testing Simple Add/Get/GetAndLock/GetIfNewer/Put/PutAndUnlock");
            Console.WriteLine("Cache       = default");
            Console.WriteLine("Region      = " + myRegion);
            Console.WriteLine("Tags        = <none>");
            Console.WriteLine("Version     = <none>");

            DataCacheItemVersion myVersionBeforeChange = null, myVersionAfterChange = null, myVersionChangedOnceMore = null;
            DataCacheLockHandle  lockHandle;
            string myKey = "KeyToMyStringTryingLock";

            try
            {
                // Initialize the object with a Add
                if ((itemVersion = myDefaultCache.Add(myKey, myObjectForCaching, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Add-Object Added to Cache [key={0}]", myKey);
                }
                else
                {
                    Console.WriteLine("**FAIL----->Add-Object did not add to cache [key={0}]", myKey);
                }

                // Do a Simple Get, lock the object for 5 seconds
                if ((item = (string)myDefaultCache.GetAndLock(myKey,
                                                              new TimeSpan(0, 0, 5), out lockHandle, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->GetAndLock-Object Get from cache [key={0}]", myKey);
                }
                else
                {
                    Console.WriteLine("**FAIL----->GetAndLock-Object did not Get from cache [key={0}]", myKey);
                }

                // Do a optimistic Get
                if ((item = (string)myDefaultCache.Get(myKey, out myVersionBeforeChange, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Get-Object returned. Get will always pass. Will not wait");
                    Console.WriteLine("          on a updating object. Current Version will be returned. [key={0}]", myKey);
                }
                else
                {
                    Console.WriteLine("**FAIL----->Get-Object did not return. [key={0}]", myKey);
                }

                try
                {
                    // Do a one more Simple Get, and attempt lock the object for 10 seconds
                    if ((item = (string)myDefaultCache.GetAndLock(myKey,
                                                                  new TimeSpan(0, 0, 10), out lockHandle, myRegion)) != null)
                    {
                        Console.WriteLine("**FAIL----->GetAndLock-Object Get from cache [key={0}]", myKey);
                    }
                    else
                    {
                        // Since a exception will catch it, this will never return null
                        Console.WriteLine("PASS----->GetAndLock-Object did not Get from cache [key={0}]", myKey);
                    }
                }
                catch (DataCacheException ex)
                {
                    Console.WriteLine("PASS----->GetAndLock hit a exception, because Object is already locked. [key={0}]", myKey);
                    Console.Write("PASS----->GetAndLock-Distributed Cache Generated Exception:");
                    Console.WriteLine(ex.ToString());
                }

                // Get the Object only if the version has changed
                if ((item = (string)myDefaultCache.GetIfNewer(myKey, ref myVersionBeforeChange, myRegion)) != null)
                {
                    Console.WriteLine("**FAIL----->GetIfNewer-Object changed. Should not return as Object has");
                    Console.WriteLine("            not been changed. [key={0}]", myKey);
                }
                else
                {
                    Console.WriteLine("PASS----->GetIfNewer-Object has not changed. Hence did not return. [key={0}]", myKey);
                }

                // Now update the object with a Put
                if ((myVersionAfterChange = (DataCacheItemVersion)myDefaultCache.Put(myKey,
                                                                                     myObjectForCaching + "Put1", myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Put1-null-version-Object changed. Put will pass even if Object");
                    Console.WriteLine("          is locked. Object will also be unlocked. [key={0}]", myKey);
                    myObjectForCaching += "Put1";
                }
                else
                {
                    Console.WriteLine("PASS----->Put1-null-version-Object did not change. [key={0}]", myKey);
                }

                // Object with older version changed
                if ((item = (string)myDefaultCache.GetIfNewer(myKey, ref myVersionBeforeChange, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->GetIfNewer-Object has been changed. [key={0}]", myKey);
                }
                else
                {
                    Console.WriteLine("**FAIL----->GetIfNewer-Object did not return. Put ");
                    Console.WriteLine("            did modify the Object. Should return. [key={0}]", myKey);
                }

                // Object with newer version after Put
                if ((item = (string)myDefaultCache.GetIfNewer(myKey, ref myVersionAfterChange, myRegion)) != null)
                {
                    Console.WriteLine("**FAIL----->GetIfNewer-Object with newer version not changed.");
                    Console.WriteLine("            Should not return. [key={0}]", myKey);
                }
                else
                {
                    Console.WriteLine("PASS----->GetIfNewer-Object with newer version not changed. [key={0}]", myKey);
                }

                // Object with newer version after Put
                if ((myVersionChangedOnceMore = (DataCacheItemVersion)myDefaultCache.Put(myKey,
                                                                                         myObjectForCaching + "Put2", myVersionBeforeChange, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Put2-version from Put1-Object changed. [key={0}]", myKey);
                    myObjectForCaching += "Put2";
                }
                else
                {
                    Console.WriteLine("**FAIL----->Put2-version from Put1-Object did not change. [key={0}]", myKey);
                }

                try
                {
                    // Try the above PutAndUnlock
                    if ((myVersionChangedOnceMore = (DataCacheItemVersion)myDefaultCache.PutAndUnlock(myKey,
                                                                                                      myObjectForCaching + "Put3", lockHandle, myRegion)) != null)
                    {
                        Console.WriteLine("PASS----->PutAndUnlock-Object updated and unlocked. [key={0}]", myKey);
                        myObjectForCaching += "Put3";
                    }
                    else
                    {
                        Console.WriteLine("**FAIL----->PutAndUnlock-Object should have updated and unlocked. [key={0}]", myKey);
                    }
                }
                catch (DataCacheException ex)
                {
                    Console.WriteLine("PASS----->PutAndUnlock-Expected exception since Object is already unlocked. [key={0}]", myKey);
                    Console.Write("PASS---->PutAndUnlock-Distributed Cache Generated Exception:");
                    Console.WriteLine(ex.ToString());
                }

                // Unlock Object
                try
                {
                    myDefaultCache.Unlock(myKey, lockHandle, myRegion);
                    Console.WriteLine("PASS----->Unlock-Object unlocked. [key={0}]", myKey);
                }
                catch (DataCacheException ex)
                {
                    Console.WriteLine("PASS----->Unlock-Expected exception since Object is already unlocked. [key={0}]", myKey);
                    Console.Write("PASS----->Unlock-Distributed Cache Generated Exception:");
                    Console.WriteLine(ex.Message);
                }

                // Finally, Test the state of object should be "This is my Object.Put1Put2"
                if ((item = (string)myDefaultCache.Get(myKey, out myVersionChangedOnceMore, myRegion)) ==
                    myObjectForCaching)
                {
                    Console.WriteLine("PASS----->Get-Object retrived from cache. [key={0}]", myKey);
                }
                else
                {
                    Console.WriteLine("**FAIL----->Get-Object was not retrived from cache. [key={0}]", myKey);
                }
            }
            catch (DataCacheException ex)
            {
                Console.Write("**FAIL---->Add-Get-GetAndLock-GetIfVersionMismatch-Put-PutAndUnlock-Distributed Cache Generated Exception:");
                Console.WriteLine(ex.ToString());
            }

            //
            // TESTING SIMPLE Add/Get ON REGION with Version
            //
            // without Tags
            // Try this
            // - Put a BreakPoint on the second Put and wait for 5 seconds before releaseing.
            DataCacheItem        cacheItem1, cacheItem2;
            DataCacheItemVersion cacheItemVersion;

            Console.WriteLine("-----------------------------------");
            Console.WriteLine("Testing Simple Add/GetCacheItem/Put");
            Console.WriteLine("Cache       = default");
            Console.WriteLine("Region      = " + myRegion);
            Console.WriteLine("Tags        = <none>");
            Console.WriteLine("Version     = yes");

            string KeyToMyStringWithVersion = "KeyToMyStringWithVersion";

            try
            {
                // Add an object to a region
                if ((itemVersion = myDefaultCache.Add(KeyToMyStringWithVersion, myObjectForCaching, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Add-Object Added to Cache. [key={0}]", KeyToMyStringWithVersion);
                }
                else
                {
                    Console.WriteLine("**FAIL----->Add-Object did not add to cache [key={0}]", KeyToMyStringWithVersion);
                }

                // Get the object added to the Cache
                if ((cacheItem1 = myDefaultCache.GetCacheItem(KeyToMyStringWithVersion, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->GetCacheItem-Object Get from cache [key={0}]", KeyToMyStringWithVersion);
                }
                else
                {
                    Console.WriteLine("**FAIL----->GetCacheItem-Object did not Get from cache [key={0}]", KeyToMyStringWithVersion);
                }

                // Get another copy of the same object (used to remember the version)
                if ((cacheItem2 = myDefaultCache.GetCacheItem(KeyToMyStringWithVersion, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->GetCacheItem-Object Get from cache [key={0}]", KeyToMyStringWithVersion);
                }
                else
                {
                    Console.WriteLine("**FAIL----->GetCacheItem-Object did not Get from cache [key={0}]", KeyToMyStringWithVersion);
                }

                // Add a newer version of the object to the cache, supply the version as well to ensure that we are updating
                // the cache only if we have the latest version
                if ((cacheItemVersion = myDefaultCache.Put(KeyToMyStringWithVersion,
                                                           (object)cacheItem1.Value, cacheItem1.Version, myRegion)) != null)
                {
                    Console.WriteLine("PASS----->Put-Object updated successfully [key={0}]", KeyToMyStringWithVersion);
                    Console.WriteLine("          New version {0} Old version", cacheItemVersion > cacheItem2.Version ? ">" : "<=");
                }
                else
                {
                    Console.WriteLine("**FAIL----->Put-Object did not update successfully [key={0}]", KeyToMyStringWithVersion);
                }

                // Try to add an object when the version of the object in the Cache is newer, it will fail
                if ((cacheItemVersion = myDefaultCache.Put(KeyToMyStringWithVersion,
                                                           (object)cacheItem2.Value, cacheItem2.Version, myRegion)) != null)
                {
                    Console.WriteLine("**FAIL----->Put-Object update. Update to new version work.  [key={0}]", KeyToMyStringWithVersion);
                }
                else // this will throw a exception, so the else will not run if the object is locked.
                {
                    Console.WriteLine("PASS----->Put-Object did not update. Update to new version worked.  [key={0}]", KeyToMyStringWithVersion);
                }
            }
            catch (DataCacheException ex)
            {
                Console.WriteLine("PASS----->Put-Object-Expected behaviour since Object is newer");
                Console.Write("PASS----->Distributed Cache Generated Exception:");
                Console.WriteLine(ex.InnerException.Message);
            }

            // Testing simple Add/Get on a Region with Tags
            // without Version
            // Each object will have a unique key
            // Each object can have multiple tags, hence the tag[]
            // Multiple Objects can have the same tag
            Console.WriteLine("----------------------");
            Console.WriteLine("Testing Simple Add/GetByTag");
            Console.WriteLine("Cache       = default");
            Console.WriteLine("Region      = " + myRegion);
            Console.WriteLine("Tags        = yes");
            Console.WriteLine("Version     = <none>");

            const int totalTags = 5;

            DataCacheTag[] someTags = new DataCacheTag[totalTags] {
                new DataCacheTag("Tag1"), new DataCacheTag("Tag2"),
                new DataCacheTag("Tag3"), new DataCacheTag("Tag4"),
                new DataCacheTag("Tag5")
            };
            List <DataCacheTag> allMyTags = someTags.ToList();
            IEnumerable <KeyValuePair <string, object> > getByTagReturnKeyValuePair;
            int totalObjects = 10;

            try
            {
                for (int objectid = 0; objectid < totalObjects; objectid++)
                {
                    // Add an object to the Cache with tags
                    if ((itemVersion = myDefaultCache.Add("MyKey" + objectid.ToString(),
                                                          (object)myObjectForCaching, allMyTags, myRegion)) != null)
                    {
                        Console.WriteLine("PASS----->Add-Object " +
                                          "MyKey" + objectid.ToString() +
                                          " added to Cache, with all tags");
                    }
                    else
                    {
                        Console.WriteLine("**FAIL----->Add-Object did not add to cache");
                    }
                }

                for (int objectid = 0; objectid < totalObjects; objectid++)
                {
                    for (int tagid = 0; tagid < totalTags; tagid++)
                    {
                        // Get the object from Cache using Tag
                        if ((getByTagReturnKeyValuePair = myDefaultCache.GetObjectsByTag(allMyTags[tagid], myRegion)) != null)
                        {
                            Console.WriteLine("PASS----->GetByTag-Object " +
                                              getByTagReturnKeyValuePair.ElementAt(tagid).Key +
                                              " get from cache. Using Tag " + tagid.ToString());
                        }
                        else
                        {
                            Console.WriteLine("**FAIL----->GetByTag-Object did not Get from cache");
                        }
                    }
                }
            }
            catch (DataCacheException ex)
            {
                Console.WriteLine("**FAIL----->Add-GetByTag-This is failing probably because you are running this sample test");
                Console.WriteLine("          within 10mins (default timeout)");
                Console.Write("**FAIL----->Distributed Cache Generated Exception:");
                Console.WriteLine(ex.ToString());
            }


            // Simple Load testing
            // Object size every line starts with 100 bytes and grows "exponentially".

            int    iterateMax = 10;
            string lotOfData  = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";

            Console.WriteLine("----------------------");
            Console.WriteLine("Testing Simple Add/Get");
            Console.WriteLine("Cache       = default");
            Console.WriteLine("Region      = " + myLoadTestRegion);
            Console.WriteLine("Tags        = <none>");
            Console.WriteLine("Version     = <none>");
            long totalSizeAdded = 0;
            long iterate;

            for (iterate = 0; iterate < iterateMax; iterate++)
            {
                try
                {
                    // Lets know how much we want to add to cache before the add
                    Console.Write(lotOfData.Length);
                    if ((itemVersion = myDefaultCache.Add(iterate.ToString(), (object)lotOfData, myLoadTestRegion)) != null)
                    {
                        Console.Write(" PASS----->Add" + iterate + " ");
                    }
                    else
                    {
                        Console.WriteLine("**FAIL----->Add-Object did not add to cache - FAIL");
                    }

                    if ((item = (string)myDefaultCache.Get(iterate.ToString(), myLoadTestRegion)) != null)
                    {
                        Console.WriteLine(item.Length + " PASS-->Get" + iterate + " ");
                    }
                    else
                    {
                        Console.WriteLine("**FAIL----->Get-Object did not Get from cache");
                        totalSizeAdded += lotOfData.Length;
                        lotOfData      += lotOfData;
                    }
                }
                catch (DataCacheException ex)
                {
                    Console.WriteLine("**FAIL----->Add-Get-This is failing probably because you are running this sample test");
                    Console.WriteLine("         within 10mins (default timeout)");
                    Console.Write("**FAIL----->Distributed Cache Generated Exception:");
                    Console.WriteLine(ex.ToString());
                }
            }

            Console.WriteLine("Total Size added " + totalSizeAdded);
            Console.ReadKey();
        }