Exemple #1
0
 private void OnStorageReady(ICDEThing pThing, object para)
 {
     MyLogFiles = new TheStorageMirror <TheBackupDefinition>(TheCDEngines.MyIStorageService)
     {
         CacheTableName     = MyLogFilesTableName,
         IsRAMStore         = true,
         IsCachePersistent  = false,
         CacheStoreInterval = 0
     };
     MyLogFiles.RegisterEvent(eStoreEvents.StoreReady, sinkStorageReady);
     MyLogFiles.RegisterEvent(eStoreEvents.DeleteRequested, sinkDeleteLog);
     MyLogFiles.RegisterEvent(eStoreEvents.ReloadRequested, sinkStorageReady);
     MyLogFiles.InitializeStore(false, false);
 }
Exemple #2
0
 //Helper Function
 private void SetupStorageMirror()
 {
     MyScriptTableStorage = new TheStorageMirror <ScriptSnapshot>(TheCDEngines.MyIStorageService)
     {
         IsRAMStore               = true,
         IsCachePersistent        = true,
         IsStoreIntervalInSeconds = true,
         CacheTableName           = $"ScriptTableFields{MyBaseThing.ID}"
     };
     MyScriptTableStorage.RegisterEvent(eStoreEvents.StoreReady, SinkStoreReady);
     MyScriptTableStorage.InitializeStore(new TheStorageMirrorParameters {
         TrackInsertionOrder = true,
         CanBeFlushed        = true,
         ResetContent        = false
     });
 }
Exemple #3
0
 private void StorageHasStarted(ICDEThing sender, object pReady)
 {
     if (pReady != null)
     {
         if (MyVisitorLogStore == null)
         {
             MyVisitorLogStore = new TheStorageMirror <TheVisitorLogData>(TheCDEngines.MyIStorageService);
             MyVisitorLogStore.RegisterEvent(eStoreEvents.StoreReady, StoreIsUp);
         }
         MyVisitorLogStore.IsRAMStore = TheCDEngines.MyIStorageService == null || TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsSimulated;
         if (MyVisitorLogStore.IsRAMStore)
         {
             MyVisitorLogStore.IsCachePersistent = true;
             MyVisitorLogStore.CacheTableName    = "VisitorLog";
             MyVisitorLogStore.SetRecordExpiration(1000000, null);
         }
         MyVisitorLogStore.CreateStore(TheBaseAssets.MyServiceHostInfo.ApplicationName + ": The Visitor Log", "Logs all visitors to the Site " + TheBaseAssets.MyServiceHostInfo.ApplicationName, null, true, false);
     }
 }
        public override bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            MyBaseThing.LastMessage = "Device Ready";
            MyBaseThing.StatusLevel = 0;
            IsConnected             = false;

            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(MyBaseThing.Address), cdeT = ePropertyTypes.TString, Required = true, Description = "", Generalize = true
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(MyBaseThing.FriendlyName), cdeT = ePropertyTypes.TString, Description = ""
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(Interval), cdeT = ePropertyTypes.TNumber, DefaultValue = 1000, RangeMin = 100, Description = "Time interval at which to poll the sensor for values"
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(CustomPort), cdeT = ePropertyTypes.TNumber, DefaultValue = 502, Description = ""
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(SlaveAddress), cdeT = ePropertyTypes.TNumber, DefaultValue = 1, Description = ""
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(AutoConnect), cdeT = ePropertyTypes.TBoolean, DefaultValue = false, Description = ""
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(KeepOpen), cdeT = ePropertyTypes.TBoolean, DefaultValue = true, Description = ""
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(Offset), cdeT = ePropertyTypes.TNumber, Description = ""
            });
            MyBaseThing.DeclareConfigProperty(new TheThing.TheConfigurationProperty {
                Name = nameof(ConnectionType), cdeT = ePropertyTypes.TNumber, DefaultValue = 3, Description = "Read Coils:1, Read Input:2, Holding Registers:3, Input Register:4, Read Multiple Register:23"
            });

            MyModFieldStore                          = new TheStorageMirror <FieldMapping>(TheCDEngines.MyIStorageService);
            MyModFieldStore.IsRAMStore               = true;
            MyModFieldStore.IsCachePersistent        = true;
            MyModFieldStore.IsStoreIntervalInSeconds = true;
            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
                if (MyDevice != null && !string.IsNullOrEmpty(MyDevice.Id))
                {
                    MyBaseThing.ID = MyDevice.Id;
                }
                if (GetProperty("CustomPort", false) == null)
                {
                    TheThing.SetSafePropertyNumber(MyBaseThing, "CustomPort", 502);
                }
                if (GetProperty("SlaveAddress", false) == null)
                {
                    TheThing.SetSafePropertyNumber(MyBaseThing, "SlaveAddress", 1);
                }
                Interval = 1000;
            }
            MyModFieldStore.CacheTableName = $"MBFLDS{MyBaseThing.ID}";
            MyModFieldStore.RegisterEvent(eStoreEvents.StoreReady, sinkStoreReady);
            MyModFieldStore.RegisterEvent(eStoreEvents.UpdateRequested, sinkUpdated);
            MyModFieldStore.RegisterEvent(eStoreEvents.Inserted, sinkUpdated);
            MyModFieldStore.InitializeStore(true, false);
            return(false);
        }
