public async Task StopWhenNotStartedTest()
        {
            //Arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "am-StopWhenNotStartedTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());
            var logEntries = new List<LogEntry>();
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    logEntries.Add(e);
                    Console.WriteLine(e.ToString());
                    return Task.FromResult(0);
                }
            };

            var adapter = new Adapter()
            {
                AdapterGuid = Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                IsEnabled = true
            };
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync(CancellationToken.None);
            }
            var unitTestingAdapter = new StubUnitTestAdapter
            {
                AdapterGuidGet = () => Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                NameGet = () => "Unit Testing Adapter",
                DescriptionGet = () => "",
                OnDeviceTypesCreatingDeviceTypeBuilder = (s) => Task.FromResult(0)
               
            };

            var adapterManager = new AdapterManager(new List<ZvsAdapter> { unitTestingAdapter }, dbConnection, log);

            //act
            await adapterManager.StopAsync(CancellationToken.None);

            //assert 
            Assert.IsTrue(logEntries.Count(o => o.Level == LogEntryLevel.Warn) == 1);
        }
        public async Task TestPropertyUpdatingOnDatabaseSettingChange()
        {
            //Arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "am-TestPropertyUpdatingOnDatabaseSettingChange" };
            Database.SetInitializer(new CreateFreshDbInitializer());

            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    return Task.FromResult(0);
                }
            };
            var unitTestingAdapter = new StubUnitTestAdapter
            {
                AdapterGuidGet = () => Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                NameGet = () => "Unit Testing Adapter",
                DescriptionGet = () => "",
                OnDeviceTypesCreatingDeviceTypeBuilder = (s) => Task.FromResult(0),
                OnSettingsCreatingAdapterSettingBuilder = (s) => Task.FromResult(0),
            };

            var adapter = new Adapter
            {
                AdapterGuid = Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                Name = "Unit Testing Adapter",
                Description = ""
            };
            adapter.Settings.Add(new AdapterSetting
            {
                UniqueIdentifier = "PropertyTest",
                Value = "2",
                ValueType = DataType.INTEGER
            });

            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync(CancellationToken.None);
            }

            var adapterManager = new AdapterManager(new List<ZvsAdapter> { unitTestingAdapter }, dbConnection, log);
            await adapterManager.StartAsync(CancellationToken.None);
            //act
            using (var context = new ZvsContext(dbConnection))
            {
                context.AdapterSettings.First().Value = "55";
                await context.SaveChangesAsync(CancellationToken.None);
            }

            //assert 
            Assert.IsTrue(unitTestingAdapter.PropertyTest == 55, "The property test property on the zvsAdapter did not properly update when the database value was changed.");
        }
        public async Task DisableAdapterAsyncTest()
        {
            //Arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "am-DisableAdapterAsyncTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());

            var log = new StubIFeedback<LogEntry>();
            var hasStopped = false;
            var unitTestingAdapter = new StubUnitTestAdapter
            {
                AdapterGuidGet = () => Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                NameGet = () => "Unit Testing Adapter",
                DescriptionGet = () => "",
                OnDeviceTypesCreatingDeviceTypeBuilder = (s) => Task.FromResult(0),
                StopAsync01 = async () => hasStopped = true
            };

            var adapterManager = new AdapterManager(new List<ZvsAdapter> { unitTestingAdapter }, dbConnection, log);

            var adapter = new Adapter
            {
                AdapterGuid = Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
            };
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync(CancellationToken.None);
            }

            //act
            var result = await adapterManager.DisableAdapterAsync(Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"), CancellationToken.None);

            //assert 
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsTrue(hasStopped, "Expected adapter StopAsync to be called.");
        }
        public async Task LoadAdaptersAsyncAutoStartTest()
        {
            //Arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "am-LoadAdaptersAsyncAutoStartTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());

            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    return Task.FromResult(0);
                }
            };

            var adapter = new Adapter()
            {
                AdapterGuid = Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                IsEnabled = true
            };
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync(CancellationToken.None);
            }
            var isStarted = false;
            var unitTestingAdapter = new StubUnitTestAdapter
            {
                AdapterGuidGet = () => Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                NameGet = () => "Unit Testing Adapter",
                DescriptionGet = () => "",
                OnDeviceTypesCreatingDeviceTypeBuilder = (s) => Task.FromResult(0),
                StartAsync01 = () =>
                {
                    isStarted = true;
                    return Task.FromResult(0);
                }
            };
            unitTestingAdapter.OnSettingsCreatingAdapterSettingBuilder = async (settingBuilder) =>
            {
                var testSetting = new AdapterSetting
                {
                    Name = "Test setting",
                    Value = 360.ToString(CultureInfo.InvariantCulture),
                    ValueType = DataType.INTEGER,
                    Description = "Unit testing only"
                };

                await
                    settingBuilder.Adapter(unitTestingAdapter)
                        .RegisterAdapterSettingAsync(testSetting, o => o.PropertyTest);
            };

            var adapterManager = new AdapterManager(new List<ZvsAdapter> { unitTestingAdapter }, dbConnection, log);

            //act
            await adapterManager.StartAsync(CancellationToken.None);

            //assert 
            Assert.IsTrue(isStarted, "Adapter not started!");
        }
        public async Task LoadAdaptersAsyncBadPropertyTest()
        {
            //Arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "am-LoadAdaptersAsync_BadProperty_Test" };
            Database.SetInitializer(new CreateFreshDbInitializer());

            var logEntries = new List<LogEntry>();
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return Task.FromResult(0);
                }
            };

            var badSettings = new AdapterSetting
            {
                Name = "Test setting2",
                Value = 360.ToString(CultureInfo.InvariantCulture),
                ValueType = DataType.STRING,
                Description = "Unit testing only",
                UniqueIdentifier = "NotExistantPropertyName"

            };

            var adapter = new Adapter()
            {
                AdapterGuid = Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
            };
            adapter.Settings.Add(badSettings);
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync(CancellationToken.None);
            }

            var unitTestingAdapter = new StubUnitTestAdapter
            {
                AdapterGuidGet = () => Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                NameGet = () => "Unit Testing Adapter",
                DescriptionGet = () => "",
                OnDeviceTypesCreatingDeviceTypeBuilder = (s) => Task.FromResult(0)
            };

            unitTestingAdapter.OnSettingsCreatingAdapterSettingBuilder = async (settingBuilder) =>
            {
                var testSetting = new AdapterSetting
                {
                    Name = "Test setting",
                    Value = 360.ToString(CultureInfo.InvariantCulture),
                    ValueType = DataType.INTEGER,
                    Description = "Unit testing only"
                };

                await
                    settingBuilder.Adapter(unitTestingAdapter)
                        .RegisterAdapterSettingAsync(testSetting, o => o.PropertyTest);
            };

            var adapterManager = new AdapterManager(new List<ZvsAdapter> { unitTestingAdapter }, dbConnection, log);

            //act
            await adapterManager.StartAsync(CancellationToken.None);

            //assert 
            Assert.IsTrue(unitTestingAdapter.PropertyTest == 360, "Expected TestSetting property to be 360");
            Assert.IsTrue(logEntries.Count(o => o.Level == LogEntryLevel.Error && o.Message.Contains("Cannot find property")) == 1, "Expected 1 Cannot find property error");
        }
        public async Task StopTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());
            var logEntries = new List<LogEntry>();
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    logEntries.Add(e);
                    Console.WriteLine(e.ToString());
                    return Task.FromResult(0);
                }
            };

            var adapter = new Adapter()
            {
                AdapterGuid = Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                IsEnabled = true
            };
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync(CancellationToken.None);
            }
            var isStartedCount = 0;
            var isStoppedCount = 0;
            var unitTestingAdapter = new StubUnitTestAdapter
            {
                AdapterGuidGet = () => Guid.Parse("a0f912a6-b8bb-406a-360f-1eb13f50aae4"),
                NameGet = () => "Unit Testing Adapter",
                DescriptionGet = () => "",
                OnDeviceTypesCreatingDeviceTypeBuilder = s => Task.FromResult(0),
                OnSettingsCreatingAdapterSettingBuilder = s => Task.FromResult(0),
                StartAsync01 = () =>
                {
                    isStartedCount++;
                    return Task.FromResult(0);
                },
                StopAsync01 = () =>
                {
                    isStoppedCount++;
                    return Task.FromResult(0);
                }
            };

            var adapterManager = new AdapterManager(new List<ZvsAdapter> { unitTestingAdapter }, dbConnection, log);

            //act
            await adapterManager.StartAsync(CancellationToken.None);
            await adapterManager.StopAsync(CancellationToken.None);

            //assert 
            Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Not all log entries are info level");
            Assert.IsTrue(isStartedCount == 1, "Plugin started too many or too few times");
            Assert.IsTrue(isStoppedCount == 1, "Plugin stopped too many or too few times");
        }
