public void CanRetrieveWithCorrectRef()
        {
            var retriever = new FileModuleTypeLoader();
            var moduleInfo = new ModuleInfo() { Ref = "file://somefile" };

            Assert.IsTrue(retriever.CanLoadModuleType(moduleInfo));
        }
        public void CannotRetrieveWithIncorrectRef()
        {
            var retriever = new FileModuleTypeLoader();
            var moduleInfo = new ModuleInfo() { Ref = "NotForLocalRetrieval" };

            Assert.IsFalse(retriever.CanLoadModuleType(moduleInfo));
        }
        public void ShouldLoadDownloadedAssemblies()
        {
            // NOTE: This test method uses a resource that is built in a pre-build event when building the project. The resource is a
            // dynamically generated XAP file that is built with the Mocks/Modules/createXap.bat batch file.
            // If this test is failing unexpectedly, it may be that the batch file is not working correctly in the current environment.

            var mockFileDownloader = new MockFileDownloader();
            const string moduleTypeName = "Microsoft.Practices.Composite.Tests.Mocks.Modules.RemoteModule, RemoteModuleA, Version=0.0.0.0";
            var remoteModuleUri = "http://MyModule.xap";
            var moduleInfo = new ModuleInfo() { Ref = remoteModuleUri };
            XapModuleTypeLoader typeLoader = new TestableXapModuleTypeLoader(mockFileDownloader);
            ManualResetEvent callbackEvent = new ManualResetEvent(false);
            typeLoader.BeginLoadModuleType(
                moduleInfo,
                delegate
                {
                    callbackEvent.Set();
                });

            Assert.IsNull(Type.GetType(moduleTypeName));

            Stream xapStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.Practices.Composite.Tests.Mocks.Modules.RemoteModules.xap");
            mockFileDownloader.InvokeOpenReadCompleted(new DownloadCompletedEventArgs(xapStream, null, false, mockFileDownloader.DownloadAsyncArgumentUserToken));
            Assert.IsTrue(callbackEvent.WaitOne(500));

            Assert.IsNotNull(Type.GetType(moduleTypeName));
        }
 /// <summary>
 /// Registers a module with the <see cref="StaticModuleEnumerator" />.
 /// </summary>
 /// <param name="moduleType">The module type. This class should implement <see cref="IModule"/>.</param>
 /// <param name="dependsOn">The names of the modules that this module depends on, if any.</param>
 /// <returns>The same instance of <see cref="StaticModuleEnumerator"/>.</returns>
 /// <remarks>The module name will be the Name of the type specified in <paramref name="moduleType"/>.</remarks>
 public StaticModuleEnumerator AddModule(Type moduleType, params string[] dependsOn)
 {
     ModuleInfo moduleInfo = new ModuleInfo(moduleType.Assembly.FullName
                                            , moduleType.FullName
                                            , moduleType.Name
                                            , dependsOn);
     _modules.Add(moduleInfo);
     return this;
 }
        public void CanCreateCatalogFromList()
        {
            var moduleInfo = new ModuleInfo("MockModule", "type");
            List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfo };

            var moduleCatalog = new ModuleCatalog(moduleInfos);

            Assert.AreEqual(1, moduleCatalog.Modules.Count());
            Assert.AreEqual(moduleInfo, moduleCatalog.Modules.ElementAt(0));
        }
        public void BeginLoadModuleType(ModuleInfo moduleInfo, ModuleTypeLoadedCallback callback)
        {
            Thread retrieverThread = new Thread(() =>
            {
                Thread.Sleep(SleepTimeOut);
                callback(moduleInfo, CallbackArgumentError);

                callbackEvent.Set();
            });
            retrieverThread.Start();
        }
        public void ShouldForwardValuesToModuleInfo()
        {
            ModuleInfoGroup group = new ModuleInfoGroup();
            group.Ref = "MyCustomGroupRef";
            ModuleInfo moduleInfo = new ModuleInfo();
            Assert.IsNull(moduleInfo.Ref);

            group.Add(moduleInfo);

            Assert.AreEqual(group.Ref, moduleInfo.Ref);
        }
        public void ShouldCallDownloadAsync()
        {
            var mockFileDownloader = new MockFileDownloader();
            var remoteModuleUri = "http://MyModule.xap";
            var moduleInfo = new ModuleInfo() { Ref = remoteModuleUri };
            XapModuleTypeLoader typeLoader = new TestableXapModuleTypeLoader(mockFileDownloader);

            typeLoader.BeginLoadModuleType(moduleInfo, delegate { });

            Assert.IsTrue(mockFileDownloader.DownloadAsyncCalled);
            Assert.AreEqual(remoteModuleUri, mockFileDownloader.downloadAsyncArgumentUri.OriginalString);
        }
        public void InitializationExceptionsAreWrapped()
        {
            Assembly asm = CompilerHelper.CompileFileAndLoadAssembly("Microsoft.Practices.Composite.Tests.Mocks.Modules.MockModuleThrowingException.cs",
                                                                     @".\MocksModulesThwrowing\MockModuleThrowingException.dll");

            ModuleLoader loader = new ModuleLoader(new MockContainerAdapter(), new MockLogger());

            ModuleInfo info = new ModuleInfo(asm.CodeBase.Replace(@"file:///", ""),
                                             "Microsoft.Practices.Composite.Tests.Mocks.Modules.MockModuleThrowingException", "MockModuleThrowingException");

            loader.Initialize(new[] { info });
        }
        public void BeginLoadModuleType(ModuleInfo moduleInfo, ModuleTypeLoadedCallback callback)
        {
            Exception error = null;
            try
            {
                this.assemblyResolver.LoadAssemblyFrom(moduleInfo.Ref);
            }
            catch (Exception ex)
            {
                error = ex;
            }

            callback(moduleInfo, error);
        }
        protected override IModuleCatalog GetModuleCatalog()
        {
            string query = App.Current.Host.Source.Query;
            var level1 = new ModuleInfo(ModuleNames.level1, string.Format("{0}.Level1Module, {0}, Version=1.0.0.0", ModuleNames.level1)) { InitializationMode = InitializationMode.OnDemand, Ref = ModuleNames.level1 + ".xap" };
            var level2 = new ModuleInfo(ModuleNames.level2, string.Format("{0}.Level2Module, {0}, Version=1.0.0.0",ModuleNames.level2)) { InitializationMode = InitializationMode.OnDemand, Ref = ModuleNames.level2 + ".xap" };
            var level3 = new ModuleInfo(ModuleNames.level3, string.Format("{0}.Level3Module, {0}, Version=1.0.0.0", ModuleNames.level3)) { InitializationMode = InitializationMode.OnDemand, Ref = ModuleNames.level3 + ".xap" };
            var level4 = new ModuleInfo(ModuleNames.level4, string.Format("{0}.Level4Module, {0}, Version=1.0.0.0", ModuleNames.level4)) { InitializationMode = InitializationMode.OnDemand, Ref = ModuleNames.level4 + ".xap" };

            ModuleCatalog cat = new ModuleCatalog();
            cat.AddModule(level1);
            cat.AddModule(level2);
            cat.AddModule(level3);
            cat.AddModule(level4);
            return cat;
        }
        /// <summary>
        /// Adds a new module that is statically referenced to the specified module info group.
        /// </summary>
        /// <param name="moduleInfoGroup">The group where to add the module info in.</param>
        /// <param name="moduleName">The name for the module.</param>
        /// <param name="moduleType">The type for the module. This type should be a descendant of <see cref="IModule"/>.</param>
        /// <param name="dependsOn">The names for the modules that this module depends on.</param>
        /// <returns>Returns the instance of the passed in module info group, to provide a fluid interface.</returns>
        public static ModuleInfoGroup AddModule(
                    this ModuleInfoGroup moduleInfoGroup,
                    string moduleName,
                    Type moduleType,
                    params string[] dependsOn)
        {
            if (moduleType == null)
            {
                throw new ArgumentNullException("moduleType");
            }

            ModuleInfo moduleInfo = new ModuleInfo(moduleName, moduleType.AssemblyQualifiedName);
            moduleInfo.DependsOn.AddRange(dependsOn);
            moduleInfoGroup.Add(moduleInfo);
            return moduleInfoGroup;
        }
 public void Initialize(ModuleInfo moduleInfo)
 {
     IModule moduleInstance = null;
     try
     {
         moduleInstance = this.CreateModule(moduleInfo.ModuleType);
         moduleInstance.Initialize();
     }
     catch (Exception ex)
     {
         this.HandleModuleInitializationError(
             moduleInfo,
             moduleInstance != null ? moduleInstance.GetType().Assembly.FullName : null,
             ex);
     }
 }
        public void ShouldReturnErrorIfDownloadFails()
        {
            var mockFileDownloader = new MockFileDownloader();
            var remoteModuleUri = "http://MyModule.xap";
            var moduleInfo = new ModuleInfo() { Ref = remoteModuleUri };
            XapModuleTypeLoader typeLoader = new TestableXapModuleTypeLoader(mockFileDownloader);
            ManualResetEvent callbackEvent = new ManualResetEvent(false);
            Exception error = null;
            typeLoader.BeginLoadModuleType(
                moduleInfo,
                delegate(ModuleInfo callbackModuleInfo, Exception moduleError)
                {
                    error = moduleError;
                    callbackEvent.Set();
                });
            mockFileDownloader.InvokeOpenReadCompleted(new DownloadCompletedEventArgs(null, new InvalidOperationException("Mock Ex"), false, mockFileDownloader.DownloadAsyncArgumentUserToken));
            Assert.IsTrue(callbackEvent.WaitOne(500));

            Assert.IsNotNull(error);
            Assert.IsInstanceOfType(error, typeof(InvalidOperationException));
        }
