public void WhenInitializingAModuleWithNoCatalogPendingToBeLoaded_ThenInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

            var serviceLocatorMock = new Mock<IServiceLocator>();
            var loggerFacadeMock = new Mock<ILoggerFacade>();

            var serviceLocator = serviceLocatorMock.Object;
            var loggerFacade = loggerFacadeMock.Object;

            compositionContainer.ComposeExportedValue(serviceLocator);
            compositionContainer.ComposeExportedValue(loggerFacade);

            aggregateCatalog.Catalogs.Add(new TypeCatalog(typeof(TestModuleForInitializer)));

            var moduleInitializer = compositionContainer.GetExportedValue<IModuleInitializer>();

            var moduleInfo = new ModuleInfo("TestModuleForInitializer", typeof(TestModuleForInitializer).AssemblyQualifiedName);

            var module = compositionContainer.GetExportedValues<IModule>().OfType<TestModuleForInitializer>().First();

            Assert.IsFalse(module.Initialized);

            moduleInitializer.Initialize(moduleInfo);

            Assert.IsTrue(module.Initialized);
        }
        public void WhenInitializingAModuleWithACatalogPendingToBeLoaded_ThenLoadsTheCatalogInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

            var serviceLocatorMock = new Mock<IServiceLocator>();
            var loggerFacadeMock = new Mock<ILoggerFacade>();

            var serviceLocator = serviceLocatorMock.Object;
            var loggerFacade = loggerFacadeMock.Object;

            compositionContainer.ComposeExportedValue(serviceLocator);
            compositionContainer.ComposeExportedValue(loggerFacade);

            var moduleInitializer = compositionContainer.GetExportedValue<IModuleInitializer>();
            var repository = compositionContainer.GetExportedValue<DownloadedPartCatalogCollection>();

            var moduleInfo = new ModuleInfo("TestModuleForInitializer", typeof(TestModuleForInitializer).AssemblyQualifiedName);

            repository.Add(moduleInfo, new TypeCatalog(typeof(TestModuleForInitializer)));

            moduleInitializer.Initialize(moduleInfo);

            ComposablePartCatalog existingCatalog;
            Assert.IsFalse(repository.TryGet(moduleInfo, out existingCatalog));

            var module = compositionContainer.GetExportedValues<IModule>().OfType<TestModuleForInitializer>().First();

            Assert.IsTrue(module.Initialized);
        }
        /// <summary>
        /// Loads the specified modules into the given container.
        /// </summary>
        /// <param name="rootContainer">The container into wich create and add the module published services.</param>
        /// <param name="modulesInfo">The list of modules to load.</param>
        /// <remarks>A <see cref="CompositionContainer"/> is created for every module in the list and added to the 
        /// <paramref name="rootContainer"/>. The Load() method is called on every module that
        /// exposes a <see cref="IModuleInitializer"/>.</remarks>
        public void Load(CompositionContainer rootContainer, params IModuleInfo[] modulesInfo)
        {
            Guard.ArgumentNotNull(rootContainer, "compositionContainer");
            Guard.ArgumentNotNull(modulesInfo, "modules");

            foreach (IModuleInfo moduleInfo in modulesInfo)
            {
                Assembly moduleAssembly = Assembly.Load(moduleInfo.AssemblyName);

                CompositionContainer container = String.IsNullOrEmpty(moduleInfo.VirtualPath)
                                                 	? rootContainer
                                                 	:
                                                 		rootContainer.Containers.AddNew<CompositionContainer>(moduleInfo.Name);

                LoadServices(container, moduleInfo);

                foreach (Type t in moduleAssembly.GetTypes())
                {
                    if (typeof (IModuleInitializer).IsAssignableFrom(t))
                    {
                        IModuleInitializer init = (IModuleInitializer) container.BuildNewItem(t);
                        _modules.Add(moduleInfo.Name, init);
                        try
                        {
                            init.Load(container);
                        }
                        catch (Exception ex)
                        {
                            ThrowModuleLoadException(ex, moduleAssembly);
                        }
                    }
                }
            }
        }
        public override void Load(CompositionContainer moduleContainer)
        {
            base.Load(moduleContainer);

            RegisterSiteMapInformation(moduleContainer.Services.Get<ISiteMapBuilderService>(true));
            RegisterRequiredPermissions(moduleContainer.Services.Get<IPermissionsCatalog>(true));
        }
        public void ModuleInUnreferencedAssemblyInitializedByModuleInitializer()
        {
            AssemblyCatalog assemblyCatalog = new AssemblyCatalog(GetPathToModuleDll());
            CompositionContainer compositionContainer = new CompositionContainer(assemblyCatalog);

            ModuleCatalog moduleCatalog = new ModuleCatalog();

            Mock<MefFileModuleTypeLoader> mockFileTypeLoader = new Mock<MefFileModuleTypeLoader>();

            compositionContainer.ComposeExportedValue<IModuleCatalog>(moduleCatalog);
            compositionContainer.ComposeExportedValue<MefFileModuleTypeLoader>(mockFileTypeLoader.Object);

            bool wasInit = false;
            var mockModuleInitializer = new Mock<IModuleInitializer>();
            mockModuleInitializer.Setup(x => x.Initialize(It.IsAny<ModuleInfo>())).Callback(() => wasInit = true);

            var mockLoggerFacade = new Mock<ILoggerFacade>();

            MefModuleManager moduleManager = new MefModuleManager(
                mockModuleInitializer.Object,
                moduleCatalog,
                mockLoggerFacade.Object);

            compositionContainer.SatisfyImportsOnce(moduleManager);

            moduleManager.Run();

            Assert.IsTrue(wasInit);
        }
		public void IndexAllFilesAutomaticallyUponStartup()
		{
			var sourceFile = MockFor<IFile>().Object;
			var sourceFileNotification = MockFor<IFileNotification>();
			sourceFileNotification
				.SetupGet(_ => _.File)
				.Returns(sourceFile);

			var sourceFilesProvider = MockFor<ISourceFilesProvider>();
			sourceFilesProvider
				.SetupGet(_ => _.SourceFiles)
				.Returns(ObservableX.Return(sourceFileNotification.Object));

			var providerSelector = MockFor<ISourceSymbolProviderSelector>();
			var parseWaitEvent = new AutoResetEvent(false);
			var symbol = MockFor<ISourceSymbol>();
			providerSelector
				.Setup(_ => _.SourceSymbolsFor(sourceFile))
				.Callback(() => parseWaitEvent.Set())
				.Returns(new[] {symbol.Object});

			var container = new CompositionContainer(typeof(ISourceSymbolIndexProvider).Assembly);
			container.AddExportedValue(sourceFilesProvider.Object);
			container.AddExportedValue(providerSelector.Object);
			container.AddExportedValue<ILogger>(new StandardLogger());

			var subject = container.GetExportedValue<ISourceSymbolIndexProvider>();
			Assert.IsNotNull(subject.Index);

			// TODO: replace by injecting immediate scheduler
			parseWaitEvent.WaitOne(TimeSpan.FromSeconds(1));

			VerifyAllMocks();
		}
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            AddGlobalServices(container.Parent.Services);
            AddModuleServices(container.Services);
        }
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            AddGlobalServices(container.Parent.Services);
            AddModuleServices(container.Services);
            RegisterSiteMapInformation(container.Services.Get<ISiteMapBuilderService>(true));
        }
 public void Load(
     [PexAssumeUnderTest]BeheerThemasModuleInitializer target,
     CompositionContainer container
 )
 {
     target.Load(container);
     // TODO: add assertions to method BeheerThemasModuleInitializerTest.Load(BeheerThemasModuleInitializer, CompositionContainer)
 }
