예제 #1
0
        private void PrepareModulesTestDirectories(string testPath, string moduleAPath, string moduleBPath)
        {
            if (Directory.Exists(testPath))
            {
                Directory.Delete(testPath, true);
            }
            Directory.CreateDirectory(testPath);

            // compile modules into a.dll / b.dll
            var compiler = new ModuleCompiler();


            compiler.OutputDirectory = moduleAPath;
            compiler.OutputName      = Path.Combine(moduleAPath, "a.dll");
            compiler.GenerateModuleFromCode(
                @"..\Source\Nomad.Tests\FunctionalTests\Data\SimplestModulePossible1.cs");

            compiler.OutputDirectory = moduleBPath;
            compiler.OutputName      = Path.Combine(moduleBPath, "b.dll");
            compiler.GenerateModuleFromCode(
                @"..\Source\Nomad.Tests\FunctionalTests\Data\SimplestModulePossible1.cs");

            // generate manifests
            var builder = new ManifestBuilder(@"TEST_ISSUER", KeyFile, @"a.dll", moduleAPath);

            builder.CreateAndPublish();
            builder = new ManifestBuilder(@"TEST_ISSUER", KeyFile, @"b.dll", moduleBPath);
            builder.CreateAndPublish();

            // add spoiling module (assembly without manifest)
            File.Copy(Path.Combine(moduleAPath, @"a.dll"), Path.Combine(testPath, "c.dll"));
        }
예제 #2
0
        public void setup()
        {
            _keyFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                        @"FunctionalTests\Signing\KeyDir\manifest-key.xml");
            _moduleDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                            @"FunctionalTests\Signing\Module");
            _assemblyName = "sample_module.dll";
            _assemblyPath = Path.Combine(_moduleDirectory, _assemblyName);
            _manifestPath = _assemblyPath + ModuleManifest.ManifestFileNameSuffix;
            _issuerName   = "test-issuer";
            if (File.Exists(_keyFileName))
            {
                File.Delete(_keyFileName);
            }

            KeysGenerator.KeysGeneratorProgram.Main(new[] { _keyFileName });

            // creating sample assembly, cause the manifest generator requires full-fledgged assembly not imposter
            var compiler = new ModuleCompiler
            {
                OutputDirectory = _moduleDirectory,
                OutputName      = _assemblyPath
            };

            compiler.GenerateModuleFromCode(ModuleCompiler.DefaultSimpleModuleSource);

            // test creating the manifests
            ManifestCreatorProgram.Main(new[]
            {
                "rsa",
                _keyFileName, _moduleDirectory,
                _assemblyName, _issuerName
            });
        }