Exemple #15
0
        public void Initialize(ModuleInfo[] moduleInfos)
        {
            List<ModuleInfo> modules = GetModulesLoadOrder(moduleInfos);

            IEnumerable<ModuleInfo> newModules = LoadAssembliesAndTypes(modules);

            foreach (ModuleInfo moduleInfo in newModules)
            {
                Type type = initializedModules[moduleInfo.ModuleType];

                try
                {
                    IModule module = CreateModule(type);
                    module.Initialize();
                }
                catch (Exception e)
                {
                    HandleModuleLoadError(moduleInfo, type.Assembly.FullName, e);
                }
            }
        }
        /// <summary>
        /// Handles any exception ocurred in the module Initialization process,
        /// logs the error using the <seealso cref="ILoggerFacade"/> and throws a <seealso cref="ModuleInitializeException"/>.
        /// This method can be overriden to provide a different behavior. 
        /// </summary>
        /// <param name="moduleInfo">The module metadata where the error happenened.</param>
        /// <param name="assemblyName">The assembly name.</param>
        /// <param name="exception">The exception thrown that is the cause of the current error.</param>
        /// <exception cref="ModuleInitializeException"></exception>
        public virtual void HandleModuleInitializationError(ModuleInfo moduleInfo, string assemblyName, Exception exception)
        {
            Exception moduleException;

            if (exception is ModuleInitializeException)
            {
                moduleException = exception;
            }
            else
            {
                if (!string.IsNullOrEmpty(assemblyName))
                {
                    moduleException = new ModuleInitializeException(moduleInfo.ModuleName, assemblyName, exception.Message, exception);
                }
                else
                {
                    moduleException = new ModuleInitializeException(moduleInfo.ModuleName, exception.Message, exception);
                }
            }

            this.loggerFacade.Log(moduleException.ToString(), Category.Exception, Priority.High);

            throw moduleException;
        }
 public void ShouldResolveModuleAndInitializeSingleModule()
 {
     IContainerFacade containerFacade = new MockContainerAdapter();
     var service = new ModuleLoader(containerFacade, new MockLogger());
     FirstTestModule.wasInitializedOnce = false;
     var info = new ModuleInfo(typeof(FirstTestModule).Assembly.Location, typeof(FirstTestModule).FullName, "FirstTestModule");
     service.Initialize(new[] { info });
     Assert.IsTrue(FirstTestModule.wasInitializedOnce);
 }
        public void FailWhenDependingOnMissingModule()
        {
            string assembly = CompilerHelper.GenerateDynamicModule("ModuleK", null, "ModuleL");
            ModuleInfo module = new ModuleInfo(assembly, "ModuleK.TestsModules.ModuleKClass", "ModuleK", "ModuleL");

            ModuleLoader loader = new ModuleLoader(new MockContainerAdapter(), new MockLogger());
            loader.Initialize(new[] { module });
        }
 public override void HandleModuleLoadError(ModuleInfo moduleInfo, string assemblyName, Exception exception)
 {
     HandleModuleLoadErrorCalled = true;
 }
        public void InexistentAssemblyFileThrows()
        {
            IContainerFacade containerFacade = new MockContainerAdapter();
            var service = new TestableModuleInitializerService(containerFacade, new MockLogger());

            var moduleInfo = new ModuleInfo(typeof(FirstTestModule).Assembly.Location + "NotValid.dll", typeof(FirstTestModule).FullName, "InexistantModule");

            bool exceptionThrown = false;
            try
            {
                service.Initialize(new[] { moduleInfo });
            }
            catch (Exception ex)
            {
                Assert.AreEqual(typeof(ModuleLoadException), ex.GetType());
                StringAssert.Contains(ex.Message, "NotValid.dll");
                StringAssert.Contains(ex.Message, "not found");
                exceptionThrown = true;
            }
            Assert.IsTrue(exceptionThrown, "No exception thrown.");
        }
        public void DuplicateModuleNameThrows()
        {
            IContainerFacade containerFacade = new MockContainerAdapter();
            var service = new TestableModuleInitializerService(containerFacade, new MockLogger());

            var firstModuleInfo = new ModuleInfo(typeof(FirstTestModule).Assembly.Location, typeof(FirstTestModule).FullName, "SameName");
            var secondModuleInfo = new ModuleInfo(typeof(SecondTestModule).Assembly.Location, typeof(SecondTestModule).FullName, "SameName");

            bool exceptionThrown = false;
            try
            {
                service.Initialize(new[] { firstModuleInfo, secondModuleInfo });
            }
            catch (Exception ex)
            {
                Assert.AreEqual(typeof(ModuleLoadException), ex.GetType());
                StringAssert.Contains(ex.Message, "SameName");
                StringAssert.Contains(ex.Message, "duplicate");
                exceptionThrown = true;
            }
            Assert.IsTrue(exceptionThrown, "No exception thrown.");
        }
        public void ShouldNotLoadAssemblyThatHasAlreadyBeenLoaded()
        {
            IContainerFacade containerFacade = new MockContainerAdapter();
            var service = new TestableModuleInitializerService(containerFacade, new MockLogger());

            var firstModuleInfo = new ModuleInfo(typeof(FirstTestModule).Assembly.Location, typeof(FirstTestModule).FullName, "FirstTestModule");
            var secondModuleInfo = new ModuleInfo(typeof(SecondTestModule).Assembly.Location, typeof(SecondTestModule).FullName, "SecondTestModule");

            Assert.AreEqual(0, service.LoadedAssemblies.Count);

            service.Initialize(new[] { firstModuleInfo, secondModuleInfo });

            Assert.AreEqual(1, service.LoadedAssemblies.Count);
        }