示例#10
0
 public BaseDebuggerSessionTest()
 {
     var container = new CompositionContainer (new DirectoryCatalog (Environment.CurrentDirectory));
     session = container.GetExportedValue<IDebuggerSession> ();
     typeProvider = session.TypeProvider;
     typeProvider.AddFilter (Path.GetDirectoryName (typeof (type1).Assembly.Location));
     vm = session.VM as VirtualMachine;
 }
		public void MetadataIsOptional()
		{
			var container = new CompositionContainer(GetType().Assembly);

			var service = container.GetExportedValue<ServiceWithLazyImport>();
			Assert.IsNotNull(service.Import);
			Assert.IsNotNull(service.Import.Value);
			Assert.AreSame(service.Import.Value, service.Import.Value);
		}
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            if (container != null)
            {
                AddGlobalServices(container.Services);
            }
        }
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            AddModuleServices(container.Services);
            RegisterTranslators(container.Services.Get<IEntityTranslatorService>(true));
            RegisterRequiredPermissions(container.Services.Get<IPermissionsCatalog>(true));
            RegisterSiteMapInformation(container.Services.Get<ISiteMapBuilderService>(true));
        }
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            AddGlobalServices(container.Services);
            container.RootContainer.RegisterTypeMapping<IUnitOfWork, SqlUnitOfWork>();
            container.RootContainer.RegisterTypeMapping<IDomainContext, LcboDrinkLocatorContext>();
            container.RootContainer.RegisterTypeMapping<IFastDomainContext, LcboDrinkLocatorContextNoChangeTracking>();
        }
 public DynamicProxyValueInterceptorContext()
 {
     var innerCatalog = new TypeCatalog(typeof(Customer));
     var interceptor = new FreezableInterceptor();
     interceptor.Freeze();
     var valueInterceptor = new DynamicProxyInterceptor(interceptor);
     Catalog = new InterceptingCatalog(innerCatalog, valueInterceptor);
     Container = new CompositionContainer(Catalog);
     Context();
 }
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            AddGlobalServices(container.Parent.Services);
            AddModuleServices(container.Services);
            RegisterSiteMapInformation(container.Services.Get<ISiteMapBuilderService>(true));

            container.RegisterTypeMapping<IAudittrailController, AudittrailController>();
        }
示例#17
0
        static int Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            
            var catalog = new AttributedAssemblyPartCatalog(System.Reflection.Assembly.GetExecutingAssembly());            
            var container = new CompositionContainer(catalog);
            container.Compose();
            var inspectors = container.GetExportedObjects<IAudioFileInspector>();
            
            /*List<IAudioFileInspector> inspectors = new List<IAudioFileInspector>();
            inspectors.Add(new WaveFileInspector());
            inspectors.Add(new MidiFileInspector());
            inspectors.Add(new SoundFontInspector());
            inspectors.Add(new CakewalkMapInspector());*/

            if (args.Length > 0)
            {
                if (args[0] == "-install")
                {
                    try
                    {
                        OptionsForm.Associate(inspectors);
                        Console.WriteLine("Created {0} file associations", inspectors.Count); 
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Unable to create file associations");
                        Console.WriteLine(e.ToString());
                        return -1;
                    }

                    return 0;
                }
                else if (args[0] == "-uninstall")
                {
                    try
                    {
                        OptionsForm.Disassociate(inspectors);
                        Console.WriteLine("Removed {0} file associations", inspectors.Count);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Unable to remove file associations");
                        Console.WriteLine(e.ToString());
                        return -1;
                    }
                    return 0;
                }
            }
            var mainForm = container.GetExportedObject<AudioFileInspectorForm>();
            mainForm.CommandLineArguments = args;
            Application.Run(mainForm);
            return 0;
        }
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            AddGlobalServices(container.Parent.Services);
            AddModuleServices(container.Services);
            RegisterSiteMapInformation(container.Services.Get<ISiteMapBuilderService>(true));

            container.RegisterTypeMapping<IBeheerController, BeheerController>();
            container.RegisterTypeMapping<ICategorieController, CategorieController>();
            container.RegisterTypeMapping<ITrefwoordController, TrefwoordController>();
        }
        public override void Load(CompositionContainer container)
        {
            if (container == (CompositionContainer)null)
                throw new ArgumentNullException("container", 
                    "Controleer of CompositionContainer beschikbaar is.");

            base.Load(container);

            AddGlobalServices(container.Parent.Services);
            AddModuleServices(container.Services);
            RegisterSiteMapInformation(container.Services.Get<ISiteMapBuilderService>(true));

            container.RegisterTypeMapping<IBeheerThemasController, BeheerThemasController>();
        }
示例#20
0
文件: Program.cs 项目: Jiyuu/SkypeFX
        /// <summary>
        /// use managed extensibility framework to discover effects and load them into the main form
        /// </summary>
        private void Compose()
        {
            var catalog = new AggregatingComposablePartCatalog();
            var mainAssemblyCatalog = new AttributedAssemblyPartCatalog(this.GetType().Assembly);
            var jsNetCatalog = new AttributedAssemblyPartCatalog(typeof(Effect).Assembly);
            //var addInEffects = new DirectoryPartCatalog("Effects");

            catalog.Catalogs.Add(mainAssemblyCatalog);
            catalog.Catalogs.Add(jsNetCatalog);
            //catalog.Catalogs.Add(addInEffects);
            var container = new CompositionContainer(catalog);

            container.AddPart(this);
            container.Compose();
        }
        public override void Load(CompositionContainer container)
        {
            base.Load(container);

            AddGlobalServices(container.Parent.Services);
            AddModuleServices(container.Services);
            RegisterSiteMapInformation(container.Services.Get<ISiteMapBuilderService>(true));

            RepositoryMembershipProvider membershipProvider = Membership.Provider as RepositoryMembershipProvider;
            if (membershipProvider != null)
            {
                membershipProvider.EmployeeService = container.Services.Get<IEmployeeService>();
                membershipProvider.ValidPassword = "******";
            }

            container.RegisterTypeMapping<IOrdersController, OrdersController>();
        }
		public void OnlyServicesWithMatchingMetadataAreProvided()
		{
			var container = new CompositionContainer(GetType().Assembly);

			var service = container.GetExportedValue<ServiceWithImports>();
			Assert.IsNotNull(service.Imports);

			var expected = new[]
			{
				new {Type = typeof(Service1), Name = "Foo"},
				new {Type = typeof(Service2), Name = "Bar"}
			};
			var actual = service.Imports
				.Select(import => new {Type = import.Value.GetType(), import.Metadata.Name});

			CollectionAssert.AreEquivalent(expected, actual.ToArray());
		}