Ejemplo n.º 7
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (IsRunning)
            {
                await
                    Log.ReportWarningAsync("Cannot start adapter manager because it is already running!",
                        cancellationToken);
                return;
            }
            IsRunning = true;

            using (var context = new ZvsContext(EntityContextConnection))
            {
                // Iterate the adapters found in dlls
                foreach (var adapter in Adapters)
                {
                    //keeps this adapter in scope 
                    var zvsAdapter = adapter;

                    //Check Database for this adapter
                    var dbAdapter = await context.Adapters
                        .FirstOrDefaultAsync(p => p.AdapterGuid == zvsAdapter.AdapterGuid, cancellationToken);

                    var changed = false;
                    if (dbAdapter == null)
                    {
                        dbAdapter = new Adapter { AdapterGuid = zvsAdapter.AdapterGuid };
                        context.Adapters.Add(dbAdapter);
                        changed = true;
                    }

                    //Update Name and Description
                    zvsAdapter.IsEnabled = dbAdapter.IsEnabled;

                    if (dbAdapter.Name != zvsAdapter.Name)
                    {
                        dbAdapter.Name = zvsAdapter.Name;
                        changed = true;
                    }

                    if (dbAdapter.Description != zvsAdapter.Description)
                    {
                        dbAdapter.Description = zvsAdapter.Description;
                        changed = true;
                    }

                    if (changed)
                    {
                        var result = await context.TrySaveChangesAsync(cancellationToken);
                        if (result.HasError)
                        {
                            await
                                Log.ReportErrorFormatAsync(cancellationToken,
                                    "Adapter not loaded. Error while saving loaded '{0}' adapter to database. {1}", zvsAdapter.Name, result.Message);
                            break;
                        }
                    }

                    await Log.ReportInfoFormatAsync(cancellationToken, "Initializing '{0}'", zvsAdapter.Name);

                    //Plug-in need access to the zvsEngine in order to use the Logger
                    await zvsAdapter.Initialize(Log, EntityContextConnection);

                    //Reload just installed settings
                    var adapterSettings = await context.AdapterSettings
                        .Include(o => o.Adapter)
                        .Where(p => p.Adapter.AdapterGuid == zvsAdapter.AdapterGuid)
                        .ToListAsync(cancellationToken);

                    //Set plug-in settings from database values
                    foreach (var setting in adapterSettings)
                        await SetAdapterProperty(adapter, setting.UniqueIdentifier, setting.Value, CancellationToken.None);

                    if (dbAdapter.IsEnabled)
                        await zvsAdapter.StartAsync();

                    if (!_adapterIdToGuid.ContainsKey(dbAdapter.Id))
                        _adapterIdToGuid.Add(dbAdapter.Id, dbAdapter.AdapterGuid);
                }
            }
            NotifyEntityChangeContext.ChangeNotifications<AdapterSetting>.OnEntityUpdated += ChangeNotificationsOnOnEntityUpdated;
        }