Exemple #23
0
 private static ModuleInfo CreateModuleInfo(string name, InitializationMode initializationMode, params string[] dependsOn)
 {
     ModuleInfo moduleInfo = new ModuleInfo(name, name);
     moduleInfo.InitializationMode = initializationMode;
     moduleInfo.DependsOn.AddRange(dependsOn);
     return moduleInfo;
 }
Exemple #24
0
 void IModuleInitializer.Initialize(ModuleInfo moduleInfo)
 {
     this.Initialize(moduleInfo);
 }
Exemple #25
0
        IEnumerable<ModuleInfo> IModuleCatalog.GetDependentModules(ModuleInfo moduleInfo)
        {
            if (GetDependentModules == null)
                return new List<ModuleInfo>();

            return GetDependentModules(moduleInfo);
        }
Exemple #26
0
 private static ModuleInfo CreateModuleInfo(Type type, InitializationMode initializationMode, params string[] dependsOn)
 {
     ModuleInfo moduleInfo = new ModuleInfo(type.Name, type.AssemblyQualifiedName);
     moduleInfo.InitializationMode = initializationMode;
     moduleInfo.DependsOn.AddRange(dependsOn);
     return moduleInfo;
 }
        public void ShouldNotInitializeIfAlreadyLoaded()
        {
            ModuleLoadTracker.ModuleLoadStack.Clear();
            IContainerFacade containerFacade = new MockContainerAdapter();
            var service = new ModuleLoader(containerFacade, new MockLogger());
            FirstTestModule.wasInitializedOnce = false;
            SecondTestModule.wasInitializedOnce = false;
            var firstModuleInfo = new ModuleInfo(typeof(FirstTestModule).Assembly.Location, typeof(FirstTestModule).FullName, "FirstTestModule");

            service.Initialize(new[] { firstModuleInfo });
            Assert.AreEqual(1, ModuleLoadTracker.ModuleLoadStack.Count, "ModuleLoadStack should only contain 1 module");
            service.Initialize(new[] { firstModuleInfo });
            Assert.AreEqual(1, ModuleLoadTracker.ModuleLoadStack.Count, "ModuleLoadStack should not have module that has already been loaded");

        }