示例#23
0
        public HelloProgram()
        {
            this.Services = new List<IHelloService>();

            if (!Directory.Exists("PlugIns"))
            {
                Directory.CreateDirectory("PlugIns");
            }

            AggregatingComposablePartCatalog catalog = new AggregatingComposablePartCatalog();
            catalog.Catalogs.Add(new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()));
            catalog.Catalogs.Add(new DirectoryPartCatalog("PlugIns"));
            
            CompositionContainer container = new CompositionContainer(catalog.CreateResolver());
            container.AddPart(this);
            container.Compose();
        }
示例#24
0
        public void Initialize(CompositionContainer composition)
        {
            sourcesWindow = composition.GetExportedValue<SourcesWindow> ();
            sourceWindow = composition.GetExportedValue<SourceWindow> ();
            windowManager.Add (sourcesWindow);
            windowManager.Add (sourceWindow);
            log = composition.GetExportedValue<LogWindow> ();
            //			windowManager.Add (log);
            windowManager.Add (composition.GetExportedValue<CallstackWindow> ());
            windowManager.Add (composition.GetExportedValue<LocalsWindow> ());
            windowManager.Add (composition.GetExportedValue<BreakpointsWindow> ());
            windowManager.Add (composition.GetExportedValue<ExecutionWindow> ());

            if (HasArguments ())
                session.Port = SdbPortFromCommandLine ();

            //else
            //{
            //    var f = new StreamReader (File.Open (@"C:\debug.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
            //    var str = f.ReadLine ();
            //    f.Close ();
            //    session.Port = int.Parse (str.Substring ("Listening on 0.0.0.0:".Length, 5));
            //}

            log.WriteLine ("Connecting to " + session.Port);

            Camera.main.backgroundColor = new Color (0.125f, 0.125f, 0.125f, 0);
            Application.runInBackground = true;

            AdjustLayout ();

            //			if (!HasArguments ())
            //				return;

            session.TraceCallback += s => Trace (s);
            typeProvider.BasePath = ProjectPathFromCommandLine ();

            sourcesWindow.StartRefreshing ();

            session.Start ();
        }
        private void LoadService(CompositionContainer container, ServiceInfo service)
        {
            IServiceCollection serviceCollection;

            switch (service.Scope)
            {
                case ServiceScope.Global:
                    serviceCollection = container.RootContainer.Services;
                    break;

                case ServiceScope.Module:
                    serviceCollection = container.Services;
                    break;

                default:
                    serviceCollection = container.RootContainer.Services;
                    break;
            }

            serviceCollection.AddNew(service.Type, service.RegisterAs);
        }
示例#26
0
        //[ImportMany(typeof(IFormExstension), AllowRecomposition = true)]
        //public List<IFormExstension> FormExtensions { get; set; }
        public void LoadExtensions()
        {
            string path = Application.StartupPath + @"\Extensions";
            if(Directory.Exists(path))
            {
                var catalog = new AggregateCatalog(
                    new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                    new DirectoryCatalog(path));
                var batch = new CompositionBatch();
                batch.AddPart(this);

                _container = new CompositionContainer(catalog);

                try
                {
                    _container.Compose(batch);
                }
                catch (CompositionException compositionException)
                {
                    MessageBox.Show(compositionException.ToString());
                }
            }
        }
示例#27
0
        public static T Resolve <T>(this CompositionContainer container)
        {
            var service = container.Resolve(typeof(T), null);

            return(service is T ? (T)service : default(T));
        }
示例#28
0
 public ExportThatNeedsContainer(CompositionContainer cc)
 {
     Console.WriteLine("ExportThatNeedsContainer: cc [{0}]", cc.GetHashCode());
 }
示例#29
0
 public MEFServiceProvider(CompositionContainer container)
 {
     _Container = container;
     ServiceProvider.Current = this;
 }
示例#30
0
 protected virtual void AddValues(CompositionContainer container)
 {
 }
示例#31
0
 static Task RunBeforeEndpointStop(CompositionContainer compositionContainer, IEndpointInstance endpoint)
 {
     return(compositionContainer.ExecuteExports <IRunBeforeEndpointStop>(_ => _.Run(endpoint)));
 }
示例#32
0
    // Other injection points excluded, but follow the same pattern as above

    #endregion

    static Task RunCustomizeConfiguration(CompositionContainer compositionContainer, EndpointConfiguration endpointConfiguration)
    {
        return(compositionContainer.ExecuteExports <ICustomizeConfiguration>(_ => _.Run(endpointConfiguration)));
    }
示例#33
0
 public static UserRequestHandler BoardSolveUserRequestHandlerFactory(Board board, CompositionContainer container)
 {
     return(new BoardSolveUserRequestHandler(board, container));
 }
示例#34
0
 public static void Compose(this CompositionContainer container, params object[] attrParts)
 {
     container.ComposeParts(attrParts);
 }
示例#35
0
 public static void BuildUp(this CompositionContainer container, object instance)
 {
     container.SatisfyImportsOnce(instance);
 }
        public void DeclaredModuleWithTypeInUnreferencedAssemblyIsUpdatedWithTypeNameFromExportAttribute()
        {
            AggregateCatalog aggregateCatalog = new AggregateCatalog();
            CompositionContainer compositionContainer = new CompositionContainer(aggregateCatalog);

            var mockFileTypeLoader = new Mock<MefFileModuleTypeLoader>();
            mockFileTypeLoader.Setup(tl => tl.CanLoadModuleType(It.IsAny<ModuleInfo>())).Returns(true);


            ModuleCatalog moduleCatalog = new ModuleCatalog();
            ModuleInfo moduleInfo = new ModuleInfo { ModuleName = "MefModuleOne", ModuleType = "some type" };
            moduleCatalog.AddModule(moduleInfo);

            compositionContainer.ComposeExportedValue<IModuleCatalog>(moduleCatalog);
            compositionContainer.ComposeExportedValue<MefFileModuleTypeLoader>(mockFileTypeLoader.Object);

            bool wasInit = false;
            var mockModuleInitializer = new Mock<IModuleInitializer>();
            mockModuleInitializer.Setup(x => x.Initialize(It.IsAny<ModuleInfo>())).Callback(() => wasInit = true);

            var mockLoggerFacade = new Mock<ILoggerFacade>();

            MefModuleManager moduleManager = new MefModuleManager(
                mockModuleInitializer.Object,
                moduleCatalog,
                mockLoggerFacade.Object);

            compositionContainer.SatisfyImportsOnce(moduleManager);
            moduleManager.Run();

            Assert.IsFalse(wasInit);

            AssemblyCatalog assemblyCatalog = new AssemblyCatalog(GetPathToModuleDll());
            aggregateCatalog.Catalogs.Add(assemblyCatalog);

            compositionContainer.SatisfyImportsOnce(moduleManager);

            mockFileTypeLoader.Raise(tl => tl.LoadModuleCompleted += null, new LoadModuleCompletedEventArgs(moduleInfo, null));

            Assert.AreEqual("MefModulesForTesting.MefModuleOne, MefModulesForTesting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", moduleInfo.ModuleType);
            Assert.IsTrue(wasInit);
        }
