public void InstantiateTheStorageMirrorTest()
        {
            #region ASSEMBLE


            TheStorageMirror <TheStorageEngineTSM> mirror;

            #endregion

            #region ACT

            mirror = new TheStorageMirror <TheStorageEngineTSM>(TheCDEngines.MyIStorageService)
            {
                IsRAMStore               = true,
                CacheStoreInterval       = 1,
                IsStoreIntervalInSeconds = true,
                IsCachePersistent        = true,
                UseSafeSave              = true,
                AllowFireUpdates         = true,
            };

            #endregion

            #region ASSERT

            Assert.IsTrue(mirror != null);
            mirror?.Dispose();
            mirror = null;

            #endregion
        }
        public void ApplyLoadToTheStorageMirrorTest()
        {
            #region ARRANGE

            PerformanceCounter         counterCPU;
            PerformanceCounter         counterRAM;
            BlockingCollection <float> metricsCPU;
            BlockingCollection <float> metricsRAM;

            counterCPU = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            counterRAM = new PerformanceCounter("Memory", "Available MBytes");
            metricsCPU = new BlockingCollection <float>(100000);
            metricsRAM = new BlockingCollection <float>(100000);

            Timer timerCPU;
            timerCPU = new Timer((state) =>
            {
                if (metricsCPU.IsAddingCompleted)
                {
                    float oldest = metricsCPU.FirstOrDefault();
                    metricsCPU.TryTake(out oldest);
                }
                metricsCPU.TryAdd(counterCPU.NextValue());
            }, null, 1000, 10);

            Timer timerRAM;
            timerRAM = new Timer((state) =>
            {
                if (metricsRAM.IsAddingCompleted)
                {
                    float oldest = metricsRAM.FirstOrDefault();
                    metricsRAM.TryTake(out oldest);
                }
                metricsRAM.TryAdd(counterRAM.NextValue());
            }, null, 1000, 10);

            counterCPU.NextValue();
            var memoryBefore = counterRAM.NextValue();
            Thread.Sleep(1000); // Per MSDN suggestion when using PerformanceCounter mechanism...

            int            totalCandidates = 1000000;
            int            countCallbacks  = 0;
            var            random          = new Random();
            var            data            = Enumerable.Range(1, totalCandidates).OrderBy(i => random.Next(1, totalCandidates));
            CountdownEvent countdown       = new CountdownEvent(totalCandidates);
            TheStorageMirror <TheStorageEngineTSM> mirror;
            mirror = new TheStorageMirror <TheStorageEngineTSM>(TheCDEngines.MyIStorageService)
            {
                IsRAMStore               = true,
                CacheStoreInterval       = 1,
                IsStoreIntervalInSeconds = true,
                IsCachePersistent        = true,
                UseSafeSave              = true,
                AllowFireUpdates         = true,
            };



            #endregion

            #region ACT

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            try
            {
                Parallel.ForEach(data, currentNumber =>
                {
                    mirror.AddAnItem(
                        new TheStorageEngineTSM()
                    {
                        TXTPattern = currentNumber.ToString()
                    },
                        state =>
                    {
                        Interlocked.Increment(ref countCallbacks);
                        countdown.Signal();
                    });
                });
            }
            catch (Exception ex)
            {
                Assert.IsTrue(true, ex.Message);
            }

            countdown.Wait();

            stopwatch.Stop();
            timerCPU.Change(Timeout.Infinite, Timeout.Infinite);
            timerCPU.Dispose();
            timerRAM.Change(Timeout.Infinite, Timeout.Infinite);
            timerRAM.Dispose();
            counterCPU?.Dispose();
            counterRAM?.Dispose();
            countdown?.Dispose();
            mirror?.Dispose();

            #endregion

            #region ASSERT

            float avgCPU = metricsCPU.Average();
            float maxCPU = 99f;

            float avgRAM = metricsRAM.Average();
            float maxRAM = memoryBefore + 1000f;

            Assert.IsTrue(
                (avgCPU <= maxCPU && avgRAM <= maxRAM && totalCandidates == countCallbacks),
                buildSummary(totalCandidates,
                             stopwatch.ElapsedMilliseconds,
                             avgCPU,
                             maxCPU,
                             avgRAM,
                             maxRAM));

            #endregion
        }
        public void GetRecordsFromTheStorageMirrorTest(
            [Values(0, 500, 5000)] int maxCount,
            [Values(50, 5000)] int totalCandidates
            )
        {
            #region ASSEMBLE

            TheStorageMirror <TheStorageEngineTSM> .StoreResponse response = null;
            var random = new Random();
            var data   = Enumerable.Range(1, totalCandidates).OrderBy(i => random.Next(1, totalCandidates));
            ManualResetEventSlim gate = new ManualResetEventSlim();
            TheStorageMirror <TheStorageEngineTSM> mirror;
            List <TheStorageEngineTSM>             TSMs = new List <TheStorageEngineTSM>();

            // Build the collection of TSMs
            foreach (var payload in data)
            {
                TSMs.Add(new TheStorageEngineTSM()
                {
                    cdeMID     = Guid.NewGuid(),
                    TXTPattern = payload.ToString()
                });
            }

            // Spin up your mirror
            mirror = new TheStorageMirror <TheStorageEngineTSM>(TheCDEngines.MyIStorageService)
            {
                IsRAMStore               = true,
                CacheStoreInterval       = 1,
                IsStoreIntervalInSeconds = true,
                IsCachePersistent        = true,
                UseSafeSave              = true,
                AllowFireUpdates         = true,
            };
            if (maxCount > 0)
            {
                mirror.SetMaxStoreSize(maxCount);
            }
            mirror.RegisterEvent(eStoreEvents.StoreReady, e => { gate.Set(); });
            mirror.InitializeStore(true);

            // Wait for mirror to initialize...
            gate.Wait(30000);

            // Add your items
            Task.Factory.StartNew(() =>
            {
                mirror.AddItems(TSMs, payload =>
                {
                    response = payload;
                    gate.Set();
                });
            });

            //Wait for response
            gate.Reset();
            gate.Wait(30000);
            if ((response != null) && response.HasErrors)
            {
                Assert.Fail("Unable to add test collection items! Reason: {0}", response.ErrorMsg);
            }

            #endregion

            #region ACT

            // Attempt to retrieve your items
            Task.Factory.StartNew(() =>
            {
                mirror.GetRecords(payload =>
                {
                    response = payload;
                    gate.Set();
                },
                                  true);
            });

            // Wait for response
            gate.Reset();
            gate.Wait(30000);
            if ((response != null) && response.HasErrors)
            {
                Assert.Fail("Unable to retrieve items! Reason: {0}", response.ErrorMsg);
            }

            mirror?.Dispose();

            #endregion

            #region ASSERT

            var expectedCount = maxCount == 0 ? totalCandidates : Math.Min(maxCount, totalCandidates);

            Assert.AreEqual(expectedCount, response.MyRecords.Count, "Not all test records were not added successfully.");

            #endregion
        }
        public void RemoveAnItemByIDFromTheStorageMirrorTest()
        {
            #region ASSEMBLE

            TheStorageMirror <TheStorageEngineTSM> .StoreResponse response = null;
            int totalCandidates       = 5000;
            int indexMiddle           = totalCandidates / 2;
            int indexCurrent          = 0;
            var random                = new Random();
            var data                  = Enumerable.Range(1, totalCandidates).OrderBy(i => random.Next(1, totalCandidates));
            ManualResetEventSlim gate = new ManualResetEventSlim();
            TheStorageMirror <TheStorageEngineTSM> mirror;
            TheStorageEngineTSM        tsmCurrent = null;
            TheStorageEngineTSM        tsmMiddle  = null;
            TheStorageEngineTSM        tsmMatch   = null;
            List <TheStorageEngineTSM> TSMs       = new List <TheStorageEngineTSM>();
            List <TheStorageEngineTSM> myRecords  = new List <TheStorageEngineTSM>();

            // Build the collection of TSMs and cache the middle one
            foreach (var payload in data)
            {
                tsmCurrent = new TheStorageEngineTSM()
                {
                    cdeMID     = Guid.NewGuid(),
                    TXTPattern = payload.ToString()
                };
                TSMs.Add(tsmCurrent);
                if ((indexCurrent++ >= indexMiddle) && (tsmMiddle == null))
                {
                    tsmMiddle = tsmCurrent;
                }
            }
            if (tsmMiddle == null)
            {
                Assert.Fail("Unable to cache the middle TSM!");
            }

            // Spin up your mirror
            mirror = new TheStorageMirror <TheStorageEngineTSM>(TheCDEngines.MyIStorageService)
            {
                IsRAMStore               = true,
                CacheStoreInterval       = 1,
                IsStoreIntervalInSeconds = true,
                IsCachePersistent        = true,
                UseSafeSave              = true,
                AllowFireUpdates         = true,
            };
            mirror.RegisterEvent(eStoreEvents.StoreReady, e => { gate.Set(); });
            mirror.InitializeStore(true);

            // Wait for mirror to initialize...
            gate.Wait(30000);

            // Add your items
            Task.Factory.StartNew(() =>
            {
                mirror.AddItems(TSMs, payload =>
                {
                    response = payload;
                    gate.Set();
                });
            });

            //Wait for response
            gate.Reset();
            gate.Wait(30000);
            if ((response != null) && response.HasErrors)
            {
                Assert.Fail("Unable to add test collection items! Reason: {0}", response.ErrorMsg);
            }

            #endregion

            #region ACT

            // Attempt to remove your middle item
            Task.Factory.StartNew(() =>
            {
                mirror.RemoveAnItemByID(tsmMiddle.cdeMID, payload =>
                {
                    response = payload;
                    gate.Set();
                });
            });

            // Wait for response
            gate.Reset();
            gate.Wait(30000);
            if ((response != null) && response.HasErrors)
            {
                Assert.Fail("Unable to remove item by ID! Reason: {0}", response.ErrorMsg);
            }

            // Attempt to retrieve your middle item
            tsmMatch = mirror.GetEntryByID(tsmMiddle.cdeMID);

            mirror?.Dispose();

            #endregion

            #region ASSERT

            Assert.IsTrue(tsmMatch == null);

            #endregion
        }
        public void AddItemsToTheStorageMirrorTest()
        {
            #region ASSEMBLE

            TheStorageMirror <TheStorageEngineTSM> .StoreResponse response = null;
            int totalCandidates       = 5000;
            var random                = new Random();
            var data                  = Enumerable.Range(1, totalCandidates).OrderBy(i => random.Next(1, totalCandidates));
            ManualResetEventSlim gate = new ManualResetEventSlim();
            TheStorageMirror <TheStorageEngineTSM> mirror;
            List <TheStorageEngineTSM>             TSMs = new List <TheStorageEngineTSM>();


            // Build the collection of TSMs
            foreach (var payload in data)
            {
                TSMs.Add(new TheStorageEngineTSM()
                {
                    TXTPattern = payload.ToString()
                });
            }

            // Spin up your mirror
            mirror = new TheStorageMirror <TheStorageEngineTSM>(TheCDEngines.MyIStorageService)
            {
                IsRAMStore               = true,
                CacheStoreInterval       = 1,
                IsStoreIntervalInSeconds = true,
                IsCachePersistent        = true,
                UseSafeSave              = true,
                AllowFireUpdates         = true,
            };
            mirror.RegisterEvent(eStoreEvents.StoreReady, e => { gate.Set(); });
            mirror.InitializeStore(true);

            // Wait for mirror to initialize...
            gate.Wait(30000);

            #endregion

            #region ACT

            // Add your items
            Task.Factory.StartNew(() =>
            {
                mirror.AddItems(TSMs, payload =>
                {
                    response = payload;
                    gate.Set();
                });
            });

            //Wait for response
            gate.Reset();
            gate.Wait(30000);

            mirror?.Dispose();

            #endregion

            #region ASSERT

            Assert.IsFalse(response.HasErrors);

            #endregion
        }