Exemple #28
0
 public void Initialize(ModuleInfo moduleInfo)
 {
     LoadCalled = true;
     this.LoadedModules.Add(moduleInfo);
 }
        public void ShouldLogModuleInitializationError()
        {
            IContainerFacade containerFacade = new MockContainerAdapter();
            var logger = new MockLogger();
            var service = new ModuleLoader(containerFacade, logger);
            ExceptionThrowingModule.wasInitializedOnce = false;
            var exceptionModule = new ModuleInfo(typeof(ExceptionThrowingModule).Assembly.Location, typeof(ExceptionThrowingModule).FullName, "ExceptionThrowingModule");

            try
            {
                service.Initialize(new[] { exceptionModule });
            }
            catch (ModuleLoadException)
            {
            }
            Assert.IsNotNull(logger.LastMessage);
            StringAssert.Contains(logger.LastMessage, "ExceptionThrowingModule");
        }
Exemple #30
0
 public void Initialize(ModuleInfo moduleInfo)
 {
     LoadBody(moduleInfo);
 }
 /// <summary>
 /// Evaluates the <see cref="ModuleInfo.Ref"/> property to see if the current typeloader will be able to retrieve the <paramref name="moduleInfo"/>.
 /// Returns true if the <see cref="ModuleInfo.Ref"/> property starts with "file://", because this indicates that the file
 /// is a local file.
 /// </summary>
 /// <param name="moduleInfo">Module that should have it's type loaded.</param>
 /// <returns>
 ///     <see langword="true"/> if the current typeloader is able to retrieve the module, otherwise <see langword="false"/>.
 /// </returns>
 public bool CanLoadModuleType(ModuleInfo moduleInfo)
 {
     return(moduleInfo.Ref != null && moduleInfo.Ref.StartsWith("file://", StringComparison.Ordinal));
 }