示例#37
0
文件: Main.cs 项目: shana/debugger
 public static void Start()
 {
     var compositionContainer = new CompositionContainer (new DirectoryCatalog (AssemblyPath));
     view = compositionContainer.GetExportedValue<MainWindow> ();
     view.Initialize (compositionContainer);
 }
 public void Load(CompositionContainer compositionContainer, params ServiceInfo[] services)
 {
     UsedCompositionContainer = compositionContainer;
     UsedServices = services;
 }
示例#39
0
 private BoardSolveUserRequestHandler(Board board, CompositionContainer container) : base("solve")
 {
     _board     = board;
     _container = container;
 }
示例#40
0
        /// <summary>
        /// Run the bootstrapper process.
        /// </summary>
        /// <param name="runWithDefaultConfiguration">If <see langword="true"/>, registers default
        /// Prism Library services in the container. This is the default behavior.</param>
        public override void Run(bool runWithDefaultConfiguration)
        {
            this.Logger = this.CreateLogger();

            if (this.Logger == null)
            {
                throw new InvalidOperationException(Resources.NullLoggerFacadeException);
            }

            this.Logger.Log(Resources.LoggerWasCreatedSuccessfully, Category.Debug, Priority.Low);

            this.Logger.Log(Resources.CreatingModuleCatalog, Category.Debug, Priority.Low);
            this.ModuleCatalog = this.CreateModuleCatalog();
            if (this.ModuleCatalog == null)
            {
                throw new InvalidOperationException(Resources.NullModuleCatalogException);
            }

            this.Logger.Log(Resources.ConfiguringModuleCatalog, Category.Debug, Priority.Low);
            this.ConfigureModuleCatalog();

            this.Logger.Log(Resources.CreatingCatalogForMEF, Category.Debug, Priority.Low);
            this.AggregateCatalog = this.CreateAggregateCatalog();

            this.Logger.Log(Resources.ConfiguringCatalogForMEF, Category.Debug, Priority.Low);
            this.ConfigureAggregateCatalog();

            this.RegisterDefaultTypesIfMissing();

            this.Logger.Log(Resources.CreatingMefContainer, Category.Debug, Priority.Low);
            this.Container = this.CreateContainer();
            if (this.Container == null)
            {
                throw new InvalidOperationException(Resources.NullCompositionContainerException);
            }

            this.Logger.Log(Resources.ConfiguringMefContainer, Category.Debug, Priority.Low);
            this.ConfigureContainer();

            this.Logger.Log(Resources.ConfiguringServiceLocatorSingleton, Category.Debug, Priority.Low);
            this.ConfigureServiceLocator();

            this.Logger.Log(Resources.ConfiguringViewModelLocator, Category.Debug, Priority.Low);
            this.ConfigureViewModelLocator();

            this.Logger.Log(Resources.ConfiguringRegionAdapters, Category.Debug, Priority.Low);
            this.ConfigureRegionAdapterMappings();

            this.Logger.Log(Resources.ConfiguringDefaultRegionBehaviors, Category.Debug, Priority.Low);
            this.ConfigureDefaultRegionBehaviors();

            this.Logger.Log(Resources.RegisteringFrameworkExceptionTypes, Category.Debug, Priority.Low);
            this.RegisterFrameworkExceptionTypes();

            this.Logger.Log(Resources.CreatingShell, Category.Debug, Priority.Low);
            this.Shell = this.CreateShell();
            if (this.Shell != null)
            {
                this.Logger.Log(Resources.SettingTheRegionManager, Category.Debug, Priority.Low);
                RegionManager.SetRegionManager(this.Shell, this.Container.GetExportedValue <IRegionManager>());

                this.Logger.Log(Resources.UpdatingRegions, Category.Debug, Priority.Low);
                RegionManager.UpdateRegions();

                this.Logger.Log(Resources.InitializingShell, Category.Debug, Priority.Low);
                this.InitializeShell();
            }

            IEnumerable <Lazy <object, object> > exports = this.Container.GetExports(typeof(IModuleManager), null, null);

            if ((exports != null) && (exports.Count() > 0))
            {
                this.Logger.Log(Resources.InitializingModules, Category.Debug, Priority.Low);
                this.InitializeModules();
            }

            this.Logger.Log(Resources.BootstrapperSequenceCompleted, Category.Debug, Priority.Low);
        }
示例#41
0
 static Task RunBeforeEndpointStart(CompositionContainer compositionContainer)
 {
     return(compositionContainer.ExecuteExports <IRunBeforeEndpointStart>(_ => _.Run()));
 }