Exemple #5
0
        protected virtual bool InitBase(string friendlyNamePrefix, string deviceType)
        {
            if (TheCommonUtils.CGuid(MyBaseThing.ID) == Guid.Empty)
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
                if (string.IsNullOrEmpty(MyBaseThing.FriendlyName))
                {
                    MyBaseThing.FriendlyName = $"{friendlyNamePrefix}: {MyBaseThing.ID}";
                }
            }

            MyBaseThing.LastUpdate = DateTimeOffset.Now;

            MyBaseThing.EngineName = MyBaseEngine.GetEngineName();
            MyBaseThing.DeviceType = deviceType;

            TheBaseEngine.WaitForStorageReadiness((pThing, pReady) =>
            {
                if (pReady != null)
                {
                    var receiverThings                      = new TheStorageMirror <TConnectionThing>(TheCDEngines.MyIStorageService);
                    receiverThings.CacheTableName           = nameof(TConnectionThing) + TheThing.GetSafeThingGuid(MyBaseThing, nameof(TConnectionThing));
                    receiverThings.IsRAMStore               = true;
                    receiverThings.CacheStoreInterval       = 1;
                    receiverThings.IsStoreIntervalInSeconds = true;
                    receiverThings.IsCachePersistent        = true;
                    receiverThings.UseSafeSave              = true;
                    receiverThings.RegisterEvent(eStoreEvents.StoreReady, (args) =>
                    {
                        var result = args.Para as TSM;
                        if (result != null && result.LVL == eMsgLevel.l1_Error)
                        {
                            MyBaseThing.SetStatus(3, "Error loading things");
                            TheBaseAssets.MySYSLOG.WriteToLog(98201, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, "Initialization", eMsgLevel.l6_Debug, String.Format("Error loading things for connection {0}", this.GetBaseThing().Address)));
                        }
                        else
                        {
                            MyConnectionThings = receiverThings;
                            if (MyConnectionThingsForm != null)
                            {
                                MyConnectionThingsForm.defDataSource = MyConnectionThings.StoreMID.ToString();
                            }
                            TheBaseAssets.MySYSLOG.WriteToLog(95272, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM(MyBaseThing.EngineName, "Initialization", eMsgLevel.l6_Debug, String.Format("Things loaded for connection {0}", this.GetBaseThing().Address)));

                            if (AutoConnect)
                            {
                                Connect();
                                if (!IsConnected)
                                {
                                    TheCommonUtils.cdeRunTaskAsync("receiverAutoConnect", async o =>
                                    {
                                        await TheCommonUtils.TaskDelayOneEye(30000, 100).ConfigureAwait(false);
                                        while (!IsConnected && AutoConnect && TheBaseAssets.MasterSwitch)
                                        {
                                            Connect();
                                            await TheCommonUtils.TaskDelayOneEye(30000, 100).ConfigureAwait(false);
                                        }
                                    }).ContinueWith(t => t.Exception);
                                }
                            }
                            mIsInitialized = true;
                            FireEvent(eThingEvents.Initialized, this, true, true);
                            FireEvent("ServerInit", this, IsConnected.ToString(), true);
                        }
                    }
                                                 );
                    receiverThings.InitializeStore(false, false);
                }
            }, true);
            return(mIsInitialized);
        }
        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 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 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
        }