예제 #3
0
        public void selective_manual_update_with_updater_wokring_on_threads()
        {
            // create the updater module for manual testing
            string updaterDir = NomadConfigurationSettings.ModuleDirectoryPath;

            ModuleCompiler.SetUpModuleWithManifest(updaterDir,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Updater\UpdaterModuleManual.cs");

            // set up two simple modules
            IModuleDiscovery basicDiscovery = SetUpTwoSimpleModulesGetTheirDiscovery();

            // override kernel configuration
            NomadConfigurationSettings.UpdaterType = UpdaterType.Manual;
            SetUpKernel();

            // skip verification about loaded modules, just load them
            Kernel.LoadModules(new CompositeModuleDiscovery(basicDiscovery, new DirectoryModuleDiscovery(updaterDir, SearchOption.TopDirectoryOnly)));

            // get updater reference, for synchronization
            var updater = Kernel.ServiceLocator.Resolve <IUpdater>();

            // initialize the updating through updater module using event aggregator and publish
            Kernel.EventAggregator.Publish(new BeginUpdateMessage());

            // no need to verify the messages - just final verification of loaded modules wait for finish
            updater.UpdateFinished.WaitOne();

            var loadedModules = Kernel.ServiceLocator.Resolve <ILoadedModulesService>().GetLoadedModules();

            Assert.AreEqual(3, loadedModules.Count); // updater + simples ;)
            AssertVersion("1.0.0.0", loadedModules, "SimplestModulePossible1");
            AssertVersion("2.0.0.0", loadedModules, "SimplestModulePossible2");
        }
        public void loading_one_module_dependent_on_others_callback()
        {
            const string dir  = @"Modules\Dependent1\ModuleA\";
            const string dir2 = @"Modules\Dependent1\ModuleB\";
            const string dir3 = @"Modules\Dependent1\ModuleC\";

            // dependant module generation
            ModuleCompiler.SetUpModuleWithManifest(dir,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Dependencies\DependencyModule1.cs");

            // second dependent module generation
            ModuleCompiler.SetUpModuleWithManifest(dir3,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Dependencies\DependencyModule2.cs");

            // depending module generation
            ModuleCompiler.SetUpModuleWithManifest(dir2,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Dependencies\ModuleWithDependency.cs",
                                                   dir + "DependencyModule1.dll", dir3 + "DependencyModule2.dll");

            // define discovery sequence
            var discovery = new CompositeModuleDiscovery(new IModuleDiscovery[]
            {
                new DirectoryModuleDiscovery(
                    dir2, SearchOption.TopDirectoryOnly),
                new DirectoryModuleDiscovery(
                    dir, SearchOption.TopDirectoryOnly),
                new DirectoryModuleDiscovery(
                    dir3, SearchOption.TopDirectoryOnly),
            });

            // perform test and assert
            LoadModulesFromDiscovery(discovery);
            AssertModulesLoadedAreEqualTo("DependencyModule1", "DependencyModule2",
                                          "ModuleWithDependency");
        }
        public void loading_module_fails_during_loading_assembly_phase_throws_an_exception_callback()
        {
            const string dir1 = @"Modules\Dependent5\ModuleA\";
            const string dir2 = @"Modules\Dependent5\ModuleB\";

            // dependant module generation
            ModuleCompiler.SetUpModuleWithManifest(dir1,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\ErrorLoad\DependencyModule1.cs");

            // second dependent module generation
            ModuleCompiler.SetUpModuleWithManifest(dir2,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\ErrorLoad\ModuleWithDependency.cs",
                                                   dir1 + "DependencyModule1.dll");

            // overwriting the dll file, causing BadImageFormatException
            File.Create(dir1 + "DependencyModule1.dll");

            // define discovery sequence
            var discovery = new CompositeModuleDiscovery(new IModuleDiscovery[]
            {
                new DirectoryModuleDiscovery(
                    dir2, SearchOption.TopDirectoryOnly),
                new DirectoryModuleDiscovery(
                    dir1, SearchOption.TopDirectoryOnly),
            });

            // perform test and assert
            Assert.Throws <NomadCouldNotLoadModuleException>(
                () => LoadModulesFromDiscovery(discovery));
        }
예제 #6
0
        public void setup()
        {
            //FIXME what is this for ?
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture("en-US");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

            _privateKeyFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                               @"res\pki\SignedByCA.pfx");
            Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                         @"res\pki\NomadFakeCa.cer");
            _assemblyName    = "sample_module.dll";
            _moduleDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                            @"FunctionalTests\Signing\Module");

            _assemblyPath = Path.Combine(_moduleDirectory, _assemblyName);
            _manifestPath = _assemblyPath + ModuleManifest.ManifestFileNameSuffix;
            _issuerName   = "test-issuer";

            _manifestSignature = _manifestPath + ModuleManifest.ManifestSignatureFileNameSuffix;

            // create fully fledgged assembly
            var compiler = new ModuleCompiler
            {
                OutputDirectory = _moduleDirectory,
                OutputName      = _assemblyPath
            };

            compiler.GenerateModuleFromCode(ModuleCompiler.DefaultSimpleModuleSource);

            CreateSignature(_privateKeyFileName, "abc123");
        }
예제 #7
0
        public void loaded_modules_appear_on_list_in_kernel_and_modules_domain()
        {
            ModuleCompiler.SetUpModuleWithManifest(dir,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Services\SimplestModulePossible1.cs");

            ModuleCompiler.SetUpModuleWithManifest(dir2,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Services\SimplestModulePossible2.cs");

            ModuleCompiler.SetUpModuleWithManifest(dir3,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Services\LoadedModulesServiceTestingModule.cs");


            // perform kernel test and assert
            LoadModulesFromDiscovery(new DirectoryModuleDiscovery(@"Modules\Services\", SearchOption.AllDirectories));

            var loadedModulesService = Kernel.ServiceLocator.Resolve <ILoadedModulesService>();

            Assert.AreEqual(3, loadedModulesService.GetLoadedModules().Count);

            //verify from VerificationModule in modules domain
            int loaded;

            using (StreamReader verificationFile =
                       File.OpenText(
                           @"Modules\Services\VerificationModule\ILoadedModulesServiceVerificationFile"))
            {
                Int32.TryParse(verificationFile.ReadLine(),
                               out loaded);
            }

            Assert.AreEqual(3, loaded);
        }
예제 #8
0
        public void event_all_modules_loaded_is_catched_upon_every_success()
        {
            NomadKernel kernel = SetupMockedKernel();

            // subscribe kernel for event
            bool hasBeenLoaded = false;

            kernel.EventAggregator.Subscribe <NomadAllModulesLoadedMessage>((message) =>
            {
                Assert.AreNotEqual(0, message.ModuleInfos.Count());
                hasBeenLoaded = true;
            });

            //  compiling simple modules
            const string dir         = @"Modules\Kernel\SimpleAllModulesLoadedAwarenessTestModules\Simple\";
            const string fileName    = "AllModulesLoadedEventAwareModule.dll";
            const string module1Name = "SimpleModule1.dll";
            const string module2Name = "SimpleModule2.dll";
            const string keyFile     = @"newkey.xml";

            CompileSimpleModules(dir, keyFile, module1Name, module2Name);

            // compiling aware module
            var compiler = new ModuleCompiler
            {
                OutputDirectory =
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                 @"Modules\Kernel\SimpleAllModulesLoadedAwarenessTestModules\Aware\")
            };

            compiler.OutputName = Path.Combine(compiler.OutputDirectory, fileName);

            string modulePath = compiler.GenerateModuleFromCode(
                @"..\Source\Nomad.Tests\FunctionalTests\Data\Kernel\AllModulesLoadedEventAwareModule.cs");

            KeysGeneratorProgram.Main(new[] { keyFile });
            compiler.GenerateManifestForModule(modulePath, keyFile);
            // set up module which subscribes for event

            // loading aware module
            IModuleDiscovery setUpDiscovery = SetUpDiscovery(new ModuleInfo(modulePath));

            Assert.DoesNotThrow(() => kernel.LoadModules(setUpDiscovery));

            // loading simple modules
            var directoryDiscovery = new DirectoryModuleDiscovery(dir, SearchOption.TopDirectoryOnly);

            Assert.DoesNotThrow(() => kernel.LoadModules(directoryDiscovery));

            //verify the method being called in a module.
            var carrier = (MessageCarrier)kernel.ModuleAppDomain.CreateInstanceAndUnwrap(
                typeof(MessageCarrier).Assembly.FullName, typeof(MessageCarrier).FullName);

            Assert.AreEqual(
                new[] { "AllModulesLoadedEventAwareModule", "AllModulesLoadedEventAwareModule" },
                carrier.List.ToArray());
            Assert.IsTrue(hasBeenLoaded);
        }
예제 #9
0
        exception_during_module_loading_is_changed_into_event_visible_from_module_and_kernel()
        {
            // set up configuration of kernel with mocks
            NomadKernel kernel = SetupMockedKernel();

            // set up listener for kernel side
            bool hasBeenCalled = false;

            kernel.EventAggregator.Subscribe <NomadAllModulesLoadedMessage>(
                (message) => hasBeenCalled = true);

            //  compile module for event aggregation
            const string dir      = @"Modules\Kernel\Event\";
            const string fileName = "EventAwareModule.dll";
            const string keyFile  = @"newkey.xml";

            var compiler = new ModuleCompiler
            {
                OutputDirectory =
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dir)
            };

            compiler.OutputName = Path.Combine(compiler.OutputDirectory, fileName);

            string modulePath = compiler.GenerateModuleFromCode(
                @"..\Source\Nomad.Tests\FunctionalTests\Data\Kernel\EventAwareModule.cs");

            KeysGeneratorProgram.Main(new[] { keyFile });
            compiler.GenerateManifestForModule(modulePath, keyFile);

            // set up module which subscribes for event
            IModuleDiscovery setUpDiscovery = SetUpDiscovery(new ModuleInfo(modulePath));

            kernel.LoadModules(setUpDiscovery);

            // set up the discovery mock
            IModuleDiscovery nonExistingDiscovery =
                SetUpDiscovery(new ModuleInfo("NonExistingModule.dll"));

            // perform test
            Assert.Throws <NomadCouldNotLoadModuleException>(
                () => kernel.LoadModules(nonExistingDiscovery),
                "Exception should  be thrown in kernel domain.");

            //verify the method being called in a module.
            var carrier = (MessageCarrier)kernel.ModuleAppDomain.CreateInstanceAndUnwrap(
                typeof(MessageCarrier).Assembly.FullName, typeof(MessageCarrier).FullName);

            Assert.AreEqual(new[] { "EventAwareModule" }, carrier.List.ToArray());
            Assert.IsTrue(hasBeenCalled);
        }
예제 #10
0
        public void discovers_all_proper_modules_with_manifests_ignores_others_assemblies()
        {
            // make another folder
            string testPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                           @"IntegrationTests\DirectoryModuleDiscovery2\");

            if (Directory.Exists(testPath))
            {
                Directory.Delete(testPath, true);
            }
            Directory.CreateDirectory(testPath);

            // compile modules into a.dll / b.dll
            var compiler = new ModuleCompiler();

            compiler.OutputDirectory = testPath;

            compiler.OutputName = Path.Combine(testPath, "a.dll");
            compiler.GenerateModuleFromCode(
                @"..\Source\Nomad.Tests\FunctionalTests\Data\SimplestModulePossible1.cs");

            compiler.OutputName = Path.Combine(testPath, "b.dll");
            compiler.GenerateModuleFromCode(
                @"..\Source\Nomad.Tests\FunctionalTests\Data\SimplestModulePossible1.cs");

            // generate manifests
            var builder = new ManifestBuilder(@"TEST_ISSUER", KeyFile, @"a.dll", testPath);

            builder.CreateAndPublish();
            builder = new ManifestBuilder(@"TEST_ISSUER", KeyFile, @"b.dll", testPath);
            builder.CreateAndPublish();

            // add spoiling module (assembly without manifest)
            File.Copy(Path.Combine(testPath, @"a.dll"), Path.Combine(testPath, "c.dll"));

            var expectedModules = new[]
            {
                new ModuleInfo(Path.Combine(testPath, "a.dll")),
                new ModuleInfo(Path.Combine(testPath, "b.dll")),
            };

            var discovery = new Nomad.Modules.Discovery.DirectoryModuleDiscovery(testPath, SearchOption.TopDirectoryOnly);

            Assert.That(discovery.GetModules().ToArray(), Is.EquivalentTo(expectedModules),
                        "Discovered modules differ from expected");
        }
예제 #11
0
        /// <summary>
        ///    Set up the Two Modules A,B into with provided version. Based on <see cref="ModuleCompiler.DefaultSimpleModuleSource"/>
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="versionString"></param>
        /// <returns></returns>
        private IModuleDiscovery SetUpModulesWithVersion(string directory,
                                                         string versionString)
        {
            string moduleA = directory + @"\ModuleA";
            string moduleB = directory + @"\ModuleB";

            ManifestBuilderConfiguration builderConfiguration = ManifestBuilderConfiguration.Default;

            builderConfiguration.VersionProvider = GetVersionProviderForVersion(versionString);

            ModuleCompiler.SetUpModuleWithManifest(moduleA, ModuleCompiler.DefaultSimpleModuleSource,
                                                   builderConfiguration);
            ModuleCompiler.SetUpModuleWithManifest(moduleB, ModuleCompiler.DefaultSimpleModuleSourceAlternative,
                                                   builderConfiguration);

            return(new CompositeModuleDiscovery(new DirectoryModuleDiscovery(moduleA, SearchOption.TopDirectoryOnly),
                                                new DirectoryModuleDiscovery(moduleB, SearchOption.TopDirectoryOnly)));
        }
예제 #12
0
        /// @brief Method to compile C# source code to check errors on it.
        /// Actually call a C# compiler to determine errors, using references.
        /// @param[in] sender Object who called this on event.
        /// @param[in] e `EventArgs` class with a list of argument to the event call.
        private void CheckSource_Click(object sender, EventArgs e)
        {
            if ((codeEditorView.TextLength > 0) && IsConsistent())
            {
                string[] refs = new string[referencesList.Items.Count];
                int      i    = 0;

                errorListView.Items.Clear();
                foreach (string s in referencesList.Items)
                {
                    refs[i++] = s;
                }

                if (ModuleCompiler.LoadModule(codeEditorView.Text, instanceName.Text, refs, null) != null)
                {
                    MessageBox.Show("Script compiled without errors.", "Plugin Editor - Check source.");
                }
                else
                {
                    ModuleCompiler.EnumerateErrors(EnumErrors);
                }
            }
        }
        loading_module_with_dependency_with_no_dependency_present_results_in_exception_callback()
        {
            const string dir  = @"Modules\Dependent3\ModuleA\";
            const string dir2 = @"Modules\Dependent3\ModuleB\";
            const string dir3 = @"Modules\Dependent3\ModuleC\";

            // dependant module generation
            ModuleCompiler.SetUpModuleWithManifest(dir,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\ChainDependencies\DependencyModule1.cs");

            // second dependent module generation
            ModuleCompiler.SetUpModuleWithManifest(dir3,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\ChainDependencies\DependencyModule2.cs",
                                                   dir + "DependencyModule1.dll");

            // third dependent module generation
            ModuleCompiler.SetUpModuleWithManifest(dir2,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\ChainDependencies\ModuleWithDependency.cs",
                                                   dir3 + "DependencyModule2.dll");

            // remove dependency
            Directory.Delete(dir3, true);

            // define discovery sequence
            var discovery = new CompositeModuleDiscovery(new IModuleDiscovery[]
            {
                new DirectoryModuleDiscovery(
                    dir2, SearchOption.TopDirectoryOnly),
                new DirectoryModuleDiscovery(
                    dir, SearchOption.TopDirectoryOnly),
            });

            // perform test and assert
            Assert.Throws <NomadCouldNotLoadModuleException>(
                () => LoadModulesFromDiscovery(discovery));
        }
예제 #14
0
        private static void CompileSimpleModules(string dir, string keyFile,
                                                 string simpleModule1Name, string simpleModule2Name)
        {
            var compiler = new ModuleCompiler
            {
                OutputDirectory =
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dir)
            };

            KeysGeneratorProgram.Main(new[] { keyFile });

            // generating not subcribed modules
            compiler.OutputName = Path.Combine(compiler.OutputDirectory, simpleModule1Name);
            string module1Path =
                compiler.GenerateModuleFromCode(ModuleCompiler.DefaultSimpleModuleSource);

            compiler.GenerateManifestForModule(module1Path, keyFile);

            compiler.OutputName = Path.Combine(compiler.OutputDirectory, simpleModule2Name);
            string module2Path =
                compiler.GenerateModuleFromCode(ModuleCompiler.DefaultSimpleModuleSourceAlternative);

            compiler.GenerateManifestForModule(module2Path, keyFile);
        }
예제 #15
0
        public void basic_usage_scenerio_with_newer_versions_avaliable_automatic_update()
        {
            // create the updater module
            string updaterDir = NomadConfigurationSettings.ModuleDirectoryPath;

            ModuleCompiler.SetUpModuleWithManifest(updaterDir,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Updater\UpdaterModule.cs");

            // set up two simple modules
            IModuleDiscovery v0Discovery = SetUpTwoSimpleModulesGetTheirDiscovery();

            //  override kernel configuration and initialize kernel
            NomadConfigurationSettings.UpdaterType = UpdaterType.Automatic;
            SetUpKernel();

            // test against loading
            var discovery = new CompositeModuleDiscovery(new DirectoryModuleDiscovery(updaterDir, SearchOption.TopDirectoryOnly),
                                                         v0Discovery);

            Kernel.LoadModules(discovery);

            // verify the versions of the loaded modules are proper
            IList <ModuleInfo> loadedModules =
                Kernel.ServiceLocator.Resolve <ILoadedModulesService>().GetLoadedModules();

            Assert.AreEqual(3, loadedModules.Count);
            AssertVersion("1.0.0.0", loadedModules, "SimplestModulePossible1");
            AssertVersion("1.0.0.0", loadedModules, "SimplestModulePossible2");

            // check if all stages of update were done
            bool avaliableUpdates = false;
            bool readyUpdates     = false;

            Kernel.EventAggregator.Subscribe <NomadAvailableUpdatesMessage>(
                message =>
            {
                if (message.Error == false)
                {
                    avaliableUpdates = true;
                }
            });


            Kernel.EventAggregator.Subscribe <NomadUpdatesReadyMessage>(message =>
            {
                if (message.Error ==
                    false)
                {
                    readyUpdates =
                        true;
                }
            });

            var updater = Kernel.ServiceLocator.Resolve <IUpdater>();

            // initialize the updating through updater module using event aggregator and publish
            Kernel.EventAggregator.Publish(new BeginUpdateMessage());

            // verify stages
            Assert.IsTrue(avaliableUpdates, "Available updates message was not published.");
            Assert.IsTrue(readyUpdates, "Updates ready message was not published.");

            // verify the outcome of the updater after finishing (this wait is for test purposes)
            updater.UpdateFinished.WaitOne();
            Assert.AreEqual(UpdaterStatus.Idle, Kernel.ServiceLocator.Resolve <IUpdater>().Status, "Problem with the state of the updater");

            // verify the versions of the newest modules are loaded
            loadedModules = Kernel.ServiceLocator.Resolve <ILoadedModulesService>().GetLoadedModules();
            Assert.AreEqual(3, loadedModules.Count);
            AssertVersion("2.0.0.0", loadedModules, "SimplestModulePossible1");
            AssertVersion("2.0.0.0", loadedModules, "SimplestModulePossible2");
        }
예제 #16
0
        public void basic_update_scenario_when_installing_new_module()
        {
            // create the updater module
            string updaterDir = NomadConfigurationSettings.ModuleDirectoryPath;

            ModuleCompiler.SetUpModuleWithManifest(updaterDir,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Updater\UpdaterModule.cs");

            // set up two simple modules -- to be loaded into kernel
            string modulaADir = Path.Combine(NomadConfigurationSettings.ModuleDirectoryPath, "moduleA");
            string modulaBDir = Path.Combine(NomadConfigurationSettings.ModuleDirectoryPath, "moduleB");

            ModuleCompiler.SetUpModuleWithManifest(modulaADir, ModuleCompiler.DefaultSimpleModuleSource);
            ModuleCompiler.SetUpModuleWithManifest(modulaBDir, ModuleCompiler.DefaultSimpleModuleSourceAlternative);
            var twoSimpleModules = new CompositeModuleDiscovery(
                new DirectoryModuleDiscovery(modulaADir, SearchOption.TopDirectoryOnly),
                new DirectoryModuleDiscovery(modulaBDir, SearchOption.TopDirectoryOnly)
                );

            // set up third simple module -- completely independent to be placed in remote repository
            string moduleCDir = Path.Combine(NomadConfigurationSettings.ModuleDirectoryPath, "moduleC");

            ModuleCompiler.SetUpModuleWithManifest(moduleCDir, ModuleCompiler.DefaultSimpleModuleSourceLastAlternative);


            // put the third one in repository
            var listOfModuleInRepositoryInfos = twoSimpleModules.GetModules();
            var listOfModuleInRepository      = new List <ModuleManifest>(twoSimpleModules.GetModules().Select(x => x.Manifest));

            SetUpModulesRepository(listOfModuleInRepository, listOfModuleInRepositoryInfos);

            // initialize kernel
            NomadConfigurationSettings.UpdaterType = UpdaterType.Automatic;
            SetUpKernel();

            // set up the subscribers for stages of update
            bool updatesChecked = false;
            bool updatesReady   = false;

            Kernel.EventAggregator.Subscribe <NomadAvailableUpdatesMessage>((m) =>
            {
                Assert.IsFalse(m.Error, "There should no error in checking");
                updatesChecked = true;
            });

            Kernel.EventAggregator.Subscribe <NomadUpdatesReadyMessage>((m) =>
            {
                Assert.IsFalse(m.Error, "There should no error in preparing");
                updatesReady = true;
            });

            // load those two modules into kernel
            var discovery = new CompositeModuleDiscovery(twoSimpleModules,
                                                         new DirectoryModuleDiscovery(updaterDir, SearchOption.TopDirectoryOnly));

            Kernel.LoadModules(discovery);

            // invoke automatic update process
            var updater = Kernel.ServiceLocator.Resolve <IUpdater>();

            Kernel.EventAggregator.Publish(new BeginUpdateMessage());

            // check stages of update
            Assert.IsTrue(updatesChecked, "Updates checked message has never been invoked");
            Assert.IsTrue(updatesReady, "Updates ready message has never been invoked ");

            // wait for updater to finish and being in a good state
            Assert.NotNull(updater.UpdateFinished, "Update finshed object is null, meaning that no one has started perform update");
            updater.UpdateFinished.WaitOne();
            Assert.AreEqual(UpdaterStatus.Idle, Kernel.ServiceLocator.Resolve <IUpdater>().Status, "Problem with the state of the updater after reload");

            // assert that there are 4 modules installed and running - 3 simples and one updater
            var loadedModules = Kernel.ServiceLocator.Resolve <ILoadedModulesService>().GetLoadedModules();

            Assert.AreEqual(4, loadedModules.Count);
        }
예제 #17
0
        public void failing_update_beacause_of_the_missing_dependencies()
        {
            // create the updater module
            string updaterDir = NomadConfigurationSettings.ModuleDirectoryPath;

            ModuleCompiler.SetUpModuleWithManifest(updaterDir,
                                                   @"..\Source\Nomad.Tests\FunctionalTests\Data\Updater\UpdaterModule.cs");

            // version for modules A, B and C
            const string versionString = "1.0.0.0";

            // create modules A with version v0 (this version and dependencies are only in manifest - not in assembly)
            var moduelADir           = Path.Combine(NomadConfigurationSettings.ModuleDirectoryPath, @"ModuleADir");
            var moduleAConfiguration = ManifestBuilderConfiguration.Default;

            moduleAConfiguration.VersionProvider             = GetVersionProviderForVersion(versionString);
            moduleAConfiguration.ModulesDependenciesProvider = GetModuleDependenciesOnSingleModule("SimplestModulePossible2", versionString);

            ModuleCompiler.SetUpModuleWithManifest(moduelADir, ModuleCompiler.DefaultSimpleModuleSource, moduleAConfiguration);

            // create module B with the same setting as A (with version v0)
            var moduelBDir = Path.Combine(NomadConfigurationSettings.ModuleDirectoryPath, @"ModuleBDir");

            moduleAConfiguration = ManifestBuilderConfiguration.Default;

            moduleAConfiguration.VersionProvider             = GetVersionProviderForVersion(versionString);
            moduleAConfiguration.ModulesDependenciesProvider = GetModuleDependenciesOnSingleModule("SimplestModulePossible3", versionString);

            ModuleCompiler.SetUpModuleWithManifest(moduelBDir, ModuleCompiler.DefaultSimpleModuleSourceAlternative, moduleAConfiguration);

            // create module C with no dependency on any other module with version v0
            var moduleCDir = Path.Combine(NomadConfigurationSettings.ModuleDirectoryPath, @"ModuleCDir");

            moduleAConfiguration = ManifestBuilderConfiguration.Default;

            moduleAConfiguration.VersionProvider = GetVersionProviderForVersion(versionString);
            ModuleCompiler.SetUpModuleWithManifest(moduleCDir, ModuleCompiler.DefaultSimpleModuleSourceLastAlternative, moduleAConfiguration);

            // create module B in version v1 which depends on module C in version v1
            var moduleBVersionUpperDir = Path.Combine(NomadConfigurationSettings.ModuleDirectoryPath, @"ModuleBUpperDir");

            moduleAConfiguration = ManifestBuilderConfiguration.Default;

            moduleAConfiguration.VersionProvider             = GetVersionProviderForVersion("2.0.0.0");
            moduleAConfiguration.ModulesDependenciesProvider = GetModuleDependenciesOnSingleModule("SimplestModulePossible3", "2.0.0.0");

            ModuleCompiler.SetUpModuleWithManifest(moduleBVersionUpperDir, ModuleCompiler.DefaultSimpleModuleSourceAlternative, moduleAConfiguration);

            // put module B into repository
            var bRepoModuleInfo = new DirectoryModuleDiscovery(moduleBVersionUpperDir, SearchOption.TopDirectoryOnly)
                                  .GetModules()
                                  .Select(x => x)
                                  .Single();


            ModulesRepository.Setup(x => x.GetAvailableModules())
            .Returns(new AvailableModules(new List <ModuleManifest>()
            {
                bRepoModuleInfo.Manifest
            }));

            ModulesRepository
            .Setup(x => x.GetModule(It.IsAny <string>()))
            .Returns(new ModulePackage()
            {
                ModuleManifest = bRepoModuleInfo.Manifest,
                ModuleZip      = GetZippedData(new List <ModuleInfo>()
                {
                    bRepoModuleInfo
                }, bRepoModuleInfo.Manifest.ModuleName)
            });

            // configure kernel
            NomadConfigurationSettings.UpdaterType = UpdaterType.Automatic;
            SetUpKernel();

            // load modules A,B,C in version v0 into Nomad
            var discovery = new CompositeModuleDiscovery(new DirectoryModuleDiscovery(moduelADir, SearchOption.TopDirectoryOnly),
                                                         new DirectoryModuleDiscovery(moduelBDir, SearchOption.TopDirectoryOnly),
                                                         new DirectoryModuleDiscovery(moduleCDir, SearchOption.TopDirectoryOnly),
                                                         new DirectoryModuleDiscovery(updaterDir, SearchOption.TopDirectoryOnly));

            Kernel.LoadModules(discovery);

            // register for updates available message
            var hasBeenInvoked = false;

            Kernel.EventAggregator.Subscribe <NomadUpdatesReadyMessage>(message =>
            {
                hasBeenInvoked = true;
                Assert.IsTrue(message.Error, "The error should be reported");

                // list of non valid modules is accurate
                Assert.AreEqual("SimplestModulePossible2", message.ModuleManifests[0].ModuleName);
            });

            // initialize check updates (automatic mode)
            Kernel.EventAggregator.Publish(new BeginUpdateMessage());

            // verify that update can not be done
            Assert.IsTrue(hasBeenInvoked, "The updates ready message was not invoked");
            Assert.AreEqual(UpdaterStatus.Invalid, Kernel.ServiceLocator.Resolve <IUpdater>().Status);
        }
예제 #18
0
 /// @brief Method to compile C# source code to check errors on it.
 /// Actually call a C# compiler to determine errors, using references.
 /// @param[in] sender Object who called this on event.
 /// @param[in] e `EventArgs` class with a list of argument to the event call.
 private void CheckSource_Click(object sender, EventArgs e)
 {
     if (String.IsNullOrEmpty(codeEditorView.Text))
     {
         MessageBox.Show("No source code to check. Please add code.",
                         "Plugin Editor - Check source.",
                         MessageBoxButtons.OK,
                         MessageBoxIcon.Exclamation);
     }
     else
     {
         string aux = null;
         if (DetectClassName(codeEditorView.Text, out aux))  //class name detected?
         {
             int i = 0;
             instanceName.Text = aux;        //show the name found in the screen field
             errorListView.Items.Clear();    //clear error list, if any
             //prepare reference list
             string[] refs = new string[referencesList.Items.Count];
             foreach (string s in referencesList.Items)
             {
                 refs[i++] = s;
             }
             try
             {
                 PluginBase plugin = ModuleCompiler.LoadModule(codeEditorView.Text, instanceName.Text, refs, null);
                 if (plugin != null)
                 {
                     ShowErrorGrid(false);    //hide the error list
                     MessageBox.Show("Plugin compiled without errors.",
                                     "Plugin Editor - Check source.",
                                     MessageBoxButtons.OK,
                                     MessageBoxIcon.Information);
                     plugin.Dispose();
                 }
                 else
                 {
                     ModuleCompiler.EnumerateErrors(EnumErrors);
                     ShowErrorGrid(true);    //show the error list
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show("Compile Error: " + ex.ToString(),
                                 "Plugin Editor - Check source.",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
             }
         }
         else   //not detected class name
         {
             instanceName.Text = "Not found!";
             MessageBox.Show("Cannot detect main plugin class name. " +
                             "Please use \"class <YourPluginName> : PluginBase {...\" " +
                             "declaration on your source code.",
                             "Plugin Editor - Check source.",
                             MessageBoxButtons.OK,
                             MessageBoxIcon.Error);
         }
     }
 }
예제 #19
0
        /// @brief Load a plugin from XML file.
        /// @details Try to open the XML definition for the plugin from the file name given as
        /// parameter. Then extract information from the XML (class name, auxiliary references
        /// and source code to compile), trying to compile the C# source code (based on
        /// Gear.PluginSupport.PluginBase class) and returning the new class instance. If the
        /// compilation fails, then it opens the plugin editor to show errors and source code.
        /// @param[in] FileName Name and path to the XML plugin file to open
        /// @returns Reference to the new plugin instance (on success) or NULL (on fail).
        public PluginBase LoadPlugin(string FileName)
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreComments = true;
            settings.IgnoreProcessingInstructions = true;
            settings.IgnoreWhitespace             = true;
            XmlReader tr       = XmlReader.Create(FileName, settings);
            bool      ReadText = false;

            List <string> references   = new List <string>();
            string        instanceName = "";
            string        code         = "";

            try
            {
                while (tr.Read())
                {
                    if (tr.NodeType == XmlNodeType.Text && ReadText)
                    {
                        code     = tr.Value;
                        ReadText = false;
                    }

                    switch (tr.Name.ToLower())
                    {
                    case "reference":
                        if (!tr.IsEmptyElement)         //prevent empty element generates error
                        {
                            references.Add(tr.GetAttribute("name"));
                        }
                        break;

                    case "instance":
                        instanceName = tr.GetAttribute("class");
                        break;

                    case "code":
                        ReadText = true;
                        break;
                    }
                }

                //Dynamic load and compile the plugin module as a class, giving the chip
                // instance as a parameter.
                PluginBase plugin = ModuleCompiler.LoadModule(
                    code,
                    instanceName,
                    references.ToArray(),
                    Chip
                    );

                if (plugin == null)     //if it fails...
                {
                    // ...open plugin editor in other window
                    PluginEditor pe = new PluginEditor(false);
                    pe.OpenFile(FileName, true);
                    pe.MdiParent = this.MdiParent;
                    pe.Show();
                }
                else               //if success compiling & instantiate the new class...
                {
                    //...add the reference to the plugin list of the emulator instance
                    AttachPlugin(plugin);
                    Properties.Settings.Default.LastPlugin = FileName;  //update location of last plugin
                    Properties.Settings.Default.Save();
                }

                return(plugin);
            }
            catch (IOException ioe)
            {
                MessageBox.Show(this,
                                ioe.Message,
                                "Failed to load program binary",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                return(null);
            }
            catch (XmlException xmle)
            {
                MessageBox.Show(this,
                                xmle.Message,
                                "Failed to load program binary",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                return(null);
            }
            finally
            {
                tr.Close();
            }
        }
예제 #20
0
        /// @brief Load a plugin from File.
        /// @note This method take care of update change state of the window.
        /// @todo Correct method to implement new plugin system.
        public bool OpenFile(string FileName, bool displayErrors)
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreComments = true;
            settings.IgnoreProcessingInstructions = true;
            settings.IgnoreWhitespace             = true;
            XmlReader tr       = XmlReader.Create(FileName, settings);
            bool      ReadText = false;

            if (referencesList.Items.Count > 0)
            {
                referencesList.Items.Clear();   //clear out the reference list
            }
            try
            {
                while (tr.Read())
                {
                    if (tr.NodeType == XmlNodeType.Text && ReadText)
                    {
                        //set or reset font and color
                        codeEditorView.SelectAll();
                        codeEditorView.SelectionFont  = defaultFont;
                        codeEditorView.SelectionColor = Color.Black;
                        codeEditorView.Text           = tr.Value;
                        ReadText = false;
                    }

                    switch (tr.Name.ToLower())
                    {
                    case "reference":
                        if (!tr.IsEmptyElement)         //prevent empty element generates error
                        {
                            referencesList.Items.Add(tr.GetAttribute("name"));
                        }
                        break;

                    case "instance":
                        instanceName.Text = tr.GetAttribute("class");
                        break;

                    case "code":
                        ReadText = true;
                        break;
                    }
                }
                _saveFileName = FileName;
                CodeChanged   = false;

                if (displayErrors)
                {
                    errorListView.Items.Clear();
                    ModuleCompiler.EnumerateErrors(EnumErrors);
                }

                return(true);
            }
            catch (IOException ioe)
            {
                MessageBox.Show(this,
                                ioe.Message,
                                "Failed to load plug-in",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                return(false);
            }
            catch (XmlException xmle)
            {
                MessageBox.Show(this,
                                xmle.Message,
                                "Failed to load plug-in",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);

                return(false);
            }
            finally
            {
                tr.Close();
            }
        }
예제 #21
0
        /// @brief Load a plugin from file.
        /// @details Try to open the XML definition for the plugin from the file name given as
        /// parameter. Then extract information from the XML (class name, auxiliary references
        /// and source code to compile), trying to compile the C# source code (based on
        /// Gear.PluginSupport.PluginCommon class) and returning the new class instance. If the
        /// compilation fails, then it opens the plugin editor to show errors and source code.
        /// @param[in] FileName Name and path to the XML plugin file to open
        /// @returns Reference to the new plugin instance (on success) or NULL (on fail).
        /// @throws Exception
        // TODO Modify the method to receive a PluginData, and delete the validation
        public void LoadPlugin(string FileName)
        {
            object objInst = null;
            //create the structure to fill data from file
            PluginData pluginCandidate = new PluginData();

            //Determine if the XML is valid, and for which DTD version
            if (!pluginCandidate.ValidatePluginFile(FileName))
            {
                string allMessages = string.Empty;
                //case not valid file, so show the errors.
                foreach (string strText in pluginCandidate.ValidationErrors)
                {
                    allMessages += (strText.Trim() + "\r\n");
                }
                /// @todo Add a custom dialog to show every error message in a grid.
                //show messages
                MessageBox.Show(allMessages,
                                "Emulator - OpenPlugin.",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            else  //...XML plugin file is valid & system version is determined
            {
                //determine time to use to build the plugin
                DateTime TimeOfBuild = AssemblyUtils.GetFileDateTime(FileName);
                for (int i = 0; i < pluginCandidate.UseExtFiles.Length; i++)
                {
                    if (pluginCandidate.UseExtFiles[i] == true)
                    {
                        TimeOfBuild = DateTime.FromBinary(Math.Max(
                                                              TimeOfBuild.ToBinary(),
                                                              AssemblyUtils.GetFileDateTime(pluginCandidate.ExtFiles[i]).ToBinary()));
                    }
                }
                //generate the full name of the assembly corresponding to the plugin candidate
                string candidateAssemblyFullName =
                    pluginCandidate.PluginAssemblyFullName(TimeOfBuild).FullName;

                //determine the version to look for the correct method to load it
                switch (pluginCandidate.PluginSystemVersion)
                {
                case "0.0":
                    if (PluginPersistence.GetDataFromXML_v0_0(FileName, ref pluginCandidate))
                    {
                        //Search and replace plugin class declarations for V0.0 plugin
                        // system compatibility.
                        pluginCandidate.Codes[0] =
                            PluginSystem.ReplacePropellerClassV0_0(
                                PluginSystem.ReplaceBaseClassV0_0(pluginCandidate.Codes[0]));
                    }
                    break;

                case "1.0":
                    PluginPersistence.GetDataFromXML_v1_0(FileName, ref pluginCandidate);
                    objInst = this.Chip;
                    break;

                default:
                    MessageBox.Show(string.Format("Plugin system version '{0}' not recognized " +
                                                  "on file \"{1}\".", pluginCandidate.PluginSystemVersion, FileName),
                                    "Emulator - Open File.",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return;
                }
                //add information into plugin's code to generate with assembly attributes
                pluginCandidate.Codes[0] = PluginSystem.InsertAssemblyDetails(
                    pluginCandidate.Codes[0],
                    TimeOfBuild,
                    pluginCandidate.InstanceName,
                    pluginCandidate.Description,
                    pluginCandidate.PluginVersion);
                try
                {
                    //Dynamic load and compile the plugin module as a class, giving the chip
                    // instance as a parameter, and casting to appropriate class
                    PluginCommon plugin = ModuleCompiler.LoadModule(
                        pluginCandidate.Codes,                  //string[] codeTexts
                        pluginCandidate.ExtFiles,               //string[] sourceFiles
                        pluginCandidate.InstanceName,           //string module
                        pluginCandidate.References,             //string[] references
                        objInst,                                //object objInstance
                        pluginCandidate.PluginSystemVersion);   //string pluginSystemVersion,
                    if (plugin == null)
                    {
                        throw new Exception("Emulator - OpenPlugin: plugin object not generated!" +
                                            " (null response from memory loading).");
                    }
                    else //if success compiling & instantiate the new instance...
                    {
                        //...add to the corresponding plugin list of the emulator instance
                        AttachPlugin(plugin);
                        //update location of last plugin
                        Properties.Settings.Default.LastPlugin = FileName;
                        Properties.Settings.Default.Save();
                    }
                }
                catch (Exception)
                {
                    //open plugin editor in other window
                    PluginEditor errorPlugin = new PluginEditor(false);
                    if (errorPlugin.OpenFile(FileName, true))
                    {
                        //remember plugin successfully loaded
                        errorPlugin.UpdateLastPluginOpened();
                        //show plugin editor loaded with the faultly one
                        errorPlugin.MdiParent = this.MdiParent;
                        //the compilation errors are displayed in the error grid
                        ModuleCompiler.EnumerateErrors(errorPlugin.EnumErrors);
                        //show the error list
                        errorPlugin.ShowErrorGrid(true);
                        errorPlugin.Show();
                    }
                }
            }
        }