示例#42
0
        static void Main(string[] args)
        {
            // important to call these before creating application host
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents(); // see http://www.codeproject.com/buglist/EnableVisualStylesBug.asp?df=100&forumid=25268&exp=0&select=984714

            // Set up localization support early on, so that user-readable strings will be localized
            //  during the initialization phase below. Use XML files that are embedded resources.
            Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CurrentCulture;
            Localizer.SetStringLocalizer(new EmbeddedResourceStringLocalizer());

            var catalog = new TypeCatalog(
                typeof(SettingsService),                // persistent settings and user preferences dialog
                typeof(StatusService),                  // status bar at bottom of main Form
                typeof(CommandService),                 // handles commands in menus and toolbars
                typeof(ControlHostService),             // docking control host
                typeof(WindowLayoutService),            // multiple window layout support
                typeof(WindowLayoutServiceCommands),    // window layout commands
                typeof(FileDialogService),              // standard Windows file dialogs
                typeof(AutoDocumentService),            // opens documents from last session, or creates a new document, on startup
                typeof(Outputs),                        // service that provides static methods for writing to IOutputWriter objects.
                typeof(OutputService),                  // rich text box for displaying error and warning messages. Implements IOutputWriter.
                typeof(RecentDocumentCommands),         // standard recent document commands in File menu
                typeof(StandardFileCommands),           // standard File menu commands for New, Open, Save, SaveAs, Close
                typeof(StandardFileExitCommand),        // standard File exit menu command
                typeof(AtfUsageLogger),                 // logs computer info to an ATF server
                typeof(CrashLogger),                    // logs unhandled exceptions to an ATF server
                typeof(UnhandledExceptionService),      // catches unhandled exceptions, displays info, and gives user a chance to save
                typeof(ContextRegistry),                // central context registry with change notification
                typeof(DocumentRegistry),               // central document registry with change notification
                typeof(MainWindowTitleService),         // tracks document changes and updates main form title
                typeof(TabbedControlSelector),          // enable ctrl-tab selection of documents and controls within the app
                typeof(DefaultTabCommands),             // provides the default commands related to document tab Controls
                typeof(SkinService),

                // Customized components of the base class
                typeof(HelpAboutCommand)                // Help -> About command with custom information
                );

            var container = new CompositionContainer(catalog);

            var toolStripContainer = new ToolStripContainer();

            toolStripContainer.Dock = DockStyle.Fill;

            var mainForm = new MainForm(toolStripContainer);

            // TODO: Add Razix Editor logo later
            //var image = GdiUtil.GetImage("Razix.Resources.RazixCodeEditorLogo.ico");
            //mainForm.Icon = GdiUtil.CreateIcon(image, 32, true);

            mainForm.Text = "Razix Engine Editor".Localize();

            var batch = new CompositionBatch();

            batch.AddPart(mainForm);
            container.Compose(batch);

            // To make the tab commands (e.g., "Copy Full Path", "Open Containing Folder") available, we have to change
            //  the default behavior to work with this sample app's unusual Editor. In most cases, an editor like this
            //  would implement IDocumentClient and this customization of DefaultTabCommands wouldn't be necessary.
            var tabCommands = container.GetExportedValue <DefaultTabCommands>();

#if !PERFORCE_VERSION_CONTROL
            var sourceControlCommands = container.GetExportedValue <SourceControlCommands>();
            sourceControlCommands.RefreshStatusOnSave = true;
#endif

            // Initialize components that require it. Initialization often can't be done in the constructor,
            //  or even after imports have been satisfied by MEF, since we allow circular dependencies between
            //  components, via the System.Lazy class. IInitializable allows components to defer some operations
            //  until all MEF composition has been completed.
            container.InitializeAll();

            // Show the main form and start message handling. The main Form Load event provides a final chance
            //  for components to perform initialization and configuration.
            Application.Run(mainForm);

            container.Dispose();
        }
示例#43
0
 static Task RunAfterEndpointStop(CompositionContainer compositionContainer)
 {
     return(compositionContainer.ExecuteExports <IRunAfterEndpointStop>(_ => _.Run()));
 }
示例#44
0
        public static IPlugins GetPlugins(ITranslator translator, IAssemblyInfo config, ILogger logger)
        {
            logger.Info("Discovering plugins...");

            if (!Plugins.IsLoaded)
            {
                var resolver = new AssemblyResolver()
                {
                    Logger = logger
                };

                AppDomain.CurrentDomain.AssemblyResolve += resolver.CurrentDomain_AssemblyResolve;

                AppDomain.CurrentDomain.AssemblyLoad += resolver.CurrentDomain_AssemblyLoad;

                Plugins.IsLoaded = true;

                logger.Trace("Set assembly Resolve and Load events for domain " + AppDomain.CurrentDomain.FriendlyName);
            }

            logger.Trace("Current domain " + AppDomain.CurrentDomain.FriendlyName);

            logger.Trace("Application base: " + AppDomain.CurrentDomain.SetupInformation.ApplicationBase);

            logger.Trace("Loaded assemblies:");
            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                var location = a.IsDynamic ? "dynamic" : a.Location;
                logger.Trace(string.Format("\t{0} {1} {2}", a.FullName, location, a.GlobalAssemblyCache));
            }

            var path = GetPluginPath(translator, config);

            logger.Info("Will use the following plugin path \"" + path + "\"");

            var catalogs = new List <ComposablePartCatalog>();

            if (Directory.Exists(path))
            {
                catalogs.Add(new DirectoryCatalog(path, "*.dll"));
                logger.Info("The plugin path exists. Will use it as DirectoryCatalog");
            }
            else
            {
                logger.Info("The plugin path does not exist. Skipping searching test framework plugins in the plugin folder.");
            }

            string[] skipPluginAssemblies = null;
            var      translatorInstance   = translator as Translator;

            if (translatorInstance != null)
            {
                skipPluginAssemblies = translatorInstance.SkipPluginAssemblies;
            }

            logger.Trace("Will search all translator references to find resource(s) with names starting from \"" + PLUGIN_RESOURCE_NAME_PREFIX + "\" ...");

            foreach (var reference in translator.References)
            {
                logger.Trace("Searching plugins in reference " + reference.FullName + " ...");

                if (skipPluginAssemblies != null && skipPluginAssemblies.FirstOrDefault(x => reference.Name.FullName.Contains(x)) != null)
                {
                    logger.Trace("Skipping the reference " + reference.Name.FullName + " as it is in skipPluginAssemblies");
                    continue;
                }
                else
                {
                    logger.Trace("skipPluginAssemblies is not set");
                }

                var assemblies = reference.MainModule.Resources.Where(res => res.Name.StartsWith(PLUGIN_RESOURCE_NAME_PREFIX));

                logger.Trace("The reference contains " + assemblies.Count() + " resource(s) needed");

                if (assemblies.Any())
                {
                    foreach (var res_assembly in assemblies)
                    {
                        logger.Trace("Searching plugins in resource " + res_assembly.Name + " ...");

                        try
                        {
                            using (var resourcesStream = ((EmbeddedResource)res_assembly).GetResourceStream())
                            {
                                var ba = new byte[(int)resourcesStream.Length];
                                resourcesStream.Read(ba, 0, (int)resourcesStream.Length);

                                logger.Trace("Read the assembly resource stream of " + resourcesStream.Length + " bytes length");

                                var trimmedName = Plugins.TrimResourceAssemblyName(res_assembly, PLUGIN_RESOURCE_NAME_PREFIX);

                                var assembly = CheckIfAssemblyLoaded(logger, ba, null, trimmedName);

                                catalogs.Add(new AssemblyCatalog(assembly));
                                logger.Trace("The assembly " + assembly.FullName + " added to the catalogs");
                            }
                        }
                        catch (ReflectionTypeLoadException ex)
                        {
                            LogAssemblyLoaderException("Could not load assembly from resources", ex, logger);
                        }
                        catch (System.Exception ex)
                        {
                            logger.Error("Could not load assembly from resources: " + ex.ToString());
                        }
                    }
                }
            }

            if (catalogs.Count == 0)
            {
                logger.Info("No AssemblyCatalogs found");
                return(new Plugins()
                {
                    plugins = new IPlugin[0]
                });
            }

            var catalog = new AggregateCatalog(catalogs);

            CompositionContainer container = new CompositionContainer(catalog);
            var plugins = new Plugins();

            logger.Info("ComposingParts to discover plugins...");

            try
            {
                container.ComposeParts(plugins);
            }
            catch (ReflectionTypeLoadException ex)
            {
                LogAssemblyLoaderException("Could not compose Plugin parts", ex, logger);
            }
            catch (System.Exception ex)
            {
                logger.Error("Could not compose Plugin parts: " + ex.ToString());
            }

            if (plugins.Parts != null)
            {
                foreach (var plugin in plugins.Parts)
                {
                    plugin.Logger = translator.Log;
                }

                logger.Info("Discovered " + plugins.Parts.Count() + " plugin(s)");
            }

            return(plugins);
        }
示例#45
0
 static Task RunAfterEndpointStart(CompositionContainer compositionContainer, IEndpointInstance endpoint)
 {
     return(compositionContainer.ExecuteExports <IRunAfterEndpointStart>(_ => _.Run(endpoint)));
 }
 public void Load()
 {
     Console.WriteLine("Loading Plugins...");
     pluginContainer = new CompositionContainer(mainCatalog);
     pluginContainer.ComposeParts(this);
 }
示例#47
0
 public TestEditorShell(CompositionContainer container)
 {
     FileDialog     = new TestFileDialog();
     ProgressDialog = new TestProgressDialog();
     _container     = container;
 }
示例#48
0
 internal void Initialize(CompositionContainer container)
 {
     _providers = container.GetExportedValues <Microsoft.CodeAnalysis.Editor.ISignatureHelpProvider>()
                  .Select(x => (ISignatureHelpProvider) new SignatureHelperProvider(x))
                  .ToImmutableArray();
 }
 public LifetimeController(Func <CompositionContainer> factory)
 {
     Container = factory();
 }
示例#50
0
        public void Start()
        {
            if (!Directory.Exists(SourcesPath))
            {
                Log.Fatal("{@SourcesPath} doesn't exist; service has nothing to do without sources", SourcesPath);
                Stop();
                return;
            }

            if (!Directory.Exists(SinksPath))
            {
                Log.Warning("{@SinksPath} doesn't exist; service has nothing to do without sinks", SinksPath);
            }

            _childDevices.CollectionChanged += (sender, args) =>
            {
                switch (args.Action)
                {
                case NotifyCollectionChangedAction.Add:
                    foreach (IDualShockDevice item in args.NewItems)
                    {
                        Log.Information("Device {Device} got attached via {ConnectionType}", item,
                                        item.ConnectionType);
                        foreach (var plugin in SinkPlugins.Select(p => p.Value))
                        {
                            plugin.DeviceArrived(item);
                        }
                    }

                    break;

                case NotifyCollectionChangedAction.Remove:
                    foreach (IDualShockDevice item in args.OldItems)
                    {
                        Log.Information("Device {Device} got removed via {ConnectionType}", item,
                                        item.ConnectionType);
                        foreach (var plugin in SinkPlugins.Select(p => p.Value))
                        {
                            plugin.DeviceRemoved(item);
                        }
                    }

                    break;
                }
            };

            #region MEF

            //Creating an instance of aggregate catalog. It aggregates other catalogs
            var aggregateCatalog = new AggregateCatalog();

            //Load parts from the current assembly if available
            var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            //Add to the aggregate catalog
            aggregateCatalog.Catalogs.Add(new DirectoryCatalog(SourcesPath, "*.dll"));
            aggregateCatalog.Catalogs.Add(new DirectoryCatalog(SinksPath, "*.dll"));
            aggregateCatalog.Catalogs.Add(asmCatalog);

            //Crete the composition container
            var container = new CompositionContainer(aggregateCatalog);

            // Composable parts are created here i.e.
            // the Import and Export components assembles here
            container.ComposeParts(this);

            #endregion

            // Log loaded sink plugins
            foreach (var plugin in SinkPlugins)
            {
                Log.Information("Loaded sink plugin {Plugin}", plugin.Metadata["Name"]);

                plugin.Value.RumbleRequestReceived += (sender, args) =>
                                                      _childDevices[(IDualShockDevice)sender].Rumble(args.LargeMotor, args.SmallMotor);
            }

            // Log and enable sources
            foreach (var emulator in BusEmulators)
            {
                Log.Information("Loaded bus emulator {Emulator}", emulator.Metadata["Name"]);

                emulator.Value.ChildDeviceAttached += (sender, args) => _childDevices.Add(args.Device);
                emulator.Value.ChildDeviceRemoved  += (sender, args) => _childDevices.Remove(args.Device);
                emulator.Value.InputReportReceived += EmulatorOnInputReportReceived;

                try
                {
                    Log.Information("Starting bus emulator {Emulator}", emulator.Metadata["Name"]);
                    emulator.Value.Start();
                    Log.Information("Bus emulator {Emulator} started successfully", emulator.Metadata["Name"]);
                }
                catch (Exception ex)
                {
                    Log.Error("Failed to start {@emulator}: {@ex}", emulator.Metadata["Name"], ex);
                }
            }

            #region IPC

            var services = new DelegateServiceFactory();
            services.Register <IPairingService>(() =>
            {
                var service = new PairingService();

                service.DeviceListRequested += (sender, args) => _childDevices
                                               .Where(d => d.ConnectionType.Equals(DualShockConnectionType.USB))
                                               .Select(d => new DualShockDeviceDescriptor
                {
                    ClientAddress  = new UniqueAddress(d.ClientAddress),
                    ConnectionType = d.ConnectionType,
                    DeviceType     = d.DeviceType,
                    HostAddress    = new UniqueAddress(d.HostAddress)
                }).ToList();

                service.DevicePairingRequested += (device, args) =>
                                                  _childDevices[device.ClientAddress].PairTo(new PhysicalAddress(args.HostAddress.AddressBytes));

                return(service);
            });

            _ipcServer = new HalibutRuntime(services, Configuration.ServerCertificate);
            _ipcServer.Listen(Configuration.ServerEndpoint);
            _ipcServer.Trust(Configuration.ClientCertificate.Thumbprint);

            #endregion
        }
示例#51
0
        static void Main(string[] args)
        {
            //MessageBox.Show(@"Get ready to debug FB exe.");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (args.Length == 0)
            {
                MessageBox.Show(CommonResources.kNoCommandLineOptions, CommonResources.kFLExBridge, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            using (var hotspot = new HotSpotProvider())
            {
                // This is a kludge to make sure we have a real reference to PalasoUIWindowsForms.
                // Without this call, although PalasoUIWindowsForms is listed in the References of this project,
                // since we don't actually use it directly, it does not show up when calling GetReferencedAssemblies on this assembly.
                // But we need it to show up in that list so that ExceptionHandler.Init can install the intended PalasoUIWindowsForms
                // exception handler.
            }

            if (Settings.Default.CallUpgrade)
            {
                Settings.Default.Upgrade();
                Settings.Default.CallUpgrade = false;
            }

            SetUpErrorHandling();

            var commandLineArgs = CommandLineProcessor.ParseCommandLineArgs(args);

#if MONO
            // Set up Xpcom for geckofx (used by some Chorus dialogs that we may invoke).
            Xpcom.Initialize(XULRunnerLocator.GetXULRunnerLocation());
            GeckoPreferences.User["gfx.font_rendering.graphite.enabled"] = true;
            Application.ApplicationExit += (sender, e) => { Xpcom.Shutdown(); };
#endif

            // An aggregate catalog that combines multiple catalogs
            using (var catalog = new AggregateCatalog())
            {
                catalog.Catalogs.Add(new DirectoryCatalog(
                                         Path.GetDirectoryName(Utilities.StripFilePrefix(typeof(ActionTypeHandlerRepository).Assembly.CodeBase)),
                                         "*-ChorusPlugin.dll"));

                // Create the CompositionContainer with the parts in the catalog
                using (var container = new CompositionContainer(catalog))
                {
                    var connHelper = container.GetExportedValue <FLExConnectionHelper>();
                    if (!connHelper.Init(commandLineArgs))
                    {
                        return;
                    }

                    // Is mercurial set up?
                    var readinessMessage = HgRepository.GetEnvironmentReadinessMessage("en");
                    if (!string.IsNullOrEmpty(readinessMessage))
                    {
                        MessageBox.Show(readinessMessage, CommonResources.kFLExBridge, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        return;
                    }

                    var l10Managers = Utilities.SetupLocalization(commandLineArgs);

                    try
                    {
                        var handlerRepository = container.GetExportedValue <ActionTypeHandlerRepository>();
                        var currentHandler    = handlerRepository.GetHandler(commandLineArgs);
                        currentHandler.StartWorking(commandLineArgs);
                        var bridgeActionTypeHandlerShowWindow = currentHandler as IBridgeActionTypeHandlerShowWindow;
                        if (bridgeActionTypeHandlerShowWindow != null)
                        {
                            Application.Run(bridgeActionTypeHandlerShowWindow.MainForm);
                        }
                        var bridgeActionTypeHandlerCallEndWork = currentHandler as IBridgeActionTypeHandlerCallEndWork;
                        if (bridgeActionTypeHandlerCallEndWork != null)
                        {
                            bridgeActionTypeHandlerCallEndWork.EndWork();
                        }
                    }
                    catch
                    {
                        connHelper.SignalBridgeWorkComplete(false);
                        throw;                         // Re-throw the original exception, so the crash dlg has something to display.
                    }
                    finally
                    {
                        foreach (var manager in l10Managers.Values)
                        {
                            manager.Dispose();
                        }
                    }
                }
            }
            Settings.Default.Save();
        }
示例#52
0
        /// <summary>
        /// By default, we are configured to use MEF
        /// </summary>
        protected override void Configure()
        {
            try
            {
                var splashScreen = new SplashScreen(Assembly.GetAssembly(typeof(AppBootstrapper)), "daxstudio-splash.png");
                splashScreen.Show(true);

                // Tell Caliburn Micro how to find controls in Fluent Ribbon

                /*
                 * defaultElementLookup = BindingScope.GetNamedElements;
                 * BindingScope.GetNamedElements = new Func<System.Windows.DependencyObject, IEnumerable<System.Windows.FrameworkElement>>(
                 *  k =>
                 *  {
                 *      List<FrameworkElement> namedElements = new List<FrameworkElement>();
                 *      namedElements.AddRange(defaultElementLookup(k));
                 *      Fluent.Ribbon ribbon = LookForRibbon(k);
                 *      if (null != ribbon)
                 *          AppendRibbonNamedItem(ribbon, namedElements);
                 *      return namedElements;
                 *  }
                 *  );
                 */

                ConventionManager.AddElementConvention <Fluent.Spinner>(Fluent.Spinner.ValueProperty, "Value", "ValueChanged");
                ConventionManager.AddElementConvention <Xceed.Wpf.Toolkit.DoubleUpDown>(Xceed.Wpf.Toolkit.DoubleUpDown.ValueProperty, "Value", "ValueChanged");
                ConventionManager.AddElementConvention <Xceed.Wpf.Toolkit.IntegerUpDown>(Xceed.Wpf.Toolkit.IntegerUpDown.ValueProperty, "Value", "ValueChanged");
                ConventionManager.AddElementConvention <Xceed.Wpf.Toolkit.WatermarkTextBox>(Xceed.Wpf.Toolkit.WatermarkTextBox.TextProperty, "Text", "TextChanged");

                // Add Fluent Ribbon resovler
                BindingScope.AddChildResolver <Fluent.Ribbon>(FluentRibbonChildResolver);


                // Fixes the default datetime format in the results listview
                // from: http://stackoverflow.com/questions/1993046/datetime-region-specific-formatting-in-wpf-listview
                FrameworkElement.LanguageProperty.OverrideMetadata(
                    typeof(FrameworkElement),
                    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

                var catalog = new AggregateCatalog(
                    AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType <ComposablePartCatalog>()
                    );
                //_container = new CompositionContainer(catalog,true);
                _container = new CompositionContainer(catalog);
                var batch = new CompositionBatch();

                if (JsonSettingProvider.SettingsFileExists())
                {
                    batch.AddExportedValue <ISettingProvider>(new JsonSettingProvider());
                }
                else
                {
                    batch.AddExportedValue <ISettingProvider>(new RegistrySettingProvider());
                }

                batch.AddExportedValue <IWindowManager>(new WindowManager());
                batch.AddExportedValue <IEventAggregator>(new EventAggregator());
                batch.AddExportedValue <Func <DocumentViewModel> >(() => _container.GetExportedValue <DocumentViewModel>());
                batch.AddExportedValue <Func <IWindowManager, IEventAggregator, DocumentViewModel> >(
                    (w, e) => _container.GetExportedValue <DocumentViewModel>());
                batch.AddExportedValue(_container);
                batch.AddExportedValue(catalog);

                _container.Compose(batch);

                // Add AvalonDock binding convetions
                AvalonDockConventions.Install();

                ConfigureKeyBindings();

                // TODO - not working
                //VisibilityBindingConvention.Install();

                LogManager.GetLog = type => new DebugLogger(type);

                // Add Application object to MEF catalog
                _container.ComposeExportedValue <Application>("System.Windows.Application", Application.Current);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
示例#53
0
 public static void RegisterInstance <T>(this CompositionContainer container, T instance)
 {
     container.RegisterInstance(null, instance);
 }
示例#54
0
 public MEFControllerFactory(CompositionContainer compositionContainer)
 {
     _compositionContainer = compositionContainer;
 }
示例#55
0
 /// <summary>
 /// Requires T2 having parameterless constructor
 /// </summary>
 public static void Register <T, T2>(this CompositionContainer container) where T2 : T, new()
 {
     container.RegisterFunc(() => new T2());
     container.RegisterFunc <T>(() => container.Resolve <T2>());
 }
示例#56
0
 /// <summary>
 ///  Builds the composition container with all necessary import/exports.
 /// </summary>
 public static void Build()
 {
     // Initialize a new container looking at all exports in the given directory.
     compositionContainer = new CompositionContainer(objCatalog);
 }
示例#57
0
        protected override void ConfigureContainer(ContainerBuilder builder)
        {
            base.ConfigureContainer(builder);

            var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var catalogs = new List <ComposablePartCatalog>
            {
                new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x))),
                new DirectoryCatalog(assemblyDirectory, "Plugins.*.dll"),
                new DirectoryCatalog(assemblyDirectory, "Plugins.dll"),
                new AssemblyCatalog(typeof(IItem).Assembly)
            };

            var pluginsPath = Path.Combine(assemblyDirectory, "Plugins");

            if (Directory.Exists(pluginsPath))
            {
                catalogs.Add(new DirectoryCatalog(pluginsPath, "Plugins.*.dll"));
                catalogs.Add(new DirectoryCatalog(pluginsPath, "Plugins.dll"));
            }
            else
            {
                pluginsPath = assemblyDirectory;
            }

            MefContainer =
                CompositionHost.Initialize(catalogs.ToArray());

            var loadConfiguration =
                new LoadConfiguration(new DirectoryInfo(Path.Combine(assemblyDirectory, "Configuration")), MefContainer);
            var localConfigurationDirectory = new DirectoryInfo(Path.Combine(assemblyDirectory, "Local.Configuration"));

            if (localConfigurationDirectory.Exists)
            {
                loadConfiguration.AddConfigurationLocation(localConfigurationDirectory);
            }
            loadConfiguration.Load();

            var dataDirectory     = Path.Combine(assemblyDirectory, "Data");
            var coreConfiguration = new CoreConfiguration(dataDirectory, pluginsPath);

            var learningStorageLocation = new DirectoryInfo(Path.Combine(coreConfiguration.DataDirectory, "Learnings"));
            var indexStorageLocation    = new DirectoryInfo(Path.Combine(coreConfiguration.DataDirectory, "Index"));

            var updateManagerAdapter = new UpdateManagerAdapter();

            var scheduler = new StdSchedulerFactory().GetScheduler();

            scheduler.JobFactory = new MefJobFactory(new SimpleJobFactory(), MefContainer);

            var batch = new CompositionBatch();

            batch.AddExportedValue(MefContainer);
            batch.AddExportedValue <ILoadConfiguration>(loadConfiguration);
            batch.AddExportedValue <ILog>(new NLogAdapterToCoreILog(NLog.LogManager.GetLogger("mef")));
            batch.AddExportedValue(coreConfiguration);
            batch.AddExportedValue(updateManagerAdapter);
            batch.AddExportedValue <IScheduler>(scheduler);
            MefContainer.Compose(batch);

            MefContainer.SatisfyImportsOnce(updateManagerAdapter);

            builder.RegisterInstance(MefContainer).AsSelf();
            builder.RegisterInstance(coreConfiguration).AsSelf();
            builder.RegisterInstance(updateManagerAdapter).AsSelf();

            builder.RegisterInstance(scheduler).As <IScheduler>();
            builder.RegisterInstance <IWindowManager>(new WindowManager());
            builder.RegisterInstance <IEventAggregator>(new EventAggregator());

            builder.RegisterModule(new LoggingModule(t => new NLogAdapterToCoreILog(NLog.LogManager.GetLogger(t.FullName)),
                                                     t => NLog.LogManager.GetLogger(t.FullName)));
            builder.RegisterModule(new SatisfyMefImports(MefContainer));

            builder.RegisterType <MainWindowViewModel>().AsSelf();
            builder.RegisterType <AutoCompleteBasedOnLucene>().AsSelf();
            builder.RegisterType <GetActionsForItem>().As <IGetActionsForItem>();

            builder.RegisterType <ConverterRepository>().As <IConverterRepository>();

            builder.RegisterType <SourceStorageFactory>().AsSelf().SingleInstance();

            builder.RegisterType <FileSystemLearningRepository>().As <ILearningRepository>().WithParameter("input", learningStorageLocation);
            builder.RegisterType <ScheduleIndexJobs>().As <IStartupTask>();
            builder.RegisterType <ScheduleUpdateCheckJob>().As <IStartupTask>();
            builder.RegisterType <IronPythonCommandsMefExport>().As <IStartupTask>();
            builder.RegisterType <LogScheduledJobs>().As <IStartupTask>();
            builder.RegisterType <ProcessMonitor>().As <IStartupTask>();

            builder.RegisterType <Shutdown>().AsSelf();

            builder.RegisterType <SeparateIndexesDirectoryFactory>()
            .As <IDirectoryFactory>().WithParameter("root", indexStorageLocation)
            .SingleInstance();
        }
示例#58
0
        public MainForm()
        {
            InitializeComponent();

            AggregateCatalog catalog = new AggregateCatalog(
                new DirectoryCatalog("Plugins/Generators"),
                new DirectoryCatalog("Plugins/Visualizers"),
                new DirectoryCatalog("Plugins/Algorithms")
                );

            CompositionContainer container = new CompositionContainer(catalog);

            container.ComposeParts(this);

            foreach (var generator in Generators)
            {
                lstGenerators.Items.Add(generator.Name);
            }

            foreach (var generator in SolutionGenerators)
            {
                lstGenerators.Items.Add(generator.Name);
            }

            foreach (var matrixVisualizer in MatrixVisualizers)
            {
                lstMatrixVisualizers.Items.Add(matrixVisualizer.Name);
            }

            foreach (var solutionVisualizer in SolutionVisualizers)
            {
                lstSolutionVisualizers.Items.Add(solutionVisualizer.Name);
            }

            foreach (var algorithm in Algorithms)
            {
                lstAlgorithms.Items.Add(algorithm.Name);
            }

            matrixes                  = new List <IMatrixData <int, EmptyData> >();
            solutionMatrixes          = new List <IMatrixData <int, SolutionData> >();
            fileStorage               = new Storage();
            lstMatrixes.DisplayMember = "Name";

            UpdateStorage();

            if (lstGenerators.Items.Count > 0)
            {
                lstGenerators.SelectedIndex = 0;
            }
            if (lstMatrixes.Items.Count > 0)
            {
                lstMatrixes.SelectedIndex = 0;
            }
            if (lstMatrixVisualizers.Items.Count > 0)
            {
                lstMatrixVisualizers.SelectedIndex = 0;
            }
            if (lstSolutionVisualizers.Items.Count > 0)
            {
                lstSolutionVisualizers.SelectedIndex = 0;
            }
            if (lstAlgorithms.Items.Count > 0)
            {
                if (lstAlgorithms.Items.IndexOf("Полный перебор") == 0)
                {
                    lstAlgorithms.SelectedIndex = 1;
                }
                else
                {
                    lstAlgorithms.SelectedIndex = 0;
                }
            }
        }
示例#59
0
 public static void Start()
 {
     Console.WriteLine("Start: " + AssemblyPath);
     var compositionContainer = new CompositionContainer(new DirectoryCatalog(AssemblyPath));
     view = compositionContainer.GetExportedValue<MainWindow>();
 }
示例#60
0
        protected virtual CompositionContainer CreateContainer()
        {
            CompositionContainer container = new CompositionContainer(this.AggregateCatalog);

            return(container);
        }